Layer Architecture and DisableEventFiring

Some time ago, I had the problem that I wanted to stop an event from triggering cascadingly. That is usually not the biggest problem. The SPItemEventReceiver class contains a protected method for static void DisableEventFiring(); and static void EnableEventFiring(); that it inherits from Microsoft.SharePoint.SPEventReceiverBase. The first method prevents code from triggering further events and the second reactivates the default functionality.

Default functionality: Every Update(), Update(bool) (SystemUpdate(), SystemUpdate(bool)) method on SPWeb, SPList or SPListItem triggers all events that are registered with the according object (for ListItems this is the list they belong to (SPListItem.ParentList)).

If you have a layer architecture and you do not want to put all your code into the feature receiver methods, then you have a little problem that can be solved by created the following class:

public class DisableEventFiring: SPEventReceiverBase, IDisposable
{
  public DisableEventFiring()
  {
     DisableEventFiring();
  }
  public void Dispose()
  {
    EnableEventFiring();
    GC.SuppressFinalize(this);
  }
}

Now you can call from anywhere in your code:

void MyMethod(SPListItem itemWithTriggerEvents)
{
  using(new DisableEventFiring())
  {
    itemWithTriggerEvents.Update(); 
    // or itemWithTriggerEvents.SystemUpdate();
  }
}

Important to understand is also the disposal of the object. Using the “using”-block you can dispose the object directly and also you don’t need to worry about reactivating the event firing.

Happy SharePointing!

Advertisements

2 Responses to Layer Architecture and DisableEventFiring

  1. Pingback: Synchronous and Asynchronous Eventhandling « SharePoint 2007 Hut

  2. Pingback: The trouble with editing items on synchronous add-events « SharePoint 2007 Hut

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: