What are Event Receivers and How to Create Sample event Receivers and attach to List/ Doc Library ?

Leave a Comment
Hi Friends,

Thanks for visiting my blog.
In  this blog, i would like to Post about  Event recivers in SharePoint 2013

1. What is Event Receiver ?
2. Why we use an event reciever ?
3. Types of  Event  Recivers?
4. Creation of Sample event Receivers and attach to Doc Library?
5. Interview Question on Event Recivers in SharePoint 2013, 2010

What is Event Receiver in SharePoint ?
In SharePoint you can add event handlers to the different lists, document libraries and content types within a SharePoint site.
Event handlers are defined in custom .NET assemblies. You can define event handlers for the different operations on list items, like adding a list item, updating a list item or deleting a list item.
Event handlers need to be registered and can best be installed and registered through the SharePoint feature framework.

Purpose of Event receivers:
If you want to catch some action in SharePoint and want to do something on each action, then you can use event recivers. Event receivers are nothing but classes.
Sometimes they are called Before events and after events.

While developing any application we need to handle some events. For example, when a new item is added to a list, we may need to perform some action like say, notifying the person who created the list item, or modifying the dependent entries in some other location etc. Handling of such events is facilitated by event receivers. We have many SharePoint event receiver classes in order to handle variety of events.

Types of Event Receivers in SharePoint ?

There are synchronous and asynchronous events.
Events ending by –ing are synchronous events: ItemAdding, ItemUpdating, ItemDeleting. Event handlers defined for these events are executed before the operation is executed on the content database. Asynchronous events are the events that end by –ed: ItemAdded, ItemUpdated, ItemDeleted. Event handlers for these events are executed after the operation is occurs in the content database.
Base Classes
There are different base classes from which you can inherit when developing event handlers. The decision from which class you are going to inherit depends on what you want to achieve with your event handler:
  •  SPItemEventReceiver: inherit from this class if you want your event handler to be executed when a list item is added, updated or deleted.
  •  SPListEventReceiver: inherit from this class if you want your event handler to be executed when the structure of your list is modified or when a content type is added or removed from the list.
  •  SPFeatureEventReceiver: you can add event handlers to a feature events like activation and deactivation, installation and deinstallation.
  •  SPEmailEventReceiver: you can also develop an event handler for emails that are sent to a SharePoint list
  •     SPWebEventReceiver: you can also handle events that occur when a site is added to or removed from a site collection.

Site Level Events

Methods under the class SPWebEventReceiver handle site level events. A brief overview of those methods is as follows.
Site Deleted – This occurs after a site collection is deleted.
Site Deleting – This occurs before a site collection is being deleted.
Web Deleted – This occurs after a website has been deleted completely. This is an asynchronous after event.
Web Deleting – This occurs before a website is deleted. This is a synchronous before event.
Web Moved – This occurs after an existing website is moved. This is an asynchronous after event.
Web Moving – This occurs before a website is moved. This is a synchronous event.

List Level Events

Methods under the class SPListEventReceiver handle list level events. A brief overview of those methods is as follows.
Field Added – This occurs after a field link is added to a list.
Field Adding – This occurs when is field is being added to a content type.
Field Deleted – This occurs after a field is deleted from a list.
Field Deleting – This occurs when a field is being deleted from a list.
Field Updated – This occurs after a field is updated in a list.
Field Updating – This occurs when a field is being updated in a list.

Item Level Events

Methods under the class SPItemEventReceiver handle item level events. A brief overview of those methods is as follows.


ItemAdded – This occurs after a new item is added to a list. This is an asynchronous after event.
ItemAdding – This occurs before an item is added to a list. This is a synchronous before event.
ItemAttachmentAdded – This occurs after an attachment is added to a list. This is an asynchronous event.
ItemAttachmentAdding – This occurs while an attachment is being added to a list.
ItemAttachmentDeleted – This occurs after an attachment is removed from an item.
ItemAttachmentDeleting – This occurs while an attachment is being removed from an item.
ItemCheckedIn – This occurs after an item is checked in.
I
temCheckedOut – This occurs after an item is checked out.
ItemCheckingIn – This occurs while an item is being checked in.
ItemCheckingOut – This occurs while an item is being checked out.
ItemDeleted – This occurs after an item is deleted from its list.
ItemDeleting – This occurs while an item is being deleted from its list.
ItemFileConverted – This occurs when the type of file is being converted.
ItemFileMoved – This occurs after a file is moved.
ItemFileMoving – This occurs while a file is being moved.
ItemUncheckedOut – This occurs after un-checking an item in a list.
ItemUncheckingOut – This occurs while an item is being unchecked.
ItemUpdated – This occurs after an item is updated.
ItemUpdating – This occurs while an item is being updated.

Feature Events

Methods under the class SPFeatureReceiver handle events related to feature. A brief overview of those methods is as follows.
FeatureActivated – This occurs after a feature is activated.
FeatureDeactivating – This occurs when a feature is being deactivated.
FeatureInstalled – This occurs after a feature is installed.
FeatureUninstalling – This occurs when a feature is being uninstalled.

Email Events

Method under the class SPEmailEmailEventReceiver handles the event related to email. A brief overview of the method is as follows.
EmailReceived: This occurs after an email message has arrived (to an email enabled list).

 Binding the Event Receivers

For the event receivers to receive an event, they should be bound to the corresponding objects. This binding can be done in three ways.

Using a feature
Using a content type
Using WSS object model


Creating a simple Event Receiver in SharePoint 2013 using  WSS Object Model.
Create an empty SharePoint 2013 project in Visual Studio 2012. In the project, select add new item and select Event Receiver


Select the type of event receiver you need to add, and select the events you need to handle.




In this sample I'm trying to update a SharePoint list based on file changes happening to a separate SharePoint library.

 Basically, the list will act like a log. So we need to create the library and a list.

 Here, I have created the Department library to add and maintain documents and also created Document Log list to log the changes happening to the library. 

In the list I have three columns, Title, Action & DateAndTime in order to catalog the changes happening to the library.



[The created document library and list]

Back to the SharePoint project. Now go to the event receiver .cs file and you'll get a bunch of methods base on your selection during event receiver creation. Edit the code as below to implement the logic. Note that the ItemAdded method is used instead of the ItemAdding method.


public override void ItemAdded(SPItemEventProperties properties)
        {
            //base.ItemAdded(properties);
            using (SPWeb web = properties.OpenWeb())
            {
                try
                {
                    SPList list = web.Lists["DocumentLog"];
                    SPListItem newItem = list.Items.Add();
                    newItem["Title"] = properties.ListItem.Name;
                    newItem["DateAndTime"] = System.DateTime.Now;
                    newItem["Action"] = "Item Added";
                    newItem.Update();
                }
                catch (Exception ex)
                {
                    throw ex;
                }
            }
        }

public override void ItemUpdating(SPItemEventProperties properties)
        {
            //base.ItemUpdating(properties);
            using (SPWeb web = properties.OpenWeb())
            {
                try
                {
                    SPList list = web.Lists["DocumentLog"];
                    SPListItem newItem = list.Items.Add();
                    newItem["Title"] = properties.ListItem.Name;
                    newItem["DateAndTime"] = System.DateTime.Now;
                    newItem["Action"] = "Item Updated";
                    newItem.Update();
                }
                catch (Exception ex)
                {
                    throw ex;
                }
            }
        }

public override void ItemDeleting(SPItemEventProperties properties)
        {
            //base.ItemDeleting(properties);
            using (SPWeb web = properties.OpenWeb())
            {
                try
                {
                    SPList list = web.Lists["DocumentLog"];
                    SPListItem newItem = list.Items.Add();
                    newItem["Title"] = properties.ListItem.Name;
                    newItem["DateAndTime"] = System.DateTime.Now;
                    newItem["Action"] = "Item Deleted";
                    newItem.Update();
                }
                catch (Exception ex)
                {
                    throw ex;
                }
            }
        }


As I am targeting to add the event receiver only to the Department document library, the Elements.xml file requires a change.



 Note that I have commented out the setting which points to all document libraries, instead pointed to Department document library. The edited Elements.xml file is as below:


<?xml version="1.0" encoding="utf-8"?>
<Elements xmlns="http://schemas.microsoft.com/sharepoint/">
  <!--   <Receivers ListTemplateId="101"> -->
  <Receivers ListUrl="Lists/Department">

   <Receiver>

        <Name>DepartmentEventReceiverItemAdded</Name>
        <Type>ItemAdded</Type>
        <Assembly>$SharePoint.Project.AssemblyFullName$</Assembly>
        <Class>MySharePointProject.ListEventReceiver.DepartmentEventReceiver</Class>
        <SequenceNumber>10000</SequenceNumber>
      </Receiver>

      <Receiver>

        <Name>ListEventReceiverItemUpdating</Name>
        <Type>ItemUpdating</Type>
        <Assembly>$SharePoint.Project.AssemblyFullName$</Assembly>
        <Class>MySharePointProject.ListEventReceiver.DepartmentEventReceiver</Class>
        <SequenceNumber>10000</SequenceNumber>
      </Receiver>
      <Receiver>
        <Name>ListEventReceiverItemDeleting</Name>
        <Type>ItemDeleting</Type>
        <Assembly>$SharePoint.Project.AssemblyFullName$</Assembly>
        <Class>MySharePointProject.ListEventReceiver.DepartmentEventReceiver</Class>
        <SequenceNumber>10000</SequenceNumber>
      </Receiver>
</Receivers>
</Elements>

Compile and deploy the solution to your site. Now you may play around with the library and observe the changes happening to the list.... :)

I have added a document, uploaded, added, modified the 3 docs and then deleted one of the docs respectively.

 The below method start executes and logic excutes

 
