EPiServer Extension Methods

Posted on May 4, 2009 by Frederik Vig in Code Snippet, EPiServer

Here are some EPiServer extension methods I use in my projects (remember that you need to use .NET 3.5 or later).

Update

These, and more have been added to the EPiServer World Community project EPiCode.Extensions on EPiCode. Be sure to check it out!

IsValue

public static bool IsValue(this PageData page, string propertyName)
{
    var propertyData = page.Property[propertyName];
 
    return (propertyData != null && !propertyData.IsNull);
}

We can now use it on every PageData object.

// using MyNamespace;
if (eventPage.IsValue("Heading"))
{
    ltlEventHeading.Text = eventPage["Heading"].ToWebString();
}

IsPublished

public static bool IsPublished(this PageData page)
{
    return page.StopPublish > DateTime.Now && page.StartPublish < DateTime.Now;
}

Or better yet, taken from the EPiServer.dll:

public static bool IsPublished(this PageData page)
{
    return CheckPublishedStatus(page, PagePublishedStatus.Published);
}
 
private static bool CheckPublishedStatus(this PageData page, PagePublishedStatus status)
{
    if (status != PagePublishedStatus.Ignore)
    {
	if (page.PendingPublish)
	{
	    return false;
	}
	if (page.Status != VersionStatus.Published)
	{
	    return false;
	}
	if ((status >= PagePublishedStatus.PublishedIgnoreStopPublish) && (page.StartPublish > Context.Current.RequestTime))
	{
	    return false;
	}
	if ((status >= PagePublishedStatus.Published) && (page.StopPublish < Context.Current.RequestTime))
	{
	    return false;
	}
    }
 
    return true;
}

Heading

public static string Heading(this PageData page)
{
    if (page.IsValue("Heading"))
    {
	return page["Heading"].ToWebString();
    }
 
    return page.PageName.ToWebString();
}

ToWebString (from EPiServer.dll using reflector)

public static string ToWebString(this object obj)
{
    string[] parsedUISafeHtmlTags = ParsedUISafeHtmlTags;
    string input = obj.ToString().Replace("&", "&amp;").Replace("<", "&lt;").Replace(">", "&gt;");
    if (((parsedUISafeHtmlTags != null) && (parsedUISafeHtmlTags.Length != 0)) && ((parsedUISafeHtmlTags.Length != 1) || (parsedUISafeHtmlTags[0].Length != 0)))
    {
	// using System.Text.RegularExpressions;
	return Regex.Replace(input, BuildRegularExpression(parsedUISafeHtmlTags), "<$1>", RegexOptions.IgnoreCase);
    }
    return input;
}
 
private static string BuildRegularExpression(string[] safeTags)
{
    return ("&lt;(/?(" + string.Join("|", safeTags) + @")/?\s*)&gt;");
}
 
private static string[] ParsedUISafeHtmlTags
{
    get
    {
	// using EPiServer.Configuration;
	string uISafeHtmlTags = Settings.Instance.UISafeHtmlTags;
	if (!string.IsNullOrEmpty(uISafeHtmlTags))
	{
	    return uISafeHtmlTags.Split(new char[] { ',' });
	}
	return new string[0];
    }
}

Related Posts: