Wednesday, September 14, 2011

SharePoint 2010 and Taxonomy API’s



Term Store, Term Sets and Terms....are good but what if i want to use them in place of list columns (Creation of a complete list for a single column value like Countries name and use this list as a reference as lookup column, in InfoPath column as source...and many more....). How i will get the term store on some places where i can refer a list simply by using a web service or rest service...


How you can utilize the SharePoint API to programmatically work with Taxonomies and create terms and fetch the terms in your term store. This should give you some nice ideas on how to get going!


1. Dll Reference:


Microsoft.SharePoint.Taxonomy


You’ll find this reference here:
C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\ISAPI\Microsoft.SharePoint.Taxonomy.dll



2. Namespaces:

So, the first thing we would like to do is to learn how we can read the taxonomies we’ve got in our store. To do this, we utilize Microsoft.SharePoint.Taxonomy.
There’s a few good-to-know classes in this namespace that we’re going to work with:
The above classes are stated in their hierarchically correct order, meaning means that you start out with the TaxonomySession which contains the TermStore, which contains the Groups.. and so on.


Reading the Metadata store (Managed Metadata Service):


Now lets generate the XML tree with it.


protected  void  Page_Load(object  sender, EventArgs  e)
{
SPSite  thisSite = SPContext .Current.Site;
TaxonomySession  session = new  TaxonomySession (thisSite);

TreeNode  treeNode = new  TreeNode ();
treeNode.Text = "Corporate MetaData" ;
tvMetadataTree.Nodes.Add(treeNode);

foreach (TermStore  termStore in  session.TermStores)
{
var  tsNode = new  TreeNode (termStore.Name, null , null , "" , null );
treeNode.ChildNodes.Add(tsNode);
//treeNode = tsNode; 

foreach (Group  group in  termStore.Groups)
{
var  node = new  TreeNode (group.Name, null , null , "" , null );
treeNode.ChildNodes.Add(node);
//treeNode = node; 
foreach (TermSet  termSet in  group.TermSets)
{
node = new  TreeNode (termSet.Name, null , null , "" , null );
treeNode.ChildNodes.Add(node);
treeNode = node;

foreach (Term  term in  termSet.Terms)
{
AddTermSet(term, treeNode);
}
}
}
}
}

void  AddTermSet(Term  term, TreeNode  treeNode)
{
var  node = new  TreeNode (term.Name, null , null , "" , null );
treeNode.ChildNodes.Add(node);
treeNode = node;

foreach  (Term  t in  term.Terms)
{
AddTermSet(t, treeNode);
}
}



The end result will be a simple TreeView control filled with the Metadata structure from the store, looking something like this:

No comments: