List Item Event Receivers in Sharepoint to handle various events occurred on Sharepoint List Items Programmatically

In this article I am explaining about Event Receivers in Sharepoint and how to Create List Event Receivers in Sharepoint Programmatically.

Before going in depth into Event Receivers in Sharepoint, we need to know what is List? and what is Event Receivers ?
Basically sharepoint is built on a foundation of Lists. Virtually every piece of data contained with in the Sharepoint contained with in a list of some form or another.

One of the powerful feature available in sharepoint is ability to create event receivers for any List Type.
An Event Receiver is a piece of managed code that is launched in response to an event that take place with in sharepoint.
List Item Event Receiver is nothing but a event receiver which will execute in response to an event happned for a Sharepoint List Item.

In this article I am explaining about how to create List Item Event Receivers in Sharepoint.

Creating List Item Event Receivers involves creating code that respond to events on list Items was to create classes that implements an interface.
To create List Item Event Receivers in Sharepoint
Open visual studio File-> New->Project-> select Class Library for C#
And enter name for project as ListItemEventReceiver and Rename the class as ItemEventReceiver.

After Creating the project, you need to add the Sharepoint DLL for your project.
For this right click on solution Explorer and select Add Reference . Browse for Microsoft.Sharepoint.dll file and click ok.
With default installation of Sharepoint, you can find this dll file at below location.

C:\Program Files\Common Files\Microsoft Shared\web server extensions\12\ISAPI\Microsoft.SharePoint.dll

So, you successfully establish the environment to Create List Item Event Receivers in Sharepoint.

The code to create List Item Event Receivers in Sharepoint is shown below.

 
using System; using System.Collections.Generic; using System.Text; using Microsoft.SharePoint; using System.IO; namespace ListItemEventReceiver { public class ItemEventReceiver:SPItemEventReceiver { public override void ItemAdded(SPItemEventProperties properties) { writeTextToLog(string.Format("[{0}] Item Added : {1}", properties.ListItem.Title, DateTime.Now.ToString())); } public override void ItemAdding(SPItemEventProperties properties) { writeTextToLog(string.Format("[{0}] Item Adding : {1}", properties.ListItem.Title, DateTime.Now.ToString())); } public override void ItemDeleting(SPItemEventProperties properties) { writeTextToLog(string.Format("[{0}] Item Deleteing : {1}", properties.ListItem.Title, DateTime.Now.ToString())); } public override void ItemUpdated(SPItemEventProperties properties) { writeTextToLog(string.Format("[{0}] Item Updated : {1}", properties.ListItem.Title, DateTime.Now.ToString())); } public override void ItemUpdating(SPItemEventProperties properties) { writeTextToLog(string.Format("[{0}] Item Updateing : {1}", properties.ListItem.Title, DateTime.Now.ToString())); } private void writeTextToLog(string text) { StreamWriter logFile = File.AppendText(@"C:\itemlog.txt"); logFile.Write(text + "\n"); logFile.Close(); } } }

To create List Item Event Receivers you need to inherits the SPItemEventReceiver class as shown above.
Then we need to override various methods live ItemAdding ItemDeleting and so on which will execute whenever we are adding new Item to the List.
Here we are logging each and every event occured in a notepad file stored in a C drive.

In this way we create the List Item Event Receiver to handle Events of List.
Now we need to deploy this List Item Event Receiver by using various methods. Here I am deploying using Features in Sharepoint.

To create feature for this List Item Event Receiver, you need to add new folder to for this solution.

Right click on solution explorer and click Add and select Newfolder and name it as Template. And add new folder to this Templatefolder and name it as Features.

Add one more folder to this Features folder and name it as ListItemEventReceiver( same as your project name).

Now we need to add two XML files to this inner folder (for the EventHandlerExample folder just we created) and name as Feature.xml and Elements.xml.

The code for Feature.xml file look like below.

 
<?xml version="1.0" encoding="utf-8"?> <Feature Id="4C78EAEA-E050-4255-9248-E9D2939592AE" Title="New List Item Event Receiver" Description="This is List Item Event Receiver" Version="1.0.0.0" Scope="Web" xmlns="http://schemas.microsoft.com/sharepoint/"> <ElementManifests> <ElementManifest Location="Elements.xml"/> </ElementManifests> </Feature>

In the above code you have Feature tag to describe the feature. For feature Id, you need to generate new GUID. For this go to Visual studio Tools and select Create GUID, click on copy and exit. The copy item look like below

// {4C78EAEA-E050-4255-9248-E9D2939592AE}
IMPLEMENT_OLECREATE(<<class>>, <<external_name>>,
0x27a581c9, 0xe8f6, 0x4046, 0xb4, 0xb7, 0xb0, 0x49, 0x73, 0x67, 0xa7, 0xe2);


Remove all items except 4C78EAEA-E050-4255-9248-E9D2939592AE and paste this code in Feature.xml file for the Feature Id.
You can find Title attribute(title of the feature) and Description(description about your feature).
Scope attribute, which defines scope for your Feature. Here scope is Web, you can have scope as site also.
At the last of Feature.xml file you can find ElementManifests tag which defines location Elements.xml for the feature.

Before going to the Elements.xml, you need to generate public key token for this project.
For this Right click on solution Explorer and select properties.
In the properties window select Signing.
Select the “sign the assembly” check box, in the drop down list select new.
Give the name for your key file .

