I have a requirement to Activate/Deactivate Site Scoped Feature. I need to Activate/Deactivate on sites. I did deploy it and when I try to add it to a site collection an exception appear.

This's the code that I use it:

SPSite site = new SPSite("url");
site.AllowUnsafeUpdates = true;
var solution = SPFarm.Local.Solutions;
foreach (SPSolution item in solution)
    // only one solution available
    // the exception raise in here   
    site.Features.Add(item.SolutionFile.Id, true);

I can't figure out what's wrong with this code.


You're using the solution Id instead of the feature Id.
A solution package (.wsp) may contain on or more features.
Solutions deploy at the farm level, while features it contains deploy at farm, Web app, site coll' or sub-site levels.
You must first deploy the solution at the farm level (PowerShell or from the Central Admin) and then you may run your code to activate the feature at any site collection level.

You need to get the Id of the feature you want to activate and hard-code it in your code:

using(SPSite site = new SPSite("url"))
    site.AllowUnsafeUpdates = true; // Not needed if not run in the context of a Web component

    site.Features.Add(new Guid("<Id_of_the_feature>"), true);

Also, note that opening the SPWeb object is not needed at all here. But closing the SPSite is required.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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