Example #1
0
        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();
        }
Example #2
0
        /// <summary>
        /// Populates a list of <see cref="TermEntry"/> with the hierarchy of terms.
        /// The list is ordered so that roots appear right before their child terms.
        public static void PopulateTermEntries(List <TermEntry> termEntries, TaxonomyField field, IEnumerable <ContentItem> contentItems, int level)
        {
            foreach (var contentItem in contentItems)
            {
                var children = Array.Empty <ContentItem>();

                if (contentItem.Content.Terms is JArray termsArray)
                {
                    children = termsArray.ToObject <ContentItem[]>();
                }

                var termEntry = new TermEntry
                {
                    Term          = contentItem,
                    ContentItemId = contentItem.ContentItemId,
                    Selected      = field.TermContentItemIds.Contains(contentItem.ContentItemId),
                    Level         = level,
                    IsLeaf        = children.Length == 0
                };

                termEntries.Add(termEntry);

                if (children.Length > 0)
                {
                    PopulateTermEntries(termEntries, field, children, level + 1);
                }
            }
        }
        public static void ConnectTaxonomyField(TaxonomyField field, SPSite site, string termGroup, string termSetName, bool isOpen = false, bool createValuesInEditForm = false)
        {
            if (site == null) { return; }

            TaxonomySession session = new TaxonomySession(site);
            ConnectTaxonomyField(field, session, termGroup, termSetName, isOpen, createValuesInEditForm);
        }
        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);
        }
Example #5
0
        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);
        }
Example #6
0
        private void MatchTaxonomyField(SPListItem targetSPListItem, SPField targetSPField, string sourceValue)
        {
            // this is a managed metadata field
            TaxonomyField   managedField = targetSPField as TaxonomyField;
            TaxonomySession session      = new TaxonomySession(targetSPListItem.Web.Site);
            TermStore       termStore    = session.TermStores[managedField.SspId];
            TermSet         termSet      = termStore.GetTermSet(managedField.TermSetId);
            int             lcid         = CultureInfo.CurrentCulture.LCID;

            // TODO: this is Classification code; to be replaced with the one below!
            Term myTerm = termSet.GetTerms(this.SubstringBefore(sourceValue, "|"), false).FirstOrDefault();

            if (myTerm != null)
            {
                string termString =
                    string.Concat(myTerm.GetDefaultLabel(lcid), TaxonomyField.TaxonomyGuidLabelDelimiter, myTerm.Id);
                int[] ids =
                    TaxonomyField.GetWssIdsOfTerm(targetSPListItem.Web.Site, termStore.Id, termSet.Id, myTerm.Id, true, 1);

                // set the WssId (TaxonomyHiddenList ID) to -1 so that it is added to the TaxonomyHiddenList
                if (ids.Length == 0)
                {
                    termString = "-1;#" + termString;
                }
                else
                {
                    termString = ids[0] + ";#" + termString;
                }

                targetSPListItem[targetSPField.Id] = termString;
            }
        }
Example #7
0
 public static void AssociateMetadata(SPSite site, Guid fieldId, string _MMSGroupName, string _MMSTermsetName)
 {
     string _MMSServiceAppName = "ManagedMetadataServiceApplication";
     if (site.RootWeb.Fields.Contains(fieldId))
     {
         TaxonomySession session = new TaxonomySession(site);
         if (session.TermStores.Count != 0)
         {
             var termStore = session.TermStores[_MMSServiceAppName];
             foreach (Group grp in termStore.Groups)
             {
                 if (grp.Name.ToUpper() == _MMSGroupName.ToUpper())
                 {
                     var group = grp;
                     var termSet = group.TermSets[_MMSTermsetName];
                     TaxonomyField field = site.RootWeb.Fields[fieldId] as TaxonomyField;
                     field.SspId = termSet.TermStore.Id;
                     field.TermSetId = termSet.Id;
                     field.TargetTemplate = string.Empty;
                     field.AnchorId = Guid.Empty;
                     field.Update();
                     break;
                 }
             }
         }
     }
 }
Example #8
0
        public override void AddFieldTo(SPFieldCollection fieldCollection)
        {
            AddFieldTo(fieldCollection, f =>
            {
                TaxonomyField field = (TaxonomyField)f;

                if (TermStoreGuid != System.Guid.Empty && TermSetGuid != System.Guid.Empty)
                {
                    field.SspId     = TermStoreGuid;
                    field.TermSetId = TermSetGuid;
                }
                else
                {
                    TaxonomySession session = new TaxonomySession(field.ParentList.ParentWeb.Site);
                    TermStore store         = session.DefaultSiteCollectionTermStore != null ? session.DefaultSiteCollectionTermStore : session.TermStores[0];
                    Group group             = store.Groups[TermGroup];
                    TermSet set             = group.TermSets[TermSet];

                    field.SspId     = store.Id;
                    field.TermSetId = set.Id;
                }

                field.AllowMultipleValues = AllowMultipleValues;
            });
        }
Example #9
0
        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();
                }
            }
        }
Example #10
0
        private static Dictionary <string, string> GetManagedPropertyNamesUncached(SPSite site)
        {
            Dictionary <string, string> dictionary        = new Dictionary <string, string>();
            SearchServiceApplication    searchApplication = GetSearchServiceApplication(site);

            if (searchApplication != null)
            {
                SPFieldCollection fields = site.RootWeb.Fields;
                foreach (KeyValuePair <string, string> entry in GetManagedPropertyNames(searchApplication))
                {
                    SPField field;
                    try {
                        field = fields.GetFieldByInternalName(entry.Key);
                    } catch (ArgumentException) {
                        continue;
                    }
                    dictionary.Add(entry.Key, entry.Value);
                    TaxonomyField taxField = CommonHelper.TryCastOrDefault <TaxonomyField>(field);
                    if (taxField != null && taxField.TextField != Guid.Empty)
                    {
                        try {
                            SPField textField = fields[taxField.TextField];
                            dictionary[textField.InternalName] = entry.Value;
                        } catch {
                        }
                    }
                }
            }
            return(dictionary);
        }
Example #11
0
        protected override SPField CreateField(Microsoft.SharePoint.SPFieldCollection fieldCollection)
        {
            TaxonomyField field = (TaxonomyField)fieldCollection.CreateNewField(FieldType, Name);

            fieldCollection.Add(field);
            return(fieldCollection[Name]);
        }
Example #12
0
        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*/);
            }
        }
        private void AssociateTaxonomyFieldToMetadataStore(SPSite curSite, Guid fieldId, string taxGroup, string taxTermSet)
        {
            Logging.Logger.Instance.Info(
                String.Format("Connecting Site Column to Managed Metadata Service: Field Guid: {0}; Group: {1}; TermSet: {2}", fieldId, taxGroup, taxTermSet),
                Logging.DiagnosticsCategories.eCaseSite);

            if (curSite.RootWeb.Fields.Contains(fieldId))
            {
                TaxonomySession session = new TaxonomySession(curSite);

                if (session.TermStores.Count != 0)
                {
                    TermStore termStore = session.DefaultKeywordsTermStore;
                    Group     group     = termStore.Groups[taxGroup];
                    TermSet   termSet   = group.TermSets[taxTermSet];

                    TaxonomyField field = curSite.RootWeb.Fields[fieldId] as TaxonomyField;

                    // Connect to MMS
                    field.SspId              = termSet.TermStore.Id;
                    field.TermSetId          = termSet.Id;
                    field.PushChangesToLists = true;
                    field.Update();
                }
            }
        }
Example #14
0
        public static void ConnectTaxonomyField(TaxonomyField field, TaxonomySession session, TermStore termStore, string termGroup, string termSetName, bool isOpen = false, bool createValuesInEditForm = false)
        {
            if (field == null || session == null || termStore == null)
            {
                return;
            }

            Group group = termStore.Groups.GetByName(termGroup);

            if (group != null)
            {
                TermSet termSet = group.TermSets.GetByName(termSetName);
                // connect the field to the specified term
                if (termSet != null)
                {
                    field.SspId     = termSet.TermStore.Id;
                    field.TermSetId = termSet.Id;
                    field.Open      = isOpen && termSet.IsOpenForTermCreation;
                    field.CreateValuesInEditForm = field.Open && createValuesInEditForm;
                }
            }

            field.TargetTemplate = string.Empty;
            field.AnchorId       = Guid.Empty;
            field.Update();
        }
        /// <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();
            }
        }
Example #16
0
        /// <summary>
        /// Aplica el Metadato al listItem especificado.
        /// </summary>
        /// <param name="listItem"></param>
        /// <param name="site"></param>
        /// <param name="campo">Field Internal Name</param>
        /// <param name="valor">Term1/Term1Son/Term1GrandSon</param>
        /// <param name="lcid"></param>
        /// <returns></returns>
        public static void SetMetadata(ref SPListItem listItem, SPSite site, string campo, string valor, int lcid, bool multi)
        {
            TaxonomySession session   = new TaxonomySession(site);
            TaxonomyField   tagsField = (TaxonomyField)listItem.Fields.GetField(campo);
            TermStore       termStore = session.TermStores[tagsField.SspId];
            TermSet         termSet   = termStore.GetTermSet(tagsField.TermSetId);
            Term            termResult;

            if (multi)
            {
                ICollection <Term> termCol = new List <Term>();
                foreach (string term in valor.Split(';'))
                {
                    termResult = CrearNuevosTerminos(ref termStore, ref termSet, valor.Split('/'), lcid);
                    termCol.Add(termResult);
                }
                tagsField.SetFieldValue(listItem, termCol);
            }
            else
            {
                termResult = CrearNuevosTerminos(ref termStore, ref termSet, valor.Split('/'), lcid);
                tagsField.SetFieldValue(listItem, termResult);
            }
            listItem.SystemUpdate();
        }
Example #17
0
        /// <summary>
        /// Function to map metadata columns with specific term set
        /// </summary>
        /// <param name="clientContext">SP client context</param>
        /// <param name="fieldCol">Field Collection object</param>
        internal static void MapMetadataColumns(ClientContext clientContext, FieldCollection fieldCol)
        {
            string            termsetName       = ConfigurationManager.AppSettings["DefaultTermSetName"];
            string            taxonomyFieldType = ConfigurationManager.AppSettings["TaxonomyFieldType"];
            TaxonomySession   taxonomySession   = TaxonomySession.GetTaxonomySession(clientContext);
            TermStore         termStore         = taxonomySession.GetDefaultSiteCollectionTermStore();
            TermSetCollection termSetCollection = termStore.GetTermSetsByName(termsetName, 1033);       // Setting LCID=1033, as the default language is English

            clientContext.Load(termStore);
            clientContext.Load(termSetCollection);
            clientContext.ExecuteQuery();
            string termStoreId = Convert.ToString(termStore.Id, CultureInfo.InvariantCulture);
            string termSetId   = Convert.ToString(termSetCollection[0].Id, CultureInfo.InvariantCulture);

            TaxonomyField taxonomyField = null;

            foreach (Field field in fieldCol)
            {
                if (field.TypeAsString.Equals(taxonomyFieldType, StringComparison.OrdinalIgnoreCase))
                {
                    taxonomyField           = clientContext.CastTo <TaxonomyField>(field);
                    taxonomyField.SspId     = new Guid(termStoreId);
                    taxonomyField.TermSetId = new Guid(termSetId);
                    taxonomyField.AnchorId  = Guid.Empty;
                    taxonomyField.Update();
                }
            }
        }
        /// <summary>
        /// Updates a single-value managed metatada column
        /// </summary>
        /// <param name="taxonomyTerm"></param>
        /// <param name="item"></param>
        /// <param name="fieldToUpdate"></param>
        public static void UpdateMMField(string taxonomyTerm, SPListItem item, string fieldToUpdate)
        {
            //Get the metadata taxonomy field, a taxonomy session, the term store, and a collection of term sets in the store
            TaxonomyField   managedMetadataField = item.ParentList.Fields[fieldToUpdate] as TaxonomyField;
            Guid            tsId        = managedMetadataField.TermSetId;
            Guid            termStoreId = managedMetadataField.SspId;
            TaxonomySession tSession    = new TaxonomySession(item.ParentList.ParentWeb.Site);
            TermStore       tStore      = tSession.TermStores[termStoreId];
            TermSet         tSet        = tStore.GetTermSet(tsId);
            TermCollection  terms       = tSet.GetTerms(taxonomyTerm, false);
            Term            term        = null;

            //If term doesn't exist, create it in the term store
            if (terms.Count == 0)
            {
                Console.WriteLine("Creating term in managed metadata, {0}", taxonomyTerm);
                term = tSet.CreateTerm(taxonomyTerm, tStore.Languages[0]);
                tStore.CommitAll();
            }
            else
            {
                term = terms[0];
            }

            //Set the managed metadata field to the term retrieved from the term store
            managedMetadataField.SetFieldValue(item, term);
            item.Update();
        }
