Monday, October 14, 2013

Create SharePoint Term Group, Term Set and Terms Using Sharepoint 2013 Client Object Model

Recently, i had to create tons of SharePoint terms with  specific term sets and groups from another system. I wanted to put together code creating term groups, sets, terms in one simple function. I created a simple console application with references to sharepoint 2013 dlls including "Microsoft.Sharepoint.Client.dll", "Microsoft.Sharepoint.Client.Runtime.dll" and "Microsoft.Sharepoint.Client.Taxonomy.dll".

Below function takes input as Taxonomy Store, Term Group, Term Set, and Array of Terms, and checks if there is any Group, Set, Terms, with given values exists in Term Store, and if they do not exists it creates Term Group, Set and Terms.

    1 using System;
    2 using System.Collections.Generic;
    3 using System.Linq;
    4 using System.Text;
    5 using System.IO;
    6 using System.Net;
    7 using Microsoft.SharePoint.Client;
    8 using Microsoft.SharePoint.Client.Taxonomy;
    9 
   10 
   11 namespace CreateSPTermGroupSetAndTerms
   12 {
   13     class Program
   14     {
   15         static void Main(string[] args)
   16         {
   17             CreateTermGroupAndTermSetAndAddTerms("Managed Metadata Service", "TestGroup1", "TestG1S2", new string[] { "TestS2T1", "TestS2T2" });
   18         }
   19 
   20         static void CreateTermGroupAndTermSetAndAddTerms(string termStoreName, string termGroupName, string termSetName, string[] termsList)
   21         {
   22             using (ClientContext clientContext = new ClientContext(ConfigurationConstants.XYZSharepointSiteCollectionUrl))
   23             {
   24                 NetworkCredential credentials = new NetworkCredential(ConfigurationConstants.XYZSharepointAdminUserName,ConfigurationConstants.XYZSharepointAdminUserPassword, ConfigurationConstants.XYZSharepointDomain);
   25                 clientContext.Credentials = credentials;
   26 
   27                 Web web = clientContext.Web;
   28 
   29                 TaxonomySession taxonomySession = TaxonomySession.GetTaxonomySession(clientContext);
   30                 clientContext.Load(taxonomySession, ts => ts.TermStores);
   31                 clientContext.ExecuteQuery();
   32 
   33                 if (taxonomySession != null)
   34                 {
   35                     TermStore termStore = null; var cTermStore = -1;
   36                     if (string.IsNullOrEmpty(termStoreName)) return;
   37                     try
   38                     {
   39                         cTermStore = taxonomySession.TermStores.Where(s => s.Name == termStoreName).Count();
   40                         termStore = taxonomySession.TermStores.GetByName(termStoreName); clientContext.Load(termStore, tStore => tStore.Name, tStore => tStore.Groups); clientContext.ExecuteQuery();
   41                     }
   42                     catch { }
   43 
   44                     if (termStore != null && cTermStore > 0)//term store exists
   45                     {
   46                         TermGroup myTermGroup = null;
   47                         var cTermStoreGroups = -1;
   48                         if (string.IsNullOrEmpty(termGroupName)) return; // if input group name is empty do nothing
   49                         try
   50                         {
   51                             cTermStoreGroups = termStore.Groups.Where(s => s.Name == termGroupName).Count();
   52                             myTermGroup = termStore.Groups.GetByName(termGroupName); clientContext.Load(myTermGroup, gs => gs.TermSets); clientContext.ExecuteQuery();
   53                         }
   54                         catch { }
   55 
   56                         if (myTermGroup == null || cTermStoreGroups == 0) //term group not exists create now
   57                         {
   58                             myTermGroup = termStore.CreateGroup(termGroupName, Guid.NewGuid());
   59                             TermSet myTermSet = myTermGroup.CreateTermSet(termSetName, Guid.NewGuid(), 1033);
   60 
   61                             if (termsList != null)
   62                             {
   63                                 foreach (string termValue in termsList)
   64                                 {
   65                                     if (!string.IsNullOrEmpty(termValue))
   66                                     {
   67                                         Term newCreatedTerm = myTermSet.CreateTerm(termValue, 1033, Guid.NewGuid());
   68                                         //newCreatedTerm.CreateLabel("Label", 1033, false);
   69                                     }
   70                                 }
   71                             }
   72                             clientContext.ExecuteQuery();
   73                             LogMessages.Instance.LogMessageToTextFile(" Successfully created Termgroup: " + termGroupName + " term set: " + termSetName + " added terms ");
   74                         }
   75                         else // if term group already exists
   76                         {
   77                             TermSet myTermSet = null;
   78                             var cTermGroupSets = -1;
   79                             if (string.IsNullOrEmpty(termSetName)) return;// if input term set is empty do nothing
   80                             try
   81                             {
   82                                 cTermGroupSets = myTermGroup.TermSets.Where(s => s.Name == termSetName).Count();
   83                                 myTermSet = myTermGroup.TermSets.GetByName(termSetName); clientContext.Load(myTermSet, gs => gs.Terms); clientContext.ExecuteQuery();
   84                             }
   85                             catch { }
   86 
   87                             if (myTermSet == null || cTermGroupSets == 0) //term set not exists create now
   88                             {
   89                                 myTermSet = myTermGroup.CreateTermSet(termSetName, Guid.NewGuid(), 1033);
   90                                 if (termsList != null)
   91                                 {
   92                                     foreach (string termValue in termsList)
   93                                     {
   94                                         if (!string.IsNullOrEmpty(termValue))
   95                                             myTermSet.CreateTerm(termValue, 1033, Guid.NewGuid());
   96                                     }
   97                                 }
   98                                 clientContext.ExecuteQuery();
   99                                 LogMessages.Instance.LogMessageToTextFile(" Successfully created  term set: " + termSetName + " added terms ");
  100                             }
  101                             else //if term set already exists
  102                             {
  103                                 if (termsList != null)
  104                                 {
  105                                     foreach (string givenTermValue in termsList)
  106                                     {
  107                                         try
  108                                         {
  109                                             TermCollection myTermCollection = myTermSet.Terms;
  110                                             clientContext.Load(myTermCollection, myTC => myTC.Include(termsAlreadyInSystem => termsAlreadyInSystem.Name)); clientContext.ExecuteQuery();
  111                                             //check if given terms already exists
  112                                             bool atLeastOneTermValueNotExistsInTermSet = false;
  113 
  114                                             bool termValueAlreadyExistsWithInTermSet = false;
  115                                             foreach (Term termInShareTermSet in myTermCollection)
  116                                             {
  117                                                 if (givenTermValue.ToLower().Trim() == termInShareTermSet.Name.ToLower().Trim())
  118                                                 {
  119                                                     termValueAlreadyExistsWithInTermSet = true;
  120                                                     LogMessages.Instance.LogMessageToTextFile(" Term with name " + givenTermValue + " already exists in term set: " + termSetName);
  121                                                     break;
  122                                                 }
  123                                             }
  124                                             if (!termValueAlreadyExistsWithInTermSet) // if term not exists add now
  125                                             {
  126                                                 if (!string.IsNullOrEmpty(givenTermValue))
  127                                                     myTermSet.CreateTerm(givenTermValue, 1033, Guid.NewGuid());
  128                                                 atLeastOneTermValueNotExistsInTermSet = true;
  129                                             }
  130 
  131                                             if (atLeastOneTermValueNotExistsInTermSet)
  132                                             {
  133                                                 clientContext.ExecuteQuery();
  134                                                 LogMessages.Instance.LogMessageToTextFile(" Successfully added not existing terms to  term set: " + termSetName);
  135                                             }
  136                                         }
  137                                         catch (Exception ex)
  138                                         {
  139                                             if (ex.Message.Contains("There is already a term with the same default label and parent term"))
  140                                                 LogMessages.Instance.LogMessageToTextFile(" Term with name " + givenTermValue + " already exists in term set: " + termSetName);
  141                                             else
  142                                                 throw ex;
  143                                         }
  144                                     }
  145                                 }
  146                             }
  147                         }
  148                     }
  149                     else
  150                     {
  151                         LogMessages.Instance.LogMessageToTextFile(" Term store with name " + termStoreName + " not exists ");
  152                     }
  153                 }
  154             }
  155         }
  156     }
  157 
  158     public class ConfigurationConstants
  159     {
  160         public static string XYZLogFileLocation = @"C:\\LogFile.txt";
  161         public static string XYZSharepointSiteCollectionUrl = "http://sharepointservername:100/";
  162         public static string XYZSharepointDomain = "domainName";
  163         public static string XYZSharepointAdminUserName = "UserName";
  164         public static string XYZSharepointAdminUserPassword = "Password";
  165     }
  166     
  215 }
  216 

No comments:

Post a Comment