Some small improvements on the FileCatalogPart
Some time ago, I published a catalog web part that reads its content from a normal .ASCX file. One of the comments on this posting suggested a better use of generics in the code and I learned a bit more about how the web part creation in the WebPartManager control works, so I cleaned up the code and it got easier to understand along the way. For more explanation, check the original post. Here is the new and improved code:
public class FileCatalogPart : CatalogPart
{
public FileCatalogPart()
{
}
private string _templateLocation;
public string TemplateLocation
{
get
{
return _templateLocation;
}
set
{
_templateLocation = value;
}
}
Dictionary<WebPartDescription, WebPart> webparts = new Dictionary<WebPartDescription, WebPart>();
public override WebPartDescriptionCollection GetAvailableWebPartDescriptions()
{
webparts.Clear();
if (TemplateLocation != null)
{
Control container = Page.LoadControl(TemplateLocation);
if (container != null)
{
// You cannot directy iterate over the Controls collection, an excption
// is thrown that the collection was changed while iterating
ArrayList iterate = new ArrayList(container.Controls);
foreach (Control child in iterate)
{
WebPart wp = null;
if (child is WebPart)
{
wp = (WebPart)child;
}
else
{
if (!( child is LiteralControl))
{
wp = this.WebPartManager.CreateWebPart(child);
}
}
if (wp != null)
{
WebPartDescription desc = new WebPartDescription(wp);
webparts[desc] = wp;
}
}
}
}
return new WebPartDescriptionCollection(webparts.Keys);
}
public override WebPart GetWebPart(WebPartDescription description)
{
return (WebPart)webparts[description];
}
}