Learn more about SQL Server tools

 

Tutorials          DBA          Dev          BI          Career          Categories          Videos          Whitepapers          Today's Tip          Join

Tutorials      DBA      Dev      BI      Categories      Events

DBA    Dev    BI    Categories

 

Elevated Code for SharePoint - RunWithElevatedPrivileges


By:   |   Read Comments   |   Related Tips: > Sharepoint

Problem

When developing for SharePoint you may find your code does not execute due to the users permission levels.

Solution

This is a common problem when developing in SharePoint. Your code works perfectly during development as your mostly likely developing as the local admin on your "Development" SharePoint server, right? However, when you try running your code as a normal SharePoint user it doesn't run correctly and throws a permissions error.

The solution is to make sure you elevate your code ( SPSecurity.RunWithElevatedPrivileges(..delegate here..) ) correctly where needed. You may be doing this already but still getting the error as there is a gotcha, your objects need to be instantiated inside the delegate.

This works:

Guid webGuid = web.ID; 
Guid siteGuid = web.Site.ID; 
string fileURL = item.File.Url;

SPSecurity.RunWithElevatedPrivileges(delegate() 
{ 
  using (SPSite site = new SPSite(siteGuid))
  { 
     using (SPWeb ElevWeb = site.OpenWeb(webGuid)) 
     { 
        SPFile ElevFile = ElevWeb.GetFile(fileURL); 
        // do something with ElevFile 
     } 
  } 
  
}); 

This fails, because the SPFile object is instantiated outside of the delegate:

Guid webGuid = web.ID; 
Guid siteGuid = web.Site.ID; 
SPFile ElevFile = item.File; 

SPSecurity.RunWithElevatedPrivileges(delegate() 
{ 
  using (SPSite site = new SPSite(siteGuid))
  { 
     using (SPWeb ElevWeb = site.OpenWeb(webGuid)) 
     { 
        // do something with ElevFile - breaks
     } 
  } 
  
}); 

There are 2 big things to know about this:

  • It runs using the App Pool account, so you must ensure that the App Pool account is a member of a site collection group with sufficient perms to to add/edit/delete or whatever your code is trying to do. If not, the code will quietly break without popping an exception
  • All objects used within the delegate must be instantiated within the delegate, otherwise the elevation will fail. You can safely call scalars instantiated outside of the delegate, but not object variables like site or web.
Next Steps


Last Update:






About the author


 









Post a comment or let the author know this tip helped.

All comments are reviewed, so stay on subject or we may delete your comment. Note: your email address is not published. Required fields are marked with an asterisk (*).

*Name    *Email    Notify for updates 


Get free SQL tips:

*Enter Code refresh code     



Learn more about SQL Server tools