And here's what I get in the DocumentLog list.



        1.What is event receiver?
An event receiver is a piece of managed code that responds to SharePoint events when specific triggering actions occur on a SharePoint object. Triggering actions include activities such as adding, updating, deleting, moving, checking in, and checking out.

2.         What Are Event Hosts?
Event hosts are common SharePoint objects that expect to receive events—in other words, objects whose event receivers "listen" for SharePoint events. These SharePoint event host object types include instances of common objects such as SharePoint site collections, sites, and lists. Each event host type has a specific set of event receiver base types from which it can inherit.

3.         What are the types of event receivers?
There are two types of event receivers available in SharePoint.
1. Syncronous Events: This event is executed in the same thread in which the triggering action is occurring. For example, when the user adds an item from the SharePoint user interface, the event is fully executed before returning to the user and showing that the item was added. These are before events that occurs before the currently requested operation happens.  This provides an opportunity for an event receiver to perform tasks before data is committed to a database. A good example of the use of Before events is performing data validation, because Before events fire prior to commitment of data. You can also use Before (or synchronous) events to cancel user actions—for example, if data validation fails.
(e.g. ItemAdding, ItemUpdating,ItemDeleting)

2. Asynchronous Events: This event occurs at a later time than the action that triggered it, and it executes on a thread that is different from the one in which the triggering action is running. These are after events. After events trigger event receivers that execute after user actions are committed to the content database; they invoke code that runs after the content database has been modified. This allows you to execute logic that occurs after a user has completed a specific action.
(e.g. ItemAdded, ItemUpdated,ItemDeleted)

4.         What is the base class for List events and List Item events?
The Base class for SharePoint events is   Microsoft.SharePoint.SPEventReceiverBase. The List and List Item events inherited based on the scope of event host as below.
   List Item: 
Microsoft.SharePoint.SPItemEventReceiver
  SharePoint List:  Microsoft.SharePoint.SPListEventReceiver

5.         How to cancel the actions using event receiver?
SharePoint before events(synchronous) can be cancelled since it get trigged before completing the operation. Any validation can be applied as well as the event can be cancelled using event properties.
E.g
public override void ItemAdding(SPItemEventProperties properties)
{
base.ItemAdding(properties);
if(condition=true)
{
properties.Cancel=True;
}
}
6.         What is the best practice to get the context of SPSite when using event receiver?
The event properties should be used to get the current SPContext. If we get the current context of the site in different object  like SPContext then your connection may get lose when your dispose the site context.  Use SPItemEventProperties.Site/SiteID properties to get the current context or use SPItemEventProperties.Context property.

7.         Best coding practice of event receiver?
a.       Enable / disable firing other event in the same SharePoint object to avoid unnecessary loops.
b.      Do not use SPcontext to get the site/web properties, instead user event properties to get site/web properties
c.       Dispose if any heavy object process in event receiver in final block
d.      Do not use RunWithElevatedPrevillege if event receiver planned to be deployed as sandbox solution
e.      Use UserToken to impersonate your current access.

8.         What is Enabling and Disabling event receiver?
SharePoint Event is nothing but triggering action occurs on a SharePoint object. The trigger may come from manual action (updating item manually) or automatic action (SPItem.Update). Both actions will fire the events. Sometimes it makes unnecessary events in the same list. These events many go infinitely and impact the server performance majorly. To avoid this unnecessary event firing, we can purposely enable/disable the other event firing on the same object. 
You can achieve this by executing the DisableEventFiring method on the list item. After the changes are saved you can activate the event handler again by executing the EnableEventFiring method on the list item.
Best practice is to execute the DisableEventFiring method right before any of the update methods and to execute the EnableEventFiring method right after one of the update methods.

9.         What is before property?
Get the string/value pairs in a hash table before the event occurred on the SharePoint item.

10.     What is after property?
Get the string/value pairs in a hash table after the event occurred on the SharePoint item.
11.     What is the difference between event receiver and workflow?
Workflows:
·         SharePoint Workflow consist a set of task(s) which can be triggered both manually and automatically.
·         SharePoint Workflows are created in SharePoint Designer, Microsoft Visio and of course through Visual Studio.
·         The workflow is triggered once an action is completed.
·         Workflow can be exported and imported
·         Workflow can be paused
·         Workflow can send mails without attachment
·         Does not required coding knowledge to work on SPD workflows
·         Multiple forms(initiation, task edit..) can be associated as part of workflow
Event Receivers:
·         SharePoint event receiver contains custom coding/logic which can be triggered automatically based on the event host type.
·         SharePoint event receivers can be created only in Visual Studio.
·         The events can be triggered before action or after action.
·         Events cannot be exported and imported
·         Events can be cancelled(synchronous) but cannot be paused
·         Even receivers  can send mails with attachment
·         Required coding knowledge
·         No custom forms associated as part of event actions





Related Post

0 comments:

Post a Comment