Optionally Running SPSecurity.RunWithElevatedPrivileges with Delgates

Comments 0

Share to social media

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();
    }
}

Load comments

About the author

Damon Armstrong

See Profile

Damon Armstrong is a consultant with SystemwarePS in Dallas, Texas. He is also a blogger and author of Pro ASP.NET 2.0 Website Programming and SharePoint 2013 Essentials for Developers. He specializes in the Microsoft stack with a focus on web technologies like MVC, ASP.NET, JavaScript, and SharePoint. When not staying up all night coding, he can be found watching a bunch of kids, studying Biblical topics, playing golf, or recovering from staying up all night coding.