Take the 2-minute tour ×
SharePoint Stack Exchange is a question and answer site for SharePoint enthusiasts. It's 100% free, no registration required.

In order to programmatically activate a feature, you need its Feature ID (some type of GUID) that is set in the .feature file. Is there a pretty way of retrieving this value programmatically, so that I can do something like:

string featureID = ""; // Get Feature ID here
web.Features.Add(new Guid(featureID));

without having to hard code it?

share|improve this question
add comment

4 Answers 4

If you know the name of the feature, you can retrieve the feature's definition ID by iterating the SPFeatureDefinitionCollection.

Guid yourGuid;
foreach (SPFeatureDefinition featureDef in web.FeatureDefinitions)
{
   if (featureDef.DisplayName == "YourTitle" &&
       featureDef.Scope == SPFeatureScope.Web) // Check the scope just to be safe
   {
      yourGuid = featureDef.Id;
      web.Features.Add(yourGuid, true);
   }
}

Just test the code, because I haven't, but this should get you there.

Edit:

I initially gave code for the site collection feature definitions... fixed it.

share|improve this answer
add comment

Not without something else to identify it.

Best alternative I can come up with is by having the FeatureId in the web.config and get it.

share|improve this answer
add comment

Disclaimer: this is a surrogate that I'm using in my project. There may be a better solution.

SharePoint provides a class called SPBuiltInFieldId that contains a list of fields identifier. What I have done is add a new class called SPBuiltInFeaturesId by copying the logics behind the original Microsoft one.

You can find the list of features id on some sites like this, my advice is to add the new ids when you need them.

Note: I will edit the post with a sample, but for now the idea is to add a static guid field to the class, one for each feature id. If you are worried about performance, know that this is what SP does with the built in fields "enum" class.

share|improve this answer
add comment

Well, as other answers mentioned, you can:

  1. Scan all features and find one you need - using its name. However, you will have to hardcode string.
  2. I haven't checked web.config method.
  3. Use external tool to generate static class which all features you need.

As @SPArchaeologist said. We use this method. Create a static class to keep all the GUIDS you need. We use .tt files which use some simple reqex to create static class with guids.

Deploy dll, and feel free to use it anywhere.

share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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