Event Receivers in SharePoint 2010

Here we will discuss Event Receivers in SharePoint 2010. Also, we will discuss how to use WebProvisioned event in SharePoint 2010. We will also discuss on, synchronous and asynchronous event receivers in sharepoint 2013.

Event Receivers in SharePoint

An event receiver is a class that contains one or more methods known as event handlers that are executed automatically by SharePoint in response to events such as adding the item to a list.

Also, we will discuss how to attach an event receiver to the SharePoint list using the SharePoint server object model code.

You can use event handlers for data validation, data integrity, etc.

SharePoint categories events into two types

  1. Before events (synchronous events)
  2. After events (asynchronous events)

Before events or synchronous events in SharePoint

These events fire before an action occur and before SharePoint has written any data to the content database.

For example, the ItemAdding event will fire when trying to add an item to a list. These events do support canceling of an event action. These events always end with ‘ing’ like FieldAdding, ItemAdding, ItemUpdating, WebAdding, WebDeleting, etc. These events are also known as synchronous events.

After events or asynchronous events in SharePoint

These events fire after the event action has completed and after SharePoint Foundation has written to the content database to commit the event action. These events do not support canceling of an event action. These events do support canceling of an event action.

These events always end with ‘ed‘ like FieldAdded, ItemAdded, ItemUpdated, WebAdded, WebDeleted, etc. These events are also known as asynchronous events.

Events, Event Receivers & Object Model

Event receivers are nothing but custom classes which are derived from event receiver base classes that are defined by Microsoft in Microsoft.SharePoint assembly.

Some of the base classes are

  • SPItemEventReceiver: There are related to SharePoint items.
  • SPListEventReceiver: Related to lists.
  • SPWebEventReceiver: Related to webs.
  • SPWorkflowEventReceiver: Related to workflows instances. etc.

Remember all these classes(except SPEmailEventReceiver and SPFeatureReceiver) are derived from a common base class know as SPEventReceiverBase.

Here there are different event receivers in SharePoint:

  • Item-Level Event Receivers:

The base class for this type of event receivers are SPItemEventReceiver and are related to SPListItem instances.

Some events are: ItemAdded, ItemAdding, ItemCheckedIn, ItemCheckingIn, ItemCheckedOut, ItemCheckingOut, ItemDeleted, ItemDeleting etc.

SharePoint List-Level Event Receivers

The base class for this type of event receivers is SPListEventReceiver and events are related to lists. These events fire whenever any changes to the fields of an existing list as well as adding or deleting list instances.

Some events are: FieldAdded, FieldAdding, FieldDeleted, FieldDeleting, FieldUpdated, FieldUpdating, ListAdded, ListAdding, ListDeleted, ListDeleting etc.

SharePoint Web-level Event Receivers

These are events related to Site Collection deletion and website creation, deletion, moving, and provisioning. The base class for this type of event receiver is SPWebEventReceiver.

Some events are SiteDeleted, SiteDeleting, WebAdding, WebDeleted, WebDeleting, WebProvisioned, etc.

SharePoint Workflow Event Receivers

These event receivers are for running workflows and the base class for these type of event receivers is SPWorkflowEventReceiver.

Some events are WorkflowStarting, WorkflowStarted, WorkflowCompleted, etc.

SharePoint E-Mail Event Receivers

These event receivers are for e-mail–enabled list instances and the base class is SPEmailEventReceiver. For this type of event receivers, you have to override the EmailReceived method.

The e-mail event receivers support e-mail–enabled list instances and events fires when the list receives e-mail messages.

Base class for email event receiver is SPEmailEventReceiver and We need to override EmailReceived virtual method.

Class example:

Public class MyEmailEventReceiver:SPEmailEventReceiver
{
public override void EmailReceived(SPList list, SPEmailMessage emailMessage, String receiverData)
{

}
}

It takes 3 parameters: current list, email message in a variable type SPEmailMessage and one more string parameter to hold configuration parameter.

You can write your code logic inside the above method.

Different list items events in SharePoint 2010

Below are different synchronous list item events in SharePoint 2010/2013.

  • ItemAdding: Occurs when a new item is added to its containing object.
  • ItemAttachmentAdding: Occurs when a user adds an attachment to an item.
  • ItemAttachmentDeleting: Occurs when a user removes an attachment from an item.
  • ItemCheckingIn: Occurs as a file is being checked in.
  • ItemCheckingOut: Occurs before an item is checked out.
  • ItemDeleting: Occurs before an existing item is completely deleted.
  • ItemFileMoving: Occurs when a file is being moved.
  • ItemUncheckedOut: Occurs before an item is being unchecked out.
  • ItemUpdating: Occurs when an existing item is changed.
  • Below are some Asynchronous list item events in SharePoint 2010.
  • ItemAdded: Occurs after a new item has been added to its containing object.
  • ItemAttachmentAdded: Occurs after a user adds an attachment to an item.
  • ItemAttachmentDeleted: Occurs after a user removes an attachment from an item.
  • ItemCheckedIn: Occurs after an item is checked in.
  • ItemCheckedOut: Occurs after an item is checked out.
  • ItemDeleted: Occurs after an existing item is completely deleted.
  • ItemFileConverted: Occurs after a file has been converted.
  • ItemFileMoved: Occurs after a file is moved.
  • ItemUncheckingOut: Occurs after an item is unchecked out.
  • ItemUpdated: Occurs after an existing item is changed.

