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

Get App Expiry Dates using Powershell

Step 1: Connect-MsolService Step 2: $applist = Get-MsolServicePrincipal -all  |Where-Object -FilterScript { ($_.DisplayName -notlike "*Microsoft*") -and ($_.DisplayName -notlike "autohost*") -and  ($_.ServicePrincipalNames -notlike "*localhost*") } Step 3: foreach ($appentry in $applist) {     $principalId = $appentry.AppPrincipalId     $principalName = $appentry.DisplayName     Get-MsolServicePrincipalCredential -AppPrincipalId $principalId -ReturnKeyValues $false | ? { $_.Type -eq "Password" } | % { "$principalName;$principalId;" + $_.KeyId.ToString() +";" + $_.StartDate.ToString() + ";" + $_.EndDate.ToString() } | out-file -FilePath d:\appsec.txt -append }

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...

🚀 Essential SPFx (SharePoint Framework) Commands for Every Developer

Whether you're new to SharePoint Framework (SPFx) or a seasoned pro, having a go-to list of core commands can significantly improve your development workflow. In this post, we'll walk through the most important SPFx CLI commands—from setting up your environment to packaging and deploying your solution. 🛠️ Setting Up Your SPFx Project Start by scaffolding a new project using the Yeoman generator provided by Microsoft. Make sure Node.js and npm are installed before you proceed. yo @microsoft/sharepoint After scaffolding the project, install all dependencies: npm install To update dependencies later: npm update 🔐 Trusting the Development Certificate If you're using the local workbench, you need to trust the developer certificate for HTTPS support: gulp trust-dev-cert 🧪 Running the Local Workbench To build and serve your project locally, use: gulp serve This command starts a local server at: https://localhost:4321/temp/workbench.html You can also test your solution in ShareP...