Thursday, 27 July 2017

SharePoint Online / Office 365 - Exporting All the Terms from Particular TermSet in .CSV file using CSOM and console application

Hi All,

In this article I’ll explain how to export term sets in .CSV file using CSOM and console application.  


There are multiple approaches to export the terms from given TermSet either using PowerShell + CSOM or using CSOM in console application. In one of my previous article "SharePointOnline / Office 365 : Exporting All The Terms From Particular TermSet In .csvfile Using CSOM & PowerShell" I explained how to export the TermSet using CSOM + PowerShell. 

In this article I’ll go through step by step for exporting TermSet using CSOM in console application.

There is no as such difference in both the approaches but if we want to make it more configurable (like configuration in .config file, for ex. – TermStore name or specific TermSet name etc. ) then Console Application approach is preferable.

I have my trial Office 365 account and term store manager page looks like, created three terms (IT, HR and Finance) in OOB term set “Department” under “People” group:

So in our console application we will export the above three terms created under “Department” term set in “People” group in default term store (since there only one termstore).

Step 1: Get the required details from config file (App.config) and connecting to Office 365:

In last article “Office365 / SharePoint Online - Connecting Office 365 / SharePoint Online Site UsingCSOM (Client Object Model)” I have given detailed steps to connect Office 365 through CSOM and Console Application. Please have a look once. Following is the code snippet for this step:

       #region Site Details - Read the details from config file
            string siteURL = ConfigurationManager.AppSettings["siteURL"];
            string userName = ConfigurationManager.AppSettings["userName"];
            string password = ConfigurationManager.AppSettings["password"];
            //Path where we need to create the .CSV file
            string csvFilePath = ConfigurationManager.AppSettings["csvfilepath"];
       #endregion

#region Connect To O365

            //Create the client context object and set the credentials
//Create the client context object and set the credentials
              ClientContext clientContext = new ClientContext(siteURL);
       SecureString securePassword = new SecureString();

foreach (char c in password.ToCharArray())    
              securePassword.AppendChar(c);

                     clientContext.Credentials = new   
                     SharePointOnlineCredentials(userName, securePassword);
        #endregion

Step 3: Get the Terms from respective TermSet : To read the Terms from respective TermSet we need to get the reference for following objects

1.       TaxonomySession : This object is the initial point for all taxonomy operations. Get reference to the TaxonomySession object as

TaxonomySession taxonomysession = TaxonomySession.GetTaxonomySession(clientContext);

2.       TermStore : Get reference to default TermStore object. Once we have TaxonomySession class, we will get the default term store as  

TermStore termStore = taxonomysession.GetDefaultSiteCollectionTermStore();

3.       TermGroupCollection : We will fetch all the groups (TermGroupCollection) from TermStore object as
                TermGroupCollection groupCollection = termStore.Groups;
                clientContext.Load(groupCollection);
                clientContext.ExecuteQuery();

4.       TermGroup : Then get the reference to the TermGroup object in which our TermSet is created, here we are fetching the terms from the term set which is created under group “People” as

TermGroup termGroup = groupCollection.GetByName("People");
clientContext.Load(termGroup);
clientContext.ExecuteQuery();

5.       TermSet : From termGroup object we will read our “Department” term set as

TermSet termSet = termGroup.TermSets.GetByName("Department");
clientContext.Load(termSet);
clientContext.ExecuteQuery();

6.       TermCollection : We have our term set ready, get all terms in it using TermCollection object as

TermCollection departmentTerms = termSet.Terms;
                       clientContext.Load(departmentTerms);
                       clientContext.ExecuteQuery();

Step 4: Write terms to .CSV file : Since now we have all “Department” terms, we will write them to .CSV file.  To write into .CSV file we will need array of string and we will use Syste.IO.File object as
ArrayList termsArrayList = new ArrayList(departmentTerms.Count);

              foreach (Term term in departmentTerms)
              {
                 termsArrayList.Add(term.Name);
              }

                             //Writing to .CSV file as path specified in .config file.
System.IO.File.WriteAllLines(csvFilePath,           (string[])termsArrayList.ToArray(typeof(string)));


Complete Code:

using Microsoft.SharePoint.Client;
using Microsoft.SharePoint.Client.Taxonomy;
using System;
using System.Collections;
using System.Configuration;
using System.Security;

namespace CSOM_ExportTermSets
{
    class Program
    {
        static void Main(string[] args)
        {
            #region Site Details - Read the details from config file
            string siteURL = ConfigurationManager.AppSettings["siteURL"];
            string userName = ConfigurationManager.AppSettings["userName"];
            string password = ConfigurationManager.AppSettings["password"];
            //Path where we need to create the .CSV file
            string csvFilePath = ConfigurationManager.AppSettings["csvfilepath"];
            #endregion

            #region ConnectTo O365

            //Create the client context object and set the credentials
            ClientContext clientContext = new ClientContext(siteURL);
            SecureString securePassword = new SecureString();

            foreach (char c in password.ToCharArray()) securePassword.AppendChar(c);

clientContext.Credentials = new SharePointOnlineCredentials(userName, securePassword);

            #endregion

            #region Get the Terms

TaxonomySession taxonomysession = TaxonomySession.GetTaxonomySession(clientContext);
    
            if (taxonomysession != null)
            {
 TermStore termStore = taxonomysession.GetDefaultSiteCollectionTermStore();
                if (termStore != null)
                {
                    TermGroupCollection groupCollection = termStore.Groups;
                    clientContext.Load(groupCollection);
                    clientContext.ExecuteQuery();

                    TermGroup termGroup = groupCollection.GetByName("People");
                    TermSet termSet = termGroup.TermSets.GetByName("Department");

                    clientContext.Load(termGroup);
                    clientContext.Load(termSet);
                    clientContext.ExecuteQuery();

                    TermCollection departmentTerms = termSet.Terms;
                    clientContext.Load(departmentTerms);
                    clientContext.ExecuteQuery();

                    ArrayList termsArrayList = new ArrayList(departmentTerms.Count);

                    foreach (Term term in departmentTerms)
                    {
                        termsArrayList.Add(term.Name);
                    }

                    //Writting to .CSV file as path specified in .config file.
System.IO.File.WriteAllLines(csvFilePath, (string[])termsArrayList.ToArray(typeof(string)));

Console.WriteLine("Terms are written in .CSV file. Please hit the any key to exit the console");
                    Console.ReadKey();
                }//if (termStore != null)
            }//if (taxonomysession != null)
            #endregion
        }//main
    }//cs
}//ns

Thanks!

Enjoy Reading :)

As usual any feedback / query / suggestions are most welcome!!!