protected override void ExecuteCmdlet() { List list = null; if (List != null) { list = List.GetList(SelectedWeb); } if (list != null) { ListItemCreationInformation liCI = new ListItemCreationInformation(); if (Folder != null) { // Create the folder if it doesn't exist var rootFolder = list.EnsureProperty(l => l.RootFolder); var targetFolder = SelectedWeb.EnsureFolder(rootFolder, Folder); liCI.FolderUrl = targetFolder.ServerRelativeUrl; } var item = list.AddItem(liCI); 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) { Hashtable values = Values ?? new Hashtable(); // Load all list fields and their types var fields = ClientContext.LoadQuery(list.Fields.Include(f => f.Id, f => f.InternalName, f => f.Title, f => f.TypeAsString)); ClientContext.ExecuteQueryRetry(); 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": { var userValues = new List <FieldUserValue>(); var value = values[key]; if (value.GetType().IsArray) { foreach (var arrayItem in value as object[]) { int userId; if (!int.TryParse(arrayItem as string, 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.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 = Guid.Empty; 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; if (!Guid.TryParse(value as string, out termGuid)) { // Assume it's a TermPath var taxonomyItem = ClientContext.Site.GetTaxonomyItemByPath(value as string); termGuid = taxonomyItem.Id; } item[key as string] = termGuid.ToString(); } #if !ONPREMISES item.SystemUpdate(); #else item.Update(); #endif break; } case "Lookup": case "LookupMulti": { int[] multiValue; if (values[key] 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) { WriteWarning($@"You are trying to set multiple values in a single value field. Skipping values for field ""{field.InternalName}"""); } 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 { ThrowTerminatingError(new ErrorRecord(new Exception("Field not present in list"), "FIELDNOTINLIST", ErrorCategory.InvalidData, key)); } } } item.Update(); ClientContext.Load(item); ClientContext.ExecuteQueryRetry(); WriteObject(item); } }
/// <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 SetTaxonomyFields(ClientContext ctx, ListItem listItem, string FileContent, string ListId, string url) { FieldCollection _fields = listItem.ParentList.Fields; ctx.Load(ctx.Web.AllProperties); ctx.Load(_fields); ctx.ExecuteQuery(); AppWebHelper hlp = new AppWebHelper(url, false); List <GlobalSetting> settings = GetGlobalConfig(hlp); LogHelper.Log(settings.Count.ToString()); var enabled = settings.Where(s => s.key == Constants.EnableKeywordCreation).SingleOrDefault(); bool KeywordCreationEnabled = Convert.ToBoolean( settings.Where(s => s.key == Constants.EnableKeywordCreation).SingleOrDefault().value); int KeywordRecognitionTreshold = Convert.ToInt32( settings.Where(s => s.key == Constants.KeywordRecognitionTreshold).SingleOrDefault().value); int KeywordCreationTreshold = Convert.ToInt32( settings.Where(s => s.key == Constants.KeywordCreationTreshold).SingleOrDefault().value); List <string> ConfiguredFields = hlp.ListTaxFields(ListId); foreach (var _f in _fields) { if (ConfiguredFields.Contains(_f.Id.ToString())) { TaxonomyField _field = ctx.CastTo <TaxonomyField>(_fields.GetById(_f.Id)); if (_f.InternalName != Constants.TaxFieldInternalName) { ctx.Load(_field); ctx.ExecuteQuery(); Collection <Term> MatchingTerms = null; MatchingTerms = AutoTaggingHelper.MatchingTerms(FileContent, ctx, _field.TermSetId, _field.AnchorId); if (MatchingTerms.Count > 0) { LogHelper.Log("Updating taxfield " + _field.Title); if (_field.AllowMultipleValues) { _field.SetFieldValueByCollection(listItem, MatchingTerms, 1033); } else { _field.SetFieldValueByTerm(listItem, MatchingTerms.First(), 1033); } listItem.Update(); ctx.ExecuteQuery(); } } else { TaxonomyTerms tt = new TaxonomyTerms(ctx); string TextLanguage = AutoTaggingHelper.LanguageIdentifier.Identify(FileContent).FirstOrDefault().Item1.Iso639_3; StringBuilder EntKeyWordsValue = new StringBuilder(); Dictionary <string, int> tokens = Tokenize(FileContent, KeywordRecognitionTreshold, TextLanguage); StringBuilder TokenString = new StringBuilder(); foreach (KeyValuePair <string, int> token in tokens) { Guid KeywordId = TaxonomyTerms.GetKeyword(token.Key); TokenString.AppendFormat("{0}|", token.Key); if (KeywordId != Guid.Empty) { EntKeyWordsValue.AppendFormat("-1;#{0}|{1};", token.Key, KeywordId); } else { if (KeywordCreationEnabled && token.Value >= KeywordCreationTreshold && !AutoTaggingHelper.IsEmptyWord(token.Key.ToLowerInvariant(), TextLanguage, hlp)) { Guid g = AddKeyWord(token.Key, ctx); if (g != Guid.Empty) { EntKeyWordsValue.AppendFormat("-1;#{0}|{1};", token.Key, g); } } } } LogHelper.Log(TokenString.ToString()); if (EntKeyWordsValue.ToString().Length > 0) { LogHelper.Log("keyword value " + EntKeyWordsValue.ToString(), LogSeverity.Error); TaxonomyFieldValueCollection col = new TaxonomyFieldValueCollection(ctx, string.Empty, _field); col.PopulateFromLabelGuidPairs(EntKeyWordsValue.ToString()); _field.SetFieldValueByValueCollection(listItem, col); listItem.Update(); ctx.ExecuteQuery(); } } } } }
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); } }
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); }