Navigate Up
Sign In
Supporters of Developer
Web

Useful Utility Functions (C#)

Item is currently unrated. Press SHIFT+ENTER to rate this item.1 star selected. Press SHIFT+ENTER to submit. Press TAB to increase rating. Press SHIFT+ESCAPE to leave rating submit mode.2 stars selected. Press SHIFT+ENTER to submit. Press TAB to increase rating. Press SHIFT+TAB to decrease rating. Press SHIFT+ESCAPE to leave rating submit mode.3 stars selected. Press SHIFT+ENTER to submit. Press TAB to increase rating. Press SHIFT+TAB to decrease rating. Press SHIFT+ESCAPE to leave rating submit mode.4 stars selected. Press SHIFT+ENTER to submit. Press TAB to increase rating. Press SHIFT+TAB to decrease rating. Press SHIFT+ESCAPE to leave rating submit mode.5 stars selected. Press SHIFT+ENTER to submit. Press SHIFT+TAB to decrease rating. Press SHIFT+ESCAPE to leave rating submit mode.

You may also be interested in: ViewPoint for SharePoint

 

Editor's note: Contributor Chris Grist is a SharePoint Architect at Beach Energy. Follow him @gristdog

Recently I have been working on a SharePoint project, and code wise it is my biggest one yet. After a short while it was evident I needed a framework of helper functions that I can use and not have to reinvent all the time. Today I would like to share them with everyone to give you a bit of a head start and not have to reinvent the wheel on some of these. Some I have pieced together from tech net, stack exchange and others blogs, so hopefully they will save you the time. Would love it if you can share your own in the comments!.

1. getWebTemplate

This function returns a web template based on the web and string provided.


 public static SPWebTemplate getWebTemplate(SPWeb w, String templateName)
        {
            SPWebTemplateCollection wtc = w.GetAvailableWebTemplates(1033);
            SPWebTemplate cwt = null;
            foreach (SPWebTemplate wt in wtc)
            {
                if (wt.Name.ToUpper().Contains(templateName.ToUpper()))
                {
                    cwt = wt;
                }
            }
 
            return cwt;
        }

Example:


getWebTemplate(Web, "License")

2. addPermissions

This function will add the specified AD Group to the specified SharePoint groups permissions.


         public static void addPermissions(SPWeb web, String groupName, String adGroupName, String role, String groupDescription)
        {
            SPGroup group = web.SiteGroups[groupName];
            SPUser adGroup = web.EnsureUser(adGroupName);
            group.AddUser(adGroup);
            group.Update();
 
            SPRoleAssignment roleAssignment = new SPRoleAssignment(group);
            SPRoleDefinition roleDefinition = web.RoleDefinitions[role];
 
            roleAssignment.RoleDefinitionBindings.Add(roleDefinition);
            web.RoleAssignments.Add(roleAssignment);
 
        }

Example:


addPermissions(topLevelSite, " Owners", "SHAREPOINT\\sp_bims_owner", "Full Control", "Full Control Group for Site");

3. createSubSite

This function will create a subsite.


public static SPWeb createSubSite(SPWeb topLevelSite, String siteName, String siteUrl, String siteDesc, uint LCID, SPWebTemplate cwt, bool uniquePermissions, bool convertIfExists)
        {
            SPWeb curWeb = topLevelSite.Webs.Add(siteUrl, siteName, siteDesc, LCID, cwt, uniquePermissions, convertIfExists);
            curWeb.AllowUnsafeUpdates = true;
            curWeb.Navigation.UseShared = true;
            curWeb.Update();
 
            return curWeb;
        }

Example:


createSubSite(topLevelSite, "Fields", "Fields", "This is the description", 1033, cwt, false, false);

4. activateFeatures

This function will activate a collection of features, I store the features to be activated in a SharePoint list, this way I don’t need to recompile to update the features needed to be activated.


public static void activateFeatures(SPSite site, SPListItemCollection featuresToActivate, String guildFieldName)
        {
            foreach (SPListItem i in featuresToActivate)
            {
                site.Features.Add(new Guid(i[guildFieldName].ToString()), false);
            }
        }


Example:


activateFeatures(newSite, properties.Web.Lists["Site Collection Features"].Items, "FeatureGUID");

5. addDefaultValues

This function sets the default value on a MMS field for a particular folder. This was used to help auto tag documents based on which folder they were uploaded to. You can easily modify this for other field types.


public static void addDefaultValues(SPList library, String folder, String column, String value, Term t)
        {
            MetadataDefaults columnDefaults = new MetadataDefaults(library);
            SPFolder rootFolder = library.RootFolder;
 
            if (t == null || t.Parent == null)
            {
 
                if (!folder.ToUpper().Equals("ROOTFOLDER"))
                {
                    rootFolder = library.RootFolder.SubFolders[folder];
                }
 
                columnDefaults.SetFieldDefault(rootFolder, column, value);
                columnDefaults.Update();
            }
            else
            {
                if (!folder.ToUpper().Equals("ROOTFOLDER"))
                {
                    SPFolder parentFolder = library.RootFolder.SubFolders[t.Parent.Name];
                    rootFolder = parentFolder.SubFolders[folder];
                }
                columnDefaults.SetFieldDefault(rootFolder, column, value);
                columnDefaults.Update();
            }
        }

Example:


addDefaultValues(topLevelSite.Lists["Documents"], "RootFolder", "License", termString);

6. createTerm

This function creates the specified term in the specified MMS term store. If the term already exists it returns the existing term using the next function.


public static Term createTerm(SPSite rootSite, String termSet, String termValue)
        {
            try
            {
                TaxonomySession session = new TaxonomySession(rootSite);
                TermSetCollection NavGroup = session.DefaultSiteCollectionTermStore.GetTermSets(termSet, 1033);
                TermSet selectedTermSet = NavGroup[0];
 
                Term createdTerm = selectedTermSet.CreateTerm(termValue, 1033);
                session.DefaultSiteCollectionTermStore.CommitAll();
 
                return createdTerm;
 
            }
            catch (Exception e)
            {
                return getTerm(rootSite, termSet, termSet);
            }
 
        }

Example:


createTerm(rootSite, "Licenses", "PEL123")

7. getTerm

Simple returns the requested term based on termset and name.


        public static Term getTerm(SPSite rootSite, String termSet, String termTitle)
        {
 
            TaxonomySession session = new TaxonomySession(rootSite);
            TermSetCollection NavGroup = session.DefaultSiteCollectionTermStore.GetTermSets(termSet, 1033);
            TermSet selectedTermSet = NavGroup[0];
 
            TermCollection termCollection = selectedTermSet.GetAllTerms();
 
            IEnumerable returnedTerms = from t in termCollection
                                        where t.Name.Contains(termTitle)
                                        orderby t.Name
                                        select t;
 
            Term returnTerm = null;
 
            foreach (Term t in returnedTerms)
            {
                returnTerm = t;
            }
 
            return returnTerm;
 
        }

Example:


getTerm(rootSite, "Licenses", "PEL123");

8. CreateFolder

This function creates a folder on the specified list


        private static void CreateFolder(SPList list, string folderName)
        {
            SPListItem newListItem;
            newListItem = list.Folders.Add("", SPFileSystemObjectType.Folder, folderName);
            newListItem.Update();
        }

Example:


 CreateFolder(myList, "My Folder");

9. HasContentType

The function checks to see if the specified list has a particular content type.


public static bool HasContentType(SPList list, string ctName)
        {
            if (string.IsNullOrEmpty(ctName)) { return false; }
            foreach (SPContentType ct in list.ContentTypes)
            {
                if (ct.Name == ctName) { return true; }
            }
            return false;
        }

Example:


HasContentType(curList, "Email")

10. HasView

This function checks to see if the specified list has a particular view.


        public static bool HasView(SPList list, string viewName)
        {
            if (string.IsNullOrEmpty(viewName))
                return false;
            foreach (SPView view in list.Views)
                if (view.Title.ToLowerInvariant() == viewName.ToLowerInvariant())
                    return true;
 
            return false;
        }

Example:


HasView(curList, "by Code");

11. IsFeatureActivated

This function checks to see if a particular feature is activated.


         public static bool IsFeatureActivated(this SPWeb web, Guid featureId)
        {
            return web.Features[featureId] != null;
        }

Example:


IsFeatureActivated(myWeb, new Guid("90fbe19b-e866-45a4-aaa8-26a6e334eb12"))

12. createTextColumn, createNumberColumn, createDateTimeColum, createMMSColumn

The following functions all create column types, they should probally be wrapped up in to one function and include other field types when time permits.


         public static void createTextColumn(SPList curList, String columnName)
        {
            SPFieldText field = curList.Fields.CreateNewField(SPFieldType.Text.ToString(), columnName) as SPFieldText;
            curList.Fields.Add(field);
            curList.Update();
        }
 
         public static void createNumberColumn(SPList curList, String columnName)
        {
            SPFieldNumber field = curList.Fields.CreateNewField(SPFieldType.Number.ToString(), columnName) as SPFieldNumber;
            curList.Fields.Add(field);
            curList.Update();
        }
 
        public static void createDateTimeColumn(SPList curList, String columnName)
        {
            SPFieldDateTime field = curList.Fields.CreateNewField(SPFieldType.DateTime.ToString(), columnName) as SPFieldDateTime;
            curList.Fields.Add(field);
            curList.Update();
        }
 
         public static void createMMSColumn(String TermStoreName, String GroupName, String TermSetName, String columnName, SPList curList)
        {
            TaxonomySession session = new TaxonomySession(curList.ParentWeb.Site);
            var termStore = session.TermStores[TermStoreName];
            var group = from g in termStore.Groups where g.Name == GroupName select g;
            var termSet = group.FirstOrDefault().TermSets[TermSetName];
 
            TaxonomyField field = curList.Fields.CreateNewField("TaxonomyFieldType", columnName) as TaxonomyField;
            field.SspId = termSet.TermStore.Id;
            field.TermSetId = termSet.Id;
            field.TargetTemplate = string.Empty;
            field.AllowMultipleValues = false; 
            field.CreateValuesInEditForm = true;
            field.Open = true;
            field.AnchorId = Guid.Empty;
 
            curList.Fields.Add(field);
 
            curList.Update();
 
 }

13. configureLibrarySettings

This function is used to configure a document library, right now it just enables versioning and sets a limit on the amount of versions.


        public static void configureLibrarySettings(SPDocumentLibrary curLib) 
        {
            curLib.EnableVersioning = true;
            curLib.EnableMinorVersions = true;
            curLib.MajorWithMinorVersionsLimit = 5;
            curLib.Update();
        }


Example:


configureLibrarySettings(myLibrary);

Categories: C#; dev

Comments

DJ

Catch correction

In example 6, wouldn't the catch be: return getTerm(rootSite, termSet, termValue);

Posted 19-Apr-2013 by DJ
chris grist

yup

yeah exactly right thanks for that!

Posted 20-Apr-2013 by chris grist
nau

gud

Today I would same to dole them among everyone to provide you a portion of a pate commence also negative own to reinvent the cog on quantity of these. dissertations superior paper Part I retain pieced unison from tech chic, stow switch besides additionals blogs, so hopefully they inclination conserve you the day.

Posted 12-Oct-2013 by nau
Network cabling service medway

Network

The prepare of evaluate similarly miscue-up had been sophisticated in epitaph an writing just not anymore amid an online endeavor writing use on your divide. The eat too the mining skill of survey is always near giant survey.

Posted 20-Nov-2013 by Network cabling service medway
replica handbags

replica handbags

Getting a CReplica Handbags or and possibly purse is just what Replica Rolex are available in the market, we must realize that the search can not regarding a piece linked to mirror and the appropriate level, be simple. Nowadays,Replica louis vuitton handbags are unquestionably not restricted for you to the basic function of holding typical essentials. Sure, have more purses and handbags than I would be able to ever possibly put to use. There are a great many manufacturers like Prada Handbags that dote on a woman's call for to have to help you be surrounded caused by the most sensational trendy articles just about about her. Therefore, it must be important for you will to bear of mind that unquestionably the bags you are usually about to select come with a new guarantee in truth it is wrong.

Posted 06-Dec-2013 by replica handbags
Dhirendra Yadav

Really Useful

Will save valuable development time for lot of folks.

Posted 05-Jan-2014 by Dhirendra Yadav
Elma Sherry

Share Point project

Chris your research about this project is perfectly appropriate and useful! i appreciate you to this phenomenal article keep it up. Desertleatherstore

Posted 08-Apr-2014 by Elma Sherry
door installation services west sussex

info

Our hacks can expertly finish inscription missions in some punishment. As a learner you might merely poverty somebody to “” or “type my thesis.” Collision us to have your chore completed faculty begone!

Notify me of comments to this article

E-mail:
   

Add Comment

Title:

 
Comment:
Email:

   


Name:

 
Url: