Monday 13 June 2016

SharePoint Event Receivers with Examples.

1. Introduction
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.
2. SharePoint Event Receiver types
There are basically two types of event receivers: Synchronous and Asynchronous event receivers.Synchronous event receivers are also known as ‘Before’ event receivers. They are used to perform some custom action before an event occurs. In this case, there is a flexibility of cancelling the event on some conditions so that the event that gets initiated will not occur.
Asynchronous event receivers are also known as ‘After’ event receivers. They are used to perform some custom action after an event occurs. These events are asynchronous because they need not happen immediately after the event is performed. They can happen sometime later also, unlike synchronous event receivers which occur immediately before an event occurs.
3. Classes of Event Receivers
There are fundamentally five classes for Event Receivers for SharePoint 2007.
Microsoft.SharePoint.SPEmailEventReceiver : This provides event handling whenever a  user sends an email to a list on which e-mail feature is enabled
Microsoft.SharePoint.SPFeatureReceiver :  This provides event handling whenever is feature is acted upon
Microsoft.SharePoint.SPItemEventReceiver : This provides event handling whenever any action is performed on a list item
Microsoft.SharePoint.SPListEventReceiver : This provides event handling whenever a list definition is modified like adding or deleting columns and modifying existing columns.
Microsoft.SharePoint.SPWebEventReceiver : This provides event handling whenever a site or a site collection is deleted or moved
Each of the classes has some virtual methods which are to be over-ridden to perform our custom action. Those methods are as follows.
3.1 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.
3.2 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.
3.3 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.
ItemCheckedOut – 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.
3.4 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.
3.5 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).
4. 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
4.1  Using Feature
In the feature, the elements.xml file should be as follows.
<Elements xmlns=”http://schemas.microsoft.com/sharepoint/“>
……………………
……………………
<Receivers ListTemplateId=”100”>
<Receiver>
<Name>VideoAddedEventReceiver</Name>
<Type>ItemAdded</Type>
<SequenceNumber>20000</SequenceNumber>
<Assembly>MyProject.MyModule.Events, Version=1.0.0.0, Culture=neutral, PublicKeyToken=0b231a5ff63cd9fa</Assembly>
<Class>MyProject.MyModule.Events.VideoAddedEventReceiver</Class>
<Data></Data>
<Filter></Filter>
</Receiver>
………………………………
……………………………..
</Receivers>
</Elements>
Any number of receivers can be bound through one feature.
Limitation: Site level events cannot be registered/bound through the feature because we cannot associate a ListTemplateId with a site.
4.2 Using  Content Type
In a content type, the elements.xml file should be as follows.
<Elements xmlns=”http://schemas.microsoft.com/sharepoint/“>
<ContentType ID=”id” Name=”name” Group=”GroupName” Description=”Description of content type” Version=”0″>
<FieldRefs>
<FieldRef ID=”FIELD ID” Name=”FIELD NAME” />
…………………………
…………………………
</FieldRefs>
<XmlDocuments>
<XmlDocument NamespaceURI=”http://schemas.microsoft.com/sharepoint/events“>
<spe:Receivers xmlns:spe=”http://schemas.microsoft.com/sharepoint/events“>
<Receiver>
<Name> VideoAddedEventReceiver </Name>
<Type> ItemAdded </Type>
<SequenceNumber>20000</SequenceNumber>
<Assembly> MyProject.MyModule.Events, Version=1.0.0.0, Culture=neutral, PublicKeyToken=0b231a5ff63cd9fa </Assembly>
<Class> MyProject.MyModule.Events.VideoAddedEventReceiver</Class>
<Data></Data>
<Filter></Filter>
</Receiver>
</spe:Receivers>
</XmlDocument>
</XmlDocuments>
</ContentType>
</Elements>
The same limitation of ‘using feature’ applies to content type also because a content type cannot be associated with a site.
Sequence Number determines when the event receiver should get executed in case if more than one event receivers are about to be executed. An event receiver with greater sequence number gets executed after its counterpart with lesser sequence number.
4.3 Using WSS object model
The below is a sample code how an event receiver is bound with a list.
public override void FeatureActivated(SPFeatureReceiverProperties properties)
{
SPWeb web = properties.Feature.Parent as SPWeb;
web.Lists[“Video Library”].EventReceivers.Add(
SPEventReceiverType.ItemAdded,
“MyProject.MyModule.Events, Version=1.0.0.0, Culture=neutral, PublicKeyToken=0b231a5ff63cd9fa”,
” MyProject.MyModule.Events.VideoAddedEventReceiver “);
}
In the above code, the custom class ‘VideoAddedEventReceiver’ of type ‘ItemAdded’ is bound with a list named ‘Video Library’.
5. Unbinding SharePoint Event Receiver
• Event receiver bound with the help of content type cannot be unbound.
• If the event receiver was bound with the help of a feature, deactivating the feature would unbind the event receiver from its associated object.
• If the event receiver was bound using WSS object model,
1. Move to the object (site collection or website or list) to which the event receiver is bound.
2. Retrieve the event receiver definition of the intended event receiver.
3. EventReceiverDefinitionObject.Delete().
4. Call the update of that object (site collection or website or list).


Example 1:
Step 1
Open Visual Studio 2013 and create an empty SharePoint Project.

Empty SharePoint Project

Step 2
Enter the site URL and select Deploy as a Farm solution and click Finish.

Enter site URL

Step 3
Open Solution Explorer and add a new item.

add new item

Step 4
Select event receiver and enter the title of the event receiver. Click the Add button.

Select event receiver

Step 5
Select List Item Events in the type of event receiver and select the custom list option from the event source. Then select "an item was added" in events and click Finish.

Select List Item Events

Step 6
The following screen will appear.

added in events

Step 7
Go to the Event receiver cs file and paste the following coding into it. Here I have an “EventReceiver” list with Title, DateTimeNow and Action Columns.
  1. public override void ItemAdded(SPItemEventProperties properties)  
  2. {  
  3.     base.ItemAdded(properties);  
  4.     using (SPWeb web = properties.OpenWeb())  
  5.     {  
  6.         try  
  7.         {  
  8.             SPListItem currentItem = properties.ListItem;  
  9.             currentItem["DateTimeNow"] = DateTime.Now.ToString();  
  10.             currentItem["Action"] = "Item Added";  
  11.             currentItem.Update();  
  12.         }  
  13.         catch (Exception ex)  
  14.         {  
  15.             throw ex;  
  16.         }  
  17.     }  
program code

Step 8

Since I am targeting to add the event receiver only to the “EventReceiver” list, the Elements.xml file requires the following change.

element
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <Elements xmlns="http://schemas.microsoft.com/sharepoint/">  
  3.   <!--<Receivers ListTemplateId="100">-->  
  4.     <Receivers ListUrl="Lists/EventReceiver">  
  5.       <Receiver>  
  6.         <Name>ListItemAddedItemAdded</Name>  
  7.         <Type>ItemAdded</Type>  
  8.         <Assembly>$SharePoint.Project.AssemblyFullName$</Assembly>  
  9.         <Class>EventReceiverItemAdded.ListItemAdded.ListItemAdded</Class>  
  10.         <SequenceNumber>10000</SequenceNumber>  
  11.       </Receiver>  
  12.   </Receivers>  
  13. </Elements>  
Step 9
Build and deploy the solution.

deploy

Step 10
In SharePoint Site click Site Actions => Site Settings => Galleries =>Solution and verify that your solution is now deployed to the site.
clip_image006
clip_image008


Step 11
Go to your custom list (EventReceiver) and add a new Item.

event receiver

Enter title

Here's the result:

results  


Example 2:

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 DocumentLog list to log the changes happening to the library. 

In the list I have three columns, TitleAction & 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 Departmentdocument 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="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.

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



===========
Thanks.

#Copied From.
http://beginnersbook.com/2013/02/event-receivers-in-sharepoint/
http://www.c-sharpcorner.com/UploadFile/5b1f04/create-a-custom-list-level-event-receiver-for-item-added-in/
http://onceinawhilescribble.blogspot.in/2013/05/creating-simple-event-receiver-in.html

1 comment:

  1. Great site for these post and i am seeing the most of contents have useful for my Carrier.Thanks to such a useful information.Any information are commands like to share him.
    Sharepoint Training in Chennai

    ReplyDelete