Monday, April 26, 2010

Attached Event Receiver only to a single list

Hi,

As we Event Receivers are very useful in SharePoint, but there is a hurdle associated with it. That is attaching an Event Receiver only to a single list.

Normally we attached the Event Receiver with the help of ListTemplateId, the syntax is:


< listtemplateid="104">
here 104 means the announcements list. You can view the other ListTemplateIds here.

For installing an Event Receiver only for a single list we can use the following approaches:

  1. Using Feature Activated method
  2. Through custom content type
  3. Defining a custom List Template

Here, we are following the first approach. The steps are described below:

1) In the Visual Studio, we first create a "Class Library" project. Inherit SPItemEventReceiver class by adding the reference to SharePoint.dll

2) Then define your custom logic for any events (ItemAdded, ItemUpdated etc) in the Event Receiver.

3) Sign the assembly, (sn -k)

4) Built the project and drag the dll to GAC.

5) Very important, we do not require any Feature.xml or elements.xml for this event receiver.

6) Add another "Class Library" project in the same solution. Inherit SPFeatureReceiver class by adding the reference to SharePoint.dll

7) Now, add the following code to add the Event Receiver (that already drag to GAC) , for a particular list.


public class ReceiverBinder: SPFeatureReceiver
{
public override void FeatureActivated(SPFeatureReceiverProperties properties)
{
using (SPWeb objCurrentWeb = properties.Feature.Parent as SPWeb)
{
SPList objTargetList = objCurrentWeb.Lists["Target List"];

string strEventReceiverAssembly = "GenerateFormHandler, Version=1.0.0.0, Culture=neutral, PublicKeyToken=e6d3b324481b2ea7";

string strEventReceiverClass = "GenerateFormHandler.GenerateForm";

objTargetList.EventReceivers.Add(SPEventReceiverType.ItemAdded,
strEventReceiverAssembly,
strEventReceiverClass);
}
}

8) Sign the assembly (sn -k)

9) Built the project and drag the dll to GAC.

10) IISReset

11) Now, create a Feature.xml file as following and place the under
12 Hive\Templates\Features\MyFeatureName\Feature.xml



< ?xml version="1.0" encoding="utf-8" ? >
< id = "{DE7FE855-8071-4722-A102-BE8B9CBFFFCA}" title="Sample Title Description=" scope="Web" hidden="FALSE" xmlns="http://schemas.microsoft.com/sharepoint/" receiverassembly="EventReceiverBinder, Version=1.0.0.0, Culture=neutral, PublicKeyToken=cd7f95539fcc1e97" receiverclass="EventReceiverBinder.ReceiverBinder">
< /Feature >



12) Very important, in the above feature,xml file, the last two elements, ReceiverAssembly and ReceiverClass calls the assembly from GAC, where we defined the FeatureActivated method.

13) Install and Activate the feature using stsadm command

14) Test the target list, to check the Event Receiver.

That's all, Thank you,
Soumyendra

No comments: