Impersonation for SharePoint 2010 LINQ to DataContext

Impersonation in SharePoint is not really the hardest to do. However the C# code snippet below was sort of new for me. In order to obtain impersonation for a DataContext, that was something.

Impersonation for the ClientContext … but the LINQ DataContext is constructed in another way… and by default using the current user… regardless the user you’ve set in SPContext.

So… here it is.

 

strUrl = SPContext.Current.Web.Url;

HttpContext backupContext = HttpContext.Current;
try
{
  
SPUserToken userToken = null;
  userToken =
SPContext.Current.Web.AllUsers[“SHAREPOINT\\system”].UserToken;

  // if there is a SPContext make it is as null so LINQ won’t execute under current context
  
if (SPContext.Current != null)   HttpContext.Current = null;

  SPSecurity.RunWithElevatedPrivileges(delegate() {
    using (SPSite oSite = newSPSite(strUrl, userToken)) {
      using (SPWeb oWeb = oSite.OpenWeb()) {
                               // creating a new HttpContext under elevated permission and
             // setting it as current control context web,
             // because of this the code will be running under elevated permission.

        HttpRequest httpRequest = newHttpRequest(“”, oWeb.Url, “”);
        HttpContext.Current = newHttpContext(httpRequest, new HttpResponse(new System.IO.StringWriter()));
        
SPControl.SetContextWeb(HttpContext.Current, oWeb);

        using (SomeDataContext dc = SomeDataContext(oWeb.Url)) 
        
{
          var comments = from c in dc.SomeDataContext
                         where c.Var1 == someVariable 
                        
select c;
                    }
      }
    }
  });

}

catch (Exception ex) {}
finally {
   // make sure that you are setting the actual SPContext back
   //
after your operation and make SharePoint happy J

   if (SPContext.Current != nullHttpContext.Current = backupContext;
}

Advertisements

One thought on “Impersonation for SharePoint 2010 LINQ to DataContext

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s