Skip to content

Instantly share code, notes, and snippets.

@vgrem
Last active August 29, 2015 14:13
Show Gist options
  • Save vgrem/46b1cded91a79da088bf to your computer and use it in GitHub Desktop.
Save vgrem/46b1cded91a79da088bf to your computer and use it in GitHub Desktop.
Enterprise Keywords management via SharePoint CSOM
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.SharePoint.Client;
using Microsoft.SharePoint.Client.Taxonomy;
namespace SharePoint.Client.Taxonomy
{
/// <summary>
/// Enterpise Keyword Manager
/// </summary>
public class KeywordsManager
{
/// <summary>
/// Set Enterprise Keyword Value
/// </summary>
/// <param name="item">List Item</param>
/// <param name="values">Keyword values</param>
public static void SetTaxKeywordValue(ListItem item,string[] values)
{
var ctx = item.Context;
var list = item.ParentList;
var field = list.Fields.GetByInternalNameOrTitle(TaxKeywordFieldName);
var taxKeywordField = ctx.CastTo<TaxonomyField>(field);
var keywords = values.Select(value => EnsureKeyword(taxKeywordField, value)).ToList();
taxKeywordField.SetFieldValueByValueCollection(item, new TaxonomyFieldValueCollection(ctx, GetTermsString(keywords), taxKeywordField));
}
/// <summary>
/// Ensure Keyword
/// </summary>
/// <param name="taxField"></param>
/// <param name="name"></param>
/// <returns></returns>
private static Term EnsureKeyword(TaxonomyField taxField, string name)
{
var ctx = taxField.Context;
var taxSession = TaxonomySession.GetTaxonomySession(ctx);
var termStore = taxSession.GetDefaultKeywordsTermStore();
var keywords = termStore.KeywordsTermSet.GetAllTerms();
var result = ctx.LoadQuery(keywords.Where(k => k.Name == name));
ctx.ExecuteQuery();
var keyword = result.FirstOrDefault();
if (keyword != null)
{
return keyword;
}
keyword = termStore.KeywordsTermSet.CreateTerm(name, DefaultLanguage, Guid.NewGuid());
ctx.Load(keyword);
ctx.ExecuteQuery();
return keyword;
}
/// <summary>
/// Retrieve formatted Term string
/// </summary>
/// <param name="term"></param>
/// <returns></returns>
private static string GetTermString(Term term)
{
return string.Format("-1;#{0}{1}{2}", term.Name, TaxonomyGuidLabelDelimiter,term.Id);
}
private static string GetTermsString(IEnumerable<Term> terms)
{
var termsString = terms.Select(GetTermString).ToList();
return string.Join(";#", termsString);
}
private const string TaxKeywordFieldName = "TaxKeyword";
private const int DefaultLanguage = 1033;
private const string TaxonomyGuidLabelDelimiter = "|";
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment