Sharepoint Event Receiver Issue with AfterProperties when trying to update list item in code

The item can be updated from the SharePoint edit form, everything was working as expected. However when I tried to updated this item in a timer job, It mades my implementation went wrong. The real reason was the AfterProperties becomes Null when ItemUpdating event is called because of a code-update to list. The explanation below is from this blog: http://karthikshare.blogspot.com/2011/09/problems-with-afterproperties-in-list.html. After reading this blog, I was able to fix my issue. This blog contains the same information from Karthik’s blog.

AfterProperties will be NULL when ItemUpdating event is called because of a code-update to list:
This is something that is not documented, and lead me into a lot of trouble:

Consider this scenario:

My SharePoint list had a column named “Email”.

I wrote an “item-updating” event handler that will update a few other child lists with updated Email, when it was altered in the parent list..(to which the event handler was attached)
Here is the code:

string oldEmail = (properties.ListItem["Email"] == null) ? "" : properties.ListItem["Email"].ToString();
string newEmail = (properties.AfterProperties["Email"] == null) ? "" : properties.AfterProperties["Email"].ToString();

if(oldEmail != newEmail )
{
   //Update the other child lists with "newEmail"
}

I tested this code by editing the list item and updating the Email and the change was correctly propagated to  the other lists.

After a few days we noticed that a lot of items in those child lists, had empty email values.

Reason:

When the item in parent list is edited directly using the SharePoint interface, then both properties.ListItem[“Email”] and properties.AfterProperties[“Email”] has the expected values.

But, when the list is being updated by code, and the code does not update the “Email” (for example, the code just updates “First Name” in the list)  then properties.AfterProperties[“Email”] will be NULL in the event receiver code. AfterProperties will have the correct value, only when Email is also updated through code.

This was not the case when editing was done through SharePoint UI.( i.e If I edit that item and change only the “First Name”, then AfterProperties[“Email”] had the correct value..)

Because of this my event receiver had reset Email in all the child lists with empty values.

Resolution:

Unfortunately, the only resolution available was to check whether “AfterProperties[“Email”]” is NULL and in that case assume that the list item is updated through code somewhere else, and do nothing.

The example is not exactly what I was facing but the resolution is really suitable.

Leave a comment