Example #19
0
 private void SetTaxonomyField(TaxonomySession metadataService, SPListItem item, Guid fieldId, string fieldValue)
 {
     TaxonomyField taxField = item.Fields[fieldId] as TaxonomyField;
     TermStore termStore = metadataService.TermStores[taxField.SspId];
     TermSet termSet = termStore.GetTermSet(taxField.TermSetId);
     SetTaxonomyFieldValue(termSet, taxField, item, fieldValue);
 }
        /// <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>
        /// 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;
        }
Example #22
0
        public static void CreateSiteColumn(ClientContext ctx, string displayName, string internalName, string termSetName)
        {
            Web rootWeb = ctx.Site.RootWeb;

            if (rootWeb.FieldExistsByName(internalName))
            {
                return;
            }

            // Create as a regular field setting the desired type in XML
            //https://msdn.microsoft.com/da-dk/library/office/microsoft.sharepoint.client.addfieldoptions.aspx

            Field field = rootWeb.Fields.AddFieldAsXml("<Field DisplayName='" + displayName + "' Name='" + internalName + "' ID='" + Guid.NewGuid() + "' Group='LB Columns' Type='TaxonomyFieldType' />", false, AddFieldOptions.AddFieldInternalNameHint);

            ctx.ExecuteQuery();

            Guid termStoreId = Guid.Empty;
            Guid termSetId   = Guid.Empty;

            GetTaxonomyFieldInfo(ctx, out termStoreId, out termSetId, termSetName);

            // Retrieve as Taxonomy Field
            TaxonomyField taxonomyField = ctx.CastTo <TaxonomyField>(field);

            taxonomyField.SspId          = termStoreId;
            taxonomyField.TermSetId      = termSetId;
            taxonomyField.TargetTemplate = String.Empty;
            taxonomyField.AnchorId       = Guid.Empty;
            taxonomyField.Update();

            ctx.ExecuteQuery();
        }
Example #23
0
 private void SetTaxonomyFieldValue(TermSet termSet, TaxonomyField taxField, SPListItem item, string value)
 {
     var terms = termSet.GetTerms(value, true, StringMatchOption.ExactMatch, 1, false);
     if (terms.Count > 0)
     {
         taxField.SetFieldValue(item, terms.First());
     }
 }
Example #24
0
 private void SetTaxonomyField(TaxonomySession metadataService, SPListItem item, Guid fieldId, List<string> fieldValues)
 {
     TaxonomyField taxField = item.Fields[fieldId] as TaxonomyField;
     TermStore termStore = metadataService.TermStores[taxField.SspId];
     TermSet termSet = termStore.GetTermSet(taxField.TermSetId);
     if (taxField.AllowMultipleValues) SetTaxonomyFieldMultiValue(termSet, taxField, item, fieldValues);
     else SetTaxonomyFieldValue(termSet, taxField, item, fieldValues.First());
 }
        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());
        }
