29 czerwca 2011

SPLimitedWebPartManager and ErrorWebPart on and off relationship

ErrorWebPart in WebParts collection 


There are times when we would like to manipulate (add/remove) or iterate over (export/import) WebParts collection associated with the SharePoint page. The task in itself is quite easy, as SharePoint API provides SPLimitedWebPartManager class. However in the console application scenario, when accessing WebParts property, all or some webpart instances can be returned as ErrorWebPart's. This behaviour can be caused by several factors, the ones I was able to discover were:

  1. Invalid SafeControl entries in Web.config (missing Assemblies) 
  2. WebParts on the page referencing assemblies that are not deployed on the farm
First step in troubleshooting this kind of problem will be checking the EvetLog and looking for the following errors:

Error: Failure in loading assembly: [AssemblyNameHere], Version=1.1.0.0, 
Culture=neutral, PublicKeyToken=[PublicKeyTokenHere]

See source code below that could be triggering  error messages  entries in the EventLog.

using (SPSite site = new SPSite(...))
{
  using (SPWeb web = site.OpenWeb(...))
  {
     using (SPLimitedWebPartManager limitedWebPartManager = web.GetLimitedWebPartManager(pageUrl, PersonalizationScope.Shared))
     {
        foreach (WebPart webPart in limitedWebPartManager.WebParts)
        {
            Type webPartType = spWebPart.GetType();
        }
     }
  }

}

The easiest way to resolve the problem, will be adding missing assembly to the GAC. And, if required add SafeControl entry in Web.config to register it correctly.

Brak komentarzy:

Prześlij komentarz

Uwaga: tylko uczestnik tego bloga może przesyłać komentarze.