Check to see if a page exists for a specific language branch
Have you ever wanted to know if a specific EPiServer page exists for a specific language? I recently came across an implementation that looked something like this:
try
{
DataFactory.Instance.GetPage(myPageLink,
new LanguageSelector("en");
}
catch
{
//The specified language does not exist
}
Obviously this implementation has one major flaw: exceptions should never be used for logical branching. You should never replace if - else with try - catch.
Creating a valuable helper class
My alternative implementation looks like this:
/// <summary>
/// Used to retrieve pages of a specific language version
/// </summary>
public class PageLanguage
{
private bool _languageExists=false;
private PageData _requestedPageLanguage=null;
/// <summary>
/// Initializes the object and checks whether or not the
/// page exists within the specified language branch
/// </summary>
/// <param name="pageLink">
/// A valid PageReference object</param>
/// <param name="languageBranch">
/// The language branch to look for/retrieve</param>
public PageLanguage(PageReference pageLink,
string languageBranch)
{
PageDataCollection languages =
DataFactory.Instance.GetLanguageBranches(pageLink);
foreach (PageData p in languages)
{
if (p.LanguageBranch == languageBranch &&
!p.PendingPublish)
{
_languageExists = true;
_requestedPageLanguage = p;
}
}
}
/// <summary>
/// Gets a value indicating whether or not the specified
/// page exists for the specified language branch
/// </summary>
public bool LanguageExists
{
get { return _languageExists; }
}
/// <summary>
/// Gets the page in the specified language if available,
/// otherwise null is returned
/// </summary>
public PageData Page
{
get { return _requestedPageLanguage; }
}
}
Using the PageLanguage class
Now I can use my newly implemented PageLanguage class in this slick manner:
PageLanguage language = new PageLanguage(
CurrentPageLink,targetLanguage);
if (language.LanguageExists)
return language.Page;
else
return fallbackPage;
11 February 2008