Tuesday, December 22, 2009

The file has been modified by SHAREPOINT\system

Sometimes your project architecture includes multiple solutions like using Event Handlers , Timer Jobs , workflows ....
You need all these componets to update a certain ListItem so imagine the following case :

Inside your workflow you get a reference to your working list item using
SPListItem cItem = WorkflowProperties.List.GetItemByID(WorkflowProperties.ItemID);

Then you Made some modifications
cItem["My Field1"]="PlaPla";
cItem["My Field2"]="PlaPla";
cItem["My Field3"]="PlaPla";
.
.
.
then Another code in the Task

then you called
cItem.Update();

and this problem has been occured
The file has been modified by SHAREPOINT\system

Cause
After you get a reference to the SPListItem and before you call the Update() method another component modified the List Item so SharePoint tells you that you have an old version of the file and there may be a conflict exists.

Solution
Put your updates inside a while loop and catch this exception if it occured try making your updates again but getting the current version of the ListItem

Code Sample

SPListItem req = CurrentRequest;
bool tryAgain = false;
do
{
try
{
req["field1"] = "value1";
req["field2"] = "value2";
req.Update();
tryAgain = false;
}
catch (Exception ex)
{
WriteToLog(ex.StackTrace, ex.Message);
if (ex.Message.Contains("has been modified by SHAREPOINT"))
{
req = CurrentRequest;
System.Threading.Thread.Sleep(1000 * 5);
tryAgain = true;
}
}
} while (tryAgain == true);


While CurrentRequest is a private proberty to get a new ListItem at every call.

private SPListItem CurrentRequest
{
get
{
SPList list = _wfp.Web.Lists[_wfp.ListId];
SPListItem req = list.GetItemById(_wfp.ItemId);
return req;
}
}



Thanks

4 comments:

  1. Thank you. This bit of information helped me with scenario..In my scenario i was updating a document set which had shared properties with the documents within. When I updated the document set, and then when to update the items within i was getting the above error message. Shared properties with document sets automatically filter down to the files within and so i was trying to update an item which has been updated in the prior step.

    Before updating i used the following to get the current item.
    SPListItem updateItem = list.GetItemById(listItem.ID);

    then performed updateItem.SystemUpdate(false);

    ReplyDelete
    Replies
    1. Thank you Dave!!! Your solution saved me!!!

      Delete
  2. Thanks Dave. I think the code above solved the concurrency problem,In some cases may be many solutions updating your item in the same time like Workflow,Event Handlers ... etc.
    and this will causes the error above.

    ReplyDelete
  3. the while loop can be infinite loop if same item remained in lock due to some antivirus/auditing ? If item is locked for an hours... same loop will continue for an hour right

    ReplyDelete