/// <summary> /// Updates a single ListItem, making sure only to update fields in the cType /// </summary> /// <param name="item"></param> private void UpdateListItem(SPListItem item) { try { SPContentType ctId = item.ContentType; foreach (KeyValuePair <Guid, string> keyValue in _fieldValues.Where(keyValue => ctId.Fields.Contains(keyValue.Key))) { if (item.Fields[keyValue.Key].TypeAsString.StartsWith("TaxonomyFieldType", StringComparison.InvariantCultureIgnoreCase)) { var field = item.Fields[keyValue.Key] as TaxonomyField; var fieldValue = item[keyValue.Key] != null ? item[keyValue.Key].ToString() : ""; var newValues = keyValue.Value; if (field != null) { if (field.AllowMultipleValues) { var values = new TaxonomyFieldValueCollection(field); if (TaxonomyAppending.Checked) { values.PopulateFromLabelGuidPairs(fieldValue); } values.PopulateFromLabelGuidPairs(newValues); field.SetFieldValue(item, values); } else { var taxValue = new TaxonomyFieldValue(field); taxValue.PopulateFromLabelGuidPair(newValues); field.SetFieldValue(item, taxValue); } } } else if (item.Fields[keyValue.Key].TypeAsString.StartsWith("DateTime", StringComparison.InvariantCultureIgnoreCase)) { var field = item.Fields[keyValue.Key] as SPFieldDateTime; if (field != null) { CultureInfo ci = new CultureInfo(Convert.ToInt32(SPContext.Current.Web.CurrencyLocaleID)); DateTime fldValue = Convert.ToDateTime(keyValue.Value); field.ParseAndSetValue(item, fldValue.ToString(ci.DateTimeFormat.ShortDatePattern, ci)); } } else { item[keyValue.Key] = keyValue.Value; } } item.Update(); } catch (Exception ex) { _messages += ex.Message + "<br/>"; SPCriticalTraceCounter.AddDataToScope(67, "SP2010 BatchEdit", 1, ex.Message + ": " + ex.StackTrace); } }
/// <summary> /// Reads a field value from a DataRow returned by a CAML query /// </summary> /// <param name="web">The context's web</param> /// <param name="dataRowFromCamlResult">The CAML-query-result data row we want to extract a field value from</param> /// <param name="fieldInternalName">The key to find the field among the data row cells</param> /// <returns>The value extracted from the data row's corresponding cell</returns> public override TaxonomyValueCollection ReadValueFromCamlResultDataRow(SPWeb web, DataRow dataRowFromCamlResult, string fieldInternalName) { var fieldValue = dataRowFromCamlResult[fieldInternalName]; if (fieldValue != null && fieldValue != System.DBNull.Value) { var site = web.Site; var field = (TaxonomyField)site.RootWeb.Fields.GetFieldByInternalName(fieldInternalName); var taxFieldVal = new TaxonomyFieldValueCollection(field); taxFieldVal.PopulateFromLabelGuidPairs(fieldValue.ToString()); var taxValueCollection = new TaxonomyValueCollection(taxFieldVal); // Watch out! Here, we're going to use the Site Collection's site column to determine // the taxonomy context. This means that if the item comes from a list where the // TermStoreMapping on the list column is different than on the site column, we're // going to initialize the wrong context for the item here. InitTaxonomyContextForValues(taxValueCollection, field, site); return(taxValueCollection); } return(null); }
public static List <Log> UpdateSite(ClientContext ctx, DefaultFields defaultFields) { const string TaxonomyFieldType = "TaxonomyFieldType"; const string TaxonomyFieldTypeMulti = "TaxonomyFieldTypeMulti"; Web web = ctx.Web; try { Log.ClearLog(); ctx.Load(web); FieldCollection fields = web.Fields; ctx.Load(fields, tcol => tcol.Where(t => t.TypeAsString == TaxonomyFieldType || t.TypeAsString == TaxonomyFieldTypeMulti)); ctx.ExecuteQuery(); /// Update Columns foreach (var column in defaultFields) { Field field = GetField(column.InternalName, fields); if (field == null) { Log.Error(web.Url, "", column.InternalName, "Invalid Field Name"); } else { TaxonomyField taxonomyField = ctx.CastTo <TaxonomyField>(field); if (taxonomyField.AllowMultipleValues) { TaxonomyFieldValueCollection taxonomyFieldValues = new TaxonomyFieldValueCollection(ctx, "", field); taxonomyFieldValues.PopulateFromLabelGuidPairs(column.TermLabel + "|" + column.Guid); var validatedValues = taxonomyField.GetValidatedString(taxonomyFieldValues); ctx.ExecuteQuery(); taxonomyField.DefaultValue = validatedValues.Value; } else { TaxonomyFieldValue taxonomyFieldValue = new TaxonomyFieldValue(); taxonomyFieldValue.WssId = -1; taxonomyFieldValue.Label = column.TermLabel; taxonomyFieldValue.TermGuid = column.Guid; var validatedValue = taxonomyField.GetValidatedString(taxonomyFieldValue); ctx.ExecuteQuery(); taxonomyField.DefaultValue = validatedValue.Value; } taxonomyField.UpdateAndPushChanges(true); ctx.ExecuteQuery(); } } } catch (Exception ex) { Log.Error(web.Url, "", "", ex.Message); } return(Log.GetLog()); }
static void Main(string[] args) { var siteurl = "https://xxx.sharepoint.com/sites/sbdev"; var pwd = "****"; var username = "******"; var authManager = new AuthenticationManager(); ClientContext context = authManager.GetSharePointOnlineAuthenticatedContextTenant(siteurl, username, pwd); List mylist = context.Web.Lists.GetByTitle("kkkk"); ListItem targetitems = mylist.GetItemById(10); var oField = mylist.Fields.GetByInternalNameOrTitle("MyTaxonomy"); context.Load(targetitems); context.Load(oField); context.ExecuteQuery(); TaxonomyField targetField; if (oField.TypeDisplayName == "Managed Metadata") { // cast field to "TaxonomyField" targetField = context.CastTo <TaxonomyField>(oField); } else { Console.WriteLine("wrong field type"); return; } TaxonomyFieldValueCollection tfvc = new TaxonomyFieldValueCollection(targetitems.Context, null, targetField); tfvc.PopulateFromLabelGuidPairs(@"group3|b3705b01-7dd2-47ad-a479-68f1c4dc4071"); tfvc.PopulateFromLabelGuidPairs(@"group4|611c72f2-f42a-41ad-94b3-f9abfc0f6295"); targetField.SetFieldValueByValueCollection(targetitems, tfvc); targetitems.Update(); context.ExecuteQuery(); Console.ReadKey(); }
protected void btnSave_Click(object sender, EventArgs e) { try { SPSecurity.RunWithElevatedPrivileges(delegate() { Control control = null; string controlValue = null; foreach (SPListItem listItem in selectedListItems) { listItem.ParentList.ParentWeb.AllowUnsafeUpdates = true; foreach (SPField field in fieldsToUpdate) { control = phDynamicFormControls.FindControl(string.Format("ctrl_{0}", field.InternalName)); controlValue = GetControlValue(control); if (control != null && GetControlValue(control) != string.Empty) { if (control.GetType().Equals(typeof(Microsoft.SharePoint.Taxonomy.TaxonomyWebTaggingControl))) { TaxonomyField fld = (TaxonomyField)field; if (fld.AllowMultipleValues) { var values = new TaxonomyFieldValueCollection(field); values.PopulateFromLabelGuidPairs(controlValue); fld.SetFieldValue(listItem, values); } } else { listItem[field.Id] = controlValue; } } } listItem.Update(); listItem.ParentList.ParentWeb.AllowUnsafeUpdates = false; } }); } catch (Exception ex) { Logger.Instance.Error("Error while saving fields during batch moving.", ex, DiagnosticsCategories.eCaseSearch); } //show any error messages that we have lblErrors.Text = errorMessages == null ? null : errorMessages.ToString(); if (errorMessages == null || errorMessages.Length == 0) { //close the modal Response.Write(string.Format(CultureInfo.InvariantCulture, "<script type=\"text/javascript\">window.frameElement.commonModalDialogClose(1, '{0}');</script>", selectedLists.Count)); Response.Flush(); Response.End(); } }
public string GetListFilter() { Dictionary <string, string> filters = new Dictionary <string, string>(); string filterQuery = ConstListFilter; string validationMessage; string tagFilterQuery = string.Empty; bool tagOrContainer = false; if (!string.IsNullOrEmpty(FileLeafRef.Text)) { filters.Add(FileLeafRef.ID, string.Format("<Contains><FieldRef Name='FileLeafRef'/><Value Type='File'>{0}</Value></Contains>", FileLeafRef.Text)); } if (!string.IsNullOrEmpty(ImageCategory.SelectedValue) && !ImageCategory.SelectedValue.Equals("-1")) { filters.Add(ImageCategory.ID, string.Format("<Eq><FieldRef Name='ImageCategory' /><Value Type='Choice'>{0}</Value></Eq>", ImageCategory.SelectedValue)); } var valid = MediaTaxonomyWebTaggingControl.Validate(out validationMessage); if (valid) { var values = new TaxonomyFieldValueCollection(string.Empty); values.PopulateFromLabelGuidPairs(MediaTaxonomyWebTaggingControl.Text); foreach (TaxonomyFieldValue value in values) { if (tagOrContainer) { tagFilterQuery = string.Format("<Or>{0}<Contains><FieldRef Name='TaxKeyword' /><Value Type='Text'>{1}</Value></Contains></Or>", tagFilterQuery, value.Label); } else { tagFilterQuery = string.Format("<Contains><FieldRef Name='TaxKeyword' /><Value Type='Text'>{0}</Value></Contains>", value.Label); } tagOrContainer = true; } } if (!string.IsNullOrEmpty(tagFilterQuery)) { filters.Add(MediaTaxonomyWebTaggingControl.ID, tagFilterQuery); } foreach (string key in filters.Keys) { filterQuery = string.Format("<And>{0}{1}</And>", filterQuery, filters[key]); } var listFilter = string.Format("<Where>{0}</Where>", filterQuery); return(listFilter); }
protected string GetMMValue(TaxonomyWebTaggingControl tc) { StringBuilder mm = new StringBuilder(); try { var values = new TaxonomyFieldValueCollection(string.Empty); values.PopulateFromLabelGuidPairs(tc.Text); foreach (TaxonomyFieldValue value in values) { if (!string.IsNullOrEmpty(mm.ToString())) mm.Append("; "); mm.Append(value.Label); } } catch (Exception ex) { Utility.HandleException(ex, Controls); } return mm.ToString(); }
/// <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(); } } } } }
/// <summary> /// Converts the specified value back. /// </summary> /// <param name="value">The value.</param> /// <param name="arguments">The arguments.</param> /// <returns> /// The converted value. /// </returns> public override object ConvertBack(object value, SharePointListItemConversionArguments arguments) { var terms = value as TaxonomyValueCollection; TaxonomyFieldValueCollection newTaxonomyFieldValueCollection = null; TaxonomyField taxonomyField = (TaxonomyField)arguments.ListItem.Fields.GetField(arguments.ValueKey); newTaxonomyFieldValueCollection = new TaxonomyFieldValueCollection(taxonomyField); var noteField = arguments.ListItem.Fields[taxonomyField.TextField]; if (terms != null && terms.Count > 0) { string labelGuidPairs = string.Join(";", terms.Select(term => term.Label + "|" + term.Id).ToArray()); // PopulateFromLabelGuidPairs takes care of looking up the WssId values and creating new items in the TaxonomyHiddenList if needed. // Main taxonomy field value format: WssID;#Label;WssID;#Label;WssID;#Label... // TODO - Make sure we support sub-level terms with format: WssID;#Label|RootTermGuid|...|ParentTermGuid|TermGuid // Reference: http://msdn.microsoft.com/en-us/library/ee577520.aspx newTaxonomyFieldValueCollection.PopulateFromLabelGuidPairs(labelGuidPairs); // Must write associated note field as well as the main taxonomy field. // Note field value format: Label|Guid;Label|Guid;Label|Guid... // Reference: http://nickhobbs.wordpress.com/2012/02/21/sharepoint-2010-how-to-set-taxonomy-field-values-programmatically/ arguments.FieldValues[noteField.InternalName] = labelGuidPairs; } else { // No taxonomy value, make sure to empty the note field as well arguments.FieldValues[noteField.InternalName] = null; } return newTaxonomyFieldValueCollection; }
/// <summary> /// Converts the specified value. /// </summary> /// <param name="value">The value.</param> /// <param name="arguments">The arguments.</param> /// <returns> /// The converted value. /// </returns> public override object Convert(object value, DataRowConversionArguments arguments) { TaxonomyValueCollection convertedValues = null; if (value == DBNull.Value) { return null; } var taxonomyFieldValueCollection = value as TaxonomyFieldValueCollection; if (taxonomyFieldValueCollection == null) { var stringValue = value as string; if (!string.IsNullOrEmpty(stringValue)) { var fieldObject = arguments.FieldCollection.Cast<SPField>() .FirstOrDefault(f => f.InternalName == arguments.ValueKey); if (fieldObject != null) { taxonomyFieldValueCollection = new TaxonomyFieldValueCollection(fieldObject); taxonomyFieldValueCollection.PopulateFromLabelGuidPairs(stringValue); } else { return null; } } } if (taxonomyFieldValueCollection != null) { if (SPContext.Current != null) { // Resolve the Term from the term store, because we want all Labels and we want to // create the TaxonomyValue object with a label in the correct LCID (we want one with // LCID = CurrentUICUlture.LCID var underLyingTerms = new List<Term>(); foreach (TaxonomyFieldValue taxonomyFieldValue in taxonomyFieldValueCollection) { if (!string.IsNullOrEmpty(taxonomyFieldValue.TermGuid)) { var foundTerm = this.taxonomyService.GetTermForId(SPContext.Current.Site, new Guid(taxonomyFieldValue.TermGuid)); if (foundTerm != null) { underLyingTerms.Add(foundTerm); } } } convertedValues = new TaxonomyValueCollection(underLyingTerms); } else { // We don't have access to a SPContext (needed to use the TaxonomyService), so we need to // fall back on the non-UICulture-respecting TaxonomyValueCollection constructor convertedValues = new TaxonomyValueCollection(taxonomyFieldValueCollection); } } return convertedValues; }
/// <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(); } } } } }