Saturday, August 1, 2009

Operation is not valid due to the current state of the object

I writed a post about this error (http://mosswat.blogspot.com/2009/02/operation-is-not-valid-due-to-current.html)

There is another cause to this error: using the "update" method in the "RunWithElevatePrivilege" scope, like this:

SPSecurity.RunWithElevatedPrivileges(delegate{
using (SPSite site = new SPSite("http://mySiteUrl"))
{
using (SPWeb web = site.OpenWeb())
{
SPListItem listItem = web.GetListItem("http://myItemUrl");
//do item modifications....
listItem.Update();
}
}

});

To resolve this issue, call the "update" method out of the "RunWithElevatedPrivileges" scope, like this;

SPSite site = null;
SPWeb web = null;
try
{
SPSecurity.RunWithElevatedPrivileges(delegate{
site = new SPSite("http://mySiteUrl");
web = site.OpenWeb();
});
SPListItem listItem = web.GetListItem("http://myItemUrl");
//do item modifications....
listItem.Update();
}
finally
{
if (site != null)
site.Dispose();
if (web != null)
web.Dispose();
}