Wednesday, June 5, 2013

All webpart appear as ErrorWebParts when using SPLimitedWebPartManager


Hi! recently I was given a task to update properties of multiple webparts(custom developed webparts created by extending existing SharePoint OTB webparts).
Now the trick was to fetch those webparts across pages multiple pages and update their properties and UI formatting instructions based on a configuration file which is provided at run time on feature activation.

Seems a simple enough task, where one needs to retreive page-url, fetch SPLimitedWebPart manager based on page-url.
Use SPLimitedWebPart Manager to iterate through collection of webparts which exist of specified page URL and update properties based on configuration input.

Like any other developer, I started of write code to implement this.
Half-way down the line when I began to query webparts collection using SPLimitedWebPart Manger,
I see all webparts returned are of type "ErrorWebParts".

Why? Because of the following code is called by the specific properties of the ContentByQueryWebpart

The webpart will always call the SPContext, there is no web-context. Therefore when initiating the
ContentByQueryWebpart

A workaround for this would be to provide it with a context. all what i do adding if condition before query on
webparts if HttpContetxt is null i'll add it.

[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;                    }
                   SPFile filePath = webToUpgrade.GetFile("[ path of your page ]");
                    SPLimitedWebPartManager webpartManager =                        filePath.GetLimitedWebPartManager(System.Web.UI.WebControls.WebParts.PersonalizationScope.Shared);
                    SPLimitedWebPartCollection webPartColl = webpartManager.WebParts;
                    foreach (var webpart in webPartColl)                    { // write your code                    }

No comments:

Post a Comment