I am trying to set the value of a Sharepoint 2013 TaxonomyField in CSOM but when I execute the last context.ExecuteQuery()
, after taxField.Update()
, a exception is thrown that reads `A first chance exception of type 'Microsoft.SharePoint.Client.ServerException' occurred in Microsoft.SharePoint.Client.Runtime.dll Additional information: Value cannot be null. Parameter name: termId'. Everything loads fine, it finds the term and I'm out of ideas.
public void AddTaxonomyFieldValue(ClientContext context, ListItem item, string destinationColumn, IEnumerable<string> terms, Guid termGroupId, Guid termSetId, int lcid)
{
var taxonomySession = TaxonomySession.GetTaxonomySession(context);
var store = taxonomySession.TermStores.GetByName("Managed Metadata Service2");
var group = store.GetGroup(termGroupId);
var set = group.TermSets.GetById(termSetId);
var existingTerms = set.GetAllTerms();
var field = item.ParentList.Fields.GetByInternalNameOrTitle(destinationColumn);
var taxField = context.CastTo<TaxonomyField>(field);
context.Load(existingTerms, et => et.Include(t => t.Labels.Include(l => l.Value, l => l.Language), t => t.Id, t=> t.PathOfTerm, t => t));
context.ExecuteQuery();
var fieldTermValues = new Collection<Term>();
foreach (var term in terms)
{
var lmi = new LabelMatchInformation(context);
lmi.TermLabel = term;
// Find existing term
var existingTerm =
existingTerms.FirstOrDefault(t => t.Labels.Any(l => l.Language == lcid && l.Value == term));
if (null == existingTerm)
{
// create new term
existingTerm = set.CreateTerm(term, lcid, new Guid());
set.TermStore.CommitAll();
context.Load(existingTerm);
context.ExecuteQuery();
}
fieldTermValues.Add(existingTerm);
}
// set taxonomy field
taxField.SetFieldValueByCollection(item, fieldTermValues, lcid);
taxField.Update();
// Exception Thrown Here
context.ExecuteQuery();
}
EDIT 1: I just noticed that the taxonomy term I created in that foreach loop has a Unique Identifier == "00000000-0000-0000-0000-000000000000" when looking at it from the Sharepoint site. So I'm thinking my problem lies there.
I figured out my problem and it was due to a bad invalid term id being created.
In the following code
// crete new term
existingTerm = set.CreateTerm(term, lcid, new Guid());
I should be doing
existingTerm = set.CreateTerm(term, lcid, Guid.NewGuid());