Accessing taxonomy/managed metadata in SharePoint app using client object model.
In SharePoint 2013, app is one of key areas. Apps provide easy way to add functionality in SharePoint. It may be required to read/write managed metadata from apps. In this blog, I will cover how to access managed metadata using client object model.
First, we need to do add reference of Microsoft.SharePoint.Client.Taxonomy, location is \ISAPI\Microsoft.SharePoint.Client.Taxonomy.dll in 15 hive
Then, we need to specify type of permission (Read/Write) app needs on Taxonomy. Steps for that
- Click on AppManifest.Xml
- Go to Permissions tab
- In permission requests, select scope = Taxonomy, Permission = Read/Writes (as applicable in your case)
Next we need to access the TermStore , Groups ,TermSet etc. This is bit similar to the way, it gets done in sever side code. One major difference is we need to request for data explicitly.
var contextToken = TokenHelper.GetContextTokenFromRequest(Page.Request);
var hostWeb = Page.Request["SPHostUrl"];
using (var clientContext = TokenHelper.GetClientContextWithContextToken(hostWeb, contextToken, Request.Url.Authority))
TaxonomySession session= TaxonomySession.GetTaxonomySession(clientContext);
First 3 lines gets context token , host web url and client context respectively. You would be familiar with them if you have written any app before.
In next line, we are creating TaxonomySession using clientContext , then we load the TermStores. After ExecuteQuery , session.TermStores will be available.
For groups -
// termstore is object of TermStore which can be retrived from TermStoreCollection (in the above code from session.TermStores)
Similary for TermSet and Terms
// group is object of TermGroup which can be retrived from TermGroupCollection (in the above code from termstore.Groups)
// termset is object of TermSet which can be retrived from TermSetCollection (in the above code from group.TermSets)
One difference you would have noticed is Class for group is TermGroup and not Group which is in server side code.