2014-02-06

EPiServer PageReference Extension: FindPagesOfType<T>(…)

Here’s my extension method for searching for pages of a given type T under an EPiSever (PageTypeBuilder) Page referred to by the PageReference which this method extends.

public static IEnumerable<T> FindPagesOfType<T>(
this PageReference pageLink, string languageBranch)
where T : TypedPageData
{
    //get page type id from type
    var pageTypeId = PageTypeResolver.Instance.GetPageTypeID(typeof(T));

    if (!pageTypeId.HasValue)
        return new List<T>(); //return empty enumerable

    // Create criteria collection
    var criterias = new PropertyCriteriaCollection
        {
            // Find pages of a specific page type                       
            new PropertyCriteria()
                {
                    Name = "PageTypeID",
                    Condition = CompareCondition.Equal,
                    Required = true,
                    Type = PropertyDataType.PageType,
                    Value =  pageTypeId.Value.ToString("0")
                }
        };

    var pages =
        DataFactory.Instance.FindPagesWithCriteria(
            pageLink,
            criterias,
            languageBranch,
            new LanguageSelector(languageBranch))
            .Cast<T>();

    return pages;
}

Example usage:

var myArticles =
PageReference.StartPage.FindPagesOfType<Article>(CurrentPage.LanguageBranch);

No comments:

Post a Comment