Friday, October 26, 2012

Disable event firing - Part 2 (outside an event)

In previous post I have shown how to disable/enable event firing in event receiver. But, sometimes, you want to disable event firing outside of an event. It is possible with this simple code:



private static void EventFiringEnabled(bool enabled)

{

    Assembly assembly = Assembly.Load("Microsoft.Sharepoint, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c");
  
    Type type = assembly.GetType("Microsoft.SharePoint.SPEventManager");

    PropertyInfo pi = type.GetProperty("EventFiringDisabled", System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.NonPublic);
  
    pi.SetValue(null, !enabled, null);
 
}  



In the next post, I'll show you how to detect all event receivers in your project.




4 comments:

  1. Another great reference. Quick question, since disabling the event receivers from within the event receiver is per thread is this also per thread?

    ReplyDelete
  2. An alternative for a reusable class is as follows:
    public class DisableEventScope : SPItemEventReceiver, IDisposable
    {
    bool previousState;
    public DisableEventScope()
    {
    previousState = base.EventFiringEnabled;
    base.EventFiringEnabled = false;
    }

    public void Dispose()
    {
    base.EventFiringEnabled = previousState;
    }
    }

    To use:

    using (DisableEventScope scope = new DisableEventScope())
    {
    //Actions to be performed without triggering event handlers
    }

    ReplyDelete