Extension method used to prevent SharePoint list item event receiver help

2.1k Views Asked by At

I came across this post with a great solution to the problem of preventing the event receiver on an SPListItem firing when performing the update from outside the event receiver. The code works 100% as described and I'm impressed with the solution, the problem is I don't fully understand it.

To keep things simple lets ignore the SystemUpdate methods, so we're dealing only with the SPListItem.Update overload and the private class declared in the code.

The bit I don't "get" is how the class rh is "linked" or "associated" with the SPListItem item. Reproducing the method to save clicking back...

public static void Update(this SPListItem item, bool doNotFireEvents)
{
    SPItemEventReceiverHandling rh = new SPItemEventReceiverHandling();
    if (doNotFireEvents)
    {
        try
        {
            rh.DisableEventFiring();
            item.Update();
        }
        finally
        {
            rh.EnableEventFiring();
        }
    }
    else
    {
        item.Update();
    }
}

I can see we instantiate an instance of SPItemEventReceiverHandling, rh, and if doNotFireEvents is true we call DisableEventFiring() on rh and then when finished we call EnableEventFiring() on rh. The link I can't see is between "rh" and "item". How does SharePoint "know" to use rh as the event receiver when doing the update?

I hope I've explained that clearly. If not let me know and I'll try clarify further.

2

There are 2 best solutions below

2
On

The code is disabling all Event Firing for Items which is why that Finally block is so important (it turns it back on regardless of update success).

Documentation: http://msdn.microsoft.com/en-us/library/microsoft.sharepoint.spitemeventreceiver_members(v=office.12).aspx

0
On

My guess is that this globally disables item event receiving. I can't see where the association is created either.

I wonder if the people who have created this work-around have tried this when items are being concurrently updated. If SharePoint is doing this on a per-request basis (global to the request but not the SharePoint instance) then it would probably be relatively safe.

These methods have been marked as an Obsolete API in the SharePoint 2010 documentation.

http://msdn.microsoft.com/en-us/library/microsoft.sharepoint.spitemeventreceiver_members.aspx