So sometimes you need to pop in some code, lets say for example in a web part.. that needs to do something that the user running the webpart doesn't normally have permission to do. There are a couple of solutions possible all relating to various forms of impersonation.
WSS3 adds an extremely easy way (albeit, not necessarily the most secure way, but let's pretend that we trust our developers implicitly, and this DLL is going into the GAC).
SPSecurity.RunWithElevatedPrivileges(delegate codeToRun)
Ok super. But a big gotcha is that if you try and pull SPContext.Current.Web from within the delegate it will return an SPWeb object in the context of the current user, not one with elevated privileges (sort of makes sense if you think about it). Unfortunately in a webpart scenario the context object is pretty key, so here's one work around (I'm sure there are others--- let me know).
//Get data to recreate "context" later with privileges
SPWeb webUserContext = SPContext.Current.Web;
Guid webGuid = webUserContext.ID;
Guid siteGuid = webUserContext.Site.ID;
// run as system administrator
SPSecurity.RunWithElevatedPrivileges(delegate()
{
// get the site in this context
using (SPSite site = new SPSite(siteGuid))
{
// get the web in this context
SPWeb web = site.OpenWeb(webGuid);
// do you stuff here
}
});
So sometimes you need to pop in some code, lets say for example in a web part.. that needs to do something that the user running the webp...