Welcome to Comunidade Bloggers |create|it| Sign in | Join | Help

André Vala

SharePoint
Office
FAST Search Server
.Net

News

  • European SharePoint Community Awards 2012 Winner
    Locations of visitors to this page

    Comunidade Portuguesa de SharePoint

    View André Vala's profile on LinkedIn

    © André Vala and Create IT, 2006-2011. Unauthorized use and/or duplication of this material without express and written permission from this blog’s author and/or owner is strictly prohibited. Excerpts and links may be used, provided that full and clear credit is given to André Vala and Create IT with appropriate and specific direction to the original content.

SharePoint Tip #10: Using RunWithElevatedPrivileges()

When developing SharePoint (MOSS or WSS) componentes, you might have to write code that some users won't have permissions to execute. For instance, if an event handler associated with a list needs to access an item of another list, and the user that caused the event to be fired has no permissions to access it, SharePoint will throw an access denied exception. 

The solution to this kind of problems is the RunWithElevatedPrivileges of the SPSecurity class (included in the assembly Microsoft.SharePoint.dll). This method allows the execution of code as the application pool identity account and, for that reason, should be used with caution. 

Example
SPSecurity.RunWithElevatedPrivileges(delegate()
{
    // begin code to be executed with app pool account
    SPSite site = new SPSite("http://server/site");
    SPWeb web = site.OpenWeb();

    SPList
lista = web.Lists["ListaAdmin"];

    web.Dispose();
    site.Dispose();
    // end of code to be executed with app pool account
}

Attention: I placed the creation of the SPSite object inside the elevated privilege zone on purpose. The reason for this is that, if the SPSite object is created outside this zone (when the user still has its original permissions) all the actions that are executed on SPWeb or SPList objects obtained from that SPSite object, even if inside the privileged zone, will use the original permissions of the user. So, it is mandatory that the creation of SPSite objects (and similars) is placed inside the elevated privilege code block. 

Posted: Tuesday, January 16, 2007 2:01 PM by andrevala

Comments

No Comments

Anonymous comments are disabled