List Event Receivers in Sharepoint to handle various events occured on Sharepoint List 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 Event Receiver is nothing but a event receiver which will execute in response to an event happned for a Sharepoint List.

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

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

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 Event Receivers in Sharepoint.

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

 
using System; using System.Collections.Generic; using System.Text; using Microsoft.SharePoint; using System.IO; namespace ListEventReceiver { public class EventReceiver:SPListEventReceiver { public override void FieldAdded(SPListEventProperties properties) { LogEvent(properties, "ColumnAdded"); } public override void FieldAdding(SPListEventProperties properties) { LogEvent(properties, "ColumnAdding"); } public override void FieldDeleted(SPListEventProperties properties) { LogEvent(properties, "ColumnDeleted"); } public override void FieldDeleting(SPListEventProperties properties) { LogEvent(properties, "ColumnDeleting"); } public override void FieldUpdated(SPListEventProperties properties) { LogEvent(properties, "ColumnUpdated"); } public override void FieldUpdating(SPListEventProperties properties) { LogEvent(properties, "ColumnUpdateing"); } private void LogEvent(SPListEventProperties properties, string eventname) { StreamWriter sw = File.AppendText(@"C:\LogEvent.txt"); StringBuilder sb = new StringBuilder(); sb.AppendFormat("[{0}] {1} Event Occured:\n", DateTime.Now.ToString(), eventname); sb.AppendFormat("\tList : {0}", properties.ListTitle); sb.AppendFormat("\t{0} - Field {1}", properties.EventType.ToString(), properties.FieldName); sw.WriteLine(sb.ToString()); sw.Close(); } } }

To create List Event Receivers you need to inherits the SPListEventReceiver class as shown above.
Then we need to override various methods live FieldAdding FiledDeleting and so on which will execute whenever we are adding new field 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 Event Receiver to handle Events of List.
Now we need to deploy this List Event Receiver by using various methods. Here I am deploying using Features in Sharepoint.

To create feature for this List 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 ListEventReceiver( 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="4B8B9A57-4361-4f50-A378-8D394D58D7FB" Title="List Event Receiver" Description="This is List 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

// {4B8B9A57-4361-4f50-A378-8D394D58D7FB}
IMPLEMENT_OLECREATE(<<class>>, <<external_name>>,
0x27a581c9, 0xe8f6, 0x4046, 0xb4, 0xb7, 0xb0, 0x49, 0x73, 0x67, 0xa7, 0xe2);


Remove all items except 4B8B9A57-4361-4f50-A378-8D394D58D7FB 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\ListEventReceiver\bin\Debug\ListEventReceiver.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\ListEventReceiver\bin\Debug\ListEventReceiver.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 e82985d30ef74a7d.

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>ListEventReceiver</Name> <Type>FieldAdded</Type> <SequenceNumber>20001</SequenceNumber> <Assembly> ListEventReceiver, Version=1.0.0.0, culture=neutral, PublicKeyToken=e82985d30ef74a7d </Assembly> <Class>ListEventReceiver.EventReceiver</Class> <Data></Data> <Filter></Filter> </Receiver> <Receiver> <Name>ListEventReceiver</Name> <Type>FieldAdding</Type> <SequenceNumber>20001</SequenceNumber> <Assembly> ListEventReceiver, Version=1.0.0.0, culture=neutral, PublicKeyToken=e82985d30ef74a7d </Assembly> <Class>ListEventReceiver.EventReceiver</Class> <Data></Data> <Filter></Filter> </Receiver> <Receiver> <Name>ListEventReceiver</Name> <Type>FieldDeleted</Type> <SequenceNumber>20001</SequenceNumber> <Assembly> ListEventReceiver, Version=1.0.0.0, culture=neutral, PublicKeyToken=e82985d30ef74a7d </Assembly> <Class>ListEventReceiver.EventReceiver</Class> <Data></Data> <Filter></Filter> </Receiver> <Receiver> <Name>ListEventReceiver</Name> <Type>FieldDeleting</Type> <SequenceNumber>20001</SequenceNumber> <Assembly> ListEventReceiver, Version=1.0.0.0, culture=neutral, PublicKeyToken=e82985d30ef74a7d </Assembly> <Class>ListEventReceiver.EventReceiver</Class> <Data></Data> <Filter></Filter> </Receiver> <Receiver> <Name>ListEventReceiver</Name> <Type>FieldUpdated</Type> <SequenceNumber>20001</SequenceNumber> <Assembly> ListEventReceiver, Version=1.0.0.0, culture=neutral, PublicKeyToken=e82985d30ef74a7d </Assembly> <Class>ListEventReceiver.EventReceiver</Class> <Data></Data> <Filter></Filter> </Receiver> <Receiver> <Name>ListEventReceiver</Name> <Type>FieldUpdating</Type> <SequenceNumber>20001</SequenceNumber> <Assembly> ListEventReceiver, Version=1.0.0.0, culture=neutral, PublicKeyToken=e82985d30ef74a7d </Assembly> <Class>ListEventReceiver.EventReceiver</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 ListEventReceiver\feature.xml -force REM IISRESET %STSADM% -o activatefeature -filename ListEventReceiver\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 column(field) to the Tasks List, update the column(field) and try to delete one column(field).
Then open LogEvent.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 Event Receivers

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


Download source code here