Manipulate Taxonomy objects using SharePoint 2013 Client Object Model

SharePoint 2013 Client Object model has the capability to manipulate (Create/Read/Update/Delete) Taxonomy objects like TermGroup, TermSets and Terms etc.This is one of major improvement in SharePoint 2013. The objective of this post is to setup a sample Taxonomy and manipulate it using SharePoint 2013 Client Object Model.

For the purpose of the demonstration, i’m using my development tenant in Office 365 preview site

My dev tenant url is https://smartguru.sharepoint.com. You can sign-up for you own Office 365 preview site here

Pic1[4]

I’ve already created a Taxonomy group called ‘Pharma Taxonomies’ with the termsets like Cardiology, Opthalmalogy and Paediatrics.  I’ll be leveraging the Client Object Model of SharePoint 2013 to add terms under under these Term Sets.

I’ve created a C# windows application having set of textboxes to acquire the values for TermSets and Terms.

pic2

Performing active authentication to Office 365 and SharePoint Online

When the code-behind of the above form tries to access Office 365 developer preview site, it will not get the ClientContext by default. We need to perform active authentication to SharePoint online in Office 365. My fellow MVP Wictor Wilen wrote an excellent blog post on How to do active authentication to Office 365 and SharePoint Online. I’d be leveraging the logic provided  in this post and also the Code Snippet to complete the active authentication and get the ClientContext of my Office 365 developer preview site.

 

I’d be posting the code-behind of the above windows form in a short while. The logic inside this form is simple, i delete the TermSets (if it exists already), create the TermSets programmatically and create appropriate Terms under the TermSets.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Microsoft.SharePoint.Client;
using Microsoft.SharePoint.Client.Taxonomy;
using Microsoft.SharePoint.Client.Publishing.Navigation;
using System.Net;
using System.Security;
using System.Globalization;


namespace TaxonomyClientSideOM
{
    public partial class Form1 : System.Windows.Forms.Form
    {
        public Form1()
        {
            InitializeComponent();

            textBox1.Text = "Pharma Term Group";
            
            textBox2.Text = "Opthalamalogy";
            textBox6.Text = "Cardiology";
            textBox10.Text = "Pediatrics";

            textBox3.Text = "ContactLens";
            textBox4.Text = "LasikSurgery";
            textBox5.Text = "Cataract";

            textBox9.Text = "CalciumChannelBlockers";
            textBox8.Text = "BetaBlockers";
            textBox7.Text = "Amlodipine";

            textBox13.Text = "PneumoCoccal";
            textBox12.Text = "Dpt";
            textBox11.Text = "Typhoid";
           
        }
     

        private static void SetPropertiesforTermSets(TermSet termSet1, string Description)
        {
            termSet1.IsAvailableForTagging = true;
            termSet1.Description = Description;
            termSet1.Owner = "lavsunswe@smartguru.onmicrosoft.com";
        }

        private static void DeleteTermSets(ClientContext context, TermStore termStore, string sGuid)
        {
            TermSet existingTermSet;

            // Handles an error that occurs if the return value is null.
            ExceptionHandlingScope exceptionScope = new ExceptionHandlingScope(context);
            using (exceptionScope.StartScope())
            {
                using (exceptionScope.StartTry())
                {
                    existingTermSet = termStore.GetTermSet(new Guid(sGuid));

                }
                using (exceptionScope.StartCatch())
                {
                }
            }
            context.ExecuteQuery();

            if (!existingTermSet.ServerObjectIsNull.Value)
            {
                MessageBox.Show(" Deleting old TermSet");
                existingTermSet.DeleteObject();
                termStore.CommitAll();
                context.ExecuteQuery();

                MessageBox.Show("Deleted Old Term Set");
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            Uri oUri = new Uri("https://smartguru.sharepoint.com");

            Office365ClaimsHelper claimsHelper = new Office365ClaimsHelper(oUri, "youruserid", "yourpassword");
                        using (ClientContext context = new ClientContext(oUri))
            {
                context.ExecutingWebRequest += claimsHelper.clientContext_ExecutingWebRequest;

                TaxonomySession taxonomySession = TaxonomySession.GetTaxonomySession(context);
                taxonomySession.UpdateCache();

                context.Load(taxonomySession, ts => ts.TermStores);
                context.ExecuteQuery();

                if (taxonomySession.TermStores.Count == 0)
                    throw new InvalidOperationException("The Taxonomy Service is offline or missing");

                TermStore termStore = taxonomySession.TermStores[0];
                context.Load(termStore,
                ts => ts.Name,
                ts => ts.WorkingLanguage);


                //Delete Opthalamalogy Term Set if already existing
                DeleteTermSets(context, termStore, "DB5FAD84-8868-433A-A18A-79B214F8DA00");

                //Delete Cardiology TermSet if already existing
                DeleteTermSets(context, termStore, "4D5493E6-FF8F-4CDF-931B-965920A7789D");

                //Delete Pediatrics if already existing
                DeleteTermSets(context, termStore, "34CE7966-17E3-404C-ADBF-7B267A319F59");


                //Fetch the Pharma Term Group if already existing
                TermGroup siteCollectionGroup = termStore.GetGroup(new Guid("5c041ce0-f499-47f2-bff1-28f01b743bad"));

                CreateTermSets(termStore, siteCollectionGroup, context);
                                
                 termStore.CommitAll();
                context.ExecuteQuery();

                MessageBox.Show("Success");
                               
            }          


        }

        private void CreateTermSets(TermStore termStore, TermGroup siteCollectionGroup, ClientContext context)
        {
            TermSet termSet1 = siteCollectionGroup.CreateTermSet(textBox2.Text, new Guid("DB5FAD84-8868-433A-A18A-79B214F8DA00"),
         termStore.WorkingLanguage);
            SetPropertiesforTermSets(termSet1, "This is " + textBox2.Text + "termset");
            CreateNewTerms(termStore, termSet1, textBox3.Text, "5BDD72EF-822C-4E79-A1E6-0D838E68ADE7");
            CreateNewTerms(termStore, termSet1, textBox4.Text, "4BDBC3B5-0BA5-4049-BB07-DAFA119799C9");
            CreateNewTerms(termStore, termSet1, textBox5.Text, "D70E624A-DD03-4E5C-B946-B40EFD4EAEEC");

            TermSet termSet2 = siteCollectionGroup.CreateTermSet(textBox6.Text, new Guid("4D5493E6-FF8F-4CDF-931B-965920A7789D"),
        termStore.WorkingLanguage);
            SetPropertiesforTermSets(termSet2, "This is " + textBox6.Text + "termset");

            CreateNavigationTermSet(context, termSet2, "http://en.wikipedia.org/wiki/Beta_blocker", textBox9.Text);
            CreateNavigationTermSet(context, termSet2, "http://en.wikipedia.org/wiki/Calcium_channel_blocker", textBox8.Text);
            CreateNavigationTermSet(context, termSet2, "http://en.wikipedia.org/wiki/Amlodipine", textBox7.Text);

            TermSet termSet3 = siteCollectionGroup.CreateTermSet(textBox10.Text, new Guid("34CE7966-17E3-404C-ADBF-7B267A319F59"),
        termStore.WorkingLanguage);
            SetPropertiesforTermSets(termSet3, "This is " + textBox10.Text + "termset");
            CreateNewTerms(termStore, termSet3, textBox13.Text, "7B65ED31-25D4-4697-9B63-497411F358A5");
            CreateNewTerms(termStore, termSet3, textBox12.Text, "48A33AEE-85D1-4AC7-B413-69E580058F8D");
            CreateNewTerms(termStore, termSet3, textBox11.Text, "715EA04A-B547-46B8-84BE-D0BEB663FB36");
        }

        private void CreateNavigationTermSet(ClientContext context, TermSet termSet2, string navurl, string termname)
        {
            NavigationTermSet navTermSet = NavigationTermSet.GetAsResolvedByWeb(context,
                termSet2, context.Web, "GlobalNavigationTaxonomyProvider");

            navTermSet.IsNavigationTermSet = true;
            navTermSet.TargetUrlForChildTerms.Value = "~site/Pages/Topics.aspx";

            NavigationTerm navterm = navTermSet.CreateTerm(termname, NavigationLinkType.SimpleLink, Guid.NewGuid());
            navterm.SimpleLinkUrl = navurl;



        }

        private static void CreateNewTerms(TermStore termStore, TermSet oTermSet, string termname, string guidstring)
        {
            Term oTerm = oTermSet.CreateTerm(termname, termStore.WorkingLanguage, new Guid(guidstring));
            oTerm.Owner = "abc@smartguru.onmicrosoft.com";
            oTerm.IsAvailableForTagging = true;

        }       

    }
}

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, “Courier New”, courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

To compile the above code, you need reference to the following assemblies.

Microsoft.SharePoint.Client.dll

Microsoft.SharePoint.Client.Runtime.dll

Microsoft.SharePoint.Client.Publishing.dll

Microsoft.SharePoint.Client.Taxonomy.dll

System.ServiceModel.dll

To keep the demonstration simple, i leave the default values for the textboxes in the above form and hit ‘Create Termsets and Terms’ button. It creates the following taxonomy terms in my Office 365 preview taxonomy store.

pic4

The entire source code is available for download in SkyDrive

 Subscribe to my blog

One thought on “Manipulate Taxonomy objects using SharePoint 2013 Client Object Model

  1. Pingback: Manipulate Taxonomy objects using SharePoint 2013 Client Object Model - My experiments with SharePoint, Azure and .NET using Visual Studio

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.