Simon Sebright
19.07.2012
0 Kommentar(e)
You have a Blog site from the OOTB template. You are building a WebPart or some other service on top and need to get the items within the site. How do you identify the Posts and Categories Lists in there robustly?
Multi-lingual Blues
If you are in a single-language scenario, then you have a certain luxury of using the names of the lists - "Posts" or "Categories" in English. However, this is not best practice, and certainly not an option if you are delivering projects in multi-lingual environments, as we are. The German names, for example, are "Beträge" and "Kategorien".
Enter the BaseTemplate
Fortunately, if you look at the properties of the lists, one thing stands out as being a pretty watertight way to identify the right lists - the BaseTemplate. Both are based on built-in base templates, allowing you to use the SharePoint API Enumerator in your code:
private static SPList GetCategoriesList(SPWeb blogWeb)
{
foreach (SPList list in blogWeb.Lists)
{
if (list.BaseTemplate == SPListTemplateType.Categories)
{
return list;
}
}
throw new Exception(String.Format("No Categories list found for blogweb {0}", blogWeb.Url));
}
Make it Generic
A similar function for your Blog Posts (using SPListTemplateType.Posts) can be refactored to produce a generic function:
private static SPList GetCategoriesList(SPWeb blogWeb)
{
return GetListWithBaseTemplate(blogWeb, SPListTemplateType.Categories);
}
private static SPList GetPostList(SPWeb blogWeb)
{
return GetListWithBaseTemplate(blogWeb, SPListTemplateType.Posts);
}
private static SPList GetListWithBaseTemplate(SPWeb blogWeb, SPListTemplateType baseTemplate)
{
foreach (SPList list in blogWeb.Lists)
{
if (list.BaseTemplate == baseTemplate)
{
return list;
}
}
throw new Exception(String.Format("No {0} list found for blogweb {1}", baseTemplate, blogWeb.Url));
}