Pages

Search This Blog

Monday, March 7, 2011

Disable - Enable Event Firing programatically

Sometimes we may write code in which we update an item programatically and that item resides in a document library which has "Item Updated" event handler registered which will in turn fire an item update event and update your item. So in this case, you may not want the event to be fired if you are updating the code programatically.

Through event handler, its possible to disable/enable that particular event by writing .EventFiringEnabled = true/false. But that will not be helpful if you want to do the same in code which is not in context of event handlers. In order to achieve this, you can create a class inherited from SPItemEventReceiver and IDisposable Interface. The SPItemEventReceiver will handle the events that will occur in the same thread in which your code is running and IDisposable will help to dispose the current object to its original state even if an exception has occured in your code.
this

public class DisableEventFiring : SPItemEventReceiver, IDisposable{
  public DisableEventFiring()
  {
   base.EventFiringEnabled = false;
  }

  void IDisposable.Dispose()
  {
   base.EventFiringEnabled = true;
  }
}

In order to use this, you just need to instanciate the object by using:

using(DisableEventFiring threadScope = new DisableEventFiring())
{
  objDocItem["Your custom Field"] = "Your custom Value";

  //item updated but event handler not fired
  objDocItem.Update()
}

No comments:

Post a Comment