Question

So, on my ItemAdded receiver, I am looking to update a list item field. Now, if the user adding the item to the list, has sufficient permissions/privileges, this all runs smoothly. If not, the code will error on the properties.ListItem.Update(); line. Not ideal.

Where my understanding falls down, is that I am running this update within a SPSecurity.RunWithElevatedPrivleges block. Code below;

public override void ItemAdded(SPItemEventProperties properties)
    {
        try
        {
            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                properties.ListItem["Title"] = "Some Text"
                properties.ListItem.Update();
            });
        }
        catch (Exception ex)
        { }
    }

The error I'm currently getting is an "unauthorised access" error. The process seems to running under the credentials of the user rather than the System account (as I would expect of I were running with elevated privileges?)

Any suggestions would be much appreciated

Was it helpful?

Solution

As I stated in a very recent answer, any code running inside an elevated section must use new fresh SharePoint objects. This means you cannot use pre-created SPListItem or anything else generated from an SPSite not created under the elevated section.
Here, you use properties.ListItem that was created long before your elevation. This object is not considered elevated.

You thus have to recreate everything in the elevated section, something like:

public override void ItemAdded(SPItemEventProperties properties)
{
   try
   {
      string webUrl = properties.WebUrl;
      Guid listId = properties.ListId;
      int itemId = properties.ListItemId;
      SPSecurity.RunWithElevatedPrivileges(delegate()
      {
         using(SPSite elevatedSite = new SPSite(webUrl)
         {
            using(SPWeb elevatedWeb = elevatedSite.OpenWeb())
            {
               SPList elevatedList = elevatedWeb.Lists[listId];
               SPListItem elevatedItem = elevatedList.GetItemById(itemId);
               elevatedItem["Title"] = "Some Text"
               elevatedItem.SystemUpdate(); // SystemUpdate instead of Update to keep "Modified by" as is
            }
         }
      });
   }
   catch (Exception ex) { }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with sharepoint.stackexchange
scroll top