Example #26
0
        List <SPTaggableList> GetModel(ClientContext ctx, AppWebHelper hlp)
        {
            List <SPTaggableList> model = null;

            try
            {
                model = new List <SPTaggableList>();
                LogHelper.Log("Inside getmodel");
                if (ctx != null)
                {
                    ListCollection lists = ctx.Web.Lists;

                    ctx.Load(lists, ListQuery => ListQuery.Include(
                                 l => l.Id, l => l.Title, l => l.BaseType,
                                 l => l.Fields.Where(
                                     f => f.TypeAsString == "TaxonomyFieldTypeMulti" || f.TypeAsString == "TaxonomyFieldType")
                                 ));

                    ctx.ExecuteQuery();

                    foreach (List list in lists)
                    {
                        if (list.BaseType == BaseType.DocumentLibrary && list.Fields.Count > 0)
                        {
                            SPTaggableList NewList = new SPTaggableList();
                            NewList.Title        = list.Title;
                            NewList.Id           = list.Id.ToString();
                            NewList.Disabled     = (hlp.ListsInfo.ContainsKey(NewList.Id) && hlp.ListsInfo[NewList.Id].ChildCount > 0) ? "Disabled" : string.Empty;
                            NewList.Asynchronous = (hlp.ListsInfo.ContainsKey(NewList.Id)) ? hlp.ListsInfo[NewList.Id].Asynchronous : true;

                            List <SPTaggableField> ListFields = new List <SPTaggableField>();
                            foreach (Field field in list.Fields)
                            {
                                TaxonomyField TaxField  = field as TaxonomyField;
                                string        key       = string.Concat(NewList.Id, "_", TaxField.Id.ToString());
                                var           isEnabled = hlp.CurrentlyEnabledFields.Where(c => c["Title"].Equals(key)).SingleOrDefault();
                                ListFields.Add(new SPTaggableField
                                {
                                    Id             = TaxField.Id.ToString(),
                                    Title          = TaxField.Title,
                                    TaggingEnabled = (isEnabled != null) ? true : false
                                });
                            }
                            NewList.Fields = ListFields;
                            model.Add(NewList);
                        }
                    }
                }

                return(model);
            }
            catch (Exception ex)
            {
                LogHelper.Log(ex.Message + ex.StackTrace);
                throw;
            }
        }
Example #27
0
        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();
            }
        }
        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);
        }
Example #29
0
 public void AssignTermSetToListColumn(SPList list, Guid fieldId, string termStoreGroupName, string termSetName, string termSubsetName)
 {
     if (list.Fields.Contains(fieldId))
     {
         TaxonomySession session   = new TaxonomySession(list.ParentWeb.Site);
         TermStore       termStore = session.DefaultSiteCollectionTermStore;
         TaxonomyField   field     = (TaxonomyField)list.Fields[fieldId];
         InternalAssignTermSetToTaxonomyField(termStore, field, termStoreGroupName, termSetName, termSubsetName);
     }
 }
Example #30
0
        private void SetTaxonomyTextValue(string fieldName, IEnumerable <Term> terms)
        {
            TaxonomyField taxonomyField = this.ObjectCache.GetField(this.WebId, this.ListId, fieldName) as TaxonomyField;

            if (taxonomyField != null)
            {
                SPField textField = this.ObjectCache.GetField(this.WebId, this.ListId, taxonomyField.TextField);
                this[textField.InternalName] = String.Join("\r\n", terms.Select(v => v.Id.ToString()).ToArray());
            }
        }
