Subscribe:

Pages

Sunday, March 25, 2012

Sitecore Extension Methods

Extension methods one of the features introduced in .net framework 3.0 that I like very much. I am writing this post to share some of the extension methods that I use in my projects and will be updating it time to time with more methods

public static class ItemExtension
{

    /// <summary>
    /// Gets the list of child items based on TemplateName parameter
    /// </summary>
    public static List<Item> GetChildrenByTemplate(this Item item, string TemplateName)
    {
        if (item.HasChildren)
        {
            return item.Children.Where(x => x.TemplateName.Equals(TemplateName)).ToList();
        }
        return null;
    }

    /// <summary>
    /// Gets the list of child items based on TemplateID parameter
    /// </summary>
    public static List<Item> GetChildrenByTemplate(this Item item, ID TemplateID)
    {
        if (item.HasChildren)
        {
            return item.Children.Where(x => x.TemplateID.Equals(TemplateID)).ToList();
        }
        return null;
    }

    /// <summary>
    /// Gets the (friendly) URL of an item
    /// </summary>
    public static string GetItemUrl(this Item item)
    {
        return Sitecore.Links.LinkManager.GetItemUrl(item);
    }

    /// <summary>
    /// Gets the (friendly) URL of an item
    /// </summary>
    public static string GetItemUrl(this Item item, Sitecore.Links.UrlOptions options)
    {
        return Sitecore.Links.LinkManager.GetItemUrl(item, options);
    }

}