Reza on blogging [MVP]

THIS BLOG HAS MOVED TO: http://blogs.devhorizon.com/reza

Subscriptions

<July 2009>
SuMoTuWeThFrSa
2829301234
567891011
12131415161718
19202122232425
2627282930311
2345678

News



toronto.sharepoint.camp


Navigation

Post Categories

Other Bloggers

Personal Links

RunWithElevatedPrivileges tricks

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!

 

//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);
                   
                       // Do your work here  
                       

                     web.Dispose();
                    }

               });


posted on Thursday, July 12, 2007 3:39 PM by rezaa

# RunWithElevatedPrivileges : Attention au pi&amp;#233;ge de l'impersonnation @ Friday, August 17, 2007 9:49 AM

Un petit pi&#233;ge qui n'as l'air de rien mais qui peut vous bloquer bien des heures. Le principe de l'impersonnation

Anonymous

# Elevating Privileges in SharePoint @ Tuesday, January 06, 2009 9:56 AM

Here’s a good tip for elevating privileges in SharePoint. http://blogs.devhorizon.com/blogs/reza_on_blogging

Anonymous

Powered by Community Server, by Telligent Systems