Sunday, July 27, 2014

How to disable event firing on list item events in SharePoint 2013

If you want to update the current item metadata or other item metadata in a list or library and also does NOT need to fire another event for the other item you've updated.

Solution 1:

  SPList list = web.Lists.TryGetList("Custom");
  SPListItem item = list.GetItemById(34);
  item["Title"] ="Updated Successfully";
  EventFiring eventFiring = newEventFiring();
  eventFiring.DisableHandleEventFiring();
  item.Update();
  eventFiring.EnableHandleEventFiring();

What I dislike about the solution, is the risk of leaving the events disabled. Assume an exception occurs, the code will never reach the line where the event firing is enabled (restored) again.

I would like to show you the best way to do it. I suggest a using-pattern, much like the TransactionScope class used for db transactions in the entity framework.

///
/// Disabled item events scope
///
class DisabledItemEventsScope : SPItemEventReceiver, IDisposable
{
   bool oldValue;
   public DisabledItemEventsScope()
   {
      this.oldValue = base.EventFiringEnabled;
      base.EventFiringEnabled = false;
   }
   public void Dispose()
   {
      base.EventFiringEnabled = oldValue;
   }
}
and in your event receiver method ItemAdded, ItemUpdated, or others.

public override void ItemUpdated(SPItemEventProperties properties)
{
   base.ItemUpdated(properties);
   SPListItem currItem = properties.ListItem;
   using (DisabledItemEventsScope scope = new DisabledItemEventsScope())
   {
      currItem["Column2"] = "updated Sucessfully";
      currItem.Update();
   }
}

No comments:

Post a Comment