Custom Content Query webpart httpcontext issue

Hi,

While working with custom content query webparts, I have faced some unexpected errors while adding or modifying the webpart through code. After exploring some blogs I found that webpart modification required http context information to implement any modification. So before we fetch the page webpart manager, we must define the context information using the below 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;
}
var manager = web.GetLimitedWebPartManager("default.aspx", PersonalizationScope.Shared);
var contentQuery = new CustomContentQueryWebpart
{
Title = "My Webpart",
ChromeType = PartChromeType.None
};
manager.AddWebPart(contentQuery, "Left", 1);


Using the above convention you can avoid most of the unexpected errors related to content query webpart.

Happy SharePointing :)..

Comments

Popular posts from this blog

Hide Ribbon on SharePoint 2013 using CSS

Get Comment Count in SharePoint

Configure external site as content sources in sharepoint search