0

I am trying to remove a feature, say Feature-X, that is activated by default as part of a site template.

The requirement is to remove Feature-X for all non-root sites or subsites created using the site template. I do this in the FeatureActivated event of a web scoped feature, say Feature-Web, which is activated by default as part of the same site template.

When the FeatureActivated event for Feature-Web event executes, I see that Feature-X has already been activated. The code below runs fine and removes Feature-X from the Features collection.

public override void FeatureActivated(SPFeatureReceiverProperties properties)
{
    SPWeb featureWeb = properties.Feature.Parent as SPWeb;

    Guid webId = featureWeb.ID;
    Guid siteId = featureWeb.Site.ID;

    using (SPSite site = new SPSite(siteId, featureWeb.Site.SystemAccount.UserToken))
    using (SPWeb web = site.OpenWeb(webId))
    {
        if (!web.IsRootWeb)
        {
            var featureGUID = new Guid("<some guid>");
            web.Features.Remove(featureGUID, true);
            web.Update(); 
        }
    }
}

However, when I open the subsite in the browser or SharePoint Manager, I see that Feature-X has not been removed. The same code removes Feature-X if run elsewhere (example in a .aspx page in the same site or a command-line app).

Does anyone know why this might be the case and how to solve this?

1 Answer 1

0

May be, I was looking at this the wrong way. One option is to cancel the feature Feature-X's activation by throwing an unhandled exception in the feature's FeatureActivated event. That will ensure that the feature is never activated.

Other suggestions/corrections to this approach are welcome.

public override void FeatureActivated(SPFeatureReceiverProperties properties)
{
    using(SPWeb web = properties.Feature.Parent as SPWeb)
    {
        if (!web.IsRootWeb)
        {
            throw new Exception("This feature is applicable for root web only.");
        }
    }
}
2
  • You could also change scope from Web to Site, and work with Site.RootWeb in your feature receiver. If you have modules in the feature, you can mark them with the attribute RootWebOnly Nov 16, 2013 at 8:51
  • Thanks for the info. I am trying to create a custom action using the feature (Feature-X in the description above). I have set the attribute RootWebOnly="TRUE", but I see that the feature creates the custom action when I create a sub site.
    – Girish
    Nov 18, 2013 at 16:28

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.