Mike Robbins

Sitecore Developer Blog

Follow me on GitHub

Sitecore extension methods

Over the past year or so, in my spare time I've been building a code library for sitecore 6.X and Sitecore 7 more recently. I've built up a big list of Sitecore extension methods so I thought I'd share some of my favorites. Feel free to comment with your own.

Sitecore 7 Indexing

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

Sitecore Publishing

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();
}
public static void UnPublishItem(this Item item)
{
  item.Publishing.UnpublishDate = DateTime.Now;
  PublishItem(item);
}

Sitecore Item Extensions

public static string Url(this Item item)
{
  return LinkManager.GetItemUrl(item);
}
public static IEnumerable<Item> ParentList(this Item item, Boolean descending = true)
{
  if (item == null)
  {
    return null;
  }
  var parents = new List<Item>();
  var currentItem = item.Parent;
  while (currentItem != null)
  {
    parents.Add(currentItem);
    currentItem = currentItem.Parent;
  }
  if (descending)
  {
    parents.Reverse();
  }
  return parents;
}
public static bool IsDerivedFrom(this Item item, ID templateId)
{
  if (item == null || emplateId.IsNull)
  {
    return false;
  }

  var templateItem = item.Database.Templates[templateId];
  var returnValue = false;
  if (templateItem != null)
  {
    var template = TemplateManager.GetTemplate(item);
    returnValue = template != null && template.ID == templateItem.ID ||
    template.DescendsFrom(templateItem.ID);
  }
  return returnValue;
}

Sitecore Account Extensions

public static MembershipUser GetMembershipUser(this Account account)
{
  return Membership.GetUser(account.Name);
}