Tuesday 26 October 2010

Creating Term Set in SharePoint 2010 Programmatically

Managed Metadata is a very nice feature introduced in SharePoint 2010. It allows you to define terms in a hierarchical collection centrally, and create a managed metadata field that is reference a term sets.

By using the Term Store Management Tool found in Managed Metadata Service, you can create a term set either manually, or by importing a CSV file. You can also create a term set programmatically, either by a feature receiver or a console application. You may ask “Why do I want to provision a term set programmatically?”. Well, by creating the term set programmatically, you are able to define a fixed ID/GUID for you term set or term, and this becomes handy if you want to provision a managed metadata field in a feature (Angus has created an excellent article on how to do this).

First, you will need to add a reference to “Microsoft.SharePoint.Taxonomy.dll”, which should not be too hard to find in Visual Studio 2010. Next, an obviously, you will need to put the following line:

Code Snippet
  1. using Microsoft.SharePoint.Taxonomy;

And here is the code:

Code Snippet
  1. string siteUrl = "http://sharepoint2010";
  2. Guid newTermSetId = new Guid("{60F494A0-C31C-4D7C-9C9B-D8AF3191F3D5}");
  3. Guid newTermId = new Guid("{E39C3477-500E-4EB0-9891-0785F840DF53}");
  4. using (SPSite site = new SPSite(siteUrl))
  5. {
  6. TaxonomySession session = new TaxonomySession(site);
  7. if (session.TermStores.Count > 0)
  8. {
  9. // Get a reference to the store
  10. TermStore store = session.TermStores["Managed Metadata Service"];
  11. // Create a group
  12. Group group = store.CreateGroup("SharePointEgg.Test");
  13. // Create a term set in the group, with a pre-defined ID
  14. TermSet termSet = group.CreateTermSet("Term Set Test", newTermSetId, 1033);
  15. // Create a term in the term set in the newly created term set, with a pre-defined ID
  16. Term term = termSet.CreateTerm("Term 01", 1033, newTermId);
  17. // Save everything by calling CommitAll
  18. store.CommitAll();
  19. }
  20. }

And here is the end result:

No comments: