Sunday 22 September 2013

Working with BeforeProperties and AfterProperties on SPItemEventReceiver

I always forget this and when I come to create a new SharePoint Event Receiver I wonder why the BeforeProperties or AfterProperties are sometimes not populated.

Consider an example, we need to handle the ItemUpdating event for a document library and prevent a user from changing a certain column.  The code might look like this:
public override void ItemUpdating(SPItemEventProperties properties)
{
 if (properties.BeforeProperties["Title"] != properties.AfterProperties["Title"])
    {
        properties.Cancel = true;
        properties.ErrorMessage = "This column cannot be changed";
    }
}
For a document library, this works just fine.  For documents, Before and After properties are guaranteed for post events, such as ItemUpdating and ItemUpdated, but Before properties are not available for post events on list items.

The Before/After properties works differently between LIST and DOCUMENT LIBRARY

SharePointList

Event
BeforeProperties
AfterProperties
ListItem
ItemAdding
Null
New  Value
Null
ItemAdded
Null
New Value
New Value
ItemUpdating
Null
Changed Value
Original Value
ItemUpdated
Null
Changed Value
Changed Value
ItemDeleting
Null
Null
Original Value
ItemDeleted
Null
Null
Null

 
SharePointDocument Library
Event
BeforeProperties
AfterProperties
ListItem
ItemAdding
Null
Null
Null
ItemAdded
Null
Null
New Value
ItemUpdating
Original Value
Changed Value
Original Value
ItemUpdated
Original Value
Changed Value
Changed Value
ItemDeleting
Null
Null
Original Value
ItemDeleted
Null
Null
Null

Properties.ListItem refers to the current list item values at this point in the event. 
Original Value refers to the value which is already existing in the content DB.
New Value refers to the value which is being added newly in add event.
Changed Value refers to the value which is being updated in Update event.
So, if we go back to our original problem listed above.  How can we prevent a user from changing a certain column for an item in a list event?  From the list table, you can see if we hook into the ItemUpdating event, we can compare the current item’s value (properties.ListItem) to the AfterProperties value.  The code would look like this:
// SPListItem item= properties.ListItem;
// String oldvalue=item[“Title”].ToString();
if (properties.ListItem["Title"] != properties.AfterProperties["Title"])
{
    properties.Cancel = true;
    properties.ErrorMessage = "This column cannot be changed";
}
Hope it Helps.. 


No comments:

Post a Comment