All About SharePoint

Liedong(Ken) Zheng,SharePoint Leader at SIMPLOT

RunWithElevatedPrivileges tricks

Posted by ken zheng on July 14, 2009

SPSecurity exposes a method called “RunWithElevatedPrivileges” which gives you an option to elevate the privilege to the application pool identity under which your code is executing. Looks nice, eh?

But Wait a second!! You are not done yet. I wish it was that easy when it comes to impersonation. In order to get this method call to properly impersonate your application pool identity you need to do some more work. Basically, SPSite and SPWeb objects created outside do not have Full Control even when referenced inside the delegate (anonymous method), so you need to find out their GUID before impersonation is performed and re-create the context one more time. Finally,never forget to dispose your objects!

You basically need to create parentWeb again via creation of a new SPSite, SPWeb etc. within the RunWithElevatedPrivileges block.

//Don’t dispose the following two objects. Sharepoint will take care of their disposal when page is completely rendered.
SPWeb webInUserContext = SPContext.Current.Web;
SPSite SiteInUserContext = SPContext.Current.Site;

Guid webGuid = webInUserContext.ID;
Guid siteGuid = SiteInUserContext.ID;

SPSecurity.RunWithElevatedPrivileges(delegate()
{
// get the site in impersonated context
using (SPSite site = new SPSite(siteGuid))
{
// get the web in the impersonated context
SPWeb web = site.OpenWeb(webGuid);
web.AllowUnsafeUpdates = true;
// Do your work here

web.Dispose();
}
});
Here is some references:
http://daniellarson.spaces.live.com/blog/cns!D3543C5837291E93!2005.entry
http://daniellarson.spaces.live.com/blog/cns!D3543C5837291E93!927entry
http://www.davehunter.co.uk/Blog/Lists/Posts/Post.aspx?List=f0e16a1a%2D6fa9%2D4130%2Dbcab%2Dbaeb97ccc4ff&ID=43

About these ads

4 Responses to “RunWithElevatedPrivileges tricks”

  1. Thalash said

    Nice work mate !!

  2. darkin said

    Thanks, man!

  3. Kulo said

    you saved my day !! thanks man!!

  4. Best article to know all ways of using RuWithElevatedPrivileges. http://sharepointquicksolutions.blogspot.in/2012/11/all-ways-of-runwithelevatedprivileges.html

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s

 
Follow

Get every new post delivered to your Inbox.

Join 28 other followers

%d bloggers like this: