Check to see if a page exists for a specific language branch

by: Ted Nyberg (Hallvarsson & Halvarsson)

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


Comments

  1. Nice sample! You could also use LanguageSelector.Fallback("en",true) and check if you got "en" back as a language.
  2. Thanks, Per! I figured there had to be an easier (and more efficient) way of checking if a specific language version exists! ;)
Post a comment    
User verification Image for user verification  
Ted Nyberg (Hallvarsson & Halvarsson)

About me

I work for the corporate communications consultancy Hallvarsson & Halvarsson in Stockholm, Sweden.

My main focus areas are architecture, design and implementation of online applications such as public web sites and intranets.

Live Messenger

Hallvarsson & Halvarsson logo
 MCPD, MCTS and MCP logos


Syndications


Archive


Tag cloud

EPiTrace logger