Thursday, May 23, 2013

Synchronous and Asynchronous Event Handlers

In SharePoint 2010 it is possible to handle events that occur on list items. These types of events come in two types: Synchronous and Asynchronous Event.


  • Synchronous: happens 'before' the actual event, you have the HttpContext and you can show an error message in the browser and cancel the event

  • Asynchronous: happens 'after' the actual event, there's no HttpContext  and you cannot directly show an error message or cancel the event


By sub-classing Microsoft.SharePoint.SPItemEventReceiver you can override the desired "event" methods.

  • Synchronous: methods ending with '-ing' (ItemAdding, ItemUpdating, ...)

  • Asynchronous: methods ending with '-ed' (ItemAdded, ItemUpdated, ...)


If you implement an override method you might want to place your code between the following lines to avoid raising other events unwantedly (and possibly causing an infinite loop).

this.DisableEventFiring(); 
...
this.EnableEventFiring();


Each override method has a parameter of type Microsoft.SharePoint.SPItemEventProperties that contains the item and event properties available for use. There's a bug in the SPItemEventProperties.AfterProperties dictionary that appears empty for synchronous events but it isn't. You can iterate over the dictionary to read and write to this collection ! This means that you can modify some of the inputted metadata before the actual item is stored in the list.

The thing to remember here is that the dictionary uses the field internal name as key, so field 'Field' could have an internal name such as 'My_x0020_custom_x0020_field'.

0 comments:

Post a Comment