Search This Blog

Wednesday, April 20, 2016

Event Receivers - SharePoint 2013

An event receiver has a set of base classes that can contains one or more methods known as event handlers that are executed automatically by SharePoint in response to events such as adding or deleting item to a list/library. You can use event handlers for the different operations on different lists, document libraries and content types.


Types of Event Receivers:


  1. Synchronous - Events are executed before the action is executed on the content database.

         Events ending with -ing are named as Synchronous Event Receivers
         Ex. Item Deleting,Item Adding.
    2.  A Synchronous - Events are executed after the action is executed on the content database.

         Events ending with -ed are named as Synchronous Event Receivers
         Ex. Item Deleted,Item Added.

Different Base Classes in Event Receivers:

     There are totally 5 base classes in SharePoint 2010,
  1. SPItemEventReceiver - Event at List item Level.
  2. SPListEventReceiver - Event at List Level.
  3. SPFeatureEventReceiver - Event activation and Deactivation at list level.
    1. FeatureInstalled: Right after feature is installed.
    2. FeatureActivated: Right after feature activation through “Site Settings” or otherwise.
    3. FeatureDeactivated: Right after feature deactivation through “Site Settings” or otherwise.
    4. FeatureUninstalled: Before feature is uninstalled.
  4. SPEmailEventReceiver :Event to send mail to list
  5. SPWebEventReceiver : Event at Web Site Level.(Site added,site deleted,etc..)
Disabling and Enabling the event Receiver

If we are modifying/updating the same List item using event receiver,then the event receiver is triggered
 again and again.So you have to prevent it from firing before you update changes to the list item. 
We can implement this functionality using EnableEventFiring attribute to true/false.

Example:
   public override void ItemAdded(SPItemEventProperties properties)
    {
        //will disable the event receiver
        EventFiringEnabled = false;
        
        //do some action on list like update List.Update()
 
        //will enable the event receiver
        EventFiringEnabled = true;
    }

Best practice is to set Disable EventFiring method right before any update action and Enable EventFiring
 method right after updating action has been completed.


No comments:

Post a Comment