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):

 

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

Leave a Reply

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