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)
{
if (Reactivate)
{
try
{
//Attempt to deactivate feature. Will fail if already deactivate.
WebApplication.Features.Remove(FeatureGuid, true);
}
catch
{
//Was not activated, or could not be deactivated.
}
}
//Now activate
WebApplication.Features.Add(FeatureGuid);
}
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.