Feature Receivers

Sometimes, you may want some custom code to run when an event is fired. In this post, I'll walk you through feature receivers. A feature receiver is code that is fired when 1 of 4 possible events occur. The events are FeatureActivated, FeatureDeactivating, FeatureInstalled, and FeatureUninstalled.

To create a feature receiver, you'll need to create a feature.xml file and a receiver class that inherits from Microsoft.SharePoint.SPFeatureReceiver (Add a reference to Microsoft.SharePoint.dll).

The feature.xml file is set up a little bit differently than a typical feature file. You'll need to add two attributes. ReceiverAssembly and ReceiverClass. ReceiverAssembly will be made up of a namespace, version, culture, and PublicKeyToken. ReceiverClass will be the namespace.class. The following image will show you what the feature.xml should look like.


Next, you'll want to create your feature receiver class. Add a new class item to your project and inherit from the SPFeatureReceiver class. You'll need to override the events that you're planning on using. In the following example, I'm overriding each method that is called when their corresponding event is fired.



For simplicity, I have each one calling the same AddAuditItem. This AddAuditItem method will add an item to the Audit list with information about the current feature. A reference to the SPFeatureReceiverProperties variable used by the caller is passed to this method as well as a string that indicates which event is being used.


Now we can deploy and test our feature receiver. Nothing special has to be done to deploy the feature portion. When you compile your code, place your assembly in the GAC and activate your feature.

I went ahead and activated and deactivated this feature and here are the results:

Labels: