Thursday, February 09, 2017

A method to get a sitecore item id given a path

This method will give you a sitecore item id back if you give it a fully qualified path as input.

void Main()
{
 var itemId= GetItemId("/sitecore/content").Dump(); 
 
 //get child items
 //Items.Where (i => i.ParentID==itemId).Select (i => new {i.ID, i.Name}).Dump();
 
 //show field information
 Fields.Where (f => f.ItemId==itemId && f.Value!="")
  .Select (f => new 
  {
   FieldName=Items.Where (i => i.ID==f.FieldId).Select (i => i.Name).Single (),
   f.Value,
   f.Language
  })
  .Dump();
  
}



Guid GetItemId(string itemPath)
 {
 
  var pathParts = itemPath.Split(new char[] { '/'}, StringSplitOptions.RemoveEmptyEntries ); 
  var parentId = Guid.Empty;
  var id = Guid.Empty;
  foreach (var part in pathParts)
  {
   if (parentId == Guid.Empty && part.Equals("sitecore", StringComparison.OrdinalIgnoreCase))
   {
     parentId = new Guid("{11111111-1111-1111-1111-111111111111}");
  id = parentId;
    }
   else
   {
    id = GetChildGuid(part, parentId);
 
    if (id != Guid.Empty)
     parentId = id;
    else
    {
     String.Format("Could not find {0}", part).Dump();
     break;
    }
   }
  }
  return id;
}
 
Guid GetChildGuid (string childName, Guid parent_guid)
{
  return Items.Where(i => i.ParentID == parent_guid && i.Name == childName)
   .Select(i => i.ID)
   .FirstOrDefault();
}