Optionally Running SPSecurity.RunWithElevatedPrivileges with Delgates

Posted by Damon Armstrong on Simple Talk See other posts from Simple Talk or by Damon Armstrong
Published on Thu, 30 Aug 2012 02:05:21 +0000 Indexed on 2012/08/30 9:46 UTC
Read the original article Hit count: 173

Filed under:

I was writing some SharePoint code today where I needed to give people the option of running some code with elevated permission.  When you run code in an elevated fashion it normally looks like this:

SPSecurity.RunWithElevatedPrivileges(()=>
{
    //Code to run
});

It wasn’t a lot of code so I was initially inclined to do something horrible like this:

public void SomeMethod(bool runElevated)
{
    if(runElevated)
    {
        SPSecurity.RunWithElevatedPrivileges(()=>
        {
            //Code to run
        });
    }
    else
    {
        //Copy of code to run
    }
}

Easy enough, but I did not want to draw the ire of my coworkers for employing the CTRL+C CTRL+V design pattern.  Extracting the code into a whole new method would have been overkill because it was a pretty brief piece of code.  But then I thought, hey, wait, I’m basically just running a delegate, so why not define the delegate once and run it either in an elevated context or stand alone, which resulted in this version which I think is much cleaner because the code is only defined once and it didn’t require a bunch of extra lines of code to define a method:

public void SomeMethod(bool runElevated)
{
    var code = new SPSecurity.CodeToRunElevated(()=>
    {
        //Code to run
    });
    if(runElevated)
    {
        SPSecurity.RunWithElevatedPermissions(code);    
    }
    else
    {
        Code();
    }
}

© Simple Talk or respective owner

Related posts about Uncategorized