Search This Blog

Thursday, September 18, 2014

Event Receivers in SharePoint 2010

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

12.     Can SharePoint events cancelled and redirected to differ page?
Yes, SharePoint Synchronous events can be cancelled since it occurs before action on SharePoint object. So the event can be cancelled and redirects to different page.
Continue:  The event is allowed to continue.
CancelNoError: The event is cancelled but no error message is displayed.
CancelWithError: The event is cancelled and an error message is displayed.
CancelWithRedirectUrl Obsolete: The event is cancelled, but a URL is provided that redirects
the user to a custom error message page, or to any desired URL.
e.g.
public override void ItemAdding(SPItemEventProperties properties)
       {
           base.ItemAdding(properties);

           properties.Cancel = true;
           properties.Status = SPEventReceiverStatus.CancelWithRedirectUrl;
           properties.RedirectUrl = "/_layouts/DeletingEventReceiver/ErrorPage.aspx";
           this.EventFiringEnabled = false;
       }
13.     How to add an event receiver to the specific list programmatically/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’.


14.     Why can’t we use SPContext in even 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.

15.     Can event receiver deployed as sandbox solution?
Yes, Event receivers can be deployed as sandbox solution. But make sure that your custom code is not using RunWithElevatedPrevillege method. Sandbox solution only can access the site collection object and it cannot access other than site collection object, network resources, database

16.     What is event binding OR how to register events on SharePoint Object?
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

17.     What is event unbinding and how to unbind?
• 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).

18.     How to find event receiver is attached to an list/library?
Registered events can be fetched using server object model or PowerShell scripts

19.     What is best either event receiver or workflow?
Its based on requirement. If business need very simple operation to be done with any custom calculation then workflow is the best option. If business need some custom business logic OR some action on before event then event receivers is best choice.

20.     Can event receiver register using feature?
Yes

21.     Can more than one event receiver register on same list/library?
Yes, the event receiver sequence specifies the order in which an event receiver is executed in cases where an event triggers multiple event receivers. For example, if you have two ItemAdded event receivers bound to the same list (one from Assembly "1" and the other from Assembly "2"), the event receiver that is bound with a lower sequence number is executed first. A practical example is adding an event receiver to a system list that already has a system event receiver bound to it. In that case, you assign the new event receiver a higher sequence number.

22.     If more than one event receiver registered on single list/library then how it works?
The event receiver sequence specifies the order in which an event receiver is executed in cases where an event triggers multiple event receivers. For example, if you have two ItemAdded event receivers bound to the same list (one from Assembly "1" and the other from Assembly "2"), the event receiver that is bound with a lower sequence number is executed first. A practical example is adding an event receiver to a system list that already has a system event receiver bound to it. In that case, you assign the new event receiver a higher sequence number.

23.     Where event receiver is deployed?
Events can be deployed on both sandbox solution and farm solution. If we use sandbox solution then it will deployed on site collection solution gallery and required DLL will be  extracted on UCCache folder when needed. If event receiver deployed as farm solution then the DLL registered in GAC and solution will be available in farm solution gallery.

24.     How to add an event receiver to the specific 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.

25.     How to add an event receiver to the content type using feature.xml file?
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.

26.     What are the new event receivers added in SharePoint 2010?
Event Host Type
Existing Events
New Events
Events Base Class
SPSite
SPWeb
SiteDeleting
SiteDeleted
WebDeleting
WebDeleted
WebMoving
WebMoved
WebAdding
WebProvisioned

SPWebEventReceiver
SPSite
SPWeb

ListAdding
ListAdded
ListDeleting
ListDeleted
SPListEventReceiver

SPSite
SPWeb
SPList
SPContentType
FieldAdding
FieldAdded
FieldDeleting
FieldDeleted
FieldUpdating
FieldUpdated

SPListEventReceiver

SPSite
SPWeb
SPList


EmailReceived
SPEmailEventReceiver
SPSite
SPWeb
SPList
SPContentType

WorkflowStarting
WorkflowStarted
WorkflowCompleted
WorkflowPostponed
SPWorkflowEventReceiver
SPSite
SPWeb
SPList
SPContentType
ItemAdding
ItemAdded
ItemDeleting
ItemDeleted
ItemUpdating
ItemUpdated
ItemFileConverted
ItemFileMoving
ItemFileMoved
ItemCheckingIn
ItemCheckedIn
ItemCheckingOut
ItemCheckedOut
ItemAttachmentAdding
ItemAttachmentAdded
ItemAttachmentDeleting
ItemAttachmentDeleted

SPItemEventReceiver



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. 

To create an event receiver, you need to inherit from one of the event receiver base classes. SharePoint Provides five event receivers base classes. Those are

SPWebEventReceiver
SPListEventReceiver (lists)
SPListEventReceiver (fields)

SPItemEventReceiver
SPMailEventReceiver

SPWorkflowEventReceiver
                  Now will see the Event Receiver base classes and supported events..

Event Receivers Base Class
Available event host types
Supported Events
SPWebEventReceiver
·         SPSite
·         SPWeb
·         SiteDeleting
·         SiteDeleted
·         WebAdding
·         WebProvisioned
·         WebDeleting
·         WebDeleted
·         WebMoving
·         WebMoved
SPListEventReceiver (lists)
·         SPSite
·         SPWeb

·         ListAdding
·         ListAdded
·         ListDeleting
·         ListDeleted
SPListEventReceiver(fields)
·         SPSite
·         SPWeb
·         SPList
·         SPContentType
·         FieldAdding
·         FieldAdded
·         FieldDeleting
·         FieldDeleted
·         FieldUpdating
·         FieldUpdated
SPItemEventReceiver
·         SPSite
·         SPWeb
·         SPList
·         SPContentType
·         ItemAdding
·         ItemAdded
·         ItemDeleting
·         ItemDeleted
·         ItemUpdating
·         ItemUpdated
·         ItemFileConverted
·         ItemFileMoving
·         ItemFileMoved
·         ItemCheckingIn
·         ItemCheckedIn
·         ItemCheckingOut
·         ItemCheckedOut
·         ItemAttachmentAdding
·         ItemAttachmentAdded
·        ItemAttachmentDeleting
·         ItemAttachmentDeleted

SPMailEventReceiver
·         SPSite
·         SPWeb
·         SPList
·         EmailReceived

SPWorkflowEventReceiver
·         SPSite
·         SPWeb
·         SPList
·         SPContentType
·         WorkflowStarting
·         WorkflowStarted
·         WorkflowCompleted
·         WorkflowPostponed



How SharePoint Events Work?
A SharePoint event receiver is bound to a SharePoint object—the event host—and responds to a user action by triggering event receiver code. You compile your event receiver code into a managed assembly—that is, a .dll file that is deployed to the global assembly cache.
Where Can I Use Event Receivers?
If you want to add behaviors to the operations that happen in SharePoint, you can use event receivers to trigger your custom code whenever a certain operation takes place.
After you write your event receivers in your event receiver class, you must compile the receiver into a managed assembly and then place it in the global assembly cache (GAC). Finally, you must bind the event receivers to a suitable event host. Later in this article, we discuss event binding and the different methods with which you can bind events.
Before Events 

A Before event occurs before the currently requested operation happens. For example, the ItemAdding event is a before event that is raised before an item is added to a SharePoint list.
Looked at another way, Before events are raised when an action occurs before SharePoint writes to the content database. 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.
Event receiver code that is triggered by a Before event executes in the same thread as the code that is executing the user action that triggered it. For this reason, Before events are always synchronous. You can identify Before events because their member names end with the "-ing" suffix—ItemAddingListAdding, and so forth.

After Events 

An After event is raised after the currently requested operation happens. For example, the ItemAdded event is an After event that is raised after an item has been added to a SharePoint list.
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.
After events can execute either synchronously or asynchronously. If the After event is synchronous, it executes in the same thread in which the triggering action occurs. However, if the After event is asynchronous, it executes in a separate thread.
You can identify After events because their member names end with the "-ed" suffix—ItemDeletedWebProvisioned, and so forth.


Now this is time for Creating the Sample Event Receivers Programmatically. To do this follows the steps:-
Step 1: Start off with a new project and select the “SharePoint 2010” template. Select “Event Receiver” project type. I’ve given the Project name as “SampleEventRecivers”. Click OK.


Step 2 The SharePoint Customization Wizard will come up as shown below. It gives you two deployment options for your feature, one is Sandboxed and other is Farm deployment. I selected Farm deployment.


Click next to get to the “Event Receiver Settings” page.
Step 3: As seen below we’ve selected our “Type of event receiver” to be “List Item Events” and “Event Source” to be the “Custom List”.

From the list of events that can be handled, select “An item was added”. You can add more events later too.
Step 4: Click Finish and wait for Visual Studio to do the skeleton work for you. In VS 2008 you have to do most of the skeleton work yourself, but in VS 2010 it’s all setup for you. Once VS finishes processing, you will have a solution structure similar to the below image.
Step 5: The event receiver class will be called EventReciever1.

Now implement the functionality in the Itemadded. Here I am going to implementing the functionality whenever a new item is added into my custom list I need to Start Custom Workflow.
using System;
using System.Security.Permissions;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Security;
using Microsoft.SharePoint.Utilities;
using Microsoft.SharePoint.Workflow;

namespace SampleEventRecivers.EventReceiver1
{
    /// <summary>
    /// List Item Events
    /// </summary>
    public class EventReceiver1 : SPItemEventReceiver
    {
       /// <summary>
       /// An item was added.
       /// </summary>
       public override void ItemAdded(SPItemEventProperties properties)
       {
               SPListItem item = properties.ListItem;
               SPWeb web = properties.Web;
               //Disable Event Firing
               this.EventFiringEnabled = false;
               // Initiate workflow
               SPSecurity.RunWithElevatedPrivileges(delegate()
               {
                   using (SPSite site = new SPSite(item.Web.Url))
                   {
                       using (SPWeb webObj = site.OpenWeb())
                       {
                           webObj.AllowUnsafeUpdates = true;
                           SPList list = webObj.Lists[properties.List.ID];
                           SPListItem current = list.GetItemById(item.ID);
                           int wfCount = list.WorkflowAssociations.Count;
                           // Check for workflow associations                       
                           if (list.WorkflowAssociations.Count > 0)
                           {
                               for (int index = 0; index < wfCount; index++)
                               {
                                   // initiate the Custom WF Start
                                   if(list.WorkflowAssociations[index].Name.Equals("CustomWFStart",StringComparison.OrdinalIgnoreCase))
                                   {
                                      list.ParentWeb.Site.WorkflowManager.StartWorkflow(current, list.WorkflowAssociations[index], string.Empty);
                                   }
                               }
                           }
                       }
                   }
               });
               //Enable Event Firing
               this.EventFiringEnabled = true;
           }
    }
}

After implementing you are functionality Build you are Solution and Deploy the Solution.

No comments:

Post a Comment