Programmatically determine is a feature is activated or even installed

Okay so ever needed to see if a particular web or site feature is activated? Well if it’s activated it will be in the SPWeb.Features SPFeatureCollection or SPSite.Features. If it’s not activated it won’t be. Simple.

To check if a feature is installed examine the feature definitions collection on the SPFarm object, below are a couple of little extension methods that demonstrate this concept.

/// <summary>
/// Defines extensions made to the <see cref="SPWeb"/> class
/// </summary>
[CLSCompliant(false)]
public static class SPWebExtensions
{
    public static bool IsFeatureActivated(this SPWeb web, Guid featureId)
    {
        return web.Features[featureId] != null;
    }

    public static bool IsFeatureInstalled(this SPWeb web, Guid featureId)
    {
        SPFeatureDefinition featureDefinition = SPFarm.Local.FeatureDefinitions[featureId];
        if (featureDefinition == null)
        {
            return false;
        }

        if (featureDefinition.Scope != SPFeatureScope.Web)
        {
            throw new GeneralApplicationException(
                string.Format("Feature with the ID {0} was installed but is not scoped at the web level.", featureId));
        }

        return true;
    }
}
About these ads
Tagged , , ,

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

%d bloggers like this: