public static void SetTaxonomyFieldValue(this ListItem item, Guid fieldId, string label, Guid termGuid) { ClientContext clientContext = item.Context as ClientContext; List list = item.ParentList; clientContext.Load(list); clientContext.ExecuteQuery(); IEnumerable <Field> fieldQuery = clientContext.LoadQuery( list.Fields .Include( fieldArg => fieldArg.TypeAsString, fieldArg => fieldArg.Id, fieldArg => fieldArg.InternalName ) ).Where(fieldArg => fieldArg.Id == fieldId); clientContext.ExecuteQuery(); TaxonomyField taxField = fieldQuery.Cast <TaxonomyField>().FirstOrDefault(); clientContext.Load(taxField); clientContext.ExecuteQuery(); TaxonomyFieldValue fieldValue = new TaxonomyFieldValue(); fieldValue.Label = label; fieldValue.TermGuid = termGuid.ToString(); fieldValue.WssId = -1; taxField.SetFieldValueByValue(item, fieldValue); item.Update(); clientContext.ExecuteQuery(); }
/// <summary> /// Helper Method to set a Taxonomy Field on a list item /// </summary> /// <param name="ctx">The Authenticated ClientContext</param> /// <param name="listItem">The listitem to modify</param> /// <param name="model">Domain Object of key/value pairs of the taxonomy field & value</param> public static void SetTaxonomyField(ClientContext ctx, ListItem listItem, Hashtable model) { FieldCollection _fields = listItem.ParentList.Fields; ctx.Load(_fields); ctx.ExecuteQuery(); foreach (var _key in model.Keys) { var _termName = model[_key].ToString(); TaxonomyField _field = ctx.CastTo <TaxonomyField>(_fields.GetByInternalNameOrTitle(_key.ToString())); ctx.Load(_field); ctx.ExecuteQuery(); Guid _id = _field.TermSetId; string _termID = AutoTaggingHelper.GetTermIdByName(ctx, _termName, _id); var _termValue = new TaxonomyFieldValue() { Label = _termName, TermGuid = _termID, WssId = -1 }; _field.SetFieldValueByValue(listItem, _termValue); listItem.Update(); ctx.ExecuteQuery(); } }
private static void SetMetadataField(ClientContext ctx, ListItem item, string term) { List sitePagesList = ctx.Web.Lists.GetByTitle("Site Pages"); Field field = sitePagesList.Fields.GetFieldByInternalName("IndboManualCategory"); ctx.Load(field); ctx.ExecuteQuery(); TaxonomyField txField = ctx.CastTo <TaxonomyField>(field); string termId = GetTermIdForTerm(term, txField.TermSetId, ctx); if (!string.IsNullOrEmpty(termId)) { TaxonomyFieldValue termValue = new TaxonomyFieldValue(); termValue.Label = term; termValue.TermGuid = termId; termValue.WssId = -1; txField.SetFieldValueByValue(item, termValue); } }
protected override void ExecuteCmdlet() { List list = null; if (List != null) { list = List.GetList(SelectedWeb); } if (list != null) { var item = Identity.GetListItem(list); if (ContentType != null) { ContentType ct = null; if (ContentType.ContentType == null) { if (ContentType.Id != null) { ct = SelectedWeb.GetContentTypeById(ContentType.Id, true); } else if (ContentType.Name != null) { ct = SelectedWeb.GetContentTypeByName(ContentType.Name, true); } } else { ct = ContentType.ContentType; } if (ct != null) { ct.EnsureProperty(w => w.StringId); item["ContentTypeId"] = ct.StringId; item.Update(); ClientContext.ExecuteQueryRetry(); } } if (Values != null) { var fields = ClientContext.LoadQuery(list.Fields.Include(f => f.InternalName, f => f.Title, f => f.TypeAsString)); ClientContext.ExecuteQueryRetry(); Hashtable values = Values ?? new Hashtable(); foreach (var key in values.Keys) { var field = fields.FirstOrDefault(f => f.InternalName == key as string || f.Title == key as string); if (field != null) { switch (field.TypeAsString) { case "User": case "UserMulti": { List <FieldUserValue> userValues = new List <FieldUserValue>(); var value = values[key]; if (value == null) { goto default; } if (value.GetType().IsArray) { foreach (var arrayItem in (value as IEnumerable)) { int userId; if (!int.TryParse(arrayItem.ToString(), out userId)) { var user = SelectedWeb.EnsureUser(arrayItem as string); ClientContext.Load(user); ClientContext.ExecuteQueryRetry(); userValues.Add(new FieldUserValue() { LookupId = user.Id }); } else { userValues.Add(new FieldUserValue() { LookupId = userId }); } } item[key as string] = userValues.ToArray(); } else { int userId; if (!int.TryParse(value as string, out userId)) { var user = SelectedWeb.EnsureUser(value as string); ClientContext.Load(user); ClientContext.ExecuteQueryRetry(); item[key as string] = new FieldUserValue() { LookupId = user.Id }; } else { item[key as string] = new FieldUserValue() { LookupId = userId }; } } #if !ONPREMISES item.SystemUpdate(); #else item.Update(); #endif break; } case "TaxonomyFieldType": case "TaxonomyFieldTypeMulti": { var value = Values[key]; if (value != null && value.GetType().IsArray) { var taxSession = ClientContext.Site.GetTaxonomySession(); var terms = new List <KeyValuePair <Guid, string> >(); foreach (var arrayItem in value as object[]) { TaxonomyItem taxonomyItem; Guid termGuid; if (!Guid.TryParse(arrayItem as string, out termGuid)) { // Assume it's a TermPath taxonomyItem = ClientContext.Site.GetTaxonomyItemByPath(arrayItem as string); } else { taxonomyItem = taxSession.GetTerm(termGuid); ClientContext.Load(taxonomyItem); ClientContext.ExecuteQueryRetry(); } terms.Add(new KeyValuePair <Guid, string>(taxonomyItem.Id, taxonomyItem.Name)); } TaxonomyField taxField = ClientContext.CastTo <TaxonomyField>(field); taxField.EnsureProperty(tf => tf.AllowMultipleValues); if (taxField.AllowMultipleValues) { var termValuesString = String.Empty; foreach (var term in terms) { termValuesString += "-1;#" + term.Value + "|" + term.Key.ToString("D") + ";#"; } termValuesString = termValuesString.Substring(0, termValuesString.Length - 2); var newTaxFieldValue = new TaxonomyFieldValueCollection(ClientContext, termValuesString, taxField); taxField.SetFieldValueByValueCollection(item, newTaxFieldValue); #if !ONPREMISES item.SystemUpdate(); #else item.Update(); #endif ClientContext.ExecuteQueryRetry(); } else { WriteWarning($@"You are trying to set multiple values in a single value field. Skipping values for field ""{field.InternalName}"""); } } else { Guid termGuid = Guid.Empty; var taxSession = ClientContext.Site.GetTaxonomySession(); TaxonomyItem taxonomyItem = null; if (value != null && !Guid.TryParse(value as string, out termGuid)) { // Assume it's a TermPath taxonomyItem = ClientContext.Site.GetTaxonomyItemByPath(value as string); } else { if (value != null) { taxonomyItem = taxSession.GetTerm(termGuid); ClientContext.Load(taxonomyItem); ClientContext.ExecuteQueryRetry(); } } TaxonomyField taxField = ClientContext.CastTo <TaxonomyField>(field); TaxonomyFieldValue taxValue = new TaxonomyFieldValue(); if (taxonomyItem != null) { taxValue.TermGuid = taxonomyItem.Id.ToString(); taxValue.Label = taxonomyItem.Name; taxField.SetFieldValueByValue(item, taxValue); } else { taxField.ValidateSetValue(item, null); } } #if !ONPREMISES item.SystemUpdate(); #else item.Update(); #endif break; } case "Lookup": case "LookupMulti": { var value = values[key]; if (value == null) { goto default; } int[] multiValue; if (value is Array) { var arr = (object[])values[key]; multiValue = new int[arr.Length]; for (int i = 0; i < arr.Length; i++) { multiValue[i] = int.Parse(arr[i].ToString()); } } else { string valStr = values[key].ToString(); multiValue = valStr.Split(',', ';').Select(int.Parse).ToArray(); } var newVals = multiValue.Select(id => new FieldLookupValue { LookupId = id }).ToArray(); FieldLookup lookupField = ClientContext.CastTo <FieldLookup>(field); lookupField.EnsureProperty(lf => lf.AllowMultipleValues); if (!lookupField.AllowMultipleValues && newVals.Length > 1) { throw new Exception("Field " + field.InternalName + " does not support multiple values"); } item[key as string] = newVals; #if !ONPREMISES item.SystemUpdate(); #else item.Update(); #endif break; } default: { item[key as string] = values[key]; #if !ONPREMISES item.SystemUpdate(); #else item.Update(); #endif break; } } } else { throw new Exception("Field not present in list"); } } #if !ONPREMISES if (SystemUpdate) { item.SystemUpdate(); } else { item.Update(); } #else item.Update(); #endif ClientContext.Load(item); ClientContext.ExecuteQueryRetry(); } WriteObject(item); } }
// This function reads the CSV file and applies the tags to the // taxonomy fields in the SharePoint list static void ImportTemplate(List list, List <TaxonomyField> taxonomyFields) { // Load TermSet for each field Dictionary <string, TermSetLookup> termSetsByInternalName = GetTermSetsByInternalName(taxonomyFields); // Load the Excel file Dictionary <string, ExcelRow> excelRowsByUrl = GetExcelRowsByUrl(termSetsByInternalName); // STEP 3: Update the list items List <string> fieldNames = taxonomyFields.Select(f => f.InternalName).ToList(); fieldNames.Add("ServerUrl"); ProcessListItems(list, fieldNames, delegate(ListItem listItem) { // Does the CSV file contain a row matching this list item? ExcelRow excelRow; if (!excelRowsByUrl.TryGetValue((string)listItem["ServerUrl"], out excelRow)) { return; // no it does not } excelRow.Processed = true; bool updated = false; foreach (KeyValuePair <string, Guid> pair in excelRow.Pairs) { TaxonomyField taxonomyField = taxonomyFields.First(f => f.InternalName == pair.Key); TaxonomyFieldValue taxonomyFieldValue = new TaxonomyFieldValue(); // (to clear the tag, you would specify the empty GUID here) taxonomyFieldValue.TermGuid = pair.Value.ToString(); TaxonomyFieldValue oldValue = (TaxonomyFieldValue)listItem.FieldValues[taxonomyField.InternalName]; if (oldValue == null || oldValue.TermGuid != taxonomyFieldValue.TermGuid) { taxonomyField.SetFieldValueByValue(listItem, taxonomyFieldValue); updated = true; } } if (updated) { Log("Updating item: " + listItem["ServerUrl"]); listItem.Update(); } Program.clientContext.ExecuteQuery(); } ); // Were any items missed? Log(""); List <ExcelRow> missedRows = excelRowsByUrl.Values.Where(row => !row.Processed).ToList(); if (missedRows.Count > 0) { Log("Failed to match these rows"); foreach (ExcelRow row in missedRows) { Log(" " + row.ListItemUrl); } } }
public static ListItem UpdateListItem(ListItem item, Hashtable valuesToSet, bool systemUpdate, Action <string> warningCallback, Action <string, string> terminatingError) { var context = item.Context as ClientContext; var list = item.ParentList; context.Web.EnsureProperty(w => w.Url); var clonedContext = context.Clone(context.Web.Url); var web = clonedContext.Web; var fields = context.LoadQuery(list.Fields.Include(f => f.InternalName, f => f.Title, f => f.TypeAsString)); context.ExecuteQueryRetry(); Hashtable values = valuesToSet ?? new Hashtable(); foreach (var key in values.Keys) { var field = fields.FirstOrDefault(f => f.InternalName == key as string || f.Title == key as string); if (field != null) { switch (field.TypeAsString) { case "User": case "UserMulti": { List <FieldUserValue> userValues = new List <FieldUserValue>(); var value = values[key]; if (value == null) { goto default; } if (value.GetType().IsArray) { foreach (var arrayItem in (value as IEnumerable)) { int userId; if (!int.TryParse(arrayItem.ToString(), out userId)) { var user = web.EnsureUser(arrayItem as string); clonedContext.Load(user); clonedContext.ExecuteQueryRetry(); userValues.Add(new FieldUserValue() { LookupId = user.Id }); } else { userValues.Add(new FieldUserValue() { LookupId = userId }); } } item[key as string] = userValues.ToArray(); } else { int userId; if (!int.TryParse(value as string, out userId)) { var user = web.EnsureUser(value as string); clonedContext.Load(user); clonedContext.ExecuteQueryRetry(); item[key as string] = new FieldUserValue() { LookupId = user.Id }; } else { item[key as string] = new FieldUserValue() { LookupId = userId }; } } break; } case "TaxonomyFieldType": case "TaxonomyFieldTypeMulti": { var value = values[key]; if (value != null && value.GetType().IsArray) { var taxSession = clonedContext.Site.GetTaxonomySession(); var terms = new List <KeyValuePair <Guid, string> >(); foreach (var arrayItem in value as object[]) { TaxonomyItem taxonomyItem; Guid termGuid; if (!Guid.TryParse(arrayItem as string, out termGuid)) { // Assume it's a TermPath taxonomyItem = clonedContext.Site.GetTaxonomyItemByPath(arrayItem as string); } else { taxonomyItem = taxSession.GetTerm(termGuid); clonedContext.Load(taxonomyItem); clonedContext.ExecuteQueryRetry(); } terms.Add(new KeyValuePair <Guid, string>(taxonomyItem.Id, taxonomyItem.Name)); } TaxonomyField taxField = context.CastTo <TaxonomyField>(field); taxField.EnsureProperty(tf => tf.AllowMultipleValues); if (taxField.AllowMultipleValues) { var termValuesString = String.Empty; foreach (var term in terms) { termValuesString += "-1;#" + term.Value + "|" + term.Key.ToString("D") + ";#"; } termValuesString = termValuesString.Substring(0, termValuesString.Length - 2); var newTaxFieldValue = new TaxonomyFieldValueCollection(context, termValuesString, taxField); taxField.SetFieldValueByValueCollection(item, newTaxFieldValue); } else { warningCallback?.Invoke($@"You are trying to set multiple values in a single value field. Skipping values for field ""{field.InternalName}"""); } } else { Guid termGuid = Guid.Empty; var taxSession = clonedContext.Site.GetTaxonomySession(); TaxonomyItem taxonomyItem = null; if (value != null && !Guid.TryParse(value as string, out termGuid)) { // Assume it's a TermPath taxonomyItem = clonedContext.Site.GetTaxonomyItemByPath(value as string); } else { if (value != null) { taxonomyItem = taxSession.GetTerm(termGuid); clonedContext.Load(taxonomyItem); clonedContext.ExecuteQueryRetry(); } } TaxonomyField taxField = context.CastTo <TaxonomyField>(field); TaxonomyFieldValue taxValue = new TaxonomyFieldValue(); if (taxonomyItem != null) { taxValue.TermGuid = taxonomyItem.Id.ToString(); taxValue.Label = taxonomyItem.Name; taxField.SetFieldValueByValue(item, taxValue); } else { taxField.ValidateSetValue(item, null); } } break; } case "Lookup": case "LookupMulti": { var value = values[key]; if (value == null) { goto default; } int[] multiValue; if (value is Array) { var arr = (object[])values[key]; multiValue = new int[arr.Length]; for (int i = 0; i < arr.Length; i++) { multiValue[i] = int.Parse(arr[i].ToString()); } } else { string valStr = values[key].ToString(); multiValue = valStr.Split(',', ';').Select(int.Parse).ToArray(); } var newVals = multiValue.Select(id => new FieldLookupValue { LookupId = id }).ToArray(); FieldLookup lookupField = context.CastTo <FieldLookup>(field); lookupField.EnsureProperty(lf => lf.AllowMultipleValues); if (!lookupField.AllowMultipleValues && newVals.Length > 1) { throw new Exception("Field " + field.InternalName + " does not support multiple values"); } item[key as string] = newVals; break; } default: { item[key as string] = values[key]; break; } } } else { terminatingError?.Invoke($"Field {key} not present in list.", "FIELDNOTINLIST"); } } #if !ONPREMISES if (systemUpdate) { item.SystemUpdate(); } else { item.Update(); } #else item.Update(); #endif context.Load(item); context.ExecuteQueryRetry(); return(item); }