Thursday, October 16, 2014

Retrieving and working with Search Navigation entries using CSOM

I’m currently working on some provisioning tasks for a search page and we want to script up the search navigation using CSOM. This would be the Everything, People, and Social tabs you see below the search box.
The issue is that Web.Navigation does not have the SearchNav property which SPWeb.Navigation has. It only has QuickLaunch and TopNavigationBar.
But just because the good guys over at Microsoft haven’t gotten around to implement all the SSOM properties doesn’t mean we’re stuck. Using Reflector I figured out the node id for the search navigation was 0x410. Which yields the following code.
string siteUrl = "http://dev/sites/search";

ClientContext clientContext = new ClientContext(siteUrl);
Web web = clientContext.Web;

var nav = web.Navigation;

NavigationNode searchNav = nav.GetNodeById(1040);
NavigationNodeCollection nodeCollection = searchNav.Children;

clientContext.Load(nodeCollection);
clientContext.ExecuteQuery();

foreach (NavigationNode navigationNode in nodeCollection)
{
    Console.WriteLine(navigationNode.Title + " : " + navigationNode.Url);
}

Take a look at http://msdn.microsoft.com/en-us/library/microsoft.sharepoint.client.navigationnodecollection(v=office.15).aspx for sample code on how to add more nodes to the collection.

Enjoy!