i:0#.w|Ali.Mazaheri

Azure, Open Source, SharePoint and ...

Adding a Managed Column to a content type via SharePoint Server 2010 OM

Note: This post is based on Beta 2 and is subject to change in future releases.


Following the previous post, here is the snippet which shows how to add a Managed Column (TaxonomyField) to an existing content type using OM:



   1:  using System;
   2:  using System.Collections.Generic;
   3:  using System.Linq;
   4:  using System.Text;
   5:  using Microsoft.SharePoint;
   6:  using Microsoft.SharePoint.Taxonomy;
   7:   
   8:  namespace ConsoleApplication
   9:  {
  10:      class Program
  11:      {
  12:          static void Main(string[] args)
  13:          {
  14:              using (SPSite sc = new SPSite(“http://intranet.litwareinc.com”))
  15:              {
  16:                  Microsoft.SharePoint.Taxonomy.TaxonomySession session = new Microsoft.SharePoint.Taxonomy.TaxonomySession(sc);
  17:                  TermStore termstore = session.TermStores[“Managed Metadata Service”];
  18:                  Group group = termstore.Groups[“Litware Corporate Taxonomy”];
  19:                  TermSet termset = group.TermSets[“Segment”];
  20:                  SPWeb web = sc.RootWeb;
  21:                  SPContentType ct = web.ContentTypes[“Training Course”];
  22:                  TaxonomyField taxField = web.Fields.CreateNewField(“TaxonomyFieldType”, “TaxonomyColumn”) as TaxonomyField;
  23:                  taxField.SspId = termstore.Id;
  24:                  taxField.TermSetId = termset.Id;
  25:                  taxField.AllowMultipleValues = false;
  26:                  taxField.Group = “Litware”;
  27:                  web.Fields.Add(taxField);
  28:                  ct.FieldLinks.Add(new SPFieldLink(web.Fields[“TaxonomyColumn”]));
  29:                  ct.Update(true);
  30:              }
  31:              Console.Read();
  32:          }
  33:   
  34:      }
  35:  }
  36: