Experience Sitecore ! | Sitecore Item Extension Methods

Experience Sitecore !

More than 200 articles about the best DXP by Martin Miles

Sitecore Item Extension Methods

Below, there is my collection of Sitecore Item's extension methods, I've collected them within few recent years of my career from various sources. I decided to store them here, all at the same place, so that I can pick them up from here when necessary, case by case.

Here they are:



Programmatically Get Datasource Items of a Sitecore Item

If you need to get the datasource item’s of a particular Sitecore item, we can write a few extension methods to help us out!
public static class ItemExtensions
{
        public static RenderingReference[] GetRenderingReferences(this Item i)
        {
            if (i == null)
            {
                return new RenderingReference[0];
            }
            return i.Visualization.GetRenderings(Sitecore.Context.Device, false);
        }
 
        public static List<Item> GetDataSourceItems(this Item i)
        {
            List<Item> list = new List<Item>();
            foreach (RenderingReference reference in i.GetRenderingReferences())
            {
                Item dataSourceItem = reference.GetDataSourceItem();
                if (dataSourceItem != null)
                {
                    list.Add(dataSourceItem);
                }
            }
            return list;
        }
 
        public static Item GetDataSourceItem(this RenderingReference reference)
        {
            if (reference != null)
            {
                return GetDataSourceItem(reference.Settings.DataSource, reference.Database);
            }
            return null;
        }
 
        private static Item GetDataSourceItem(string id, Database db)
        {
            Guid itemId;
            return Guid.TryParse(id, out itemId)
                                    ? db.GetItem(new ID(itemId))
                                    : db.GetItem(id);
        }
}

Example of the call:
foreach (Item dataSourceItem in Sitecore.Context.Item.GetDataSourceItems())
{
    // do something
} 

Programmatically Get Personalization Datasource Items of a Sitecore Item

In the previous blog post, Programmatically Get Datasource Items of a Sitecore Item we learned how to get the datasource items from the rendering references. This does not include the items that have been added through personalization and rules. By adding the following methods to our previous post, we can get those items.
public static List<Item> GetPersonalizationDataSourceItems(this Item i)
{
    List<Item> list = new List<Item>();
    foreach (RenderingReference reference in i.GetRenderingReferences())
    {
        list.AddRange(reference.GetPersonalizationDataSourceItem());
    }
    return list;
}
 
private static List<Item> GetPersonalizationDataSourceItem(this RenderingReference reference)
{
    List<Item> list = new List<Item>();
    if (reference != null && reference.Settings.Rules != null && reference.Settings.Rules.Count > 0)
    {
        foreach (var r in reference.Settings.Rules.Rules)
        {
            foreach (var a in r.Actions)
            {
                var setDataSourceAction = a as Sitecore.Rules.ConditionalRenderings.SetDataSourceAction<Sitecore.Rules.ConditionalRenderings.ConditionalRenderingsRuleContext>;
                if (setDataSourceAction != null)
                {
                    Item dataSourceItem = GetDataSourceItem(setDataSourceAction.DataSource, reference.Database);
                    if (dataSourceItem != null)
                    {
                        list.Add(dataSourceItem);
                    }
                }
            }
        }
    }
    return list;
}
This code loops through the rules of your personalized component and if the action is Sitecore.Rules.ConditionalRenderings.SetDataSourceAction, then we know that this will be:
foreach (Item personalizationItem in Sitecore.Context.Item.GetPersonalizationDataSourceItems())
{
     // do something
}

Get Multi Variate Test Datasource Items of a Sitecore Item

In the previous two blog posts, Programmatically Get Datasource Items of a Sitecore Item and Programmatically Get Personalization Datasource Items of a Sitecore Item we learned how to get the datasource items and personalization datasource items from the rendering references. This does not include the items that have been added through Multi Variate Testing. By adding the following methods to our previous post, we can get those items.
public static List<Item> GetMultiVariateTestDataSourceItems(this Item i)
{
    List<Item> list = new List<Item>();
    foreach (RenderingReference reference in i.GetRenderingReferences())
    {
        list.AddRange(reference.GetMultiVariateTestDataSourceItems());
    }
    return list;
}
 
private static List<Item> GetMultiVariateTestDataSourceItems(this RenderingReference reference)
{
    List<Item> list = new List<Item>();
    if (reference != null && !string.IsNullOrEmpty(reference.Settings.MultiVariateTest))
    {
        using (new SecurityDisabler())
        {
            var mvVariateTestForLang = Sitecore.Analytics.Testing.TestingUtils.TestingUtil.MultiVariateTesting.GetVariableItem(reference);
            //var mvVariateTestForLang = reference.Settings.GetMultiVariateTestForLanguage(Sitecore.Context.Language); // < Sitecore 7.5
            Sitecore.Data.Items.Item variableItem = null;
 
            if (mvVariateTestForLang != null)
            {
                variableItem = mvVariateTestForLang.InnerItem;
                //variableItem = reference.Database.GetItem(mvVariateTestForLang); // < Sitecore 7.5
            }
 
            if (variableItem != null)
            {
                foreach (Item mvChild in variableItem.Children)
                {
                    var mvDataSourceItem = mvChild.GetInternalLinkFieldItem("Datasource");
                    if (mvDataSourceItem != null)
                    {
                        list.Add(mvDataSourceItem);
                    }
                }
            }
        }
    }
    return list;
}
 
public static Item GetInternalLinkFieldItem(this Item i, string internalLinkFieldName)
{
    if (i != null)
    {
        InternalLinkField ilf = i.Fields[internalLinkFieldName];
        if (ilf != null && ilf.TargetItem != null)
        {
            return ilf.TargetItem;
        }
    }
    return null;
}
This code shown is for Sitecore 7.5 and above while the commented out lines are for versions of Sitecore below 7.5. Now that we have these extension methods, we are able to write some nice code like this:
foreach (Item multiVariateTestDataSourceItem in Sitecore.Context.Item.GetMultiVariateTestDataSourceItems())
{
     // do something
}

Is Media Item / Is Content Item

Those two properties are built in and come with sitecore initially. They simple verify item path, wether that falls under /sitecore/content or /sitecore/media library
item.Paths.IsContentItem;
item.Paths.IsMediaItem;

DoesLanguageVersionExist

This extension method will be used to check ifitem exist in current provided language
        
public static bool DoesLanguageVersionExist(this Item item, Language languageToCheck)
        {
            bool isExist = false;
            Sitecore.Data.Items.Item itemInLanguage = item.Database.GetItem(item.ID, languageToCheck);
            isExist = itemInLanguage.Versions.Count > 0;
            return isExist;
        }

GetBooleanField

Gets value of Checkbox field
        public static bool GetBooleanField(this Item item, string fieldName)
        {
            Field fieldValue = item.Fields[fieldName];

            if (fieldValue != null)
                return (fieldValue.Value == "1" ? true : false);
            else
                return false;
        }

GetMediaItemField

Returns MediaItem from Media Field
        public static MediaItem GetMediaItemField(this Item item, string fieldName)
        {
            Field fieldValue = item.Fields[fieldName];
            MediaItem mediaItem = null;

            if ((fieldValue != null) && (fieldValue.HasValue))
                mediaItem = ((ImageField)fieldValue).MediaItem;

            return mediaItem;
        }

GetStringField

Retrieves value of a string-based field - Single Line, Multiline, etc.
        public static String GetStringField(this Item item, String fieldName)
        {
            string fieldValue = string.Empty;
            if (item != null)
            {
                Field field = item.Fields[fieldName];
                if ((field != null) && (!string.IsNullOrEmpty(field.Value)))
                    fieldValue = field.Value;
            }
            return fieldValue;
        }

GetDateField

Gets DateTime value out of Date of DateTime field
        public static DateTime GetDateField(this Item item, String fieldName)
        {
            DateField fieldValue = item.Fields[fieldName];
            DateTime dateTime = DateTime.Now;
            if ((fieldValue != null) && (fieldValue.InnerField.Value != null))
                dateTime = fieldValue.DateTime;

            return dateTime;
        }

GetHtmlField

Gets the value of HtmlField
        public static HtmlField GetHtmlField(this Item item, String fieldName)
        {
            HtmlField htmlField = item.Fields[fieldName];
            return htmlField;
        }

Gets LInk Field out of corresponding item
        public static LinkField GetLinkField(this Item item, String fieldName)
        {   
            LinkField linkField = item.Fields[fieldName];
            return linkField;
        }

GetReferenceField

Gets Reference Field out of corresponding item - Droplink, Droptree, Grouped Droplink etc.
        public static ReferenceField GetReferenceField(this Item item, String fieldName)
        {            
            ReferenceField referenceField = item.Fields[fieldName];
            return referenceField;
        }

GetReferenceFieldItem

Gets an associated item out of Reference Field of an item - Droplink, Droptree, Grouped Droplink etc.
        public static Item GetReferenceFieldItem(this Item item, String fieldName)
        {
            Item targetItem = null;
            ReferenceField referenceField = item.Fields[fieldName];
            if ((referenceField != null) && (referenceField.TargetItem != null))
                targetItem = referenceField.TargetItem;

            return targetItem;
        }

GetMultilistField

Returns Multilist Field
        public static MultilistField GetMultilistField(this Item item, String fieldName)
        {
            MultilistField multilistField = item.Fields[fieldName];
            return multilistField;
        }

GetMultilistFieldItems

Returns associated items of Multilist Field; works also with Checklist, Treelist, Treelist-Ex
        public static Item[] GetMultilistFieldItems(this Item item, String fieldName)
        {            
            Item[] targetItems = null;
            MultilistField multilistField = item.Fields[fieldName];
            if ((multilistField != null) && (multilistField.InnerField != null))
                targetItems = multilistField.GetItems();

            return targetItems;
        }

Publish

Performs publishing of an item. Deep parameter makes publishing recursice against all the subitems
public static void Publish(this Item item, bool deep)
{
    var publishOptions = new PublishOptions(item.Database,
                                        Database.GetDatabase("web"),
                                        PublishMode.SingleItem,
                                        item.Language,
                                        DateTime.Now);
    var publisher = new Publisher(publishOptions);
    publisher.Options.RootItem = item;
    publisher.Options.Deep = deep;
    publisher.Publish();
}

Unpublish

Unpublishes current item
public static void UnPublish(this Item item)
{
    item.Publishing.UnpublishDate = DateTime.Now;
    item.Publish(true);
}

IsPublished

Finds out if item is already published
public static bool IsPublished(this Item pItem)
{
    Database lWebDb = Factory.GetDatabase("web");
    if (pItem != null && lWebDb != null)
    {
        Item lWebItem = lWebDb.GetItem(pItem.ID, pItem.Language, pItem.Version);
        if (lWebItem == null || pItem.Statistics.Updated > lWebItem.Statistics.Updated)
        {
            return false;
        }
    }
    return true;
}

ParentList

Gets an array of all hierarchial parent items of a current item, can be useful for creating breadcrumbs
public static IEnumerable<Item> ParentList(this Item item, Boolean descending = true)
{
    if (item == null)
        return null;
 
    List<Item> parents = new List<Item>();
 
    Item currentItem = item.Parent;
    while (currentItem != null)
    {
        parents.Add(currentItem);
 
 
        currentItem = currentItem.Parent;
    }
 
    if (descending)
        parents.Reverse();
 
    return parents;
}

GetReferrersAsItems

Get referrers of an item using the link database
public static IEnumerable<Item> GetReferrersAsItems(this Item item)
{
    var links = Globals.LinkDatabase.GetReferrers(item);
    return links.Select(i => i.GetTargetItem()).Where(i => i != null);
}

IsDerived

Tells, if a given item derives from a specific template
public static bool IsDerived(this Item item, ID templateId)
{
  if (item == null)
    return false;
 
  if (templateId.IsNull)
    return false;
 
  TemplateItem templateItem = item.Database.Templates[templateId];
 
  bool returnValue = false;
  if (templateItem != null)
  {
    Template template = TemplateManager.GetTemplate(item);
 
    returnValue = template != null && template.ID == templateItem.ID || template.DescendsFrom(templateItem.ID);
  }
 
  return returnValue;
}

ChildrenDerivedFrom

Returns children items derived from a specific template
 
public static IEnumerable<Item> ChildrenDerivedFrom(this Item item, ID templateId)
{
    ChildList children = item.GetChildren();
    List<Item> childrenDerivedFrom = new List<Item>();
 
    foreach (Item child in children)
    {
        if (child.IsDerived(templateId))
            childrenDerivedFrom.Add(child);
    }
 
    return childrenDerivedFrom;
}

IsTemplate

Checks wether specific item is a template item
public static bool IsTemplate(this Item item)
{
    return item.Database.Engines.TemplateEngine.IsTemplatePart(item);
}

HasLanguage

Tells, if an Item has a version in a specific language
public static bool HasLanguage(this Item item, string languageName)
{
    return ItemManager.GetVersions(item, LanguageManager.GetLanguage(languageName)).Count > 0;
}

public static bool HasLanguage(this Item item, Language language)
{
    return ItemManager.GetVersions(item, language).Count > 0;
}

LanguageVersionCount

Gives the amount of versions that a given item has in a given language
public static int LanguageVersionCount(this Item item, Language lang)
{
    if (item == null)
        return 0;
    Item currentItem = item.Database.GetItem(item.ID, lang);
    if (currentItem.Versions.Count > 0)
        return currentItem.Versions.Count;
    else
        return 0;
}

AddItemToIndex

Adds given item into specified index
public static void AddItemToIndex(this Item item, string indexName)
{
    var tempItem = (SitecoreIndexableItem)item;
    ContentSearchManager.GetIndex(indexName).Refresh(tempItem);
}

UpdateItemInIndex

Updates current item within an index
public static void UpdateItemInIndex(this Item item, string indexName)
{
    var tempItem = (SitecoreIndexableItem)item;
 
    ContentSearchManager.GetIndex(indexName).Delete(tempItem.UniqueId);
    AddItemToIndex(item, indexName);
}

PublishItem

One more version of Publish method for current item
public static void PublishItem(this Item item)
{
    var publishOptions = new PublishOptions(item.Database,
        Database.GetDatabase("web"),
        PublishMode.SingleItem,
        item.Language,
        DateTime.Now); // Create a publisher with the publishoptions
 
    var publisher = new Publisher(publishOptions);
 
    // Choose where to publish from
    publisher.Options.RootItem = item;
 
    // Publish children as well?
    publisher.Options.Deep = true;
 
    // Do the publish!
    publisher.Publish();
}

Url

Returns user-friendly URL of an item
public static string Url(this Item item)
{
    return LinkManager.GetItemUrl(item);
}

GetMembershipUser

Returns the System.Web.Security.MembershipUser associated with a Sitecore.Security.Accounts.User object
public static MembershipUser GetMembershipUser(this Account account)
{
return Membership.GetUser(account.Name);
}

HasBaseTemplate

Returns true if current template item is derived from another template
public static bool HasBaseTemplate(
      this TemplateItem me,
      ID templateID,
      bool includeSelf = false,
      bool recursive = true)
    {
      if (includeSelf && me.ID == templateID)
      {
        return true;
      }
 
      if (recursive)
      {
        foreach (TemplateItem baseTemplate in me.BaseTemplates)
        {
          if (baseTemplate.HasBaseTemplate(
            templateID,
            true /*includeSelf*/,
            true /*recursive*/))
          {
            return true;
          }
        }
      }
 
      return false;
    }

HasChild

Identifies if current item has a child with a specific ID
public static bool HasChild(this Item item, string childIdStr)
{
    ID childId = new ID(childIdStr);
    return HasChild(item,childId);
}

public static bool HasChild(this Item item, ID childId)
{
    foreach (Item child in item.Children)
    {
        if (child.ID == childId)
            return true;
    }
    return false;
}

HasDescendant

Identifies if current item has a decscendant with a specific ID
public static bool HasDescendant(this Item item, string descendantIdstr)
{
    ID descendantId = new ID(descendantIdstr);
    return HasDescendant(item, descendantId);
}

public static bool HasDescendant(this Item item, ID descendantId)
{
    foreach (Item child in item.Children)
    {
        if (child.ID == descendantId)
            return true;
        
HasDescendant(child, descendantId); } return false; }

IsStandardValue

Indicates whether an item is a standard value item or not
public static bool IsStandardValues(this Item item)
{
  if (item == null)
    return false;
  bool isStandardValue = false;
         
  if (item.Template.StandardValues != null)
    isStandardValue = (item.Template.StandardValues.ID == item.ID);
         
  return isStandardValue;
}

HasRenderings

Indicates if an item has versioned renderings.
public static bool HasRenderings(this Item item)
{
    return item.Visualization.GetRenderings(Context.Device, false).Any();
}
public static bool HasRenderings(this Item item, DeviceItem device)
{
    return item.Visualization.GetRenderings(device, false).Any();
}

HasVersionedRenderings

Indicates if an item has versioned renderings.
public static bool HasVersionedRenderings(this Item item)
{
   if (item.Fields[FieldIDs.FinalLayoutField] == null)
      return false;

   var field = item.Fields[FieldIDs.FinalLayoutField];
   return !string.IsNullOrWhiteSpace(field.GetValue(false, false));
}

public static bool HasVersionedRenderingsOnLanguage(this Item item, Language language)
{
    return item != null && item.Database.GetItem(item.ID, language).HasVersionedRenderings();
}
public static bool HasVersionedRenderingsOnAnyLanguage(this Item item)
{
   return ItemManager.GetContentLanguages(item).Any(item.HasVersionedRenderingsOnLanguage),
}
public static bool HasVersionedRenderingsOnContextLanguage(this Item item)
{
   return item.HasVersionedRenderingsOnLanguage(Context.Language);
}

Pingbacks and trackbacks (1)+

Comments are closed