2011-03-17

Getting BeforeProperties and AfterProperties in Event Receivers

You're here because you're trying to find away of comparing values of a record before or after saving it in an event receiver, and BeforeProperties and AfterProperties are giving you null, right? Well chances are you searched and found posts about saving the values to a cache, and a lot of other rubbish... I know I did.

Anyway the proper way of doing things is real simple, and I stumbled upon it using Powershell to check my event receivers.

SPEventReceiverDefinition has a Synchronization property.

An Asynchronous event passes the objects to another thread and you lose the BeforeProperties and AfterProperties.
A Synchronous event keeps the thread and you can access the BeforeProperties and AfterProperties.

In my case after specifying the event receiver as Synchronous I was able to compare existing values with values in properties.AfterProperties on an Receiver Type = ItemUpdating.

So to set a Receiver as Synchronous, just add Synchronous to your definition (elements.xml) or in code set the Synchronization property.

Eg:
<?xml version="1.0" encoding="utf-8"?>
<Elements xmlns="http://schemas.microsoft.com/sharepoint/">
<Receivers>
<Receiver>
...
...
<Synchronization>Synchronous</Synchronization>
</Receiver>
</Receivers>
</Elements>