April 9, 2012

Console application - accessing all webparts of a publishing page


Recently, we have been working on a sharepoint console app that finds invalid metadata terms assigned to web part properties. To get started we were trying to get all web parts on a publishing page.


There were several CQWP on page which were showing as error webparts when you get them using LimitedWebPartManager.


Since CQWP and other publishing site web parts uses HttpContext.Current, we have to create a fake object in order to get it working properly. Here is the code that was included before GetLimitedWebPart call:

   1:  if (HttpContext.Current == null)
   2:  {
   3:  HttpRequest request = new HttpRequest("", web.Url, "");
   4:  HttpContext.Current = new HttpContext(request,
   5:  new HttpResponse(new StringWriter()));
   6:  HttpContext.Current.Items["HttpHandlerSPWeb"] = web;
   7:  WindowsPrincipal wP = new WindowsPrincipal(System.Security.Principal.WindowsIdentity.GetCurrent());
   8:  HttpContext.Current.User = Thread.CurrentPrincipal = wP;
   9:  }​
If you have any questions you can reach out our SharePoint Consulting team here.

No comments:

Post a Comment