Friday, June 1, 2012

Access WebParts using HttpContext from Console Application

I Created Console Application to export WebParts from SharePoint but I faced problem with web parts used HttpContext like CQWP (With Console Application HttpContext.Current is null). I cannot read web part properties. After some investigation I found the solution create a dummy HttpContext with the following code:

  if (HttpContext.Current == null) {
      HttpRequest request = new HttpRequest("", web.Url, "");
      HttpContext.Current = new HttpContext(request, new HttpResponse(new StringWriter()));
      HttpContext.Current.Items["HttpHandlerSPWeb"] = web;

Don't forget to set HttpContext.Current to null after finishing.
Now I can access web parts from console application.

No comments: