Guide to EPiCode Extensions

Posted on September 30, 2010 by Frederik Vig in ASP.NET, EPiServer

Last updated: 21.11.2010

EPiCode Extensions is a library with over 75 extension methods that are really useful to us as EPiServer developers. The project has grown rapidly in short time, with new extension methods being added every week.

The goal of the library is to help out with the most used tasks during development of an EPiServer site and make them easy and fun to use and extend.

Note: this blog post is a work in progress and will be updated as the library progresses.

Encoding

ToWebString

This extension method will remove all HTML code except for what is specified as allowed under your sites UISafeHtmlTags (located in episerver.config under sitesettings).

Method signature
public static string ToWebString(this object obj){...}
Example

Example 1: This example uses Page Type Builder to first check if the property Heading as any value, if so return that, if not, return PageName and then ToWebString encode it to escape HTML code that isen’t specified in UISafeHtmlTags (typically everything except for: b,i,u,br)

[PageTypeProperty(Searchable = true, SortOrder = 10, Tab = typeof(Tabs.Information), Type = typeof(PropertyString))]
public virtual string Heading
{
    get { return (this.GetPropertyValue(page => page.Heading) ?? PageName).ToWebString(); }
}

Example 2: This time we use ToWebString() inside a Repeater, encoding the property Name’s value.

<asp:Repeater runat="server">
<ItemTemplate><h2><%# Eval("Name").ToWebString() %></h2></ItemTemplate>
</asp:Repeater>

ToHtmlEncoded

This method calls HttpUtility.HtmlEncode().

HTML encoding makes sure that text is displayed correctly in the browser and not interpreted by the browser as HTML. For example, if a text string contains a less than sign (<) or greater than sign (>), the browser would interpret these characters as the opening or closing bracket of an HTML tag. When the characters are HTML encoded, they are converted to the strings < and >, which causes the browser to display the less than sign and greater than sign correctly.

HttpUtility.HtmlEncode method

Method signature
public static string ToHtmlEncoded(this string text){...}
Example

Here I store the zip code that the user typed in, but HtmlEncode before to escape potential harmful code.

this._stateManager.StoreValue("zipcode", txtZipCode.Text.ToHtmlEncoded());

ToJavaScriptEncoded

This method uses EPiServer’s ClientScriptUtility.ToScriptSafeString().

Make a string safe to be embedded into a script block, by replacing any characters that would invalidate the script with script-safe characters.

EPiServer’s ClientScriptUtility.ToScriptSafeString method

Method signature
public static string ToUrlEncoded(this string text){...}
Example

ToUrlEncoded

This method calls HttpUtility.UrlPathEncode().

The UrlPathEncode() method converts each space character into the string “%20″, which represents a space in hexadecimal notation. Use the UrlPathEncode() method when you encode the path portion of a URL in order to guarantee a consistent decoded URL, regardless of which platform or browser performs the decoding.

HttpUtility.UrlPathEncode method

Method signature
public static string ToJavaScriptEncoded(this string text){...}
Example

Here I UrlPathEncode the CurrentPages external URL.

http://www.facebook.com/widgets/like.php?href=<%= CurrentPage.GetExternalUrl().ToUrlEncoded() %>

HTML markup

Extension methods that help us produce good, clean semantic HTML markup.

HtmlImage

Method signature
public static string HtmlImage(this PageData page, string imagePropertyName) {...}
public static string HtmlImage(this PageData page, string imagePropertyName, object attributes) {...}
public static string HtmlImage(this PageData page, string imagePropertyName, string altTextPropertyName) {...}
public static string HtmlImage(this PageData page, string imagePropertyName, string altTextPropertyName, object attributes) {...}
 
public static string HtmlImage(this PageData page, Func<PageData, string> imagePath) {...}
public static string HtmlImage(this PageData page, Func<PageData, string> imagePath, object attributes) {...}
public static string HtmlImage(this PageData page, Func<PageData, string> imagePath, string altText) {...}
public static string HtmlImage(this PageData page, Func<PageData, string> imagePath, string altText, object attributes) {...}
public static string HtmlImage(this PageData page, Func<PageData, string> imagePath, Func<PageData, string> altText) {...}
public static string HtmlImage(this PageData page, Func<PageData, string> imagePath, Func<PageData, string> altText, object attributes) {...}
 
public static string HtmlImage(this string imagePath){...}
public static string HtmlImage(this string imagePath, string altText){...}
public static string HtmlImage(this string imagePath, object attributes){...}
public static string HtmlImage(this string imagePath, string altText, object attributes){...}
Example

Example 1: Here we use Page Type Builder with the property type PropertyImageUrl.

<p><%= CurrentPage.FeaturedImage.HtmlImage() %></p>
Result: <p><img alt="" src="/Global/LogoTypes/logo.png" /></p>
 
<p><%= CurrentPage.FeaturedImage.HtmlImage("My featured image") %></p>
Result: <p><img alt="My featured image" src="/Global/LogoTypes/logo.png" /></p>
 
<p><%= CurrentPage.FeaturedImage.HtmlImage(new{@class = "featured"}) %></p>
Result: <p><img alt="" class="featured" src="/Global/LogoTypes/logo.png" /></p>

Example 2: Same as the previous example, only without using Page Type Builder.

<p><%= CurrentPage.HtmlImage("FeaturedImage") %></p>
Result: <p><img alt="" src="/Global/LogoTypes/logo.png" /></p>
 
<p><%= CurrentPage.HtmlImage(p => p.PropertyValue<string>("FeaturedImage"), "My featured image")%></p>
Result: <p><img alt="My featured image" src="/Global/LogoTypes/logo.png" /></p>
 
<p><%= CurrentPage.HtmlImage("FeaturedImage", new{@class = "featured"}) %></p>
Result: <p><img alt="" class="featured" src="/Global/LogoTypes/logo.png" /></p>

If the property has no value no img tag will render.

HtmlLink

Method signature
public static string HtmlLink(this PageData page){...}
public static string HtmlLink(this PageData page, string linkText){...}
public static string HtmlLink(this PageData page, Func<PageData, string> linkText){...}
public static string HtmlLink(this PageData page, object attributes){...}
public static string HtmlLink(this PageData page, string linkText, object attributes){...}
public static string HtmlLink(this PageData page, Func<PageData, string> linkText, object attributes){...}
Example

For examples see: Extending PageData with some cool Html Helpers.

StripHtml

Method signature
public static string StripHtml(this PageData page){...}
public static string StripHtml(this PageData page, int maxTextLength){...}
public static string StripHtml(this PageData page, string propertyName){...}
public static string StripHtml(this PageData page, string propertyName, int maxTextLength){...}
public static string StripHtml(this PageData page, Func<PageData, string> htmlText){...}
public static string StripHtml(this PageData page, Func<PageData, string> htmlText, int maxTextLength){...}
 
public static string StripHtml(this string htmlText, int? maxTextLength){...}
Example

In this example we remove all HTML markup and strip the text (if it’s to long) to a specified length.

<p><%= CurrentPage.MainIntro.StripHtml(255) %></p>
<p><%= CurrentPage.StripHtml("MainIntro", 255) %></p>
 
Result: <p>255 characters of text...</p>

This is usually used in lists.

FormatHtml

Method signature
public static string FormatHtml(this PageData page, string propertyName, string startTag, string endTag){...}
public static string FormatHtml(this PageData page, string propertyName,string format){...}
 
public static string FormatHtml(this string text, string startTag, string endTag){...}
Example
<%= CurrentPage.Author.FormatHtml("<p>", "</p>") %>
 
Result: <p>Frederik</p>

If the property has no value nothing will get rendered.

PageData and PageDataCollection

GetExternalUrl

Method signature
public static string GetExternalUrl(this PageData page){...}
 
public static string GetExternalUrl(this PageReference pageReference){...}
Example
<%= CurrentPage.GetExternalUrl() %>
 
Result: http://playground/en/Test/

GetDescendants

This method will return either all the descending pages or all the descending pages down to a certain level. Very useful when creating lists.

Method signature
public static IEnumerable<PageData> GetDescendants(this PageData rootPage){...}
public static IEnumerable<PageData> GetDescendants(this PageData rootPage, int levels){...}

HasChildren

Method signature
public static bool HasChildren(this PageData pageData){...}

GetChildren

This method returns the children of the page.

Method signature
public static PageDataCollection GetChildren(this PageData page){...}
 
public static PageDataCollection GetChildren(this PageReference pageReference){...}

GetPage

This method returns a PageData object

Method signature
public static PageData GetPage(this PageReference pageReference){...}

GetAncestorAtLevel

Gets the ancestor at a given level from a root page. If the page provided is at this level, it is returned.

This method is especially useful when finding the root page for a secondary navigation structure.

Method signature
public static PageData GetAncestorAtLevel(this PageData page, PageReference rootPage, int offset){...}

GetAncestors

Get all the ancestors of a page or get all the ancestors of a page up to a given root page.

Method signature
public static IEnumerable<PageData> GetAncestors(this PageData page){...}
public static IEnumerable<PageData> GetAncestors(this PageData page, PageReference rootPage){...}

GetParent

Gets the parent PageData object, returns null if no parent is found or if the page is in the recycle bin.

Method signature
public static PageData GetParent(this PageData page){...}

PropertyValueWithDefault

Returns the EPiServer property value. If null or empty returns default value.

Method signature
public static T PropertyValueWithDefault<T>(this PageData page, string propertyName, T defaultValue){...}
Example
<%= CurrentPage.PropertyValueWithDefault("MainBody", "Nothing to see..") %>

PropertyValue

Get EPiServer property value. You’ll be using this method a lot if you don’t have Page Type Builder.

Method signature
public static T PropertyValue<T>(this PageData page, string propertyName){...}
Example

Example 1: Here we simply get the value of the MainIntro property.

<%= CurrentPage.PropertyValue<string>("MainIntro") %>

Example 2: Here we get the value of the MyPage property (which is a Page property) and then we get the PageData object with the GetPage extension method.

<%= CurrentPage.PropertyValue<PageReference>("MyPage").GetPage()

ToPageDataCollection

Method signature
public static PageDataCollection ToPageDataCollection (this IEnumerable<PageData> pages){...}
 
public static PageDataCollection ToPageDataCollection(this LinkItemCollection linkItemCollection){...}
Example

Example 1: Here we convert the collection to a PageDataCollection so that we can use EPiServer’s filter methods.

CurrentPage.GetDescendants()
                .ToPageDataCollection()
                .FilterForVisitor();

Example 2: Here we convert a LinkItemCollection to a PageDataCollection which makes it easier to work with the objects in the collection.

CurrentPage.MyLinkItemCollection.ToPageDataCollection()
                                             .FilterCount(2);

GetProperty

Sometimes we need to work with the PropertyData object of a property.

Method signature
public static PropertyData GetProperty(this PageData page, string propertyNames){...}

IsEPiServerPage

Checks that this is a valid EPiServer page.

Method signature
public static bool IsEPiServerPage(this PageData page) {...}

IsSelected

Method signature
public static bool IsSelected(this PageData page, PageData currentPage){...}
Example

See The SelectedTemplate and duplicate code

IsPublished

Method signature

Checks that the page is published.

public static bool IsPublished(this PageData page){...}

IsValue

Very useful for checking if the property has any value (the one that ships with EPiServer only checks for CurrentPage, not for any PageData object).

Method signature
public static bool IsValue(this PageData page, string propertyName){...}
Example
if (ParentPage.IsValue("MegaMenuLinksInColumn"))
{
    this.Menu.GroupItemCount = (int)ParentPage["MegaMenuLinksInColumn"];
}

ToPresentationString

Method signature
public static string ToPresentationString(this PropertyXhtmlString propertyData, PageBase page){...}

Categories