Now save all Items and Build project to generate dll file for your project.

Open visual studio command prompt and type


gacutil /i C:\Projects\ListItemEventReceiver\bin\Debug\ListItemEventReceiver.dll


Execute above line to add assembly to the GAC(Global Assembly Cache).

Now we need public token key for this Assembly. For this I executed following command in the command prompt.


sn -T C:\Projects\ListItemEventReceiver\bin\Debug\ListItemEventReceiver.dll


Then you can get the public key token value. Copy and paste this key at some place.

Here I got the public key token as 20e824cfaea3d6b2.

Now go to Elements.xml file. The code for this xml file look like below.


<?xml version="1.0" encoding="utf-8"?> <Elements xmlns="http://schemas.microsoft.com/sharepoint/"> <Receivers ListTemplateId="107"> <Receiver> <Name>ListItemEventReceiver</Name> <Type>ItemAdded</Type> <SequenceNumber>30000</SequenceNumber> <Assembly> ListItemEventReceiver, Version=1.0.0.0, culture=neutral, PublicKeyToken=20e824cfaea3d6b2 </Assembly> <Class>ListItemEventReceiver.ItemEventReceiver</Class> <Data></Data> <Filter></Filter> </Receiver> <Receiver> <Name>ListItemEventReceiver</Name> <Type>ItemAdding</Type> <SequenceNumber>30000</SequenceNumber> <Assembly> ListItemEventReceiver, Version=1.0.0.0, culture=neutral, PublicKeyToken=20e824cfaea3d6b2 </Assembly> <Class>ListItemEventReceiver.ItemEventReceiver</Class> <Data></Data> <Filter></Filter> </Receiver> <Receiver> <Name>ListItemEventReceiver</Name> <Type>ItemDeleted</Type> <SequenceNumber>30000</SequenceNumber> <Assembly> ListItemEventReceiver, Version=1.0.0.0, culture=neutral, PublicKeyToken=20e824cfaea3d6b2 </Assembly> <Class>ListItemEventReceiver.ItemEventReceiver</Class> <Data></Data> <Filter></Filter> </Receiver> <Receiver> <Name>ListItemEventReceiver</Name> <Type>ItemDeleting</Type> <SequenceNumber>30000</SequenceNumber> <Assembly> ListItemEventReceiver, Version=1.0.0.0, culture=neutral, PublicKeyToken=20e824cfaea3d6b2 </Assembly> <Class>ListItemEventReceiver.ItemEventReceiver</Class> <Data></Data> <Filter></Filter> </Receiver> <Receiver> <Name>ListItemEventReceiver</Name> <Type>ItemUpdated</Type> <SequenceNumber>30000</SequenceNumber> <Assembly> ListItemEventReceiver, Version=1.0.0.0, culture=neutral, PublicKeyToken=20e824cfaea3d6b2 </Assembly> <Class>ListItemEventReceiver.ItemEventReceiver</Class> <Data></Data> <Filter></Filter> </Receiver> <Receiver> <Name>ListItemEventReceiver</Name> <Type>ItemUpdating</Type> <SequenceNumber>30000</SequenceNumber> <Assembly> ListItemEventReceiver, Version=1.0.0.0, culture=neutral, PublicKeyToken=20e824cfaea3d6b2 </Assembly> <Class>ListItemEventReceiver.ItemEventReceiver</Class> <Data></Data> <Filter></Filter> </Receiver> </Receivers> </Elements>

In the above code, you have Receivers tag. For this you have ListTemplateId attribute. We have 107 for this. Sharepoint defines the id’s for all Lists. For Tasks List id value is 107.
For the Receiver tag, you have several tag like Name(Name of the event handler)
Type — It defines handler type
SequenceNumber – Sharepoint gave the SequenceNumber’s for all Features. After 20000 we can give any value for this.
For Assembly tag, you need to give namespace of the EventHandler, version and PublicKeyToken(just we created, for me it is c23b446df2567fdb).
For Class you have to give namespace.classname, here EventHandlerExample.CancelContactListItem.

So, you are successfully created the all required Feature elements. Then you need to install feature and activate it for particular web.

For this I created one batch file to install and activate this feature as a batch.

Open notepad, paste below code


@SET TEMPLATEDIR="c:\program files\common files\microsoft shared\web server extensions\ 12\Template" @SET STSADM="c:\program files\common files\microsoft shared\web server extensions\ 12\bin\stsadm" Echo Copying files to TEMPLATE directory xcopy /e /y TEMPLATE\* %TEMPLATEDIR% Echo Installing feature %STSADM% -o installfeature -filename ListItemEventReceiver\feature.xml -force REM IISRESET %STSADM% -o activatefeature -filename ListItemEventReceiver\feature.xml -URL http://home-pt72rbbzr0

Save it as install.bat.

In the above code, to activate the feature you need to give youe sharepoint web url, for me it is http://home-pt72rbbzr0.

Add this file to you project and Rebuild your project.

After successfully creating the feature, just open install.bat. Then the Feature is installed and activated for given URL.

After installing the feature, go to Tasks List and add Item to the Tasks List, update the Item and try to delete Item.
Then open itemlog.txt in C drive, where we are storing each event occured, then you will find information regarding all events which you performed jsut before as shown below.

Sharepoint List Item Event Receivers

In this way you can create List Item Event Receivers to handle various events for a sharepoint List Item.


Download source code here