Wednesday, June 25, 2014

SharePoint 2010: How to use RunWithElevatedPrivileges

I ran into a bit of a problem, when I needed to change the permissions on an item. Doesn't sound that bad, right? Well, it is, when you only work with an event receiver, which is started by any user. The solution sounded simple, but still took me a while: RunWithElevatedPrivileges.
There are a couple of issues you might come in contact with, so I will try to post a couple of those in this post.

Tips & possible issues:
1. Create everything from scratch!
In one of my first attempts I just used the existing SPWeb I already used. But nope. This will only work, if the user already got enough permissions for his / her actions, which of course means: It did not work. You will have to get your web, lists, items, everthing again if you want to manipulate them with elevated priviledges.

2. Dispose your web!
Yeah, I know: It should always be the case. But believe me, while coding I forgot it twice in my RWEP-code block. The problem with this is pretty simple. The web you were using still exists so it would still be possible to work with this web. Including elevated priviledges. Not that nice, so please just dispose your web.

3. Don't use it all the time!
Yes, you could do that, BUT! you shouldn't. As always use least priviledges need, and for most of the things my event receivers are doing, I don't need a lot of permissions. And so shouldn't you, because otherwise your software concept might have a few problems.

How does it work?
The shortest explanation is this one:
A delegate method that is to run with elevated rights. This method runs under the Application Pool identity, which has site collection administrator privileges on all site collections hosted by that application pool.

And here is the code that made it work:
        using (SPSite site = new SPSite(properties.Web.Url))
              using (SPWeb myWeb = site.OpenWeb())
                     // Add your code!


I only tried this on SharePoint 2010, so maybe it's a bit different on SharePoint 2013 or Office 365.

1 comment:

  1. Hey Danny, wenn du nen site oder Web Objekt mit using instanziert, dann ist kein dispose mehr notwendig, weil das Objekt am Ende des using zerstört wird. Grüsse, Stan