GetActiveSubCategories

Method signature
public static CategoryCollection GetActiveSubCategories(this CategoryList allActiveCategoryIds, string parentCategoryName){...}
public static CategoryCollection GetActiveSubCategories(this CategoryList allActiveCategoryIds, int parentCategoryId){...}
public static CategoryCollection GetActiveSubCategories(this CategoryList allActiveCategoryIds, Category parentCategory){...}
Example

See Extending EPiServer Categories

Filters

FilterForVisitor

Method signature
public static PageDataCollection FilterForVisitor(this PageDataCollection pageDataCollection){...}
Example
CurrentPage.GetChildren().FilterForVisitor();

FilterAccess

Method signature
public static PageDataCollection FilterAccess(this PageDataCollection pageDataCollection, AccessLevel accessLevel){...}
Example
CurrentPage.GetChildren().FilterAccess(AccessLevel.Edit);

FilterCompareTo

Method signature
public static PageDataCollection FilterCompareTo(this PageDataCollection pageDataCollection, string propertyName, string propertyValue){...}
Example

Filters out all pages that don’t have Visible in menu set to true (checked).

CurrentPage.GetChildren().FilterCompareTo("PageVisibleInMenu", "true");

FilterCount

Method signature
public static PageDataCollection FilterCount(this PageDataCollection pageDataCollection, int count){...}
Example
CurrentPage.GetChildren().FilterCount(3);

FilterPropertySort

Method signature
public static PageDataCollection FilterPropertySort(this PageDataCollection pageDataCollection, string propertyName){...}
public static PageDataCollection FilterPropertySort(this PageDataCollection pageDataCollection, string propertyName, FilterSortDirection filterSortDirection){...}
Example
CurrentPage.GetChildren().FilterPropertySort("PageSortIndex");

FilterSkipCount

Method signature
public static PageDataCollection FilterSkipCount(this PageDataCollection pageDataCollection, int skipCount){...}
Example

Great for pagination.

CurrentPage.GetChildren().FilterSkipCount(5)
                                  .FilterCount(10);

FilterSort

Method signature
public static PageDataCollection FilterSort(this PageDataCollection pageDataCollection, FilterSortOrder sortOrder){...}
Example
CurrentPage.GetChildren().FilterSort(FilterSortOrder.Alphabetical);

Globalization

Translate

Method signature
public static string Translate(this object obj, string xpath) {...}

Working with Server Controls

RenderToString

Method signature
public static string RenderToString(this Control control){...}
Example

FindChildControls

Find all child controls matching a predicate.

Method signature
public static IEnumerable<T> FindChildControls<T>(this Control parentControl, Predicate<Control> predicate) where T : Control{...}
Example

Example 1: Here we find all the TextBox controls on the page.

Page.FindChildControls<TextBox>(c => c is TextBox);

Example 2: Here we find the a button on the page with the ID btnSubmit.

Page.FindChildControls<Button>(c => c.ID == "btnSubmit").First();

AddToHeader

Moves a control up to the head section if it exists.

Method signature
public static bool AddToHeader(this Control control){...}

AddToParent

oves a control up to the first element that exists with the FindControl method .

Method signature
public static bool AddToParent(this Control control, string path){...}

Working with Strings

IsNullOrEmpty

Method signature
public static bool IsNullOrEmpty(this string text){...}
Example

Do something if MainIntro is null or empty.

if (CurrentPage.MainIntro.IsNullOrEmpty()) {...}

IsNotNullOrEmpty

Method signature
public static bool IsNotNullOrEmpty(this string text){...}
Example

Do something if MainIntro is not null or empty.

if (CurrentPage.MainIntro.IsNotNullOrEmpty()) {...}

Get started

Head over to EPiCode and download the latest release. Reference EPiCode.Extensions in your project, and you’re all set! We also recommend registering the namespace in your web.config file for easy access.

<pages>
    <namespaces>
        <add namespace="EPiCode.Extensions"/>
    </namespaces>
</pages>

Happy coding!

Related Posts: