14. June 2011 03:38
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):
private void ActivateWebApplicationFeature(SPWebApplication WebApplication, Guid FeatureGuid, bool Reactivate)
//Attempt to deactivate feature. Will fail if already deactivate.
//Was not activated, or could not be deactivated.
For a feature scoped at the Site level, you simply leverage the SPSite object
And for the Web scoped features, of course, just use the SPWeb
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.