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();
}

1 comment:

Coepd BA Trainings said...

We at Coepd declared Data Science Internship Programs (Self sponsored) for professionals who want to have hands on experience. We are providing this program in alliance with IT Companies in COEPD Hyderabad premises. This program is dedicated to our unwavering participants predominantly acknowledging and appreciating the fact that they are on the path of making a career in Data Science discipline. This internship is designed to ensure that in addition to gaining the requisite theoretical knowledge, the readers gain sufficient hands-on practice and practical know-how to master the nitty-gritty of the Data Science profession. More than a training institute, COEPD today stands differentiated as a mission to help you "Build your dream career" - COEPD way.

http://www.coepd.com/AnalyticsInternship.html