An article on Microsoft TechNet defines managed metadata as being "a hierarchical collection of centrally managed terms that you can define, and then use as attributes for items in Microsoft SharePoint Server 2010," and I would argue that it's the most important new feature packaged in SharePoint Server 2010. It provides a central storage space for keywords, an enterprise management of metadata terms, and a content type for SharePoint 2010. Creating term sets using the browser is very straightforward thanks to the Term Store Management Tool. However, the Tool does have some limitations. It doesn't provide a way to include multiple language translations for tags or synonyms, and it doesn't merge terms into an existing taxonomy. Microsoft has implemented a fantasy application programming interface (API) that developers can use to create and manage taxonomies (types of terms).
Challenge:
How can I create term sets and managed metadata columns programmatically?
Solution:
I. Prerequisites
Before we create term sets, there is one thing we need to make sure is running on your SharePoint Server: Managed Metadata Service. This service uses managed metadata and shares content types across site collections, Web applications, and even farms. I recommend you create a new service as a term store for creating term sets instead of the existing service. Read this article for how to Create, update, publish, or delete a managed metadata service application (SharePoint Server 2010) from Microsoft TechNet.
From your SharePoint 2010 Central Administration page, go to Application Management -> Manage service applications (under the Service Applications heading), and check if the service is in Started mode.
In my example, I had already created a new metadata service named MyManagedMetadataService.
When we enable managed metadata in our SharePoint Server 2010 application, a managed metadata service and a connection are created automatically. This service specifies a database to be used as the term store containing term sets, and a connection provides access to the service. Select the Managed Metadata Service Connection, and click the Properties button on the Ribbon.
With the Edit Managed Metadata Service Connection dialog opened, verify that the check box "Consumes content types from the Content Type Gallery at [your site collection]" is checked.
This selection specifies which Web Application will be the source containing metadata for other content types to consume from.
Click on your service name to open the Term Store Management Tool.
Term Store Management Tool:
Note: In this post, I won't be showing you how to use this tool to create term sets, but will focus on using the API programmatically.
II. Creating Term Sets
A term set is a collection of terms, and terms is just a word which is used to associate with items in a SharePoint List. Each term set is organized in a group to categorize, and to enable us to easily mange our set of terms. Therefore, to create term sets, we have to identify a group to group term sets within.
First, make sure your solutions have a reference to Microsoft.SharePoint.Taxonomy.dll, which can be found at {SharePoint Root}ISAPI.
1: public void AddTermsTo(string groupName, string termSetName, List<string> terms)
2: {
3: //create new group if the groupName was not created.
4: Group group = termStore.Groups.Where(g => g.Name == groupName).Count() > 0 ? termStore.Groups[groupName] : termStore.CreateGroup(groupName); 5: //create new term set if the termSetName was not created.
6: TermSet termSet = group.TermSets.Where(s => s.Name == termSetName).Count() > 0 ? group.TermSets[termSetName] : group.CreateTermSet(termSetName);
7:
8: //add terms to term set.
9: int lcid = CultureInfo.CurrentCulture.LCID;
10: foreach (string termName in terms)
11: {
12: if (termSet.GetTerms(termName, false).Count <= 0)
13: {
14: termSet.CreateTerm(termName, lcid);
15: }
16: }
17:
18: termStore.CommitAll();
19: }
The code identifies if the group name and term set name were already created. If not, it creates new group and term set, then adds the terms collection into terms set.
The termStore here is an instance of your Managed Metadata Service, and to get this object we need a reference to TaxonomySession, and pass SPSite as parameter to its constructor.
1: TaxonomySession taxonomySession = new TaxonomySession(site);
2: TermStore termStore = taxonomySession.TermStores["MyManagedMetadataService"];
Now let's try to create term sets with the following example.
1: MyTaxonomySession taxonomySession = new MyTaxonomySession(spSite);
2: List<string> regionTerms = new List<string>();
3: regionTerms.Add("East");
4: regionTerms.Add("West");
5: regionTerms.Add("South");
6: regionTerms.Add("North");
7: taxonomySession.AddTermsTo("Company Terms", "Regions", regionTerms);
8:
9: List<string> productTerms = new List<string>();
10: productTerms.Add("ProductA");
11: productTerms.Add("ProductB");
12: productTerms.Add("ProductC");
13: productTerms.Add("ProductD");
14: taxonomySession.AddTermsTo("Company Terms", "Products", productTerms);
Then, check with Term Store Management Tools to see if they were created successfully.
Go to your root site collection, open Site Actions -> Site Settings -> Term store management under Site Administration:
Boom! Fortunately, they were created!
Note: If you have multiple Managed Metadata Services running on your server, make sure you selected the right one, and it's the one you're using.
III. Creating Managed Metadata Column
Creating term sets is just half of the battle. In this next step, I'm going to show you how to use these term sets as a Managed Metadata Column in your Document Library or Task List.
In this example, I have a Document Content Type named My Company Docs with one field only at my root site collection.
And I have a Document Library named My Document Library which inherits the above content type.
And some sample items for this library:
Now when I run the code below, it creates two Metadata columns, using our two term sets, into the Site Column Galleries, and adds the columns to our content type.
1: taxonomySession.CreateMetaDataColumn(spWeb, groupName, "Products", "Metadata_Products", "South");
2: taxonomySession.CreateMetaDataColumn(spWeb, groupName, "Regions", "Metadata_Regions", "ProductC");
3: public void CreateMetaDataColumn(SPWeb spWeb, string groupName, string termSetName, string fieldName, string defaultValue)
4: {
5: SPSecurity.RunWithElevatedPrivileges(delegate()
6: {
7: Microsoft.SharePoint.Administration.SPWebApplication webApp = spWeb.Site.WebApplication;
8: //webApp.FormDigestSettings.Enabled = false;
9: spWeb.AllowUnsafeUpdates = true;
10:
11: Group group = termStore.Groups[groupName];
12: TermSet termset = group.TermSets[termSetName];
13:
14: if (!spWeb.Fields.ContainsField(fieldName))
15: {
16: TaxonomyField taxField = spWeb.Fields.CreateNewField(TAXONOMY_FIELD_TYPE, fieldName) as TaxonomyField;
17: taxField.SspId = termStore.Id;
18: taxField.TermSetId = termset.Id;
19: taxField.AllowMultipleValues = false;
20: taxField.Group = groupName;
21: taxField.DefaultValue = defaultValue;
22: spWeb.Fields.Add(taxField);
23: }
24:
25: SPContentType spContentType = spWeb.ContentTypes[MY_CONTENTTYPE];
26: if (!spContentType.Fields.ContainsField(fieldName))
27: {
28: spContentType.FieldLinks.Add(new SPFieldLink(spWeb.Fields[fieldName]));
29: spContentType.Update(true, false);
30: }
31:
32: spWeb.Update();
33: spWeb.AllowUnsafeUpdates = false;
34: //webApp.FormDigestSettings.Enabled = true;
35: });
36: }
If you run into a security problem when running this code, disable your page validation in the Web Application's General Settings. To do this, go to SharePoint 2010 Central Administration -> Application Management -> Manage web application, click the General Settings button on the Ribbon, then set Security Validation to Off.
After you have successfully executed these statements, check that the columns were added to the content type, and remember to turn the Security Validation on again.
Then, look at our Document Library to see if it was updated with this modified content type.
Note: remember to modify your current view to show these metadata columns.
Now edit one of your items, to see how Metadata column is used.
Click on the icon with the surrounding red box, and the term set of this metadata column appears, then select a term for your item.
And that's Managed Metadata, how to create a term set, and how to create a Metadata Column using term sets. I hope that you found this post to be helpful.
Here is my entire class for creating Term Sets and Metadata Column: MyTaxonomySession.cs
See Also:
Concepts
- Managed Metadata Service application overview (SharePoint 2010) [TechNet]
-
Create, update, publish, or delete a managed metadata service application (SharePoint Server 2010) [TechNet]
Other Resources:
- Video How Do I: Use the SharePoint 2010 Managed Metadata Service? [TechNet]
- Creating Term Sets using powershell script [Advantive]