/// <summary> /// Helper Method to set a Taxonomy Field on a list item /// </summary> /// <param name="ctx">The Authenticated ClientContext</param> /// <param name="listItem">The listitem to modify</param> /// <param name="model">Domain Object of key/value pairs of the taxonomy field & value</param> public static void SetTaxonomyField(ClientContext ctx, ListItem listItem, Hashtable model) { FieldCollection _fields = listItem.ParentList.Fields; ctx.Load(_fields); ctx.ExecuteQuery(); foreach(var _key in model.Keys) { var _termName = model[_key].ToString(); TaxonomyField _field = ctx.CastTo<TaxonomyField>(_fields.GetByInternalNameOrTitle(_key.ToString())); ctx.Load(_field); ctx.ExecuteQuery(); Guid _id = _field.TermSetId; string _termID = AutoTaggingHelper.GetTermIdByName(ctx, _termName, _id ); var _termValue = new TaxonomyFieldValue() { Label = _termName, TermGuid = _termID, WssId = -1 }; _field.SetFieldValueByValue(listItem, _termValue); listItem.Update(); ctx.ExecuteQuery(); } }
internal static void AddOrder (this ClientContext ctx, string title, string customerId, string ProductId, string price) { var orders = ctx.Web.Lists.GetByTitle("Order"); ListItem li = orders.AddItem(new ListItemCreationInformation()); li["Title"] = title; li["Customer"] = new FieldLookupValue() { LookupId = customerId.ToInt32()}; li["Product_2"] = new TaxonomyFieldValue() { TermGuid = ProductId, Label="", WssId=-1}; li["Price"] = price; li.Update(); ctx.ExecuteQuery(); }
public static void AddAccusseDeLecture(string webUrl, int docID, string docName, User lecteur, string taxLabel = null, string termGuid = null) { using (ClientContext ctx = SPConnection.GetSPOLContext(webUrl)) { List itemList = ctx.Web.Lists.GetByTitle("Accusés de lecture"); ListItemCreationInformation itemCreateInfo = new ListItemCreationInformation(); ListItem itemtoADD = itemList.AddItem(itemCreateInfo); itemtoADD["Title"] = docName; FieldUserValue usrValue = new FieldUserValue(); usrValue.LookupId = lecteur.Id;; itemtoADD["Lecteur"] = usrValue; if (!string.IsNullOrEmpty(taxLabel)) { var termValue = new TaxonomyFieldValue(); termValue.Label = taxLabel; termValue.TermGuid = termGuid; termValue.WssId = -1; itemtoADD["UF_x0020_du_x0020_lecteur"] = termValue; } FieldLookupValue val = new FieldLookupValue(); val.LookupId = docID; itemtoADD["Document"] = val; itemtoADD["Document_x0020_lu"] = false; itemtoADD["Commentaires_x0020__x0028_inform"] = ""; itemtoADD.Update(); ctx.ExecuteQuery(); } }
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> /// Helper Method to set a Taxonomy Field on a list item /// </summary> /// <param name="ctx">The Authenticated ClientContext</param> /// <param name="listItem">The listitem to modify</param> /// <param name="model">Domain Object of key/value pairs of the taxonomy field & value</param> public static void SetTaxonomyField(ClientContext ctx, ListItem listItem, Hashtable model) { FieldCollection _fields = listItem.ParentList.Fields; ctx.Load(_fields); ctx.ExecuteQuery(); foreach (var _key in model.Keys) { var _termName = model[_key].ToString(); TaxonomyField _field = ctx.CastTo <TaxonomyField>(_fields.GetByInternalNameOrTitle(_key.ToString())); ctx.Load(_field); ctx.ExecuteQuery(); Guid _id = _field.TermSetId; string _termID = AutoTaggingHelper.GetTermIdByName(ctx, _termName, _id); var _termValue = new TaxonomyFieldValue() { Label = _termName, TermGuid = _termID, WssId = -1 }; _field.SetFieldValueByValue(listItem, _termValue); listItem.Update(); ctx.ExecuteQuery(); } }
/// <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 void SetTaxonomyFieldValue(this ListItem item, Guid fieldId, string label, Guid termGuid) { ClientContext clientContext = item.Context as ClientContext; List list = item.ParentList; clientContext.Load(list); clientContext.ExecuteQuery(); IEnumerable <Field> fieldQuery = clientContext.LoadQuery( list.Fields .Include( fieldArg => fieldArg.TypeAsString, fieldArg => fieldArg.Id, fieldArg => fieldArg.InternalName ) ).Where(fieldArg => fieldArg.Id == fieldId); clientContext.ExecuteQuery(); TaxonomyField taxField = fieldQuery.Cast <TaxonomyField>().FirstOrDefault(); clientContext.Load(taxField); clientContext.ExecuteQuery(); TaxonomyFieldValue fieldValue = new TaxonomyFieldValue(); fieldValue.Label = label; fieldValue.TermGuid = termGuid.ToString(); fieldValue.WssId = -1; taxField.SetFieldValueByValue(item, fieldValue); item.Update(); clientContext.ExecuteQuery(); }
/// <summary> /// Writes a taxonomy 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 termInfo = fieldValueInfo.Value as TaxonomyValue; TaxonomyFieldValue newTaxonomyFieldValue = null; TaxonomyField taxonomyField = (TaxonomyField)item.Fields.GetField(fieldValueInfo.FieldInfo.InternalName); newTaxonomyFieldValue = new TaxonomyFieldValue(taxonomyField); var noteField = item.Fields[taxonomyField.TextField]; if (termInfo != null && termInfo.Term != null) { string labelGuidPair = TaxonomyItem.NormalizeName(termInfo.Term.Label) + TaxonomyField.TaxonomyGuidLabelDelimiter + termInfo.Term.Id.ToString().ToUpperInvariant(); // PopulateFromLabelGuidPair takes care of looking up the WssId value and creating a new item in the TaxonomyHiddenList if needed. // Main taxonomy field value format: 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/ee567833.aspx newTaxonomyFieldValue.PopulateFromLabelGuidPair(labelGuidPair); // Must write associated note field as well as the main taxonomy field. // Note field value format: Label|Guid // Reference: http://nickhobbs.wordpress.com/2012/02/21/sharepoint-2010-how-to-set-taxonomy-field-values-programmatically/ item[noteField.InternalName] = labelGuidPair; } else { // No taxonomy value, make sure to empty the note field as well item[noteField.InternalName] = null; } item[fieldValueInfo.FieldInfo.InternalName] = newTaxonomyFieldValue; }
/// <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 TaxonomyValue 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 TaxonomyFieldValue(field); taxFieldVal.PopulateFromLabelGuidPair(fieldValue.ToString()); var taxValue = new TaxonomyValue(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. InitTaxonomyContextForValue(taxValue, field, site); return(taxValue); } return(null); }
//CheckTermGroupName //GetDeatils public Advertisment GetDeatils(ClientContext context, string listTitle, int id) { Advertisment adDetails = new Advertisment(); if (context != null) { List list = context.Web.Lists.GetByTitle(listTitle); ListItem newItem = list.GetItemById(id); context.Load(newItem); context.ExecuteQuery(); TaxonomyFieldValue taxFieldValue = newItem["Kategorier"] as TaxonomyFieldValue; FieldUserValue user = (FieldUserValue)newItem["S_x00e4_ljare"]; adDetails = new Advertisment { ID = Convert.ToInt32(newItem["ID"]), ProductTitle = newItem["Title"].ToString(), Description = Convert.ToString(newItem["ubza"]), Created = Convert.ToDateTime(newItem["Created"]), Price = Convert.ToDecimal(newItem["Pris"]), Category = taxFieldValue.Label, ImageUrl = ((FieldUrlValue)(newItem["Bild"])).Url, Seller = user.Email, SellerToken = VerifyUser(user), }; } return(adDetails); }
//RetriveallFields //GetItems public List <Advertisment> GetItems(ClientContext context, string listTitle) { ListItemCollection listItems = RetriveList2(context, listTitle); List <Advertisment> products = new List <Advertisment>(); foreach (var items in listItems) { TaxonomyFieldValue taxFieldValue = items["Kategorier"] as TaxonomyFieldValue; FieldUserValue user = (FieldUserValue)items["S_x00e4_ljare"]; Advertisment product = new Advertisment { ID = Convert.ToInt32(items["ID"]), ProductTitle = items["Title"].ToString(), Description = Convert.ToString(items["ubza"]), Created = Convert.ToDateTime(items["Created"]), Price = Convert.ToDecimal(items["Pris"]), Category = taxFieldValue.Label, Seller = user.Email, SellerToken = VerifyUser(user), }; products.Add(product); } return(products); }
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(); } } }
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); }
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 SetMetadataFields(ClientContext cc, JObject inputFields, FieldCollection fields, ListItem item) { foreach (KeyValuePair <string, JToken> inputField in inputFields) { var field = fields.GetByInternalNameOrTitle(inputField.Key); cc.Load(field); cc.ExecuteQuery(); Console.WriteLine(field.TypeAsString); if (field.TypeAsString.Equals("TaxonomyFieldType")) { var taxKeywordField = cc.CastTo <TaxonomyField>(field); Guid _id = taxKeywordField.TermSetId; string _termID = TermHelper.GetTermIdByName(cc, inputField.Value.ToString(), _id); TaxonomyFieldValue termValue = new TaxonomyFieldValue() { Label = inputField.Value.ToString(), TermGuid = _termID, //WssId = -1 //WssId = (int)taxObj["WssId"] }; taxKeywordField.SetFieldValueByValue(item, termValue); taxKeywordField.Update(); } else if (field.TypeAsString.Equals("User")) { var user = FieldUserValue.FromUser(inputField.Value.ToString()); item[inputField.Key] = user; } else if (field.TypeAsString.Equals("DateTime") && inputField.Value.ToString() != "") { string dateTimeStr = inputField.Value.ToString(); dateTimeStr = dateTimeStr.Replace("~t", ""); item[inputField.Key] = Convert.ToDateTime(dateTimeStr); } else if (inputField.Value.ToString() == "") { continue; } else { item[inputField.Key] = inputField.Value.ToString(); } // This method works but not practical //string termValue = "-1;#" + taxObj["Label"].ToString() + "|" + taxObj["TermGuid"].ToString(); //item[inputField.Key] = termValue; item.SystemUpdate(); //cc.ExecuteQuery(); } }
public static void SettingAndGettingFieldValues(ClientContext ctx) { List list = ctx.Web.GetListByUrl("lists/books"); ListItem item = list.GetItemById(1); ctx.Load(item); ctx.ExecuteQuery(); Console.WriteLine(item["OD1_TaxCode"].ToString()); Console.WriteLine(item["OD1_Book"].ToString()); /////////////////// //// setting ///// ////////////////// // lookup field ListItem lookUpItem = list.GetItemById(4); ctx.Load(lookUpItem); ctx.ExecuteQuery(); item["OD1_Book"] = lookUpItem.Id; item.Update(); ctx.ExecuteQuery(); // tax field Term term = ctx.Site.GetTermByName("02806e1e-aeb7-4542-bf7e-0d1a3fdbc9d3".ToGuid(), "Romance"); item.SetTaxonomyFieldValue("{FB53E9CD-CC30-432C-95F1-E64CE1B4F2A1}".ToGuid(), term.GetDefaultLabel(1033).Value, term.Id); /////////////////// //// getting ///// ////////////////// // lookup field FieldLookupValue lookupval = item["OD1_Book"] as FieldLookupValue; Console.WriteLine(lookupval.LookupValue); Console.WriteLine(lookupval.LookupId); TaxonomyFieldValue taxval = item["OD1_TaxCode"] as TaxonomyFieldValue; Console.WriteLine(taxval.Label); Console.WriteLine(taxval.TermGuid.ToString()); // alternate way of setting taxonomy item. //TaxonomyField taxField = list.Fields.GetById("{FB53E9CD-CC30-432C-95F1-E64CE1B4F2A1}".ToGuid()) as TaxonomyField; //taxField.SetFieldValueByTerm(item, term, 1033); }
private TermInfo ConvertToTermInfo(TaxonomyFieldValue taxonomyFieldValue) => new TermInfo { Label = taxonomyFieldValue.Label, TermGuid = taxonomyFieldValue.TermGuid, WssId = taxonomyFieldValue.WssId, TermSetId = _termSetId.ToString() };
public static string TaxonomyValueToString(TaxonomyFieldValue value) { if (value == null) { return(string.Empty); } return(value.Label); }
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()); }
public static string ToNormalString(this TaxonomyFieldValue value) { if (value == null) { return(string.Empty); } return(value.Label); }
private static string FormatTaxonomyString(TaxonomyField sharePointField, TaxonomyValue valueToApply) { var sharePointTaxonomyFieldValue = new TaxonomyFieldValue(sharePointField); string path = TaxonomyItem.NormalizeName(valueToApply.Term.Label) + TaxonomyField.TaxonomyGuidLabelDelimiter + valueToApply.Term.Id.ToString().ToUpperInvariant(); sharePointTaxonomyFieldValue.PopulateFromLabelGuidPair(path); return(sharePointTaxonomyFieldValue.ValidatedString); }
private static void addTaxonomyFieldValue(DataRow newRow, Property prop, object FieldValue) { TaxonomyFieldValue taxanomyValue = FieldValue as TaxonomyFieldValue; if (taxanomyValue != null) { newRow[prop.Name] = taxanomyValue.TermGuid; newRow[prop.Name + Constants.InternalProperties.Suffix_Value] = taxanomyValue.Label; } }
/// <summary> /// Sets value to a Taxonomy field. /// </summary> /// <param name="fieldName">Field name.</param> /// <param name="value">A <see cref="Term"/> object to set.</param> public virtual void SetTaxonomy(string fieldName, Term value) { TaxonomyFieldValue taxonomyFieldValue = new TaxonomyFieldValue(""); taxonomyFieldValue.TermGuid = value.Id.ToString(); taxonomyFieldValue.Label = value.Name; taxonomyFieldValue.WssId = value.EnsureWssId(this.Site, fieldName.Equals("TaxKeyword")); this[fieldName] = taxonomyFieldValue; SetTaxonomyTextValue(fieldName, new[] { value }); }
/// <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) { if (value == System.DBNull.Value) { return null; } TaxonomyValue convertedValue = null; var taxonomyFieldValue = value as TaxonomyFieldValue; if (taxonomyFieldValue == 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) { taxonomyFieldValue = new TaxonomyFieldValue(fieldObject); taxonomyFieldValue.PopulateFromLabelGuidPair(stringValue); } else { return null; } } } if (taxonomyFieldValue != null && !string.IsNullOrEmpty(taxonomyFieldValue.TermGuid)) { 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 Term underlyingTerm = this.taxonomyService.GetTermForId(SPContext.Current.Site, new Guid(taxonomyFieldValue.TermGuid)); if (underlyingTerm != null) { convertedValue = new TaxonomyValue(underlyingTerm); } } 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 TaxonomyValue constructor convertedValue = new TaxonomyValue(taxonomyFieldValue); } } return convertedValue; }
public static SPTerm ToSPTerm(this TaxonomyFieldValue value, IEnumerable <SPTerm> terms) { if (value == null) { return(new SPTerm()); } var guid = new Guid(value.TermGuid); return(terms.FirstOrDefault(t => t.Id == guid)); }
public static TaxonomyFieldValue GetTaxonomyFieldValue(SPSite site, TaxonomyField field, string value, bool addIfDoesNotExist /*, out bool newTermAdded*/) { TaxonomyFieldValue taxonomyFieldValue = new TaxonomyFieldValue(field); TaxonomyFieldValue tempValue = GetTaxonomyFieldValue(site, field.SspId, field.TermSetId, value, addIfDoesNotExist /*, out newTermAdded*/); if (tempValue != null) { taxonomyFieldValue.PopulateFromLabelGuidPair(tempValue.ToString()); } return(taxonomyFieldValue); }
protected override ActivityExecutionStatus Execute(ActivityExecutionContext executionContext) { // Get the workflow context for the workflow activity. NWWorkflowContext ctx = NWWorkflowContext.GetContext( this.__Context, new Guid(this.__ListId), this.__ListItem.Id, this.WorkflowInstanceId, this); string resolvedFieldValue = ctx.AddContextDataToString(this.TaxFieldValue); string resolvedListID = ctx.AddContextDataToString(this.lookupList); int resolvedItemID = int.Parse(ctx.AddContextDataToString(this.itemID)); base.LogProgressStart(ctx); Nintex.Workflow.Diagnostics.EventLogger.Log( "Updating '" + TaxonomyFieldName + "' Value '" + TaxFieldValue + "' ", Microsoft.SharePoint.Administration.TraceSeverity.Verbose, _ErrorSource); try { SPList list = ctx.Web.Lists.GetList(new Guid(resolvedListID), false); SPListItem item = list.GetItemById(resolvedItemID); TaxonomyField taxonomyField = list.Fields[TaxonomyFieldName] as TaxonomyField; TaxonomyFieldValue taxonomyFieldValue = new TaxonomyFieldValue(taxonomyField); String[] TermValues = resolvedFieldValue.Split('|'); if (TermValues[0].Length > 0) { // value|GUID if (TermValues.Length == 2) { taxonomyFieldValue.Label = TermValues[0]; taxonomyFieldValue.TermGuid = TermValues[1]; } taxonomyField.SetFieldValue(item, taxonomyFieldValue); item.SystemUpdate(false); } } catch (Exception ex) { Nintex.Workflow.Diagnostics.EventLogger.Log( "Error occured while updating '" + TaxonomyFieldName + "' Value '" + resolvedFieldValue + "' " + ex.Message, Microsoft.SharePoint.Administration.TraceSeverity.Unexpected, _ErrorSource); } base.LogProgressEnd(ctx, executionContext); return(ActivityExecutionStatus.Closed); }
/// <summary> /// Sets a default for a field at a location. /// </summary> /// <param name="metadata">Provides the method to set the default value for the field</param> /// <param name="folder"><see cref="SPFolder"/> location at which to set the default value</param> /// <param name="list">List of the TaxonomyField containing the validatedString corresponding to the default value.</param> public void ApplyFieldOnMetadata(MetadataDefaults metadata, SPFolder folder, SPList list) { var term = this.Term; var labelGuidPair = term.GetDefaultLabel((int)list.ParentWeb.Language) + "|" + term.Id; var taxonomyField = list.Fields.GetField(this.FieldName) as TaxonomyField; var newTaxonomyFieldValue = new TaxonomyFieldValue(taxonomyField); // PopulateFromLabelGuidPair takes care of looking up the WssId value and creating a new item in the TaxonomyHiddenList if needed. // Reference: http://msdn.microsoft.com/en-us/library/ee567833.aspx newTaxonomyFieldValue.PopulateFromLabelGuidPair(labelGuidPair); metadata.SetFieldDefault(folder, this.FieldName, newTaxonomyFieldValue.ValidatedString); }
public static TaxonomyFieldValue GetTaxonomyFieldValue(SPSite site, TaxonomyField field, string value, out List <int> wssIds) { TaxonomySession taxonomySession = new TaxonomySession(site); TermStore termStore = taxonomySession.TermStores[field.SspId]; TermSet termSet = termStore.GetTermSet(field.TermSetId); wssIds = new List <int>(); TaxonomyFieldValue taxonomyFieldValue = TaxonomyFieldControl.GetTaxonomyValue(value); wssIds.AddRange(TaxonomyField.GetWssIdsOfTerm(site, termStore.Id, termSet.Id, new Guid(taxonomyFieldValue.TermGuid), true, 100)); return(taxonomyFieldValue); }
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); }
/// <summary> /// Initializes a <see cref="TermInfo"/> instance from a taxonomy field value and definition. /// </summary> /// <param name="field">The list field from which the TaxonomyFieldValue was extracted. This is needed to extract the full TaxonomyContext.</param> /// <param name="fieldValue">The actual taxonomy field value.</param> /// <returns>The easily serializable <see cref="TermInfo"/> object</returns> public TermInfo CreateFromTaxonomyFieldValue(TaxonomyField field, TaxonomyFieldValue fieldValue) { if (field == null) { throw new ArgumentNullException("field"); } if (fieldValue == null) { throw new ArgumentNullException("fieldValue"); } var termInfo = new TermInfo(); return(termInfo); }
//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); } }
/// <summary> /// Initializes a <see cref="TermInfo"/> instance from a taxonomy field value and definition. /// </summary> /// <param name="field">The list field from which the TaxonomyFieldValue was extracted. This is needed to extract the full TaxonomyContext.</param> /// <param name="fieldValue">The actual taxonomy field value.</param> /// <returns>The easily serializable <see cref="TermInfo"/> object</returns> public TermInfo CreateFromTaxonomyFieldValue(TaxonomyField field, TaxonomyFieldValue fieldValue) { if (field == null) { throw new ArgumentNullException("field"); } if (fieldValue == null) { throw new ArgumentNullException("fieldValue"); } var termInfo = new TermInfo(); return termInfo; }
/// <summary> /// Initializes a new instance of the <see cref="TaxonomyValue"/> class. /// </summary> /// <remarks>This constructor will not ensure the label respect the CurrentUICulture</remarks> /// <param name="taxonomyValue">The taxonomy value.</param> public TaxonomyValue(TaxonomyFieldValue taxonomyValue) { Guid termGuid; if (taxonomyValue == null) { throw new ArgumentNullException("taxonomyValue"); } if (!GuidExtension.TryParse(taxonomyValue.TermGuid, out termGuid)) { throw new ArgumentException("Cannot parse the Taxonomy field value's TermGuid.", "taxonomyValue"); } this.Id = termGuid; this.Label = taxonomyValue.Label; }
/// <summary> /// Initializes a new instance of the <see cref="TaxonomyValue"/> class. /// </summary> /// <remarks>This constructor will not ensure the label respect the CurrentUICulture</remarks> /// <param name="fieldValue">The actual taxonomy field value.</param> public TaxonomyValue(TaxonomyFieldValue fieldValue) { Guid termGuid; if (fieldValue == null) { throw new ArgumentNullException("fieldValue"); } if (!Guid.TryParse(fieldValue.TermGuid, out termGuid)) { throw new ArgumentException("Cannot parse the Taxonomy field value's TermGuid.", "fieldValue"); } this.Term = new TermInfo(termGuid, fieldValue.Label, null); this.Context = null; }
public static TaxonomyFieldValue GetTaxonomyFieldValue(string termName, Microsoft.SharePoint.Client.Field mmField, ClientContext clientContext) { //Cast field to TaxonomyField to get its TermSetId TaxonomyField taxField = clientContext.CastTo <TaxonomyField>(mmField); //Get term ID from name and term set ID string termId = GetTermIdForTerm(termName, taxField.TermSetId, clientContext); if (!string.IsNullOrEmpty(termId)) { //Set TaxonomyFieldValue TaxonomyFieldValue termValue = new TaxonomyFieldValue(); termValue.Label = termName; termValue.TermGuid = termId; termValue.WssId = -1; return(termValue); } return(null); }
public static TaxonomyFieldValue GetTaxonomyFieldValue(string termName, Field mmField, ClientContext clientContext) { //Ref: Steve Curran - http://sharepointfieldnotes.blogspot.com/2013_06_01_archive.html //Cast field to TaxonomyField to get its TermSetId TaxonomyField taxField = clientContext.CastTo<TaxonomyField>(mmField); //Get term ID from name and term set ID string termId = GetTermIdForTerm(termName, taxField.TermSetId, clientContext); if (!string.IsNullOrEmpty(termId)) { //Set TaxonomyFieldValue TaxonomyFieldValue termValue = new TaxonomyFieldValue(); termValue.Label = termName; termValue.TermGuid = termId; termValue.WssId = -1; return termValue; } return 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) { TaxonomyValue convertedValue = null; if (value == DBNull.Value) { return null; } var taxonomyFieldValue = value as TaxonomyFieldValue; if (taxonomyFieldValue == null) { var stringValue = value as string; if (!string.IsNullOrEmpty(stringValue)) { taxonomyFieldValue = new TaxonomyFieldValue(stringValue); } } if (taxonomyFieldValue != null && !string.IsNullOrEmpty(taxonomyFieldValue.TermGuid)) { 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 Term underlyingTerm = this.taxonomyService.GetTermForId(SPContext.Current.Site, new Guid(taxonomyFieldValue.TermGuid)); if (underlyingTerm != null) { convertedValue = new TaxonomyValue(underlyingTerm); } } 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 TaxonomyValue constructor convertedValue = new TaxonomyValue(taxonomyFieldValue); } } return convertedValue; }
/// <summary> /// Set a taxonomy value for a SPListItem /// </summary> /// <param name="web">The web.</param> /// <param name="item">The SPListItem.</param> /// <param name="fieldName">Field name to update.</param> /// <param name="termGroupName">Term group name.</param> /// <param name="termSetName">Term Set Name.</param> /// <param name="termLabel">Term Label.</param> public void SetTaxonomyFieldValue(SPWeb web, SPListItem item, string fieldName, string termGroupName, string termSetName, string termLabel) { var term = this._taxonomyService.GetTaxonomyValueForLabel(web.Site, termGroupName, termSetName, termLabel); var taxonomySession = new TaxonomySession(web.Site); TermStore termStore = taxonomySession.DefaultSiteCollectionTermStore; var termGroup = termStore.Groups[termGroupName]; var termSet = termGroup.TermSets[termSetName]; var taxField = item.Fields.GetFieldByInternalName(fieldName); if (term != null) { var taxonomyFieldValue = new TaxonomyFieldValue(taxField); string path = TaxonomyItem.NormalizeName(term.Label) + TaxonomyField.TaxonomyGuidLabelDelimiter + term.Id.ToString(); taxonomyFieldValue.PopulateFromLabelGuidPair(path); int[] ids = TaxonomyField.GetWssIdsOfTerm(web.Site, termStore.Id, termSet.Id, term.Id, true, 1); if (ids.Length == 0) { taxonomyFieldValue.WssId = -1; } ((TaxonomyField)taxField).SetFieldValue(item, taxonomyFieldValue); item.Update(); } }
/// <summary> /// Set default value for a taxonomy site column /// </summary> /// <param name="web">The web.</param> /// <param name="field">The field.</param> /// <param name="termGroupName">The term group name.</param> /// <param name="termSetName">the term set name.</param> /// <param name="termLabel">The term label.</param> public void SetDefaultTaxonomyValue(SPWeb web, SPField field, string termGroupName, string termSetName, string termLabel) { var term = this._taxonomyService.GetTaxonomyValueForLabel(web.Site, termGroupName, termSetName, termLabel); var taxonomySession = new TaxonomySession(web.Site); TermStore termStore = taxonomySession.DefaultSiteCollectionTermStore; var termGroup = termStore.Groups[termGroupName]; var termSet = termGroup.TermSets[termSetName]; if (term != null) { var statusTaxonomyFieldDefaultValue = new TaxonomyFieldValue(field); string path = TaxonomyItem.NormalizeName(term.Label) + TaxonomyField.TaxonomyGuidLabelDelimiter + term.Id.ToString(); statusTaxonomyFieldDefaultValue.PopulateFromLabelGuidPair(path); int[] ids = TaxonomyField.GetWssIdsOfTerm(web.Site, termStore.Id, termSet.Id, term.Id, true, 1); if (ids.Length == 0) { statusTaxonomyFieldDefaultValue.WssId = -1; } statusTaxonomyFieldDefaultValue.TermGuid = statusTaxonomyFieldDefaultValue.TermGuid.ToUpperInvariant(); field.DefaultValue = statusTaxonomyFieldDefaultValue.ValidatedString; field.Update(); } }
/// <summary> /// OnSubmitFile method for the content organizer /// </summary> /// <param name="contentOrganizerWeb">The web.</param> /// <param name="recordSeries">Record series.</param> /// <param name="userName">Submitting user name.</param> /// <param name="fileContent">File content.</param> /// <param name="properties">File properties.</param> /// <param name="finalFolder">The final folder.</param> /// <param name="resultDetails">Result processing details.</param> /// <returns>The CustomRouterResult.</returns> public override CustomRouterResult OnSubmitFile(EcmDocumentRoutingWeb contentOrganizerWeb, string recordSeries, string userName, Stream fileContent, RecordsRepositoryProperty[] properties, SPFolder finalFolder, ref string resultDetails) { this.ResolveDependencies(); var web = new SPSite(contentOrganizerWeb.DropOffZoneUrl).OpenWeb(); // Get routed document properties var documentProperties = EcmDocumentRouter.GetHashtableForRecordsRepositoryProperties( properties, recordSeries); // Example: Get a conventional field (8553196d-ec8d-4564-9861-3dbe931050c8 = FileLeafRef) string originalFileName = documentProperties["8553196d-ec8d-4564-9861-3dbe931050c8"].ToString(); // EncodedAbsUrl field string originalFileUrl = documentProperties["7177cfc7-f399-4d4d-905d-37dd51bc90bf"].ToString(); // Example: Get the SharePoint user who perform the action var user = web.EnsureUser(userName); // Example: Deal with errors if (originalFileName.ToLower().Contains("error")) { // Display error message SPUtility.TransferToErrorPage( string.Format(CultureInfo.InvariantCulture, "This is an error message")); // Save the error file in the Drop Off Library this.SaveDocumentToDropOffLibrary( fileContent, documentProperties, contentOrganizerWeb.DropOffZone, originalFileName, contentOrganizerWeb, user); return CustomRouterResult.SuccessCancelFurtherProcessing; } // Here is the business logic // Example: get a taxonomy field from document properties string confidentialityTaxValue = documentProperties[MyFields.MyTaxField.InternalName].ToString(); string confidentiality = new TaxonomyFieldValue(confidentialityTaxValue).Label; // Example: Set a new field to the item var indexDate = SPUtility.CreateISO8601DateTimeFromSystemDateTime( DateHelper.GetSharePointDateUtc(web, DateTime.Now)); // Be careful, if you want to add or modify some properties, use internal GUID instead of InternalName if (!documentProperties.ContainsKey(MyFields.MyIndexDate.ID.ToString())) { documentProperties.Add(MyFields.MyIndexDate.ID.ToString(), indexDate); } else { documentProperties[MyFields.MyIndexDate.ID.ToString()] = indexDate; } // Save the file in the final destination. You can get the newly created file here and apply further actions. var file = EcmDocumentRouter.SaveFileToFinalLocation( contentOrganizerWeb, finalFolder, fileContent, originalFileName, originalFileUrl, documentProperties, user, true, string.Empty); web.Dispose(); return CustomRouterResult.SuccessContinueProcessing; }
private static void SetProductCategory(ListItem item, Guid termID) { TaxonomyFieldValue taxonomyFieldValue = new TaxonomyFieldValue(); taxonomyFieldValue.TermGuid = termID.ToString(); fieldProductCategory.SetFieldValueByValue(item, taxonomyFieldValue); }
// This function reads the CSV file and applies the tags to the // taxonomy fields in the SharePoint list static void ImportTemplate(List list, List<TaxonomyField> taxonomyFields) { // Load TermSet for each field Dictionary<string, TermSetLookup> termSetsByInternalName = GetTermSetsByInternalName(taxonomyFields); // Load the Excel file Dictionary<string, ExcelRow> excelRowsByUrl = GetExcelRowsByUrl(termSetsByInternalName); // STEP 3: Update the list items List<string> fieldNames = taxonomyFields.Select(f => f.InternalName).ToList(); fieldNames.Add("ServerUrl"); ProcessListItems(list, fieldNames, delegate(ListItem listItem) { // Does the CSV file contain a row matching this list item? ExcelRow excelRow; if (!excelRowsByUrl.TryGetValue((string)listItem["ServerUrl"], out excelRow)) return; // no it does not excelRow.Processed = true; bool updated = false; foreach (KeyValuePair<string, Guid> pair in excelRow.Pairs) { TaxonomyField taxonomyField = taxonomyFields.First(f => f.InternalName == pair.Key); TaxonomyFieldValue taxonomyFieldValue = new TaxonomyFieldValue(); // (to clear the tag, you would specify the empty GUID here) taxonomyFieldValue.TermGuid = pair.Value.ToString(); TaxonomyFieldValue oldValue = (TaxonomyFieldValue)listItem.FieldValues[taxonomyField.InternalName]; if (oldValue == null || oldValue.TermGuid != taxonomyFieldValue.TermGuid) { taxonomyField.SetFieldValueByValue(listItem, taxonomyFieldValue); updated = true; } } if (updated) { Log("Updating item: " + listItem["ServerUrl"]); listItem.Update(); } Program.clientContext.ExecuteQuery(); } ); // Were any items missed? Log(""); List<ExcelRow> missedRows = excelRowsByUrl.Values.Where(row => !row.Processed).ToList(); if (missedRows.Count > 0) { Log("Failed to match these rows"); foreach (ExcelRow row in missedRows) Log(" " + row.ListItemUrl); } }
public static void SetTaxonomyFieldValue(this ListItem item, Guid fieldId, string label, Guid termGuid) { ClientContext clientContext = item.Context as ClientContext; List list = item.ParentList; clientContext.Load(list); clientContext.ExecuteQuery(); IEnumerable<Field> fieldQuery = clientContext.LoadQuery( list.Fields .Include( fieldArg => fieldArg.TypeAsString, fieldArg => fieldArg.Id, fieldArg => fieldArg.InternalName ) ).Where(fieldArg => fieldArg.Id == fieldId); clientContext.ExecuteQuery(); TaxonomyField taxField = fieldQuery.Cast<TaxonomyField>().FirstOrDefault(); clientContext.Load(taxField); clientContext.ExecuteQuery(); TaxonomyFieldValue fieldValue = new TaxonomyFieldValue(); fieldValue.Label = label; fieldValue.TermGuid = termGuid.ToString(); fieldValue.WssId = -1; taxField.SetFieldValueByValue(item, fieldValue); item.Update(); clientContext.ExecuteQuery(); }
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); } }
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 static TaxonomyFieldValue GetTaxonomyFieldValue(SPSite site, TaxonomyField field, string value, bool addIfDoesNotExist/*, out bool newTermAdded*/) { TaxonomyFieldValue taxonomyFieldValue = new TaxonomyFieldValue(field); TaxonomyFieldValue tempValue = GetTaxonomyFieldValue(site, field.SspId, field.TermSetId, value, addIfDoesNotExist/*, out newTermAdded*/); if (tempValue != null) { taxonomyFieldValue.PopulateFromLabelGuidPair(tempValue.ToString()); } return taxonomyFieldValue; }
private static bool TryParseTaxonomyFieldValue(string value, out TaxonomyFieldValue taxValue) { bool res = false; taxValue = new TaxonomyFieldValue(); if (!string.IsNullOrEmpty(value)) { string[] split = value.Split(new string[] { ";#" }, StringSplitOptions.None); int wssId = 0; if (split.Length > 0 && int.TryParse(split[0], out wssId)) { taxValue.WssId = wssId; res = true; } if (res && split.Length == 2) { var term = split[1]; string[] splitTerm = term.Split(new string[] { "|" }, StringSplitOptions.None); Guid termId = Guid.Empty; if (splitTerm.Length > 0) { res = Guid.TryParse(splitTerm[splitTerm.Length - 1], out termId); taxValue.TermGuid = termId.ToString(); if (res && splitTerm.Length > 1) { taxValue.Label = splitTerm[0]; } } else { res = false; } res = true; } else if (split.Length == 1 && int.TryParse(value, out wssId)) { taxValue.WssId = wssId; res = true; } } return res; }
public TaxonomyFieldValue GetTaxonomyField(ClientContext ctx, ListItem listItem, string fieldName, string term) { FieldCollection _fields = listItem.ParentList.Fields; ctx.Load(_fields); ctx.ExecuteQuery(); TaxonomyField _field = ctx.CastTo<TaxonomyField>(_fields.GetByInternalNameOrTitle(fieldName)); ctx.Load(_field); ctx.ExecuteQuery(); Guid _id = _field.TermSetId; string _termID = AutoTaggingHelper.GetTermIdByName(ctx, term, _id); var _termValue = new TaxonomyFieldValue() { Label = term, TermGuid = _termID, WssId = -1 }; return _termValue; }
public static string TaxonomyValueToString(TaxonomyFieldValue value) { if (value == null) return string.Empty; return value.Label; }
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> /// Sets the default value for a managed metadata field /// </summary> /// <param name="field">Field to be wired up</param> /// <param name="taxonomyItem">Taxonomy TermSet or Term</param> /// <param name="defaultValue">default value for the field</param> public static void SetTaxonomyFieldDefaultValue(this Field field, TaxonomyItem taxonomyItem, string defaultValue) { if (string.IsNullOrEmpty(defaultValue)) { throw new ArgumentException("defaultValue"); } var clientContext = field.Context as ClientContext; taxonomyItem.ValidateNotNullOrEmpty("taxonomyItem"); var anchorTerm = taxonomyItem as Term; if (anchorTerm != default(Term) && !anchorTerm.IsPropertyAvailable("TermSet")) { clientContext.Load(anchorTerm.TermSet); clientContext.ExecuteQueryRetry(); } var termSet = taxonomyItem is Term ? anchorTerm.TermSet : taxonomyItem as TermSet; if (termSet == default(TermSet)) { throw new ArgumentException("Bound TaxonomyItem must be either a TermSet or a Term"); } // set the SSP ID and Term Set ID on the taxonomy field var taxField = clientContext.CastTo<TaxonomyField>(field); if (!termSet.IsPropertyAvailable("Terms")) { clientContext.Load(termSet.Terms); clientContext.ExecuteQueryRetry(); } Term defaultValTerm = termSet.Terms.GetByName(defaultValue); if (defaultValTerm != null) { clientContext.Load(defaultValTerm); clientContext.ExecuteQueryRetry(); TaxonomyFieldValue taxValue = new TaxonomyFieldValue(); taxValue.WssId = -1; taxValue.TermGuid = defaultValTerm.Id.ToString(); taxValue.Label = defaultValTerm.Name; //get validate string var validateValue = taxField.GetValidatedString(taxValue); field.Context.ExecuteQueryRetry(); taxField.DefaultValue = validateValue.Value; taxField.Update(); clientContext.ExecuteQueryRetry(); } }
/// <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 term = value as TaxonomyValue; TaxonomyFieldValue newTaxonomyFieldValue = null; TaxonomyField taxonomyField = (TaxonomyField)arguments.ListItem.Fields.GetField(arguments.ValueKey); newTaxonomyFieldValue = new TaxonomyFieldValue(taxonomyField); var noteField = arguments.ListItem.Fields[taxonomyField.TextField]; if (term != null) { string labelGuidPair = term.Label + "|" + term.Id; // PopulateFromLabelGuidPair takes care of looking up the WssId value and creating a new item in the TaxonomyHiddenList if needed. // Main taxonomy field value format: 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/ee567833.aspx newTaxonomyFieldValue.PopulateFromLabelGuidPair(labelGuidPair); // Must write associated note field as well as the main taxonomy field. // Note field value format: Label|Guid // Reference: http://nickhobbs.wordpress.com/2012/02/21/sharepoint-2010-how-to-set-taxonomy-field-values-programmatically/ arguments.FieldValues[noteField.InternalName] = labelGuidPair; } else { // No taxonomy value, make sure to empty the note field as well arguments.FieldValues[noteField.InternalName] = null; } return newTaxonomyFieldValue; }
/// <summary> /// Get the validated string for a Taxonomy Field /// </summary> /// <param name="web">Web to look for</param> /// <param name="fieldName">Field to search</param> /// <param name="termSet">The term set</param> /// <param name="termLabel">The term label</param> /// <param name="termGroup">The term group</param> /// <returns>The validated string.</returns> public string GetTaxonomyFieldValueValidatedString(SPWeb web, string fieldName, string termGroup, string termSet, string termLabel) { SPField field = web.Fields.GetFieldByInternalName(fieldName); TaxonomyValue term = this._taxonomyService.GetTaxonomyValueForLabel(web.Site, termGroup, termSet, termLabel); if (term != null) { // Must be exist in the Taxonomy Hidden List var taxonomyFieldValue = new TaxonomyFieldValue(field); taxonomyFieldValue.PopulateFromLabelGuidPair(TaxonomyItem.NormalizeName(term.Label) + "|" + term.Id); return taxonomyFieldValue.ValidatedString; } return string.Empty; }