Problem:
When running SPListItem.Update commands inside SPSecurity.RunWithElevatedPrivileges block you get error: Operation is not valid due to the current state of the object.
Thoughts:
I will call this a workaround since I don’t know why it works and is this really how it should be done.
Workaround:
You must not call the SPListItem.Update inside the RunWithElevatedPrivileges block. Instead you should only instantiate the SPSite or SPWeb there and call Update afterwards, like this:
private static string CreateSiteLink(SPWeb newSite, int groupId, string text)
{
string retVal = "";
SPWeb elevatedRootWeb = null;
try
{
SPSecurity.RunWithElevatedPrivileges(delegate()
{
using (SPSite elevatedSite = new SPSite(newSite.Site.ID))
{
elevatedRootWeb = elevatedSite.RootWeb;
}
});
SPList userInformation = elevatedRootWeb.Lists["User Information List"];
if (userInformation != null)
{
try
{
elevatedRootWeb.AllowUnsafeUpdates = true;
SPListItem item = userInformation.GetItemById(groupId);
if (item["Notes"] != null)
{
item["Notes"] = string.Format(text, newSite.ServerRelativeUrl, newSite.Name);
item.Update();
}
elevatedRootWeb.AllowUnsafeUpdates = false;
}
catch (Exception e)
{
retVal = " Site link for group " + groupId + " couldn't be created. (" + e.Message + ")";
}
}
else
{
retVal = " Site link for group " + groupId + " couldn't be created. (User Information List not found)";
}
finally
{
elevatedRootWeb.Dispose();
}
return retVal;
}