A Feature Receiver, simply put, is code that you (the developer) can choose to "attach" to a specific feature and that code will (generally) run when either you activate or deactivate the feature. More specifically, when you click on the Activate or Deactivate button.
Feature Receivers are important as they provide you the opportunity to run any feature initialization that is required on Activate, and any clean up that is required on Deactivate. In our case, we wish to do the following:
Open the SP2010ProposalLibrary Visual Studio Solution you created in the previous recipe:
ProposalLibrary.EventReceiver.cs
file that opens, uncomment the methods for FeatureActivated
and FeatureDeactivating
, and delete the remaining lines of comments.Provide the following lines of code for the FeatureActivated
method:
SPWeb site = properties.Feature.Parent as SPWeb; // Enable Management of Content Types for Proposals Library SPList listProposalLibrary = site.Lists["Proposals"]; listProposalLibrary.ContentTypesEnabled = true; listProposalLibrary.Update();
FeatureDeactivating
method:SPWeb site = properties.Feature.Parent as SPWeb; if (site != null) { SPList list = site.Lists.TryGetList("Proposals"); if (list != null) { list.Delete(); } }
Done! That was easy!
Now, let us deploy the Solution and observe the results:
FeatureActivated
method just a few minutes ago in the How to do it... section.Actually, this is the first C# code you have written in this chapter! You have seen so far in this chapter that much can be accomplished through declarative (using XML) provisioning instructions.
Anything is possible as far as initialization and clean up goes with Feature Receivers. For example, you may have decided to pre-populate your list with sample data. You will find many examples in your future where you will want to take advantage of the powerful capabilities provided by Feature Receivers!
52.15.59.163