//public static string GetTaxonomyId(ListItem item, string fieldName) //{ // TaxonomyFieldValue taxFieldValue = item[fieldName] as TaxonomyFieldValue; // return taxFieldValue.TermGuid; //} public static List <string> GetTaxonomiesId(ListItem item, string fieldName) { List <string> Ids = new List <string>(); // string er = item[fieldName].ToString(); try { System.Collections.Generic.Dictionary <System.String, System.Object> sds = item[fieldName] as System.Collections.Generic.Dictionary <System.String, System.Object>; TaxonomyFieldValueCollection taxFieldValues = sds.ElementAt(1).Value as TaxonomyFieldValueCollection; object[] DSD = sds.ElementAt(1).Value as object[]; foreach (Dictionary <System.String, System.Object> dic in DSD) { Ids.Add(dic["TermGuid"].ToString()); } } catch (Exception ex) { TaxonomyFieldValueCollection taxFieldValues = item[fieldName] as TaxonomyFieldValueCollection; foreach (TaxonomyFieldValue taxFieldValue in taxFieldValues) { Ids.Add(taxFieldValue.TermGuid); } } return(Ids); }
private static void addMultiTaxonomyFieldValue(DataRow newRow, Property prop, object FieldValue) { string LookupMultiComplete = string.Empty; string LookupMultiValue = string.Empty; StringBuilder strMultiComplete = new StringBuilder(); StringBuilder strMultiValue = new StringBuilder(); TaxonomyFieldValueCollection taxanomyValues = FieldValue as TaxonomyFieldValueCollection; if (taxanomyValues != null) { foreach (TaxonomyFieldValue taxanomyValue in taxanomyValues) { if (taxanomyValue != null) { strMultiComplete = strMultiComplete.AppendFormat("{0};", taxanomyValue.TermGuid); strMultiValue = strMultiValue.AppendFormat("{0};", taxanomyValue.Label); } } if (strMultiComplete.Length > 0) { LookupMultiComplete = strMultiComplete.ToString().Substring(0, strMultiComplete.Length - 1); } if (strMultiValue.Length > 0) { LookupMultiValue = strMultiValue.ToString().Substring(0, strMultiValue.Length - 1); } newRow[prop.Name] = LookupMultiComplete; newRow[prop.Name + Constants.InternalProperties.Suffix_Value] = strMultiValue; } }
private static TaxonomyFieldValueCollection CreateSharePointTaxonomyFieldValue( TaxonomyField sharepointTaxonomyField, TaxonomyValueCollection dynamiteCollection, List <string> labelGuidPairsListOutParam) { if (labelGuidPairsListOutParam == null) { labelGuidPairsListOutParam = new List <string>(); } TaxonomyFieldValueCollection sharePointValueCollection = null; foreach (var TaxonomyValue in dynamiteCollection) { string labelGuidPair = TaxonomyItem.NormalizeName(TaxonomyValue.Term.Label) + TaxonomyField.TaxonomyGuidLabelDelimiter + TaxonomyValue.Term.Id.ToString().ToUpperInvariant(); labelGuidPairsListOutParam.Add(labelGuidPair); } if (labelGuidPairsListOutParam.Count >= 1) { sharePointValueCollection = new TaxonomyFieldValueCollection(sharepointTaxonomyField); labelGuidPairsListOutParam.ForEach(labelGuidPair => { TaxonomyFieldValue taxoFieldValue = new TaxonomyFieldValue(sharepointTaxonomyField); taxoFieldValue.PopulateFromLabelGuidPair(labelGuidPair); sharePointValueCollection.Add(taxoFieldValue); }); } return(sharePointValueCollection); }
public static void SetDefaultValue(SPSite site, TaxonomyField field, string defaultValue, bool addIfDoesNotExist /*, out bool newTermAdded*/) { if (field.AllowMultipleValues) { TaxonomyFieldValueCollection oTaxonomyFieldValues = GetTaxonomyFieldValues(site, field, new[] { defaultValue }, addIfDoesNotExist /*, out newTermAdded*/); string validatedString = field.GetValidatedString(oTaxonomyFieldValues); if (field.DefaultValue != validatedString) { field.DefaultValue = validatedString; field.Update(); } } else { TaxonomyFieldValue oTaxonomyFieldValue = GetTaxonomyFieldValue(site, field, defaultValue, addIfDoesNotExist /*, out newTermAdded*/); //string validatedString = field.GetValidatedString(oTaxonomyFieldValue); if (field.DefaultValue != oTaxonomyFieldValue.ValidatedString) { field.DefaultValue = oTaxonomyFieldValue.ValidatedString; field.Update(); } } }
/// <summary> /// Writes a Taxonomy Multi field value to a SPListItem /// </summary> /// <param name="item">The SharePoint List Item</param> /// <param name="fieldValueInfo">The field and value information</param> public override void WriteValueToListItem(SPListItem item, FieldValueInfo fieldValueInfo) { var termInfos = fieldValueInfo.Value as TaxonomyValueCollection; TaxonomyFieldValueCollection newTaxonomyFieldValueCollection = null; TaxonomyField taxonomyField = (TaxonomyField)item.Fields.GetField(fieldValueInfo.FieldInfo.InternalName); var noteField = item.Fields[taxonomyField.TextField]; if (termInfos != null && termInfos.Count > 0) { List <string> labelGuidPairsListOutParam = new List <string>(); newTaxonomyFieldValueCollection = CreateSharePointTaxonomyFieldValue(taxonomyField, termInfos, labelGuidPairsListOutParam); item[taxonomyField.Id] = newTaxonomyFieldValueCollection; // 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/ string labelGuidPairsAsString = string.Join(";", labelGuidPairsListOutParam.ToArray()); item[noteField.InternalName] = labelGuidPairsAsString; } else { // No taxonomy value, make sure to empty the note field as well item[noteField.InternalName] = null; } item[fieldValueInfo.FieldInfo.InternalName] = newTaxonomyFieldValueCollection; }
/// <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 void SetDefaultValue(SPSite site, TaxonomyField field, string[] defaultValue, bool addIfDoesNotExist /*, out bool newTermAdded*/) { if (defaultValue == null || defaultValue.Length == 0) { //newTermAdded = false; return; } if (field.AllowMultipleValues) { TaxonomyFieldValueCollection oTaxonomyFieldValues = GetTaxonomyFieldValues(site, field, defaultValue, addIfDoesNotExist /*, out newTermAdded*/); string validatedString = field.GetValidatedString(oTaxonomyFieldValues); if (field.DefaultValue != validatedString) { field.DefaultValue = validatedString; field.Update(); } } else { SetDefaultValue(site, field, defaultValue[0], addIfDoesNotExist /*, out newTermAdded*/); } }
public static TaxonomyFieldValueCollection GetTaxonomyFieldValues(TermSet termSet, IEnumerable <string> values, bool addIfDoesNotExist, out bool newTermsAdded) { TaxonomyFieldValueCollection termValues = TaxonomyFieldControl.GetTaxonomyCollection(""); newTermsAdded = false; if (values != null && values.Count() > 0) { bool[] newTermAddedResult = new bool[values.Count()]; termValues.AddRange(values.Where(termValue => termValue != null) .Select((value, i) => { bool newTermAdded; TaxonomyFieldValue val = GetTaxonomyFieldValue(termSet, value, addIfDoesNotExist, out newTermAdded); newTermAddedResult[i] = newTermAdded; return(val); })); newTermsAdded = newTermAddedResult.Any(newTermAdded => newTermAdded); } return(termValues); }
/// <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); } }
public static List <KeyValuePair <string, string> > GetMultiTaxonomyValues(this ListItem item, string internalName) { var retValues = new List <KeyValuePair <string, string> >(); var mdColVal = item[internalName] as Dictionary <string, object>; if (mdColVal != null) { var taxValues = mdColVal["_Child_Items_"] as object[]; foreach (var taxValue in taxValues) { var taxDict = taxValue as Dictionary <string, object>; retValues.Add(new KeyValuePair <string, string>(taxDict["TermGuid"].ToString(), taxDict["Label"].ToString())); } } else { var mdColValTF = item[internalName]; TaxonomyFieldValueCollection tfvc = mdColValTF as TaxonomyFieldValueCollection; if (tfvc != null) { foreach (var taxonomyCat in tfvc) { retValues.Add(new KeyValuePair <string, string>(taxonomyCat.TermGuid, taxonomyCat.Label)); } } } return(retValues); }
private static string GetTaxonomyFieldValidatedValue(TaxonomyField field, string defaultValue) { string res = null; object parsedValue = null; field.EnsureProperty(f => f.AllowMultipleValues); if (field.AllowMultipleValues) { parsedValue = new TaxonomyFieldValueCollection(field.Context, defaultValue, field); } else { TaxonomyFieldValue taxValue = null; if (TryParseTaxonomyFieldValue(defaultValue, out taxValue)) { parsedValue = taxValue; } } if (parsedValue != null) { var validateValue = field.GetValidatedString(parsedValue); field.Context.ExecuteQueryRetry(); res = validateValue.Value; } return(res); }
/// <summary> /// Updating Previous Documents Recursively using CAML Query /// </summary> /// <param name="clientContext">Client Context</param> /// <param name="list">List of Matters</param> /// <param name="practiceGroupMetadataDefaultValue">Default Value to be Set for practice group</param> /// <param name="areaOfLawMetadataDefaultValue">Default Value to be Set for Area of Law</param> /// <param name="subAreaOfLawMetadataDefaultValue">default Value to be Set for Sub Area of Law</param> /// <param name="clientName">Current Client name</param> public static void UpdatePreviousDocuments(ClientContext clientContext, List list, string practiceGroupMetadataDefaultValue, string areaOfLawMetadataDefaultValue, string subAreaOfLawMetadataDefaultValue, string clientName) { try { Web site = clientContext.Web; User currentUser = site.CurrentUser; clientContext.Load(currentUser); Console.WriteLine(string.Format(CultureInfo.InvariantCulture, Constants.ProcessingMessageDocuments, list.Title)); CamlQuery CAMLQuery = new CamlQuery(); CAMLQuery.ViewXml = string.Format(CultureInfo.InvariantCulture, Constants.CAMLQueryRetrieveAllDocuments, practiceGroupFieldName, areaOfLawFieldName, subAreaOfLawFiedName);; ListItemCollection listItems = list.GetItems(CAMLQuery); clientContext.Load(listItems); clientContext.ExecuteQuery(); foreach (ListItem item in listItems) { bool checkoutByCurrent = false; if (null != item[Constants.CheckOutFieldKey]) { string checkOutUser = ((Microsoft.SharePoint.Client.FieldLookupValue)(item[Constants.CheckOutFieldKey])).LookupValue; if (currentUser.Title == checkOutUser) { checkoutByCurrent = true; } else { Console.WriteLine(string.Format(CultureInfo.InvariantCulture, Constants.FailureMessageUpdationDocument, item[Constants.DocNameFieldKey], checkOutUser)); } } if (null == item[Constants.CheckOutFieldKey] || checkoutByCurrent)// Checkout Functionality { TaxonomyFieldValueCollection practicegroupTaxanomyColl = item[practiceGroupFieldName] as TaxonomyFieldValueCollection; if (0 >= practicegroupTaxanomyColl.Count) { item[practiceGroupFieldName] = practiceGroupMetadataDefaultValue; item.Update(); } TaxonomyFieldValueCollection areaOfLawTaxanomyColl = item[areaOfLawFieldName] as TaxonomyFieldValueCollection; if (0 >= areaOfLawTaxanomyColl.Count) { item[areaOfLawFieldName] = areaOfLawMetadataDefaultValue; item.Update(); } TaxonomyFieldValueCollection subAreaOfLawTaxanomyColl = item[subAreaOfLawFiedName] as TaxonomyFieldValueCollection; if (0 >= subAreaOfLawTaxanomyColl.Count) { item[subAreaOfLawFiedName] = subAreaOfLawMetadataDefaultValue; item.Update(); } clientContext.ExecuteQuery(); Console.WriteLine(string.Format(CultureInfo.InvariantCulture, Constants.SucessMessageUpdationDocument, item[Constants.DocNameFieldKey])); } } } catch (Exception e) { Console.WriteLine(string.Format(CultureInfo.InvariantCulture, Constants.FailureMessageDocument, clientName, list.Title, e.Message)); } }
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()); }
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 static string TaxonomyCollectionValueToString(TaxonomyFieldValueCollection value) { if (value == null) return string.Empty; if (value.ToList().Count == 0) return string.Empty; return value .ToList() .Select(lv => TaxonomyValueToString(lv)) .Aggregate((all, current) => all + LookupCollectionItemSeparator + current); }
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); }
private string[] getTags(SPListItem it) { TaxonomyFieldValueCollection itemTags = ((TaxonomyFieldValueCollection)it[tagColumnName]); string[] ret = new string[itemTags.Count]; int i = 0; foreach (TaxonomyFieldValue tag in itemTags) { ret[i] = tag.Label; i++; } return(ret); }
public static string Serialize(this TaxonomyFieldValueCollection taxValues) { string terms = ""; foreach (TaxonomyFieldValue taxValue in taxValues) { terms += taxValue.SerializeTerm() + ','; } if (terms.Length > 0) { terms = terms.Substring(0, terms.Length - 1); } return(String.Format("[{0}]", terms)); }
private void OnTaxonomyMultiValueChanged(object sender, string fieldName) { TaxonomyFieldValueCollection collection = new TaxonomyFieldValueCollection(""); foreach (Term term in (IEnumerable)sender) { TaxonomyFieldValue value = new TaxonomyFieldValue(""); value.Label = term.Name; value.TermGuid = term.Id.ToString(); value.WssId = term.EnsureWssId(this.Site, fieldName.Equals("TaxKeyword")); collection.Add(value); } this[fieldName] = collection.ToString(); SetTaxonomyTextValue(fieldName, (IEnumerable <Term>)sender); }
public static string TaxonomyCollectionValueToString(TaxonomyFieldValueCollection value) { if (value == null) { return(string.Empty); } if (value.ToList().Count == 0) { return(string.Empty); } return(value .ToList() .Select(lv => TaxonomyValueToString(lv)) .Aggregate((all, current) => all + LookupCollectionItemSeparator + current)); }
//public static string GetUrl(this SPListItem item, string fieldName) //{ // object value = GetValue(item, fieldName); // return GetUrl(value); //} //public static string GetUrl(this SPListItem item, Guid fieldId) //{ // object value = GetValue(item, fieldId); // return GetUrl(value); //} //public static int GetRating(this SPListItem item, string fieldName) //{ // object value = GetValue(item, fieldName); // return GetRating(value); //} //public static int GetRating(this SPListItem item, Guid fieldId) //{ // object value = GetValue(item, fieldId); // return GetRating(value); //} //public static TaxonomyFieldValue GetTaxonomyValue(this SPListItem item, Guid fieldId) //{ // var value = item[fieldId]; // TaxonomyFieldValue ret = value != null // ? (TaxonomyFieldControl.GetTaxonomyValue(value.ToString()) // ?? new TaxonomyFieldValue(string.Empty)) // : new TaxonomyFieldValue(string.Empty); // return ret; //} //public static TaxonomyFieldValue GetTaxonomyValue(this SPListItem item, string fieldName) //{ // var value = item[fieldName]; // TaxonomyFieldValue ret = value != null // ? (TaxonomyFieldControl.GetTaxonomyValue(value.ToString()) // ?? new TaxonomyFieldValue(string.Empty)) // : new TaxonomyFieldValue(string.Empty); // return ret; //} //public static TaxonomyFieldValueCollection GetTaxonomyValues(this SPListItem item, Guid fieldId) //{ // var value = item[fieldId]; // TaxonomyFieldValueCollection ret = value != null // ? (TaxonomyFieldControl.GetTaxonomyCollection(value.ToString()) // ?? new TaxonomyFieldValueCollection(string.Empty)) // : new TaxonomyFieldValueCollection(string.Empty); // return ret; //} //public static TaxonomyFieldValueCollection GetTaxonomyValues(this SPListItem item, string fieldName) //{ // var value = item[fieldName]; // TaxonomyFieldValueCollection ret = value != null // ? (TaxonomyFieldControl.GetTaxonomyCollection(value.ToString()) // ?? new TaxonomyFieldValueCollection(string.Empty)) // : new TaxonomyFieldValueCollection(string.Empty); // return ret; //} //public static string GetTaxonomyLabel(this SPListItem item, Guid fieldId) //{ // return GetTaxonomyValue(item, fieldId).Label; //} //public static string GetTaxonomyLabel(this SPListItem item, string fieldName) //{ // return GetTaxonomyValue(item, fieldName).Label; //} //public static string[] GetTaxonomyLabels(this SPListItem item, Guid fieldId) //{ // return GetTaxonomyValues(item, fieldId).Where(@tax => tax.Label != null).Select(@tax => tax.Label).ToArray(); //} //public static string[] GetTaxonomyLabels(this SPListItem item, string fieldName) //{ // return GetTaxonomyValues(item, fieldName).Where(@tax => tax.Label != null).Select(@tax => tax.Label).ToArray(); //} public static void SetTaxonomyValue(this SPListItem item, string fieldName, string value, bool addIfDoesNotExist) { TaxonomyField taxonomyField = (TaxonomyField)item.Fields[fieldName]; if (taxonomyField.AllowMultipleValues) { TaxonomyFieldValueCollection taxValue = TaxonomyHelper.GetTaxonomyFieldValues(item.Web.Site, taxonomyField, new[] { value }, addIfDoesNotExist); taxonomyField.SetFieldValue(item, taxValue); } else { TaxonomyFieldValue taxValue = TaxonomyHelper.GetTaxonomyFieldValue(item.Web.Site, taxonomyField, value, addIfDoesNotExist); taxonomyField.SetFieldValue(item, taxValue); } }
public static List <SPTerm> ToSPTermList(this TaxonomyFieldValueCollection values, IEnumerable <SPTerm> terms) { var result = new List <SPTerm>(); if (values == null || values.Count < 1) { return(result); } foreach (var value in values) { result.Add(value.ToSPTerm(terms)); } return(result); }
public static List <string> ToStringList(this TaxonomyFieldValueCollection values) { var result = new List <string>(); if (values == null || values.Count < 1) { return(result); } foreach (var value in values) { result.Add(value.Label); } return(result); }
public static TaxonomyFieldValueCollection GetTaxonomyFieldValues(SPSite site, Guid sspId, Guid termSetId, IEnumerable <string> values, bool addIfDoesNotExist /*, out bool newTermsAdded*/) { bool newTermsAdded; TaxonomySession taxonomySession = new TaxonomySession(site); TermStore termStore = taxonomySession.TermStores[sspId]; TermSet termSet = termStore.GetTermSet(termSetId); TaxonomyFieldValueCollection val = GetTaxonomyFieldValues(termSet, values, addIfDoesNotExist, out newTermsAdded); if (newTermsAdded) { termStore.CommitAll(); } return(val); }
public void SetBlankTaxonomyFieldMultiValueTest() { var fieldName = "TaxKeyword"; using (var clientContext = TestCommon.CreateClientContext()) { // Retrieve list var list = clientContext.Web.Lists.GetById(_listId); clientContext.Load(list); clientContext.ExecuteQueryRetry(); // Retrieve Termset TaxonomySession session = TaxonomySession.GetTaxonomySession(clientContext); var termSet = session.GetDefaultSiteCollectionTermStore().GetTermSet(_termSetId); clientContext.Load(termSet); clientContext.ExecuteQueryRetry(); //Add Enterprise keywords field var keywordField = clientContext.Web.Fields.GetByInternalNameOrTitle(fieldName); var keywordTaxonomyField = clientContext.CastTo <TaxonomyField>(keywordField); clientContext.Load(keywordTaxonomyField, f => f.Id, f => f.TextField); list.Fields.Add(keywordTaxonomyField); // Create Item ListItemCreationInformation itemCi = new ListItemCreationInformation(); var item = list.AddItem(itemCi); item.Update(); clientContext.Load(item); clientContext.ExecuteQueryRetry(); item.SetTaxonomyFieldValues(keywordField.Id, new List <KeyValuePair <Guid, string> >()); clientContext.Load(item, i => i[fieldName]); clientContext.ExecuteQueryRetry(); var hiddenField = list.Fields.GetById(keywordTaxonomyField.TextField); clientContext.Load(hiddenField, f => f.InternalName); clientContext.ExecuteQueryRetry(); TaxonomyFieldValueCollection taxonomyFieldValueCollection = item[fieldName] as TaxonomyFieldValueCollection; object hiddenFieldValue = item[hiddenField.InternalName]; Assert.AreEqual(0, taxonomyFieldValueCollection.Count, "taxonomyFieldValueCollection is not empty"); Assert.IsNull(hiddenFieldValue, "hiddenFieldValue is not null"); } }
/// <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, SharePointListItemConversionArguments arguments) { TaxonomyValueCollection convertedValues = null; var taxonomyFieldValueCollection = value as TaxonomyFieldValueCollection; if (taxonomyFieldValueCollection == null) { var stringValue = value as string; if (!string.IsNullOrEmpty(stringValue)) { taxonomyFieldValueCollection = new TaxonomyFieldValueCollection(stringValue); } } 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> /// /// </summary> /// <param name="context"></param> /// <param name="changeList"></param> /// <param name="item"></param> /// <param name="taxonomyTermName"></param> /// <param name="keyPhrases"></param> /// <returns></returns> private static Result SetTaxFieldValueAgainstKeyPhrase(ClientContext context, List changeList, ListItem item, string taxonomyTermName, IEnumerable <string> keyPhrases) { try { Trace.TraceInformation($"TermName: {taxonomyTermName}"); // Get Field and cast to taxonomy var txField = context.CastTo <TaxonomyField>( changeList.Fields.GetByInternalNameOrTitle( taxonomyTermName)); context.Load(txField); context.ExecuteQuery(); if (!txField.AllowMultipleValues) { throw new ArgumentException("Can only set values on Taxonomy Fields that allow Multiple Values."); } Trace.TraceInformation($"TermSetId: {txField.TermSetId}"); var matchedTerms = GetMatchedKeywordsFromMms(keyPhrases, GetTermsFromMms(context, txField.TermSetId)); Trace.TraceInformation($"Matched Terms: {string.Join(",", matchedTerms.Select(term => term.Name))}"); //Create Taxonomy Field Value and set on item. var taxonomyFieldValue = string.Join(";#", matchedTerms.Select(term => $"-1;#{term.Name}|{term.Id}")); var tx = new TaxonomyFieldValueCollection(context, taxonomyFieldValue, txField); txField.SetFieldValueByValueCollection(item, tx); item.SystemUpdate(); context.ExecuteQuery(); return(Result.Pass); } catch (Exception ex) { // This occurs either because: // 1. The column does not exist. // 2. The column is not a Taxonomy Field // 3. The column doesn't allow Multiple Values. The will error as it is not supported. Trace.TraceWarning($"Error: {ex}"); return(Result.Fail); } }
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(); }
public static void SetTaxonomyValues(this SPListItem item, string fieldName, bool addIfDoesNotExist, params string[] values) { TaxonomyField taxonomyField = (TaxonomyField)item.Fields[fieldName]; if (taxonomyField.AllowMultipleValues) { TaxonomyFieldValueCollection taxValue = TaxonomyHelper.GetTaxonomyFieldValues(item.Web.Site, taxonomyField, values, addIfDoesNotExist); taxonomyField.SetFieldValue(item, taxValue); } else { TaxonomyFieldValue taxValue = values != null && values.Length > 0 ? TaxonomyHelper.GetTaxonomyFieldValue(item.Web.Site, taxonomyField, values[0], addIfDoesNotExist) : new TaxonomyFieldValue(taxonomyField); taxonomyField.SetFieldValue(item, taxValue); } }
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(); }
public static TaxonomyFieldValueCollection GetTaxonomyFieldValues(SPSite site, TaxonomyField field, IEnumerable <string> values, bool addIfDoesNotExist /*, out bool newTermsAdded*/) { if (values == null) { throw new ArgumentNullException("values"); } TaxonomySession taxonomySession = new TaxonomySession(site); TermStore termStore = taxonomySession.TermStores[field.SspId]; TermSet termSet = termStore.GetTermSet(field.TermSetId); TaxonomyFieldValueCollection termValues = new TaxonomyFieldValueCollection(field); bool newTermsAdded = false; if (values != null && values.Count() > 0) { bool[] newTermAddedResult = new bool[values.Count()]; termValues.AddRange( values.Where(termValue => termValue != null) .Select((value, i) => { bool newTermAdded; TaxonomyFieldValue val = GetTaxonomyFieldValue(termSet, value, addIfDoesNotExist, out newTermAdded); newTermAddedResult[i] = newTermAdded; return(val); })); newTermsAdded = newTermAddedResult.Any(newTermAdded => newTermAdded); } if (newTermsAdded) { termStore.CommitAll(); } return(termValues); }
private static bool SetFieldValue(ref ListItem item, string fieldName, List <Term> fieldValue, bool overwrite = true) { var hasChanged = false; var itemValue = item[fieldName] as TaxonomyFieldValueCollection; var itemTermLabels = (from term in itemValue orderby term.Label select term.Label).ToArray(); var fieldTermLabels = (from term in fieldValue orderby term.Name select term.Name).ToArray(); if ((itemValue == null && fieldValue != null) || (overwrite && !itemTermLabels.SequenceEqual(fieldTermLabels))) { var field = GetFieldFromInternalName(item, fieldName); string termValuesString = String.Empty; foreach (var term in fieldValue) { termValuesString += "-1;#" + term.Name + "|" + term.Id.ToString("D") + ";#"; } termValuesString = termValuesString.Substring(0, termValuesString.Length - 2); var termsFieldValue = new TaxonomyFieldValueCollection(item.Context, termValuesString, field); item[fieldName] = termsFieldValue; hasChanged = true; } return(hasChanged); }
private static string GetTaxonomyFieldValidatedValue(TaxonomyField field, string defaultValue) { string res = null; object parsedValue = null; field.EnsureProperty(f => f.AllowMultipleValues); if (field.AllowMultipleValues) { parsedValue = new TaxonomyFieldValueCollection(field.Context, defaultValue, field); } else { TaxonomyFieldValue taxValue = null; if (TryParseTaxonomyFieldValue(defaultValue, out taxValue)) { parsedValue = taxValue; } } if (parsedValue != null) { var validateValue = field.GetValidatedString(parsedValue); field.Context.ExecuteQueryRetry(); res = validateValue.Value; } return res; }
public static TaxonomyFieldValueCollection GetTaxonomyFieldValues(SPSite site, TaxonomyField field, IEnumerable<string> values, bool addIfDoesNotExist/*, out bool newTermsAdded*/) { if (values == null) throw new ArgumentNullException("values"); TaxonomySession taxonomySession = new TaxonomySession(site); TermStore termStore = taxonomySession.TermStores[field.SspId]; TermSet termSet = termStore.GetTermSet(field.TermSetId); TaxonomyFieldValueCollection termValues = new TaxonomyFieldValueCollection(field); bool newTermsAdded = false; if (values != null && values.Count() > 0) { bool[] newTermAddedResult = new bool[values.Count()]; termValues.AddRange( values.Where(termValue => termValue != null) .Select((value, i) => { bool newTermAdded; TaxonomyFieldValue val = GetTaxonomyFieldValue(termSet, value, addIfDoesNotExist, out newTermAdded); newTermAddedResult[i] = newTermAdded; return val; })); newTermsAdded = newTermAddedResult.Any(newTermAdded => newTermAdded); } if (newTermsAdded) { termStore.CommitAll(); } return termValues; }
public static TaxonomyFieldValueCollection GetTaxonomyFieldValues(SPSite site, TaxonomyField field, string values, out List<int> wssIds) { if (values == null) throw new ArgumentNullException("values"); TaxonomySession taxonomySession = new TaxonomySession(site); TermStore termStore = taxonomySession.TermStores[field.SspId]; TermSet termSet = termStore.GetTermSet(field.TermSetId); TaxonomyFieldValueCollection termValues = new TaxonomyFieldValueCollection(field); termValues.AddRange(TaxonomyFieldControl.GetTaxonomyCollection(values)); wssIds = new List<int>(); foreach (TaxonomyFieldValue termValue in termValues) { wssIds.AddRange(TaxonomyField.GetWssIdsOfTerm(site, termStore.Id, termSet.Id, new Guid(termValue.TermGuid), false, 500)); } return termValues; }
/// <summary> /// Sets a value of a taxonomy field that supports multiple values /// </summary> /// <param name="item">The item to process</param> /// <param name="fieldId">The ID of the field to set</param> /// <param name="termValues">The key and values of terms to set</param> public static void SetTaxonomyFieldValues(this ListItem item, Guid fieldId, IEnumerable<KeyValuePair<Guid, String>> termValues) { ClientContext clientContext = item.Context as ClientContext; List list = item.ParentList; clientContext.Load(list); clientContext.ExecuteQueryRetry(); IEnumerable<Field> fieldQuery = clientContext.LoadQuery( list.Fields .Include( fieldArg => fieldArg.TypeAsString, fieldArg => fieldArg.Id, fieldArg => fieldArg.InternalName ) ).Where(fieldArg => fieldArg.Id == fieldId); clientContext.ExecuteQueryRetry(); TaxonomyField taxField = fieldQuery.Cast<TaxonomyField>().FirstOrDefault(); clientContext.Load(taxField); clientContext.ExecuteQueryRetry(); if (taxField.AllowMultipleValues) { var termValuesString = String.Empty; foreach (var term in termValues) { 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); item.Update(); clientContext.ExecuteQueryRetry(); } else { throw new ArgumentException(CoreResources.TaxonomyExtensions_Field_Is_Not_Multivalues, taxField.StaticName); } }
/// <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. /// </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; }
public void EnsureField_WhenTaxonomySingleOrMultiAndWebField_AndSiteCollectionSpecificTermSet_ShouldApplyDefaultValue() { using (var testScope = SiteTestScope.BlankSite()) { // Arrange var testTermSet = new TermSetInfo(Guid.NewGuid(), "Test Term Set"); // keep Ids random because, if this test fails midway, the term // set will not be cleaned up and upon next test run we will // run into a term set and term ID conflicts. var levelOneTermA = new TermInfo(Guid.NewGuid(), "Term A", testTermSet); var levelOneTermB = new TermInfo(Guid.NewGuid(), "Term B", testTermSet); var levelTwoTermAA = new TermInfo(Guid.NewGuid(), "Term A-A", testTermSet); var levelTwoTermAB = new TermInfo(Guid.NewGuid(), "Term A-B", testTermSet); TaxonomySession session = new TaxonomySession(testScope.SiteCollection); TermStore defaultSiteCollectionTermStore = session.DefaultSiteCollectionTermStore; Group defaultSiteCollectionGroup = defaultSiteCollectionTermStore.GetSiteCollectionGroup(testScope.SiteCollection); TermSet newTermSet = defaultSiteCollectionGroup.CreateTermSet(testTermSet.Label, testTermSet.Id); Term createdTermA = newTermSet.CreateTerm(levelOneTermA.Label, Language.English.Culture.LCID, levelOneTermA.Id); Term createdTermB = newTermSet.CreateTerm(levelOneTermB.Label, Language.English.Culture.LCID, levelOneTermB.Id); Term createdTermAA = createdTermA.CreateTerm(levelTwoTermAA.Label, Language.English.Culture.LCID, levelTwoTermAA.Id); Term createdTermAB = createdTermA.CreateTerm(levelTwoTermAB.Label, Language.English.Culture.LCID, levelTwoTermAB.Id); defaultSiteCollectionTermStore.CommitAll(); TaxonomyFieldInfo taxoFieldInfo = new TaxonomyFieldInfo( "TestInternalNameTaxo", new Guid("{0C58B4A1-B360-47FE-84F7-4D8F58AE80F6}"), "NameKey", "DescriptionKey", "GroupKey") { DefaultValue = new TaxonomyValue(levelOneTermA), TermStoreMapping = new TaxonomyContext(testTermSet) // choices limited to all terms in test term set }; TaxonomyMultiFieldInfo taxoMultiFieldInfo = new TaxonomyMultiFieldInfo( "TestInternalNameTaxoMulti", new Guid("{B2517ECF-819E-4F75-88AF-18E926AD30BD}"), "NameKeyMulti", "DescriptionKey", "GroupKey") { DefaultValue = new TaxonomyValueCollection( new List<TaxonomyValue>() { new TaxonomyValue(levelTwoTermAA), new TaxonomyValue(levelTwoTermAB) }), TermStoreMapping = new TaxonomyContext(levelOneTermA) // choices limited to children of a specific term, instead of having full term set choices }; using (var injectionScope = IntegrationTestServiceLocator.BeginLifetimeScope()) { IFieldHelper fieldHelper = injectionScope.Resolve<IFieldHelper>(); var fieldsCollection = testScope.SiteCollection.RootWeb.Fields; // Act SPField fieldSingle = fieldHelper.EnsureField(fieldsCollection, taxoFieldInfo); SPField fieldMulti = fieldHelper.EnsureField(fieldsCollection, taxoMultiFieldInfo); var fieldValue = new TaxonomyFieldValue(fieldSingle.DefaultValue); var fieldMultiValueCollection = new TaxonomyFieldValueCollection(fieldMulti.DefaultValue); // Assert Assert.AreNotEqual(-1, fieldValue.WssId); // a lookup ID to the TaxonomyHiddenList should be properly initialized at all times (lookup ID == -1 means you're depending on too much magic) Assert.AreEqual("Term A", fieldValue.Label); Assert.AreEqual(levelOneTermA.Id, new Guid(fieldValue.TermGuid)); Assert.AreNotEqual(-1, fieldMultiValueCollection[0].WssId); // lookup ID to TaxoHiddenList should also be initialized on multi-values Assert.AreEqual("Term A-A", fieldMultiValueCollection[0].Label); Assert.AreEqual(levelTwoTermAA.Id, new Guid(fieldMultiValueCollection[0].TermGuid)); Assert.AreNotEqual(-1, fieldMultiValueCollection[1].WssId); Assert.AreEqual("Term A-B", fieldMultiValueCollection[1].Label); Assert.AreEqual(levelTwoTermAB.Id, new Guid(fieldMultiValueCollection[1].TermGuid)); // Same asserts, but on re-fetched field (to make sure DefaultValue was persisted properly) SPField fieldSingleRefetched = testScope.SiteCollection.RootWeb.Fields[taxoFieldInfo.Id]; SPField fieldMultiRefetched = testScope.SiteCollection.RootWeb.Fields[taxoMultiFieldInfo.Id]; fieldValue = new TaxonomyFieldValue(fieldSingleRefetched.DefaultValue); fieldMultiValueCollection = new TaxonomyFieldValueCollection(fieldMultiRefetched.DefaultValue); Assert.AreNotEqual(-1, fieldValue.WssId); // a lookup ID to the TaxonomyHiddenList should be properly initialized at all times (lookup ID == -1 means you're depending on too much magic) Assert.AreEqual("Term A", fieldValue.Label); Assert.AreEqual(levelOneTermA.Id, new Guid(fieldValue.TermGuid)); Assert.AreNotEqual(-1, fieldMultiValueCollection[0].WssId); // lookup ID to TaxoHiddenList should also be initialized on multi-values Assert.AreEqual("Term A-A", fieldMultiValueCollection[0].Label); Assert.AreEqual(levelTwoTermAA.Id, new Guid(fieldMultiValueCollection[0].TermGuid)); Assert.AreNotEqual(-1, fieldMultiValueCollection[1].WssId); Assert.AreEqual("Term A-B", fieldMultiValueCollection[1].Label); Assert.AreEqual(levelTwoTermAB.Id, new Guid(fieldMultiValueCollection[1].TermGuid)); } // Cleanup term set so that we don't pollute the metadata store newTermSet.Delete(); defaultSiteCollectionTermStore.CommitAll(); } }
public void EnsureField_WhenTaxonomySingleOrMultiAndListField_AndGlobalTermSet_ShouldApplyDefaultValue() { using (var testScope = SiteTestScope.BlankSite()) { // Arrange Guid testGroupId = new Guid("{B7B56932-E191-46C7-956F-4C6E5E4F6020}"); var testTermSet = new TermSetInfo(Guid.NewGuid(), "Test Term Set") // keep Ids random because, if this test fails midway, the term { // must specify group, otherwise we would be describing a term set belonging to a site-specific group Group = new TermGroupInfo(testGroupId, "Dynamite Test Group") }; // set will not be cleaned up and upon next test run we will // run into a term set and term ID conflicts. var levelOneTermA = new TermInfo(Guid.NewGuid(), "Term A", testTermSet); var levelOneTermB = new TermInfo(Guid.NewGuid(), "Term B", testTermSet); var levelTwoTermAA = new TermInfo(Guid.NewGuid(), "Term A-A", testTermSet); var levelTwoTermAB = new TermInfo(Guid.NewGuid(), "Term A-B", testTermSet); TaxonomySession session = new TaxonomySession(testScope.SiteCollection); TermStore defaultSiteCollectionTermStore = session.DefaultSiteCollectionTermStore; // Cleanup group (maybe the test failed last time and the old group ended up polluting the term store this.DeleteGroupIfExists(defaultSiteCollectionTermStore, testGroupId); Group testGroup = defaultSiteCollectionTermStore.CreateGroup("Dynamite Test Group", testGroupId); TermSet newTermSet = testGroup.CreateTermSet(testTermSet.Label, testTermSet.Id); Term createdTermA = newTermSet.CreateTerm(levelOneTermA.Label, Language.English.Culture.LCID, levelOneTermA.Id); Term createdTermB = newTermSet.CreateTerm(levelOneTermB.Label, Language.English.Culture.LCID, levelOneTermB.Id); Term createdTermAA = createdTermA.CreateTerm(levelTwoTermAA.Label, Language.English.Culture.LCID, levelTwoTermAA.Id); Term createdTermAB = createdTermA.CreateTerm(levelTwoTermAB.Label, Language.English.Culture.LCID, levelTwoTermAB.Id); defaultSiteCollectionTermStore.CommitAll(); TaxonomyFieldInfo taxoFieldInfo = new TaxonomyFieldInfo( "TestInternalNameTaxo", new Guid("{0C58B4A1-B360-47FE-84F7-4D8F58AE80F6}"), "NameKey", "DescriptionKey", "GroupKey") { DefaultValue = new TaxonomyValue(levelOneTermA), TermStoreMapping = new TaxonomyContext(testTermSet) // choices limited to all terms in test term set }; TaxonomyMultiFieldInfo taxoMultiFieldInfo = new TaxonomyMultiFieldInfo( "TestInternalNameTaxoMulti", new Guid("{B2517ECF-819E-4F75-88AF-18E926AD30BD}"), "NameKeyMulti", "DescriptionKey", "GroupKey") { DefaultValue = new TaxonomyValueCollection( new List<TaxonomyValue>() { new TaxonomyValue(levelTwoTermAA), new TaxonomyValue(levelTwoTermAB) }), TermStoreMapping = new TaxonomyContext(levelOneTermA) // choices limited to children of a specific term, instead of having full term set choices }; ListInfo listInfo = new ListInfo("sometestlistpath", "DynamiteTestListNameKey", "DynamiteTestListDescriptionKey"); using (var injectionScope = IntegrationTestServiceLocator.BeginLifetimeScope()) { IListHelper listHelper = injectionScope.Resolve<IListHelper>(); var list = listHelper.EnsureList(testScope.SiteCollection.RootWeb, listInfo); IFieldHelper fieldHelper = injectionScope.Resolve<IFieldHelper>(); var fieldsCollection = list.Fields; // Ensure one of the two on the root web (tweak the definition a little bit on the list def) fieldHelper.EnsureField(testScope.SiteCollection.RootWeb.Fields, taxoMultiFieldInfo); taxoMultiFieldInfo.Required = RequiredType.Required; // Act SPField fieldSingle = fieldHelper.EnsureField(fieldsCollection, taxoFieldInfo); SPField fieldMulti = fieldHelper.EnsureField(fieldsCollection, taxoMultiFieldInfo); var fieldValue = new TaxonomyFieldValue(fieldSingle.DefaultValue); var fieldMultiValueCollection = new TaxonomyFieldValueCollection(fieldMulti.DefaultValue); // Assert Assert.AreNotEqual(-1, fieldValue.WssId); // a lookup ID to the TaxonomyHiddenList should be properly initialized at all times (lookup ID == -1 means you're depending on too much magic) Assert.AreEqual("Term A", fieldValue.Label); Assert.AreEqual(levelOneTermA.Id, new Guid(fieldValue.TermGuid)); Assert.AreNotEqual(-1, fieldMultiValueCollection[0].WssId); // lookup ID to TaxoHiddenList should also be initialized on multi-values Assert.AreEqual("Term A-A", fieldMultiValueCollection[0].Label); Assert.AreEqual(levelTwoTermAA.Id, new Guid(fieldMultiValueCollection[0].TermGuid)); Assert.AreNotEqual(-1, fieldMultiValueCollection[1].WssId); Assert.AreEqual("Term A-B", fieldMultiValueCollection[1].Label); Assert.AreEqual(levelTwoTermAB.Id, new Guid(fieldMultiValueCollection[1].TermGuid)); Assert.IsTrue(fieldMulti.Required); // Same asserts, but on re-fetched field (to make sure DefaultValue was persisted properly) SPField fieldSingleRefetched = testScope.SiteCollection.RootWeb.Lists[list.ID].Fields[taxoFieldInfo.Id]; SPField fieldMultiRefetched = testScope.SiteCollection.RootWeb.Lists[list.ID].Fields[taxoMultiFieldInfo.Id]; fieldValue = new TaxonomyFieldValue(fieldSingle.DefaultValue); fieldMultiValueCollection = new TaxonomyFieldValueCollection(fieldMulti.DefaultValue); Assert.AreNotEqual(-1, fieldValue.WssId); // a lookup ID to the TaxonomyHiddenList should be properly initialized at all times (lookup ID == -1 means you're depending on too much magic) Assert.AreEqual("Term A", fieldValue.Label); Assert.AreEqual(levelOneTermA.Id, new Guid(fieldValue.TermGuid)); Assert.AreNotEqual(-1, fieldMultiValueCollection[0].WssId); // lookup ID to TaxoHiddenList should also be initialized on multi-values Assert.AreEqual("Term A-A", fieldMultiValueCollection[0].Label); Assert.AreEqual(levelTwoTermAA.Id, new Guid(fieldMultiValueCollection[0].TermGuid)); Assert.AreNotEqual(-1, fieldMultiValueCollection[1].WssId); Assert.AreEqual("Term A-B", fieldMultiValueCollection[1].Label); Assert.AreEqual(levelTwoTermAB.Id, new Guid(fieldMultiValueCollection[1].TermGuid)); Assert.IsTrue(fieldMultiRefetched.Required); } // Cleanup term group so that we don't pollute the metadata store this.DeleteGroupIfExists(defaultSiteCollectionTermStore, testGroupId); } }
private TaxonomyFieldValueCollection GetTaxonomyFieldValueCollection(TaxonomyField fieldToSet) { byte someData = 0; // Create a temporary item to create the proper TaxonomyHiddenList items necessary to initialize the WSSids for the folder metadata defaults string tempPageName = string.Format(CultureInfo.InvariantCulture, "Temp-{0}.aspx", Guid.NewGuid().ToString()); SPFile tempFile = ((SPDocumentLibrary)fieldToSet.ParentList).RootFolder.Files.Add(tempPageName, new byte[1] { someData }); SPListItem tempItem = tempFile.Item; SPContentType contentTypeWithField = FindContentTypeWithField(fieldToSet.ParentList.ContentTypes, fieldToSet); SPContentTypeId contentTypeId = contentTypeWithField.Id; tempItem[SPBuiltInFieldId.ContentTypeId] = contentTypeId; tempItem.Update(); // re-fetch temp item, now with proper content types tempItem = fieldToSet.ParentList.GetItemById(tempItem.ID); var itemField = tempItem.Fields[fieldToSet.Id] as TaxonomyField; TaxonomyFieldValueCollection fieldValues = new TaxonomyFieldValueCollection(fieldToSet); foreach (Term term in this.Terms) { TaxonomyFieldValue fieldValue = new TaxonomyFieldValue(fieldToSet); fieldValue.TermGuid = term.Id.ToString(); fieldValue.Label = term.Name; fieldValues.Add(fieldValue); } // Force population of field values to hit the TaxonomyHiddenList and generate some WSSid's itemField.SetFieldValue(tempItem, fieldValues); // Those taxonomy field values in the collection don't have a proper ValidatedString, but their WSSid's have been populated TaxonomyFieldValueCollection finalValue = tempItem[itemField.InternalName] as TaxonomyFieldValueCollection; // Clean up the temporary item tempFile.Delete(); return finalValue; }
/// <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; }