I'm attempting to set the enterprise keywords field of a document library and it's not working.
I've been at this for days trying to find out what I was missing, which is obviously very frustrating.
All other managed metadata fields can be set, so thats not the issue.
No error is thrown.
On LISTS the following code works like a charm, but even with a newly created document library the enterprise keywords will not update. Please help !
The code I've been using to try to figure out this problem is as follows, it works on lists but not libraries:
SPSite sp = new SPSite("http://myserver");
var web = sp.OpenWeb();
var tax = new TaxonomySession(sp);
// my document list
var list = web.Lists["myfrickingdocuments"];
// hidden list to get wssid's
var hidden = web.Lists["TaxonomyHiddenList"];
//enterprise keywords field
var field1 = list.Fields.GetFieldByInternalName("TaxKeyword") as TaxonomyField;
var field2 = list.Fields.GetFieldByInternalName("TaxKeywordTaxHTField");
// grabs the already populated keywords termset (previous code added all the taxonomy terms)
// then grabs the first term.
var atermset = tax.TermStores[0].GetTermSet(field1.TermSetId);
var aterm = atermset.Terms[0];
// grab the existing term from the taxonomy hiddenlist
var firstterm =
hidden.Items.Cast<SPListItem>().
Where(o =>o["IdForTerm"].ToString().Equals(aterm.Id.ToString())).FirstOrDefault();
// loop through all the items in the list and set the same enterprise keywords values
// just to test the concept
for (int x = 0; x < list.Items.Count; x++)
{
var item = list.Items[x];
// get the term label in english
string termlabel = aterm.GetDefaultLabel(1033);
// create the taxonomy field value
var termfield = new TaxonomyFieldValue(firstterm["ID"].ToString()+ ";#" + aterm.Name,field1);
// set the enterprise keyword fields
item[field1.Id] = termfield;
item[field2.Id] = aterm.Name + "|" + aterm.Id.ToString();
// update the data in sp
item.SystemUpdate();
}