How to: Programmatically Activate a Feature
Posted
Friday, February 22, 2008 10:01 AM
by
CoreyRoth
Today, I am continuing my series of posts on how to do basic tasks in SharePoint. Sometimes there is a need to activate a feature on a site collection or site using code. There are various reasons why you want to do this, but in my case, I needed to activate multiple features on multiple sites. The SPFeatureCollection object keeps track of which features are activated on a given site or site collection (not all features available for activation). There are a number of ways to access it. You can use the Features property on a given SPWeb or SPSite object. You can also make use of the WebFeatures or SiteFeatures from SPContext.Current. To activate a feature, call the Add method and pass it the GUID of the feature. Be warned that it will throw an InvalidOperationException if the feature is already activated. As with all SharePoint collections, the only way to determine if it exists is to use the indexer and see if it throws an exception. Here is an example of activating a feature at the site level.
SPWeb currentSite = SPContext.Current.Web;
{
currentSite.Features.Add(new Guid("{043C4BDD-9745-441a-A9A7-0BCD9B910319}"));
If you don't know the GUID of the feature but you do know the name of the Feature, you have to the FeatureDefinitions collection off of the SPFarm object. Unfortunately, you have to iterate through the whole collection and look at the title to find the feature you need. There is an example of it in the SDK.
Deactivating a feature is just as simple (provided you know the GUID). In this case I am using the WebFeatures properties off of the current context.
SPContext
.Current.WebFeatures.Remove(new Guid("{043C4BDD-9745-441a-A9A7-0BCD9B910319}"));
I know some might consider this a simple topic, but my goal is to help newcomers to SharePoint as much as possible.