Quantcast
Channel: Sharing The Point » C#
Viewing all articles
Browse latest Browse all 3

Disable Event Receivers During an Update

$
0
0

There comes a time in developing SharePoint solutions where you may find yourself asking:

This is not the time I want my event receiver to run
This is not the place where I can set EventFiringEnabled = false
This is not the way I want this call to SystemUpdate() to behave

You’ve probably developed an event receiver before that updated something, and you used EventFiringEnabled to keep the receiver from recursively calling itself (or its 2007 method equivalent). However, have you ever encountered a time where you were programmatically updating something in a Workflow, in PowerShell, etc… and you noticed that when calling SystemUpdate() your event receivers still fired, and this caused you an issue? The good news is that there is a way to get around this. It relies on utilizing EventFiringEnabled.

The summary of how EventFiringEnabled works is that it is a thread-specific setting that effects any items being updated. We just need to do 2 things:

  1. Create an event receiver that just has methods for disabling and enabling event firings (you don’t need to override a single method)
  2. Create some code where we instantiate a new instance of this event receiver, and execute your code in between calling your Disable and Enable methods on the event receiver instance

I like to take this a little further and create a delegate that I can pass into a utility function that allows me just to pass some code into a method, and I know that it gets executed without events firing. This is the same pattern that SPSecurity.RunWithElevatedPrivileges uses, and it’s helpful.

Here’s the code to help you make this happen:

Event Receiver Code

public class SPRunWithoutEventsFiringEventReceiver : SPItemEventReceiver
  {
    #region Methods
    public void DisableEvents()
    {
      this.EventFiringEnabled = false;
    }
 
    public void EnableEvents()
    {
      this.EventFiringEnabled = true;
    }
    #endregion
  }

Utility Method

public static class SPUtilities
  {
    public delegate void RunWithoutEventsFiringDelegate();
 
    public static void RunWithoutEventsFiring(RunWithoutEventsFiringDelegate code)
    {
      SPRunWithoutEventsFiringEventReceiver eventReceiver = new SPRunWithoutEventsFiringEventReceiver();
      try
      {
        eventReceiver.DisableEvents();
        code();
      }
      finally
      {
        eventReceiver.EnableEvents();
      }
    }
  }

Example Usage

SPUtilities.RunWithoutEventsFiring(delegate()
      {
        item["Title"] = "New Update";
        item.SystemUpdate(false);
      });

I hope that you found the article helpful, and that this comes in handy on one of your future projects!

Cheers,
Matt


Viewing all articles
Browse latest Browse all 3

Latest Images

Trending Articles





Latest Images