January 21, 2014

All CQWP web part appears as ErrorWebPart when fetching using object model in Console Application

In console application, while looping through all web parts in a page, if a page contains ContentByQueryWebpart, exception those web part will be rendered as ErrorWebParts
Because of the following code is called by the specific properties of the ContentByQueryWebpart
(actually its parent, the CmsDataFormWebpart):

   1:  internal static string MakeServerRelativeUrl(string url)
   2:  {
   3:      return concatenateUrls(SPContext.GetContext(HttpContext.Current).Site.ServerRelativeUrl, url);
   4:  }
The webpart will always call the SPContext, but from a console application there is no web-context. Therefore when initiating the
ContentByQueryWebpart, it will always thow an exception like:
"An error occured while setting the value of this property: Microsoft.SharePoint.Publishing.WebControls.ContentByQueryWebPart:MainXslLink - Exception has been thrown by the target of an invocation."
Workaround for this would be to provide it with a context.


   1:  if (HttpContext.Current == null)
   2:              {
   3:           isContextNull = true;
   4:                  HttpRequest request = new HttpRequest("", myweb.Url, "");
   5:                  HttpContext.Current = new HttpContext(request, new HttpResponse(new StringWriter()));
   6:                  HttpContext.Current.Items["HttpHandlerSPWeb"] = myweb;
   7:               }

If you have any questions you can reach out our SharePoint Consulting team here.

1 comment:

  1. Hi,

    I am facing the sma issue, but the above code is not resolving this issue. any help would be appreicated

    ReplyDelete