Example #31
0
        private string GetTermIdForTaxonomyField(TaxonomyField field, string term, ListItem pendingItem, Microsoft.SharePoint.Client.File pendingFile)
        {
            if (_terms == null)
            {
                _terms = new Dictionary <string, IDictionary <string, string> >();
            }

            if (!_terms.Keys.Contains(field.Title))
            {
                _terms[field.Title] = new Dictionary <string, string>();
            }

            if (_terms[field.Title].Keys.Contains(term))
            {
                return(_terms[field.Title][term].ToString());
            }

            var termId = string.Empty;

            //before we go forward,save pending item
            pendingItem.Update();
            ctx.Load(pendingFile);
            ctx.ExecuteQuery();

            TaxonomySession tSession = TaxonomySession.GetTaxonomySession(ctx);

            ctx.Load(tSession.TermStores);
            ctx.ExecuteQuery();
            TermStore ts   = tSession.TermStores.First();
            TermSet   tset = ts.GetTermSet(field.TermSetId);

            LabelMatchInformation lmi = new LabelMatchInformation(ctx);

            lmi.Lcid            = 1033;
            lmi.TrimUnavailable = true;
            lmi.TermLabel       = term;

            TermCollection termMatches = tset.GetTerms(lmi);

            ctx.Load(tSession);
            ctx.Load(ts);
            ctx.Load(tset);
            ctx.Load(termMatches);

            ctx.ExecuteQuery();

            if (termMatches != null && termMatches.Count() > 0)
            {
                termId = termMatches.First().Id.ToString();
            }

            _terms[field.Title][term] = termId;

            return(termId);
        }
        public static void ConnectTaxonomyField(TaxonomyField field, TaxonomySession session, string termGroup, string termSetName, bool isOpen = false, bool createValuesInEditForm = false)
        {
            TermStore termStore;

            if (field != null && field.SspId != default(Guid))
            {
                termStore = session.TermStores.SingleOrDefault(ts => ts.Id == field.SspId) ?? session.DefaultKeywordsTermStore;
            }
            else
            {
                termStore = session.DefaultKeywordsTermStore;
            }

            ConnectTaxonomyField(field, session, termStore, termGroup, termSetName, isOpen, createValuesInEditForm);
        }
Example #33
0
        /// <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 void ConnectTaxonomyField(TaxonomyField field, TaxonomySession session, TermStore termStore, string termGroup, string termSetName, bool isOpen = false, bool createValuesInEditForm = false)
        {
            if (field == null || session == null || termStore == null) { return; }

            Group group = termStore.Groups.GetByName(termGroup);

            if (group != null)
            {
                TermSet termSet = group.TermSets.GetByName(termSetName);
                // connect the field to the specified term
                if (termSet != null)
                {
                    field.SspId = termSet.TermStore.Id;
                    field.TermSetId = termSet.Id;
                    field.Open = isOpen && termSet.IsOpenForTermCreation;
                    field.CreateValuesInEditForm = field.Open && createValuesInEditForm;
                }
            }

            field.TargetTemplate = string.Empty;
            field.AnchorId = Guid.Empty;
            field.Update();
        }
        private static void AssignTermSetToTaxonomyField(TermStore termStore, TaxonomyField field, string termStoreGroupName, string termSetName, string termSubsetName)
        {
            int originalWorkingLanguage = termStore.WorkingLanguage;
            termStore.WorkingLanguage = Language.English.Culture.LCID;

            Group group = termStore.Groups[termStoreGroupName];
            TermSet termSet = group.TermSets[termSetName];

            // Connect to MMS
            field.SspId = termSet.TermStore.Id;
            field.TermSetId = termSet.Id;
            field.TargetTemplate = string.Empty;

            // Select a sub node of the termset to limit selection
            if (!string.IsNullOrEmpty(termSubsetName))
            {
                Term term = termStore.GetTerms(termSubsetName, true)[0];
                field.AnchorId = term.Id;
            }
            else
            {
                field.AnchorId = Guid.Empty;
            }

            field.Update();

            termStore.WorkingLanguage = originalWorkingLanguage;
        }
        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;
        }
 public static void ConnectTaxonomyField(TaxonomyField field, TaxonomySession session, string termStoreName, string termGroup, string termSetName, bool isOpen = false, bool createValuesInEditForm = false)
 {
     TermStore termStore = session.TermStores.SingleOrDefault(ts => string.Equals(ts.Name, termStoreName));
     ConnectTaxonomyField(field, session, termStore, termGroup, termSetName, isOpen, createValuesInEditForm);
 }
        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;
        }
