Just a quick post to demonstrate how you can disable events (item, list, web and workflow) for the currently running thread.
There are many reasons why you may want to do this, one of which could be for a unit test where you programmatically create a list item, execute tests against it and then as part of the clean up process, delete the list item. If you have an ItemDeleting event defined against the item that prohibits deletions, then you’ll end up with potentially lots of stray unit test files in your library or list. You can use SystemUpdate to perform changes against an item without events firing, but there’s no way out of the box to stop other events from firing, at least not without a little extra coding.
This solution is pretty simple and concise.
First, create a class that inherits from one of the event receiver classes (see SPEventReceiverBase Class.
public class EventFiringToggle : SPItemEventReceiver { public void DisableEvents() { this.EventFiringEnabled = false; } public void EnableEvents() { this.EventFiringEnabled = true; } } |
As you can see, the above class is for item events.
Two methods are defined in this class, one for disabling and one for enabling events against list items.
For 2007, change the class to:
public class EventFiringToggle : SPItemEventReceiver { public void DisableEvents() { this.DisableEventFiring(); } public void EnableEvents() { this.EnableEventFiring(); } } |
In keeping with our scenaria of wanting to delete an item that has an event setup to stop this, we can now write the following code:
EventFiringToggle toggle = new EventFiringToggle(); try { toggle.DisableEvents(); listItem.Delete(); } catch { //Handle exception and log it } finally { toggle.EnableEvents(); } |