Wednesday, April 02, 2014

Managed metadata – lookup terms using custom properties in CSOM


SharePoint Server 2013 introduces the notion of custom properties on specific terms in managed metadata termset and with  the added support for .NET client object model (CSOM) for managed metadata APIs you have some quite interesting scenarios that you can imagine (Check out managed metadata and navigation in SharePoint Server 2013)

A typical scenario is one in which you have a master system for which you want to export some parts to a termset in the managed metadata store. To make this to happen you will however need a key from the master system to be linked to the different terms that you are creating. Listed below is some sample code to look for a specific term based on a custom property.

   1:          static Term GetTermByCustomID(string customid)
   2:          {
   3:              Term retTerm = null;
   5:              CustomPropertyMatchInformation matchinfo = new CustomPropertyMatchInformation(Program.clientContext);
   6:              matchinfo.CustomPropertyName = "ID";
   7:              matchinfo.CustomPropertyValue = customid;
   8:              matchinfo.TrimUnavailable = false;
  10:              var terms = termSet.GetTermsWithCustomProperty(matchinfo);
  11:              Program.clientContext.Load(terms);
  12:              Program.clientContext.ExecuteQuery();
  14:              if (terms.Count > 0)
  15:              {
  16:                  retTerm = terms[0];
  17:              }
  19:              return retTerm;
  21:          }

One of the things which puzzled me for quite a while was the TrimUnavailable property – but recently the documentation got updated which made it a little more clear - see TermSet.GetTermsWithCustomProperty method (String, String, StringMatchOption, Int32, Boolean) – apparently it is indicates whether to trim out Term objects that have the IsAvailableForTagging property set to false.

No comments: