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

How to do Enable-SPFeature equievalent in object model. I want to enable some features (lists) in my publishing site in event receiver. For example:

Enable-SPFeature announcementslist -url URL_OF_SITE

How can i activate announcementslist by code in event receiver?

share|improve this question
add comment

1 Answer 1

up vote 1 down vote accepted

You can use SPWeb or SPSite to activate features on subsite or a certain site collection respectively. Here is an example of SPWeb.

        try
        {
           SPWeb oWebSite = SPContext.Current.Web;
           feature = oWebSite.Features[new GUID("94C94CA6-B32F-4da9-A9E3-1F3D343D7ECB")];
           if (feature == null)//if feature is not activated  
           //Activating a feature using Object Model    
           oWebSite.Features.Add(new GUID("94C94CA6-B32F-4da9-A9E3-1F3D343D7ECB");
         }
         catch (Exception ex)
         {

         }
share|improve this answer
    
oWeb.Features.Add is equal to Enable-SPFeature ? And what to do for activating the feature in site collection scope. –  ozdogan Nov 9 '12 at 9:11
1  
use SPSite.Features.Add to add/activate a Site Collection scope feature, call the Add method and pass it the GUID of the feature. Be warned that it will throw an InvalidOperationException if the feature is already activated. –  Falak Mahmood Nov 9 '12 at 9:16
    
Very thanks Falak.. What is the best practice to handle exception. Or can we firstly look if the feature is already activated, before running the code? –  ozdogan Nov 9 '12 at 9:20
1  
I have updated the code with general exception handling. –  Falak Mahmood Nov 9 '12 at 9:31
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.