Tuesday, May 13, 2008

SPSecurity.RunWithElevatedPrivileges

In the code-behind of a SharePoint page layout, I needed to modify the quicklaunch (left-side) navigation and add a few folders to the document library if they didn't exist. I retrieved the current SPWeb like this:
SPWeb web = SPContext.Current.Site.OpenWeb();
Then I made the changes I needed to to web.Navigation.Quicklaunch, etc. This all worked fine because of my permissions within SharePoint, but when our test user would go to the site, the page would fail with a message about "The list does not exist.". At the end of the AccessDenied.aspx URL was a GUID. I looked up the guid in the AllLists table in the database and found out which list it was. This was a red herring. There wasn't really a problem getting to the list because I was already accessing the list to populate some information on the page. Anyway, I tried to use SPSecurity.RunWithElevatedPrivileges(..) to make it so the regular user that was being impersonated could make the same navigation changes I was making as a site admin. It didn't work, but thanks to this forum entry I found out what I had to do. Basically, I had to spin up a new instance of the SPWeb and make my changes in that context. Here's what the code looks like:
SPSecurity.RunWithElevatedPrivileges
(delegate()
{
SPWeb aWeb = (new SPSite(web.Url).AllWebs[web.ID]);
aWeb.AllowUnsafeUpdates = true;

BuildLeftSideNav(aWeb);
});
So, the long story short...this is how you make RunWithElevatedPrivileges work. Also, you don't have to use an anonymous method like I did; you can pass a method name to RunWithElevatedPrivileges as long as it returns void and takes no parameters.

0 comments: