Question

The reason why item-updating event receiver fires twice in case of document libraries is because of check-in/checkout.

Also it can fire twice in case of doc library/list if we are updating the current item values with in this item updating event.

How can we handle both these cases via code?

Was it helpful?

Solution

For the scenario when you are the one triggering the second ItemUpdating by changing item values you can use the EventFiringEnabled parameter (you should use a try - catch -finally around it):

this.EventFiringEnabled = false;
// Do the changes
item.Update();
this.EventFiringEnabled = true;

The other scenario is tougher, and the reason behind why I use ItemUpdated instead when ever possible!

You could check the BeforeProperties, ListItem and AfterPropertiesin your ItemUpdating event receiver to check if there is updates being made that you have to take action on. If not, then just return.

Here is a guide for when you can use .BeforePropertiesand when you should go in the .ListItem instead

OTHER TIPS

public override void ItemUpdating(SPItemEventProperties properties)
{
  try
  {
    //is the item checked out?
    if (isCheckin(properties) == false)
    {
         this.EventFiringEnabled = false;

         //do your stuff

    }
  }
  catch(Exception a)
  {
    //catch any errors
  }
  finally
  {
    this.EventFiringEnabled = true; 
  }
} 

private bool isCheckin(SPItemEventProperties properties)
{
    if (properties.AfterProperties["vti_sourcecontrolcheckedoutby"] == null 
         && properties.BeforeProperties["vti_sourcecontrolcheckedoutby"] != null)
    {
        return true;
    }
    return false;
}

https://www.simple-talk.com/dotnet/.net-tools/managing-itemupdating-and-itemupdated-events-firing-twice-in-a-sharepoint-item-event-receiver/

@Robert about the before properties, yes your right they would be the same regardless.... only possible solution that i can think of would be using this instead

private bool isCheckin(SPItemEventProperties properties)
{
    string BeforeVal = properties.ListItem["vti_sourcecontrolcheckedoutby"];

    if (properties.AfterProperties["vti_sourcecontrolcheckedoutby"] == null 
         && BeforeVal != null)
    {
        return true;
    }
    return false;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with sharepoint.stackexchange
scroll top