Monday, September 9, 2013

Programatically activating SharePoint features

I've been attempting to programatically activate the features for a custom solution on particular SharePoint site collections.
Given a SPSite object, there's a number of blogs you can find via Google that offer the following code snippet to activate a feature:

    site.Features.Add(some GUID);

I was attempting to do this locally from the Central Admin box of our development farm, while the targeted site collection was hosted on one of our Web Front Ends.
This resulted in an exception:

Feature '<some GUID>' is not installed in this farm, and can not be added to this scope.

What the heck? I can see the feature sitting right there and I'm pretty sure that GUID is correct.
Let's make sure though. Since the SPFeatureCollection on SPSite.Features won't have deactivated features, I'm going to go ahead and manually activate the features so I can see them and access their GUIDs.
Again, given a SPSite object, we can loop through all the features on it and output their names and IDs in a little console app:
SPFeatureCollection featureColl = siteCollection.Features;

foreach (SPFeature feature in featureColl)

{
try


{


Console.WriteLine("ID:{0}; Name:{1}",

feature.Definition.Id.ToString(),

feature.Definition.GetTitle(System.Globalization.CultureInfo.CurrentCulture));

}

catch (Exception ex)
{
Console.WriteLine("Caught ex " + ex.ToString());
}
}

Here I ran into an even more interesting problem. The features from my custom solution didn't show up, yet every single other feature did. Here's where the lightbulb flicked on: we were missing all 6 of the custom features from the list, and there were exactly 6 null reference exceptions caught and written to the console. That's awfully strange.

It turns out that since these features are pushed out by our solution and only exist on that site collection level and not farm-wide, they can only be activated locally from that Web Front End.

Once I ran the code on the Web Front End instead of the Central Admin box, the exceptions stopped happening and my features were activated.

So, if you want to do it from the Central Admin box anyway, I found it's much easier by PowerShell sending commands over to the target box with a PowerShell session. It's a lot easier too. Here's how you can activate the View feature from PowerShell inside an invoke-command script block:

Enable-SPfeature Solution.Featurename -URL $SiteURL

Arguably a whole lot easier to just activate them by name than the whole mess I went through before.

No comments:

Post a Comment