Thursday, November 8, 2012

Create Feature Event Receiver and debug it.

Feature event receiver is a self-explanatory term; these events are related to features activities. There are different feature events such as FeatureActivating, FeatureActivated, FeatureDeactivating, featureDeactivated etc…

In this post I will show how to create feature event receivers and how to debug it in part2.

Here we will track feature receiver activated and deactivated activity in SharePoint custom list.

1. Create custom list called FeatureReceiverLog.
2. Launch visual studio as administrator.
3. Create empty SharePoint project and name it as FeatureReceiverLog and add new feature to it.
4. Right click on feature folder and add new feature and name it as FeatureReceiverLog. Now, right click on ‘Feature1’ and add feature event receiver. Uncomment featureActivated and FeatureDeactivating methods. The project structure should look like below fig.

image
5. Below is code which will track feature activation and deactivation in SharePoint list

public override void FeatureActivated(SPFeatureReceiverProperties properties)
{
Addmessage( ref properties, "Activated");
}
public override void FeatureDeactivating(SPFeatureReceiverProperties properties)
{
Addmessage(ref properties, "Deactivating");
}
private void Addmessage(ref SPFeatureReceiverProperties Properties,String Message)
{
using (SPWeb web = Properties.Feature.Parent as SPWeb)
{
SPList list = web.Lists["FeatureReceiverLog"];
SPListItem item = list.AddItem();
item["FeatureReceiverLog"] = string.Format("feature {0} has been {1}", Properties.Feature.Definition.DisplayName, Message);
item.Update();
item = null;
list = null;
}
}



6. You can see below message in list when you will activate and deactivate the feature.
image

Now its little tricky to debug events related to feature activation and deactivation, Debugging feature event receiver.

No comments:

Post a Comment