Sunday, June 7, 2020

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);
    }

No comments:

Post a Comment