Tag Archives: SPFeatureCollection

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;
    }
}
Tagged , , ,