Example #39
0
 private static void ValidateTaxonomyFieldDefaultValue(TaxonomyField field)
 {
     //get validated value with correct WssIds
     var validatedValue = GetTaxonomyFieldValidatedValue(field, field.DefaultValue);
     if (!string.IsNullOrEmpty(validatedValue) && field.DefaultValue != validatedValue)
     {
         field.DefaultValue = validatedValue;
         field.UpdateAndPushChanges(true);
         field.Context.ExecuteQueryRetry();
     }
 }
Example #40
0
 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 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*/);
            }
        }
Example #43
0
        public TermSetLookup(TaxonomyField taxonomyField, TermSet termSet)
        {
            this.taxonomyField = taxonomyField;
            this.terms = termSet.GetAllTerms();

            Program.clientContext.Load(this.terms,
              termsArg => termsArg.Include(
                termArg => termArg.Id,
                termArg => termArg.Name
              )
            );
        }
        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;
        }
        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();
                }
            }
        }
        static void CreateWingtipSiteColumns()
        {
            Console.WriteLine();

              fieldProductCode = CreateSiteColumn("ProductCode", "Product Code", "Text");
              fieldProductCode.EnforceUniqueValues = true;
              fieldProductCode.Indexed = true;
              fieldProductCode.Required = true;
              fieldProductCode.Update();
              clientContext.ExecuteQuery();
              clientContext.Load(fieldProductCode);
              clientContext.ExecuteQuery();

              fieldProductDescription = clientContext.CastTo<FieldMultiLineText>(CreateSiteColumn("ProductDescription", "Product Description", "Note"));
              fieldProductDescription.NumberOfLines = 4;
              fieldProductDescription.RichText = false;
              fieldProductDescription.Update();
              clientContext.ExecuteQuery();

              fieldProductListPrice = clientContext.CastTo<FieldCurrency>(CreateSiteColumn("ProductListPrice", "List Price", "Currency"));
              fieldProductListPrice.MinimumValue = 0;
              fieldProductListPrice.Update();
              clientContext.ExecuteQuery();

              fieldProductCategory = clientContext.CastTo<TaxonomyField>(CreateSiteColumn("ProductCategory", "Product Category", "TaxonomyFieldType"));
              fieldProductCategory.SspId = localTermStoreID;
              fieldProductCategory.TermSetId = termSetId;
              fieldProductCategory.AllowMultipleValues = false;
              fieldProductCategory.Update();
              clientContext.ExecuteQuery();

              fieldProductColor = clientContext.CastTo<FieldMultiChoice>(CreateSiteColumn("ProductColor", "Product Color", "MultiChoice"));
              string[] choicesProductColor = { "White", "Black", "Grey", "Blue", "Red", "Green", "Yellow" };
              fieldProductColor.Choices = choicesProductColor;
              fieldProductColor.Update();
              clientContext.ExecuteQuery();

              fieldMinimumAge = clientContext.CastTo<FieldNumber>(CreateSiteColumn("MinimumAge", "Minimum Age", "Number"));
              fieldMinimumAge.MinimumValue = 1;
              fieldMinimumAge.MaximumValue = 100;
              fieldMinimumAge.Update();
              clientContext.ExecuteQuery();

              fieldMaximumAge = clientContext.CastTo<FieldNumber>(CreateSiteColumn("MaximumAge", "Maximum Age", "Number"));
              fieldMaximumAge.MinimumValue = 1;
              fieldMaximumAge.MaximumValue = 100;
              fieldMaximumAge.Update();
              clientContext.ExecuteQuery();

              fieldProductImageUrl = clientContext.CastTo<FieldUrl>(CreateSiteColumn("ProductImageUrl", "Product Image Url", "URL"));
              fieldProductImageUrl.DisplayFormat = UrlFieldFormatType.Image;
              fieldProductImageUrl.Update();
              clientContext.ExecuteQuery();
        }
Example #47
0
        private static void InternalAssignTermSetToTaxonomyField(TermStore termStore, TaxonomyField field, string termStoreGroupName, string termSetName, string termSubsetName)
        {
            Group group = termStore.Groups[termStoreGroupName];
            TermSet termSet = group.TermSets[termSetName];

            // Connect to MMS
            field.SspId = termSet.TermStore.Id;
            field.TermSetId = termSet.Id;
            field.TargetTemplate = string.Empty;

            // Select a sub node of the termset to limit selection
            if (!string.IsNullOrEmpty(termSubsetName))
            {
                Term term = termSet.GetTerms(termSubsetName, true)[0];
                field.AnchorId = term.Id;
            }
            else
            {
                field.AnchorId = Guid.Empty;
            }

            field.Update();
        }
        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;
        }
Example #49
0
        private static void InternalAssignTermSetToTaxonomyField(TermStore termStore, TaxonomyField field, Guid termStoreGroupId, Guid termSetId, Guid termSubsetId)
        {
            Group group = termStore.Groups[termStoreGroupId];
            TermSet termSet = group.TermSets[termSetId];

            // Connect to MMS
            field.SspId = termSet.TermStore.Id;
            field.TermSetId = termSet.Id;
            field.TargetTemplate = string.Empty;

            // Select a sub node of the termset to limit selection
            field.AnchorId = Guid.Empty != termSubsetId ? termSubsetId : Guid.Empty;
            field.Update();
        }
 public static void SetDefaultTermValue(TermSet termSet, TaxonomyField field, string defaultTermValue)
 {
     Term defaultTerm = termSet.Terms[defaultTermValue];
     if (null != defaultTerm)
     {
         field.DefaultValue = string.Format("1;#{0}|{1}", defaultTerm.Name, defaultTerm.Id);
     }
     field.Update(true);
 }
 private static SPContentType FindContentTypeWithField(SPContentTypeCollection contentTypeCollection, TaxonomyField fieldToSet)
 {
     return contentTypeCollection.Cast<SPContentType>().FirstOrDefault(ct =>
     {
         return ct.Fields.Cast<SPField>().Any(spField => spField.InternalName == fieldToSet.InternalName);
     });
 }
 public static void SetDefaultTermValue(Group group, TaxonomyField field, string defaultTermText)
 {
     TermSet termSet = group.TermSets[field.TermSetId];
     if (null != termSet)
     {
         SetDefaultTermValue(termSet, field, defaultTermText);
     }
 }
 public void SetDefaultTermValue(TermSet termSet, TaxonomyField field, string defaultTermValue)
 {
     SharePointUtilities.SetDefaultTermValue(termSet, field, defaultTermValue);
 }
        private string GetTermIdForTaxonomyField(TaxonomyField field, string term, ListItem pendingItem,Microsoft.SharePoint.Client.File pendingFile)
        {
            if (_terms == null)
                _terms = new Dictionary<string, IDictionary<string, string>>();

            if (!_terms.Keys.Contains(field.Title))
                _terms[field.Title] = new Dictionary<string, string>();

            if (_terms[field.Title].Keys.Contains(term))
                return _terms[field.Title][term].ToString();

            var termId = string.Empty;

            //before we go forward,save pending item
            pendingItem.Update();
            ctx.Load(pendingFile);
            ctx.ExecuteQuery();

            TaxonomySession tSession = TaxonomySession.GetTaxonomySession(ctx);
            ctx.Load(tSession.TermStores);
            ctx.ExecuteQuery();
            TermStore ts = tSession.TermStores.First();
            TermSet tset = ts.GetTermSet(field.TermSetId);

            LabelMatchInformation lmi = new LabelMatchInformation(ctx);

            lmi.Lcid = 1033;
            lmi.TrimUnavailable = true;
            lmi.TermLabel = term;

            TermCollection termMatches = tset.GetTerms(lmi);
            ctx.Load(tSession);
            ctx.Load(ts);
            ctx.Load(tset);
            ctx.Load(termMatches);

            ctx.ExecuteQuery();

            if (termMatches != null && termMatches.Count() > 0)
                termId = termMatches.First().Id.ToString();

            _terms[field.Title][term] = termId;

            return termId;
        }