Attach event receiver to list in SharePoint 2010 using Server Object Model

Now, let us discuss how to attach an event receiver to a SharePoint 2010 list using SharePoint 2010 server object model code.

SharePoint event receivers are very important. By using event receivers you can respond to various SharePoint list or list item events.

You can handle events whenever users add an item to a list, or whenever a user deleting items from a list etc. There are two types of Event Receiver in SharePoint:

  • Synchronous Event Receiver
  • Asynchronous Event Receiver

Here we will discuss how to attach an event receiver to a SharePoint list by using the SharePoint 2010 server object model. Before reading this check out my other article on steps by steps to Create an event handler to prevent items from deleting an item from SharePoint list using Visual Studio 2010.

For SharePoint online, we can not use the server-side code, for that we can use remote event receiver. You can read: Steps to create a Remote event receiver using visual studio 2015 for SharePoint Online and deploy into Microsoft Azure

Here we need to retrieve the 4-part assembly name. Read an article on How to get the 4-part assembly name by using Visual Studio external tool? or you can also check How to get the 4 part assembly name of a custom web part in SharePoint 2010? We need this 4-part assembly name while attaching the event receiver to the list.

Below is the full code to attach an event receiver to a SharePoint list using the SharePoint 2010 server object model code.

try
{
SPWeb mySite = SPContext.Current.Web;
SPList myList = mySite.Lists["MyListName"];
string assemblyName= "4 part Assembly name";
string eventReceiverName = "Namespace.ClassOfEventHandler";
lst.EventReceivers.Add(SPEventReceiverType.ItemAdded, assemblyName, eventReceiverName);
//Here we have added the event receiver to the ItemAdded event, you can also attach event receivers to ItemUpdated or ItemDeleted event.
myList.Update()
}
catch (Exception ex)
{

}
finally
{

}

WebProvisioned event in SharePoint 2010

Now, let us see how to use the webprovisioned event in SharePoint 2010 using Visual Studio 2010.

First of all, let us understand what the event is. This is event comes with SharePoint 2010, that allows us to execute something when a subsite in the site collection gets created. Here we will see an example that will change the Theme of the subsite whenever the subsite will get created.

A point to remember is this event does not fire when the root web site of a new site collection is created in SharePoint 2010. This method can be configured to operate in either synchronous or asynchronous modes. And this can be set in Synchronization tag in the Elements.xml file.

To do this we have created an event receiver and we have to write code in the WebProvisioned event, that will respond to change the Theme of the newly created site.

First open Visual Studio 2010 -> File -> New Project -> Then from the New Project dialog box go to SharePoint 2010 and choose Event Receiver from the list of Templates. Give the name and location and click on ok.

In the next step give the local deployment URL and click on deploy as a farm solution and click on Ok.

Then the SharePoint Customization Wizard will come and here it is important to choose the event receiver settings. Here we will choose the event receiver type as Web Events and then we can choose the events which all we want. Here we only needed the A site was provisioned event. And then click on Finish.

Visual Studio automatically added Feature as Feature1, Package and our event receiver class as EventReceiver1.

First of all double click on the Feature and change the scope, Here I am changing the scope as Site.

Then lets give a look at the Elements the XML file. Initially Visual studio automatically place the below tag to the elements.xml file:

<?xml version=”1.0″ encoding=”utf-8″?>
<Elements xmlns=”http://schemas.microsoft.com/sharepoint/”>
<Receivers >
<Receiver>
<Name>EventReceiver1WebProvisioned</Name>
<Type>WebProvisioned</Type>
<Assembly>$SharePoint.Project.AssemblyFullName$</Assembly>
<Class>EventReceiverProject2.EventReceiver1.EventReceiver1</Class>
<SequenceNumber>10000</SequenceNumber>
</Receiver>
</Receivers>
</Elements>

My suggestion is do not modify the code. Here one thing to remember is that we can make the event receiver as synchronous or asynchronous.

By default it is ssynchronous. If you will make this to Synchronous then any UI changes you will do, it will affect immeditely after the site is created. So lets make the event to Synchronous by adding in Synchronization tag, So our Elements.xml file should look like below now.

And also another point is we need to define the scope here with the Scope attribute of Receivers tag. So the full code will look like below.

