Umbraco CMS Content Query functions using Examine

Michael Roma on Jun 16, 2015

This post discusses a ContentHelper class that can be used to query the Umbraco content tree. Click here to download the source The following functions take a Umbraco path or an IPublishedContent object to search for content under that given path/content. It also takes a parameter for “Type” which can be used to select only certain Document Types. You can use String.Empty for the path to search all documents.

// function that queries for the given path and type
public static IEnumerable&ltIPublishedContent&gt Query(string path, string type, bool cache)
{
	// define query
	Func&ltIEnumerable&ltIPublishedContent&gt&gt f = delegate()
	{
		// get the helper
		var helper = new UmbracoHelper(UmbracoContext.Current);

		// get examine
		var examine = Examine.ExamineManager.Instance;

		// build the criteria
		var criteria = examine.CreateSearchCriteria();

		// check if a type
		if (!String.IsNullOrEmpty(type))
		{
			criteria.NodeTypeAlias(type);
		}

		// check if a path
		if (!String.IsNullOrEmpty(path))
		{
			criteria.Field(“__Path”, path.MultipleCharacterWildcard());
		}

		// get the results
		var results = examine.Search(criteria);

		// return the list
		if (results != null)
		{
			return helper.TypedContent(results.Select(x => x.Id)).Where(x => x != null).OrderBy(x => x.SortOrder);
		}

		// else, empty 
		return new List();
	};

	// else, return
	return f();            
}

// function that query for the path of the given item and type
public static IEnumerable&ltIPublishedContent&gt Query(IPublishedContent item, string type)
{
	return Query(item.Path, type);
}
The following is a helper that finds the closest parent with the given Document Type
// function that finds the closest parent for the given type and given document
public static IPublishedContent GetClosestParent(IPublishedContent item, string type)
{
	// loop while a document
	while (item != null)
	{
		// check if the correct type
		if (item.DocumentTypeAlias == type)
		{
			// return it
			return item;
		}

		// go up
		item = item.Parent;
	}

	// if here, nothing
	return null;
}

// function that finds the closest parent for the given type and current document
public static IPublishedContent GetClosestParent(string type)
{
	// get the current document, if exists
	if (UmbracoContext.Current != null && UmbracoContext.Current.PageId.HasValue)
	{
		return GetClosestParent(GetContentById(UmbracoContext.Current.PageId.Value), type);
	}

	// else, null
	return null;
}