Programmatically Activating SharePoint Features

14 Jun

SharePoint features can exist at several different scopes, including Web, Site, and Web Application.  Each of these can be activated and deactivated programmatically, but they have to be handled slightly differently.

 

This can be extremely useful for automated deployment tools, or any number of other purposes.

 

Given a WebApplication scoped feature, you’ll need an SPWebApplication object (which you can get from the property on your SPSite object if needed):

 

For example, if you wanted a method which could activate a WebApplication scoped feature, an optionally deactivate and reactivate (useful after upgrading the feature during a deployment):

 

        <span class="kwrd">private</span> <span class="kwrd">void</span> ActivateWebApplicationFeature(SPWebApplication WebApplication, Guid FeatureGuid, <span class="kwrd">bool</span> Reactivate)
        {
            <span class="kwrd">if</span> (Reactivate)
            {
                <span class="kwrd">try</span>
                {
                    <span class="rem">//Attempt to deactivate feature.  Will fail if already deactivate.</span>
                    WebApplication.Features.Remove(FeatureGuid, <span class="kwrd">true</span>);
                }
                <span class="kwrd">catch</span>
                {
                    <span class="rem">//Was not activated, or could not be deactivated.</span>
                }
            }

            <span class="rem">//Now activate</span>
            WebApplication.Features.Add(FeatureGuid);
        }
&nbsp;

For a feature scoped at the Site level, you simply leverage the SPSite object

{SPSite}.Features.Add(FeatureGuid);

{SPSite}.Features.Remove(FeatureGuid, true);

 

And for the Web scoped features, of course, just use the SPWeb

{SPWeb}.Features.Add(FeatureGuid);

{SPWeb}.Features.Remove(FeatureGuid, true);

 

The boolean on the remove indicates whether to force deactivation.  Note that if the feature ID can not be found, permissions are not available, or it is already in the requested state, you will get a failure – So be sure to wrap your code with the appropriate error handling.

 

 

http://findreviews.me

Tweet about this on TwitterShare on Google+Share on FacebookShare on RedditEmail this to someoneShare on LinkedInShare on StumbleUpon

Leave a Reply

Your email address will not be published. Required fields are marked *