<?xml version=”1.0″ encoding=”utf-8″?>
<Elements xmlns=”http://schemas.microsoft.com/sharepoint/”>
<Receivers Scope=”Site”>
<Receiver>
<Name>EventReceiver1WebProvisioned</Name>
<Type>WebProvisioned</Type>
<Assembly>$SharePoint.Project.AssemblyFullName$</Assembly>
<Class>EventReceiverProject2.EventReceiver1.EventReceiver1</Class>
<SequenceNumber>10000</SequenceNumber>
<Synchronization>Synchronous</Synchronization>
</Receiver>
</Receivers>
</Elements>

Now lets discuss the EventReceiver1 class.

Visual studio automatically put the below code, with the override WebProvisioned method. The code is:

using System;
using System.Security.Permissions;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Security;
using Microsoft.SharePoint.Utilities;
using Microsoft.SharePoint.Workflow;

namespace EventReceiverProject2.EventReceiver1
{ ///

/// Web Events
///

public class EventReceiver1 : SPWebEventReceiver
{

/// A site was provisioned.

public override void WebProvisioned(SPWebEventProperties properties)
{
base.WebProvisioned(properties);
}
}
}

In the override method we will define the code that will change the theme. So the full code will be

using System;
using System.Security.Permissions;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Security;
using Microsoft.SharePoint.Utilities;
using Microsoft.SharePoint.Workflow;

namespace EventReceiverProject2.EventReceiver1
{

/// Web Events

public class EventReceiver1 : SPWebEventReceiver
{

/// A site was provisioned.

public override void WebProvisioned(SPWebEventProperties properties)
{
try
{
base.WebProvisioned(properties);
SPWeb web = properties.Web;
web.Navigation.UseShared = true;
string ThemeURL = “[Your Site URL]/_catalogs/theme/Mission.thmx”;
ThmxTheme.SetThemeUrlForWeb(web, ThemeURL);
web.Update();
}
catch (Exception ex)
{
throw;
}
}
}
}

Here you can check the theme url from the Theme gallery. That is it. Then build the solution and then deploy the solution. It will automatically attach the event receiver. Then try to create a site and see the site’s theme after that.

List of SharePoint 2010 Event Model

Now, we will discuss various SharePoint event model in SharePoint server 2010.

Following the List of SharePoint Event Model:

  • Before and After Events
  • Event Hosts
  • Event Receivers and Handling Events
  • Binding Event Handlers

Before and After Events

These events fire before an action occur and before SharePoint has written any data to the content database. For this reason, Before events are always synchronous.

You can identify Before events because their member names end with the “-ing” suffix – for example, ItemAdding, ListAdding.

After events, on the other hand, trigger event handlers that execute after user actions are committed to the content database and they invoke code that runs after the content database has been modified. This provides an opportunity to develop code that executes logic that occurs after a user has completed a specific action.

Because After events execute in a different process from the triggering action, they can execute either synchronously or asynchronously. You can identify After events because their member names end with the “-ed” suffix – for example, ItemDeleted, WebProvisioned.

Event Hosts

Event hosts are objects, such as site collections, Webs, lists and list items, that expect to receive events – or, in other words, objects whose event receivers “listen” for SharePoint Foundation events. These SharePoint Foundation 2010 event host object types include instances of common objects such as SPSite, SPWeb, SPList, and SPContentType.

Each of the event host types has specific event receiver base types from which you can inherit, to create an event receiver collection.

Event Receivers and Handling Events

SharePoint Foundation event handlers are a compiled module of custom managed code whose invocation is triggered by a specified event that you have specified. Event handler code is compiled into a .dll file and deployed to the GAC.

Binding Event Handlers

After your event handler code is compiled and deployed to the GAC, you need to bind it to a receiver object. Also known by the term “register,” binding is the process by which event handler code is associated with an object type.

Following Event types in SharePoint 2010

  • Site Events
  • Web Events
  • List Events
  • List Field Events
  • Item Events

Working with date column in list in SharePoint 2010 Event Receiver

Now, we will see how to work with the date column in the SharePoint 2010 list using the event receiver.

Suppose we want to set the Expiration date to Today + 30 days after an item has been created for a list suppose Announcements list, this we can achieve by using the SharePoint object model.

Below is the full code which you can add in an event receiver in SharePoint 2010.

using (SPSite site = new SPSite("http://SiteURL"))
{
using (SPWeb web = site.RootWeb)
{
SPList list = web.Lists.TryGetList("Announcements");
if (list != null)
{
SPField field = list.Fields[SPBuiltInFieldId.Expires];
field.DefaultFormula = "=TODAY()+30";
field.Update();
}
}
}

If you want to do this while item creating, then you can write an event receiver and attach the event receiver to the list.

You may like following SharePoint event receivers tutorials:

I hope this article helps to learn about event receivers in SharePoint 2010. We also discussed how to attach an event receiver in SharePoint using the server object model code.

Donwload Hub site pdf

Download SharePoint Online Tutorial PDF FREE!

Get update on Webinars, video tutorials, training courses etc.

>