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 :)..

Advertisements

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 )

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s