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:
- using Microsoft.SharePoint.Taxonomy;
And here is the code:
- string siteUrl = "http://sharepoint2010";
- Guid newTermSetId = new Guid("{60F494A0-C31C-4D7C-9C9B-D8AF3191F3D5}");
- Guid newTermId = new Guid("{E39C3477-500E-4EB0-9891-0785F840DF53}");
- using (SPSite site = new SPSite(siteUrl))
- {
- TaxonomySession session = new TaxonomySession(site);
- if (session.TermStores.Count > 0)
- {
- // Get a reference to the store
- TermStore store = session.TermStores["Managed Metadata Service"];
- // Create a group
- Group group = store.CreateGroup("SharePointEgg.Test");
- // Create a term set in the group, with a pre-defined ID
- TermSet termSet = group.CreateTermSet("Term Set Test", newTermSetId, 1033);
- // Create a term in the term set in the newly created term set, with a pre-defined ID
- Term term = termSet.CreateTerm("Term 01", 1033, newTermId);
- // Save everything by calling CommitAll
- store.CommitAll();
- }
- }
And here is the end result:
No comments:
Post a Comment