Commonly used SharePoint reusable functions

1. Programmatically get/search SharePoint List items

public static SPListItemCollection GetListItems(SPList list, string fieldName, string fieldValue)

        {

            SPListItemCollection items = null;

            if (list != null && !string.IsNullOrEmpty(fieldName) && !string.IsNullOrEmpty(fieldValue))

            {

                StringBuilder sbQuery = new StringBuilder();

                sbQuery.Append("<Where>");

                sbQuery.AppendFormat("<Eq><FieldRef Name=\"{0}\" /><Value Type=\"Text\">{1}</Value></Eq>", fieldName, fieldValue);

                sbQuery.Append("</Where>");

                SPQuery query = new SPQuery();

                query.ViewAttributes = "Scope='RecursiveAll'";

                query.Query = sbQuery.ToString();

                items = list.GetItems(query);

            }

            return items;

        }

 

2. Programmatically upload a file to a document library

public static void UploadFile(string siteUrl, string docLibraryName, string folderName, string fileName, Stream fStream)

        {

            if (string.IsNullOrEmpty(siteUrl) ||

                string.IsNullOrEmpty(docLibraryName) ||

                string.IsNullOrEmpty(folderName) ||

                string.IsNullOrEmpty(fileName))

            // string.IsNullOrEmpty(fileFullPath))

            {

                throw new ArgumentNullException("Arguments are passed with null or empty string values");

            }

                SPSecurity.RunWithElevatedPrivileges(delegate

                {

                    using (SPSite site = new SPSite(siteUrl))

                    {

                        using (SPWeb web = site.OpenWeb())

                        {

                            SPFolder documents = web.GetFolder(Constants.MSEKBDocLibrary);

                          SPFileCollection fileCollection = documents.Files;

                            string fileWebUrl = string.Concat(siteUrl, "/", docLibraryName, "/", folderName, "/", fileName);

                            SPFile file = web.GetFile(fileWebUrl);

          if (file != null && !file.Exists)

                            {

                                try

                                {

                       var contents = new byte[fStream.Length];

                                    fStream.Read(contents, 0, (int)fStream.Length);

                                    web.AllowUnsafeUpdates = true;

                                    SPFile currentFile = fileCollection.Add(

                                        string.Concat(Constants.MSEKBDocLibrary, "/", folderName, "/", fileName),

                                        contents,

                                        false);

                                    web.AllowUnsafeUpdates = false;

                                }

                                catch (Exception ex)

                                {

                                    throw;

                                }

                     finally

                                {

                                    web.AllowUnsafeUpdates = false;

                                }

                            }

                        }

                    }

                });

   }

        }

 

3. Programmatically create a SharePoint List column

public static void CreateColumn(SPList list, SPFieldType fieldType, string fieldDisplayName, string fieldName, int defaultValue = -1)

        {

            bool fieldExist = false;

            string[] fieldsList = fieldName.Split(',');

            try

            {

                foreach (string field in fieldsList)

                {

                    if (list.Fields.ContainsField(field))

                    {

                        fieldExist = true;

                        break;

                    }

                }

                if (list != null && !fieldExist)

                {

                    string fieldXml = "<Field Type ='" + fieldType.ToString() + "'";

                    fieldXml = string.Concat(fieldXml, " Name='", fieldName, "' ");

                    fieldXml = string.Concat(fieldXml, " Description='", fieldDisplayName, "' ");

                  fieldXml = string.Concat(fieldXml, " DisplayName='", fieldName, "' ");

                    fieldXml = string.Concat(fieldXml, " AllowDeletion='TRUE' Required='FALSE' ShowInDisplayForm='TRUE' ShowInEditForm='FALSE' ShowInVersionHistory='TRUE' ShowInListSettings='TRUE' ShowInViewForms='TRUE' ShowInNewForm='FALSE' >");

                    if (defaultValue != -1)

                    {

                        fieldXml = string.Concat(fieldXml, "<Default>", defaultValue, "</Default></Field>");

                    }

                    else

                    {

                        fieldXml = string.Concat(fieldXml, "</Field>");

                    }

                    list.Fields.AddFieldAsXml(fieldXml);

                    SPField listField = list.Fields[fieldName];

                    listField.Title = fieldDisplayName;

                    listField.ReadOnlyField = true;

                    listField.Update();

                }

            }

            catch (Exception ex)

     {

                throw;

            }

            finally

            {

            }

        }

 

4. Programmatically check SharePoint blocked file extensions

public static bool IsFileTypeBlocked(string extension)

        {

            bool blocked = false;

            SPSecurity.RunWithElevatedPrivileges(delegate()

            {

                try

                {

                    System.Collections.ObjectModel.Collection<String> types = SPContext.Current.Site.WebApplication.BlockedFileExtensions;

                    foreach (string type in types)

                    {

                        if (extension.Equals(type))

                        {

                            blocked = true;

                            break;

                        }

                    }

                }

                catch (Exception ex)

                {

                    throw;

                }

                finally

                {

                }

            });

            return blocked;

        }

5. Programmatically delete a file in a SharePoint document library

public static bool DeleteFile(string filePath)

        {

       bool deleted = false;

            try

            {

           SPSecurity.RunWithElevatedPrivileges(

                    delegate

                    {

                        using (SPSite site = new SPSite(filePath))

                        {

                            using (SPWeb web = site.OpenWeb())

                            {

                                SPFile file = web.GetFile(filePath);

                                if (file != null && file.Exists)

                                {

                                    web.AllowUnsafeUpdates = true;

                                    file.Delete();

                                    web.Update();

                                    web.AllowUnsafeUpdates = false;

                                    deleted = true;

  }

                            }

                        }

                    });

            }

            catch (Exception ex)

            {

                deleted = false;

                throw;

            }

            finally

            {

            }

            return deleted;

        }

 

6. Programmatically create a folder in a SharePoint document library

public static bool CreateNewFolderInLibrary(string siteUrl, string libraryName, string folderName)

        {

            bool folderCreated = false;

            if (!string.IsNullOrEmpty(siteUrl) &&

                !string.IsNullOrEmpty(libraryName) &&

                !string.IsNullOrEmpty(folderName))

            {

                SPSecurity.RunWithElevatedPrivileges(delegate()

                {

                    try

                    {

                        using (SPSite site = new SPSite(siteUrl))

                        {

                            using (SPWeb web = site.OpenWeb())

                            {

                                if (web != null)

                                {

                                    SPFolder documents = web.GetFolder(libraryName);

                                    if (!web.GetFolder(string.Concat(libraryName, "/", folderName)).Exists)

                                    {

                                        web.AllowUnsafeUpdates = true;

                                        documents.SubFolders.Add(folderName);

              web.AllowUnsafeUpdates = false;

                                        folderCreated = true;

                                    }

                                    else

                                    {

                   folderCreated = true;

                                    }

                                }

                            }

                        }

                    }

                    catch (Exception exGetValue)

                    {

                        folderCreated = false;

                        throw;

                    }

                    finally

                    {

                    }

                });

            }

            else

            {

                throw new ArgumentNullException("Arguments are passed with null or empty string values");

            }

            return folderCreated;

        }

 

7. Programmatically create a folder in a SharePoint custom list

public static void CreateNewFolderInList(string siteUrl, string listName, string folderName)

        {

            bool folderExist = false;

            if (!string.IsNullOrEmpty(siteUrl) &&

                !string.IsNullOrEmpty(listName) &&

                !string.IsNullOrEmpty(folderName))

            {

                SPSecurity.RunWithElevatedPrivileges(delegate()

         {

  using (SPSite site = new SPSite(siteUrl))

                    {

                        using (SPWeb web = site.OpenWeb())

                        {

                            try

                            {

                                if (web != null)

                                {

                                    SPList list = web.Lists[listName];

                                    SPListItemCollection folders = list.Folders;

                    // check if same Folder Already Exist

                                    for (int counter = 0; counter < folders.Count; counter++)

                                    {

                                        if (folders[counter].Name == folderName)

                                        {

                                            folderExist = true;

                                            break;

                                        }

                                    }

        if (!folderExist)

                                    {

                                        web.AllowUnsafeUpdates = true;

                                        SPListItem folderItem = list.Items.Add(list.RootFolder.ServerRelativeUrl, SPFileSystemObjectType.Folder);

                                        folderItem["Title"] = folderName;

                                        folderItem.Update();

                                        web.AllowUnsafeUpdates = false;

                                    }

                                }

                            }

                            catch (Exception exGetValue)

                            {

                                throw;

                            }

                            finally

         {

                                web.AllowUnsafeUpdates = false;

                            }

                        }

                    }

                });

            }

            else

            {

                throw new ArgumentNullException("Arguments are passed with null or empty string values");

            }

        }

 

8. Programmatically add an item to a SharePoint custom list

public static void AddListItem(string siteUrl, string listName, string folderName, Hashtable listItemValues, out int recordsCount)

        {

            recordsCount = 0;

            int internalRecordsCount = 0;

       SPSecurity.RunWithElevatedPrivileges(

                delegate

                {

                    using (SPSite site = new SPSite(siteUrl))

                    {

                        using (SPWeb web = site.OpenWeb())

                        {

  try

                            {

                                SPList kbLinksList = web.Lists.TryGetList(listName);

                                SPListItemCollection items = null;

                          if (kbLinksList != null && listItemValues != null)

                                {

                                    string fieldValue = listItemValues["Title"

].ToString();

                                    items = this.GetListItems(listName, "Title", fieldValue);

                                    if (items != null)

                                    {

                                        internalRecordsCount = items.Count;

                                        // Items should not exist in case of add.

                                        if (items.Count == 0)

                                        {

                                            this.CreateNewFolderInList(web.Url, listName, folderName);

                                            SPListItem listItem = kbLinksList.Items.Add("/Lists/" + listName + "/" + folderName, SPFileSystemObjectType.File);

                                            foreach (string key in listItemValues.Keys)

                                            {

                                                if (listItemValues[key] != null && listItem.Fields.ContainsField(key))

                                                {

                                                    string columnName = key;

                                                    string value = listItemValues[key].ToString();

                                                    this.UpdateMetaData

 (web, listItem, columnName, value);

                                                }

                                            }

                                            web.AllowUnsafeUpdates = true;

                             listItem.Update();

                                            web.AllowUnsafeUpdates = false;

                                        }

                                    }

                                }

                            }

  catch (Exception genexception)

                            {

                                throw;

                            }

                            finally

                            {

                                web.AllowUnsafeUpdates = false;

                            }

                        }

                    }

                });

            recordsCount = internalRecordsCount;

        }

 

 

/// <summary>

        /// Update Metadata method does update the property values for a SharePoint list or library item.

        /// Currently it is supported for following type of SharePoint fields. It can be extended for other fields in future.

        /// 1. MultiChoice

        /// 2. Text

        /// 3. Note

        /// 4. Integer

        /// 5. Number

        /// 6. User

        /// </summary>

        /// <param name="item">SharePoint List Item to update</param>

        /// <param name="fieldName">Name of the field</param>

        /// <param name="fieldValue"> Value of the field</param>

public static void UpdateMetaData(SPWeb web, SPListItem item, string fieldName, string fieldValue)

        {

            businessLayerTrace.TraceEvent(

                    TraceEventType.Verbose, Constants.TraceIDs.ID_101, "Method Entry : Microsoft.Services.MsEngage.Site.RecommendedResource.ShareIPManager.UpdateMetaData (FieldName = " + fieldName + ", FieldValue = " + fieldValue + ")");

            if (item != null && item.ParentList.Fields.ContainsField(fieldName))

            {

                SPField spField = item.Fields.GetField(fieldName);

                if (spField != null)

                {

                    switch (spField.Type)

                    {

                        case SPFieldType.MultiChoice:

                            string[] fieldValues = fieldValue.Split(SPFieldMultiChoiceValue.Delimiter.ToCharArray());

                   if (fieldValues != null && fieldValues.Length > 0)

                            {

                                SPFieldMultiChoiceValue multiChoiceCollection = new SPFieldMultiChoiceValue();

                                foreach (string multiChoiceValue in fieldValues)

                                {

                                    if (!string.IsNullOrEmpty(multiChoiceValue))

                                    {

                                        multiChoiceCollection.Add(multiChoiceValue);

                                    }

                                }

                                item[fieldName] = multiChoiceCollection.ToString();

                            }

                            break;

                        case SPFieldType.MultiChoice:

SPFieldUserValueCollection userValueCollection = new SPFieldUserValueCollection();

                    string value = fieldValue as string;

                    if (!string.IsNullOrEmpty(value))

                    {

                        string[] users = value.Split(',');

                        foreach (string user in users)

                        {

                            if (!string.IsNullOrEmpty(user))

                            {

                                SPUser spUser = web.EnsureUser(user);

                                if (spUser != null)

                                {

         userValueCollection.Add(new SPFieldUserValue(item.Web, spUser.ID, spUser.Name));

                                }

                            }

                        }

                        item[fieldName] = userValueCollection;

                            break;

                 default:

                            item[fieldName] = fieldValue;

                            break;

                    }

                }

            }

        }

 

9. Programmatically edit an item to a SharePoint custom list

public static void EditListItem(string siteUrl, string listName, Hashtable listItemValues, out int recordsCount)

        {

            recordsCount = 0;

            int internalRecordsCount = 0;

            SPSecurity.RunWithElevatedPrivileges(

                delegate

                {

                    using (SPSite site = new SPSite(siteUrl))

                    {

                        using (SPWeb web = site.OpenWeb())

                        {

                            try

                            {

                                SPList kbLinksList = web.Lists.TryGetList(listName);

                                SPListItemCollection items = null;

                                if (kbLinksList != null && listItemValues != null)

                                {

                                    string fieldValue = listItemValues["Title"].ToString();

                           items = this.GetListItems(listName, "Title", fieldValue);

                                    if (items != null)

                                    {

                                        internalRecordsCount = items.Count;

/// Ensure only one record exists

                                        if (items.Count > 0 && items.Count < 2)

                                        {

                                            SPListItem listItem = items[0];

                                            foreach (string key in listItemValues.Keys)

                                            {

                                                string columnName = key;

                              string value = listItemValues[key].ToString();

                                            this.UpdateMetaData

 (web, listItem, columnName, value);

                                            }

                                            web.AllowUnsafeUpdates = true;

                                            listItem.Update();

                                            web.AllowUnsafeUpdates = false;

                                        }

                                    }

                                }

                            }

                            catch (Exception genexception)

                            {

                                throw;

                            }

                         finally

                            {

                                web.AllowUnsafeUpdates = false;

                            }

                        }

                    }

                });

            recordsCount = internalRecordsCount;

        }

 

10. Programmatically check whether SharePoint custom list item exists

public static bool IsListItemExists(string siteUrl, string listName, string folderName, string fieldName, string fieldValue)

        {

            bool itemExists = false;

            if (!string.IsNullOrEmpty(siteUrl) &&

                !string.IsNullOrEmpty(listName) &&

                !string.IsNullOrEmpty(fieldName) &&

                !string.IsNullOrEmpty(fieldValue))

            {

                SPSecurity.RunWithElevatedPrivileges(delegate()

                {

                    try

                    {

                        SPListItemCollection items = null;

                        using (SPSite site = new SPSite(siteUrl))

                        {

                            using (SPWeb web = site.OpenWeb())

  {

                                if (web != null)

                                {

                                    SPList list = web.Lists[listName];

                                    if (list != null)

                  {

                                        StringBuilder sbQuery = new StringBuilder();

                                        sbQuery.Append("<Where>");

                                        sbQuery.AppendFormat("<Eq><FieldRef Name=\"{0}\" /><Value Type=\"Text\">{1}</Value></Eq>", fieldName, fieldValue);

                                        sbQuery.Append("</Where>");

                                        SPQuery query = new SPQuery();

                                        if (!string.IsNullOrEmpty(folderName))

                                        {

                                            query.Folder = list.RootFolder.SubFolders[folderName];

                                        }

                                       query.Query = sbQuery.ToString();

                                        items = list.GetItems(query);

                                        itemExists = items != null && items.Count > 0; ;

                                    }

                       }

                            }

                        }

                    }

                    catch (Exception exGetValue)

                    {

                        throw;

                    }

                    finally

                    {

                    }

                });

            }

            else

            {

                throw new ArgumentNullException("Arguments are passed with null or empty string values");

            }

            return itemExists;

        }