Skip to main content

Update Taxonomy in SharePoint Online using CSOM

    public static void UpdateTaxonomy(ClientContext ctx, string url)
    {
        List list = ctx.Web.Lists.GetByTitle("SampleLibrary");
        var fields = list.Fields;
        var field = fields.GetByInternalNameOrTitle("Taxonomy");
        CamlQuery query = new CamlQuery();
        query.ViewXml = "@<View><Query><Where><Eq><FieldRef Name='ID' /><Value Type='Counter'>1</Value></Eq></Where></Query></View>";
        var listItems = list.GetItems(query);
        ctx.Load(list);
        ctx.Load(listItems);
        ctx.Load(fields);
        ctx.Load(field);
        ctx.ExecuteQuery();
        if (listItems.Count != 1)
        {
            return;
        }
        var item = listItems[0];
        var txField = ctx.CastTo<TaxonomyField>(field);
        var tags = new string[] { "Test1" };
        var tagsString = EnsureTerms(tags, url, list.Id, "Taxonomy", ctx);
        string[] term = tagsString.Split('|');
        string[] termLabel = term[0].Split('#');
        var termValue = new TaxonomyFieldValue();
        termValue.Label = termLabel[1];
        termValue.TermGuid = term[1];
        termValue.WssId = -1;
        txField.SetFieldValueByValue(item, termValue);
        txField.Update();
        item["FileName"] = "Ramesh Beerla";
        item.Update();
        ctx.Load(item);
        ctx.ExecuteQuery();
    }
 
    private static string EnsureTerms(string[] termStrings, string targetUrl, Guid listId, string fieldName, ClientContext clientContext)
    {
        try
        {
            //Get the List Object
            var list = clientContext.Web.Lists.GetById(listId);
            var field = list.Fields.GetByInternalNameOrTitle(fieldName);

            //Get the Taxonomy Field
            var taxKeywordField = list.Context.CastTo<TaxonomyField>(field);
            clientContext.Load(taxKeywordField);
            clientContext.ExecuteQuery();
            clientContext.Load(taxKeywordField, f => f.TermSetId, f => f.SspId);
            clientContext.ExecuteQuery();

            //From the TaxonomyField, get the TermSetID in which we are going to create the Terms.
            var ssspId = taxKeywordField.SspId;
            var termSetId = taxKeywordField.TermSetId;

            //Get the TAxonomy Session
            var taxSession = TaxonomySession.GetTaxonomySession(clientContext);
            clientContext.Load(taxSession);
            clientContext.ExecuteQuery();

            //Get the TermStore
            var termStores = taxSession.TermStores;
            clientContext.LoadQuery(termStores.Where(t => t.Id == ssspId));
            clientContext.Load(termStores);
            clientContext.ExecuteQuery();

            var termStore = termStores.FirstOrDefault(s => s.Id == ssspId);
            clientContext.Load(termStore);
            clientContext.ExecuteQuery();

            //Get the TermSet
            var termSet = termStore.GetTermSet(termSetId);

            var allTerms = new List<Term>();

            Func<string, Term> EnsureTerm = (term) =>
            {
                try
                {
                    var allTermsInTermSet = termSet.GetAllTerms();
                    var results = clientContext.LoadQuery(allTermsInTermSet.Where(k => k.Name == term));
                    clientContext.ExecuteQuery();

                    if (results != null)
                    {
                        var result = results.FirstOrDefault();
                        if (result != null)
                        {
                            clientContext.Load(result, t => t.Name, t => t.Id);
                            clientContext.ExecuteQuery();
                            return result;
                        }
                    }

                    clientContext.Load(termSet);
                    clientContext.ExecuteQuery();
                    var newTerm = termSet.CreateTerm(term, termStore.DefaultLanguage, Guid.NewGuid());
                    termStore.CommitAll();
                    clientContext.Load(newTerm);
                    clientContext.Load(newTerm, t => t.Name, t => t.Id);
                    clientContext.ExecuteQuery();

                    return newTerm;
                }
                catch (Exception ex)
                {
                    if (ex.Message == "The data is not available. The query may not have been executed.")
                    {

                        clientContext.Load(termSet);

                        clientContext.ExecuteQuery();
                        var newTerm = termSet.CreateTerm(term, termStore.DefaultLanguage, Guid.NewGuid());
                        clientContext.Load(newTerm);
                        termStore.CommitAll();
                        clientContext.Load(newTerm);
                        clientContext.ExecuteQuery();
                        clientContext.Load(newTerm, t => t.Name, t => t.Id);
                        clientContext.ExecuteQuery();
                        return newTerm;

                    }
                    else
                    {


                        throw;
                    }
                }
            };

            foreach (string termString in termStrings)
            {
                try
                {
                    Thread.Sleep(1000);
                    if (termString != null)
                    {
                        allTerms.Add(EnsureTerm(termString));
                    }
                }
                catch (Exception)
                {
                    // Log the Exception
                }
            }

            return GetTermsString(allTerms);
        }
        catch (Exception ex)
        {
            //Log the Exception
        }

        return string.Empty;
    }

    public static string GetTermString(Term term)
    {

        if (term == null)
        {
            new ArgumentNullException("term");
        }


        return string.Format("-1;#{0}{1}{2}", term.Name, "|", term.Id);
    }

    public static string GetTermsString(IEnumerable<Term> terms)
    {
        if (terms == null)
        {
            new ArgumentNullException("terms");
        }

        var termsString = terms.Select(GetTermString).ToList();
        return string.Join(";#", termsString);
    }

Comments

Popular posts from this blog

Key Limitations of Microsoft Power Automate (as of August 2025)

Microsoft Power Automate is a powerful tool for automating business processes, but like any platform, it comes with a set of limitations. Understanding these constraints is essential to designing efficient, scalable, and compliant workflows—especially as your automation strategy grows in complexity.  Here are the most important limits you need to know:  1. Switch Cases Each Switch action supports a maximum of 25 cases. If you need more, consider using nested Switches or alternate logic like parallel branches or conditionals.  2. Actions per Workflow A single flow can contain up to 500 actions. For complex workflows, you may need to split logic into separate flows or use child flows to stay within this limit.  3. Nesting Depth You can nest actions (e.g., conditionals or loops) up to 8 levels deep. Going beyond this will result in a design error.  4. Variables per Flow Each flow can define up to 250 variables. This includes all variable types (string, inte...

Bulk Import Excel Data to SharePoint List Using PowerShell and PnP

  Managing large datasets in SharePoint can be tricky, especially when you're dealing with Excel files and need to avoid list view threshold issues. In this guide, I’ll walk you through a PowerShell script that efficiently imports data from Excel into a SharePoint Online list using PnP PowerShell — with batching support for performance. Prerequisites Make sure you have the following before running the script: SharePoint Online site URL Excel file with data properly formatted PnP PowerShell module installed ( Install-Module PnP.PowerShell ) Appropriate SharePoint permissions What the Script Does Connects to your SharePoint site Loads and reads an Excel file Converts Excel date values Batches records in groups (to avoid the 5000 item threshold) Adds the items to your SharePoint list or library Logs execution time PowerShell Script $siteUrl = "[Site Collection URL]" Connect-PnPOnline -Url $siteUrl -UseWebLogin # Capture the start time $startTime...

Enable or Disable the Social Bar (Like, Views, Save for later) in SharePoint at tenant level

SharePoint Online provides various social features in modern experience SharePoint sites. One of the features available for SharePoint site pages is the social bar (Like, No. of Comments, Views, Save for later), which is situated at the bottom of site pages. Social bar allows users to engage with page content by liking and saving pages for later reference. Social bar also shows the number of page views and comments on modern site pages. However, organizations may have specific requirements that necessitate enabling or disabling the social bar on SharePoint site pages. Unfortunately, there are no settings available for enabling/disabling social bar using SharePoint user interface. In this blog post, we will explore how to achieve this at SharePoint tenant level using SharePoint Online PowerShell, PnP PowerShell and CLI for Microsoft 365 scripts. Using SharePoint Online PowerShell Use below SharePoint Online PowerShell script to enable or disable the social bar from site pages for all Sh...