Exemplo n.º 1
0
        public void ImportTerm(TermSet termSet, XElement termElement, bool recurse = true)
        {
            try
            {
                //Get the term name
                string termName = (string)termElement.Attribute("Name");

                //Check if the term exist
                Term term = termSet.GetTerms(termName, false).FirstOrDefault();

                //If the term does not exist, create it
                if (term == null)
                {
                    int lcid = CultureInfo.CurrentCulture.LCID;
                    term = termSet.CreateTerm(termName, lcid);
                }

                //Create the child terms
                if (recurse)
                {
                    foreach (XElement childElement in termElement.Elements())
                    {
                        ImportTerm(term, childElement, recurse);
                    }
                }
            }
            catch (Exception e)
            {
            }
        }
Exemplo n.º 2
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;
            }
        }
Exemplo n.º 3
0
        public static string GetTermIdForTerm(string term, Guid termSetId, ClientContext clientContext)
        {
            string termId = string.Empty;

            //Get term set from ID
            TaxonomySession tSession = TaxonomySession.GetTaxonomySession(clientContext);
            TermStore       ts       = tSession.GetDefaultSiteCollectionTermStore();
            TermSet         tset     = ts.GetTermSet(termSetId);

            LabelMatchInformation lmi = new LabelMatchInformation(clientContext);

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

            //Search for matching terms in the term set based on label
            TermCollection termMatches = tset.GetTerms(lmi);

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

            clientContext.ExecuteQuery();

            //Set term ID to first match
            if (termMatches != null && termMatches.Count() > 0)
            {
                termId = termMatches.First().Id.ToString();
            }

            return(termId);
        }
Exemplo n.º 4
0
        /// <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();
        }
Exemplo n.º 5
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());
     }
 }
Exemplo n.º 6
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);
        }
Exemplo n.º 7
0
        protected Term FindTermInTermSet(TermSet termSet, TaxonomyTermDefinition termModel)
        {
            Term result = null;

            var context = termSet.Context;

            if (termModel.Id.HasValue)
            {
                var scope = new ExceptionHandlingScope(context);
                using (scope.StartScope())
                {
                    using (scope.StartTry())
                    {
                        result = termSet.Terms.GetById(termModel.Id.Value);
                        context.Load(result);
                    }

                    using (scope.StartCatch())
                    {
                    }
                }

                context.ExecuteQueryWithTrace();
            }
            else if (!string.IsNullOrEmpty(termModel.Name))
            {
                var termName = NormalizeTermName(termModel.Name);

                var terms = termSet.GetTerms(new LabelMatchInformation(context)
                {
                    Lcid            = termModel.LCID,
                    TermLabel       = termName,
                    TrimUnavailable = false
                });

                context.Load(terms);
                context.ExecuteQueryWithTrace();

                result = terms.FirstOrDefault();
            }

            if (result != null &&
                result.ServerObjectIsNull.HasValue &&
                result.ServerObjectIsNull == false)
            {
                context.Load(result);
                context.ExecuteQueryWithTrace();

                return(result);
            }

            return(null);
        }
Exemplo n.º 8
0
 private void SetTaxonomyFieldMultiValue(TermSet termSet, TaxonomyField taxField, SPListItem item, List<string> fieldValues)
 {
     var fieldTerms = new List<Term>();
     foreach (var value in fieldValues)
     {
         var terms = termSet.GetTerms(value, true);
         if (terms.Count > 0)
         {
             terms.ToList().ForEach(t => fieldTerms.Add(t));
         }
     }
     taxField.SetFieldValue(item, fieldTerms);
 }
Exemplo n.º 9
0
        /// <summary>Fixes the SP field taxonomy.</summary>
        /// <param name="contextSpSite">The context sp site.</param>
        /// <param name="fileSPListItem">The file sp list item.</param>
        /// <param name="sourceValue">The source value.</param>
        /// <returns>The fix sp field taxonomy.</returns>
        private string FixSPFieldTaxonomy(SPSite contextSpSite, SPListItem fileSPListItem, string sourceValue)
        {
            string s    = "\t\tTaxonomy\n\t\t-" + contextSpSite.Url + ",\n\t\t-" + sourceValue + "\n";
            int    lcid = CultureInfo.CurrentCulture.LCID;

            // this is a managed metadata field
            TaxonomyField   taxonomyField   = this.ContextSPField as TaxonomyField;
            TaxonomySession taxonomySession = new TaxonomySession(contextSpSite);
            TermStore       termStore       = taxonomySession.TermStores[taxonomyField.SspId];
            TermSet         termSet         = termStore.GetTermSet(taxonomyField.TermSetId);

            s += "\t\tlcid:\t\t" + lcid + "\n\t\ttaxField:\t" + taxonomyField.Title + "\n";
            s += "\t\ttermstores:\t" + taxonomySession.TermStores.Count + "\n";
            s += "\t\ttermstore:\t" + termStore.Name + "\n\t\ttermset:\t" + termSet.Name + "\n";

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

            if (myTerm != null)
            {
                s += "\t\tmyTerm:\t\t" + myTerm.Name + "\n";
                s += "\t\twas:" + fileSPListItem[this.ContextSPField.Id] + "\n";
                string termString = String.Concat(myTerm.GetDefaultLabel(lcid),
                                                  TaxonomyField.TaxonomyGuidLabelDelimiter,
                                                  myTerm.Id);
                int[] ids = TaxonomyField.GetWssIdsOfTerm(
                    contextSpSite,
                    termStore.Id,
                    termSet.Id,
                    myTerm.Id,
                    true,
                    1);
                s += "\t\ttermString:\t" + termString + "\n\t\tids:\t\t" + ids.Length + "\n";

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

                fileSPListItem[this.ContextSPField.Id] = termString;
            }

            s += "\t\tis_:" + fileSPListItem[this.ContextSPField.Id] + "\n";
            return(s);
        }
Exemplo n.º 10
0
        static void Main(string[] args)
        {
            ClientContext context = new ClientContext("http://ecm.wingtip.com");

            TaxonomySession session = TaxonomySession.GetTaxonomySession(context);

            context.Load(session, taxSession => taxSession.TermStores.Include(
                             taxStore => taxStore.Groups.Include(
                                 taxGroup => taxGroup.TermSets.Include(tax => tax.Name)
                                 )));
            context.ExecuteQuery();

            TermStore termStore = session.TermStores[0];
            TermGroup termGroup = termStore.Groups[0];
            TermSet   termSet   = termGroup.TermSets[0];

            //// get UNITED STATES term
            //var terms = termSet.Terms;
            //context.Load(terms);
            //context.ExecuteQuery();
            //Term unitedStatesTerm = terms[0];
            //context.Load(unitedStatesTerm);
            //context.ExecuteQuery();

            //// add region
            //Term newRegion = unitedStatesTerm.CreateTerm("Pacific", 1033, Guid.NewGuid());
            //newRegion.SetCustomProperty("PrimaryPOC", "Rob Walters");
            //newRegion.IsAvailableForTagging = false;

            //// add state
            //Term newState = newRegion.CreateTerm("Hawaii", 1033, Guid.NewGuid());

            // search for PACIFIC term
            var searchQuery = new LabelMatchInformation(context)
            {
                TermLabel       = "Pacific",
                TrimUnavailable = false
            };
            var foundTerms = termSet.GetTerms(searchQuery);

            context.Load(foundTerms);
            context.ExecuteQuery();

            // update term
            foundTerms[0].Name = "Pacific Region";

            // save changes
            termStore.CommitAll();
            context.ExecuteQuery();
        }
Exemplo n.º 11
0
 private static void CrearTermino(ref TermStore termStore, ref TermSet termSet, string[] arbol, ref Term termResult, string cadenaAnterior, int j, int lcid)
 {
     if (j == 0)
     {
         termResult = termSet.CreateTerm(arbol[j], lcid);
         termStore.CommitAll();
     }
     else
     {
         Term termPadre = new List <Term>(termSet.GetTerms(arbol[j - 1], false, StringMatchOption.ExactMatch, 100000, false)).Find(t => t.GetPath().ToLower().Equals(cadenaAnterior.Remove(cadenaAnterior.Length - 1, 1).ToLower()));
         termResult = termPadre.CreateTerm(arbol[j], lcid);
         termStore.CommitAll();
     }
 }
Exemplo n.º 12
0
        static void Main(string[] args)
        {
            SPSite          siteCollection = new SPSite("http://ecm.wingtip.com");
            TaxonomySession taxSession     = new TaxonomySession(siteCollection);
            TermStore       termStore      = taxSession.TermStores[0];
            Group           termGroup      = termStore.Groups.Single(tg => tg.Name == "Example Taxonomies");
            TermSet         termSet        = termGroup.TermSets.Single(ts => ts.Name == "Corporate Locations");

            //// add region
            //Term unitedStatesTerm = termSet.Terms[0];
            //Term newRegion = unitedStatesTerm.CreateTerm("Mountain Region", 1033);
            //newRegion.SetCustomProperty("PrimaryPOC", "Janice Galvin");
            //newRegion.IsAvailableForTagging = false;

            //// add state
            //Term newState = newRegion.CreateTerm("Colorado", 1033);

            // search for CENTRAL term
            var foundTerm = termSet.GetTerms("Central", 1033, false).First();

            foundTerm.Name = "Central Region";
            foundTerm.IsAvailableForTagging = false;

            // search for EAST term
            foundTerm      = termSet.GetTerms("East", 1033, false).First();
            foundTerm.Name = "East Region";
            foundTerm.IsAvailableForTagging = false;

            // search for WEST term
            foundTerm      = termSet.GetTerms("West", 1033, false).First();
            foundTerm.Name = "West Region";
            foundTerm.IsAvailableForTagging = false;

            // save changes
            termStore.CommitAll();
        }
Exemplo n.º 13
0
        protected Term FindTermInTermSet(TermSet termSet, TaxonomyTermDefinition termModel)
        {
            Term result = null;

            if (termModel.Id.HasValue)
            {
                result = termSet.GetTerm(termModel.Id.Value);
            }
            else if (!string.IsNullOrEmpty(termModel.Name))
            {
                result = termSet.GetTerms(termModel.Name, termModel.LCID, false).FirstOrDefault();
            }

            return(result);
        }
Exemplo n.º 14
0
        public Term GetTerm(ClientContext clientContext, TermStore termStore, TermSet termSet, bool recursive, Expression <Func <Term, object> >[] expressions = null)
        {
            Term term = null;

            if (_id != Guid.Empty)
            {
                term = termStore.GetTerm(_id);
            }
            else if (!string.IsNullOrEmpty(_title) && termSet != null && termStore != null)
            {
                var termName = TaxonomyExtensions.NormalizeName(_title);
                if (!recursive)
                {
                    term = termSet.Terms.GetByName(termName);
                }
                else
                {
                    var lmi = new LabelMatchInformation(clientContext)
                    {
                        TrimUnavailable = true,
                        TermLabel       = termName
                    };

                    var termMatches = termSet.GetTerms(lmi);
                    clientContext.Load(termMatches);
                    clientContext.ExecuteQueryRetry();

                    if (termMatches.AreItemsAvailable)
                    {
                        term = termMatches.FirstOrDefault();
                    }
                }
            }
            else
            {
                throw new PSArgumentException("Not enough parameters specified to succesfully find the term");
            }
            if (expressions != null)
            {
                clientContext.Load(term, expressions);
            }
            else
            {
                clientContext.Load(term);
            }
            clientContext.ExecuteQueryRetry();
            return(term);
        }
Exemplo n.º 15
0
        static void Main(string[] args)
        {
            CargaPropiedades(args);
            string timeStamp = DateTime.Now.Year.ToString("0000") + DateTime.Now.Month.ToString("00") + DateTime.Now.Day.ToString("00") + DateTime.Now.Hour.ToString("00") + DateTime.Now.Minute.ToString("00") + DateTime.Now.Second.ToString("00") + DateTime.Now.Millisecond.ToString("000") + ".txt";

            logProceso       = new StreamWriter("LogProceso" + timeStamp);
            logDesprotegidos = new StreamWriter("LogDesprotegidos" + timeStamp);
            logDesprotegidos.WriteLine(rama);
            using (SPSite site = new SPSite(url))
            {
                using (SPWeb web = site.OpenWeb())
                {
                    TaxonomySession session = new TaxonomySession(site);
                    termStore = session.TermStores[servicio];
                    termSet   = termStore.Groups[nombreGrupo].TermSets[nombreTermSet];
                    Term term = termSet.GetTerms(rama.Split('¬').Last(), false, StringMatchOption.ExactMatch, 100000, false).First(c => c.GetPath().ToLower().Replace(';', '¬').Equals(rama.ToLower()));
                    if (grupos)
                    {
                        //if (ramaVirgen)
                        //{
                        AplicarGruposNuevos(web, term, term.Id.ToString());
                        //}
                        //else
                        //{
                        //    RefactorGrupos(web, term, term.Id.ToString());
                        //}
                    }
                    else
                    {
                        AplicarOrdenVerdes(web, term, term.Id.ToString());
                    }
                    logProceso.Close();
                    logDesprotegidos.Close();
                    StreamReader reader = new StreamReader("LogDesprotegidos" + timeStamp);
                    if (!reader.ReadToEnd().Contains("Documento Desprotegido"))
                    {
                        reader.Close();
                        File.Delete("LogDesprotegidos" + timeStamp);
                    }
                }
            }
        }
Exemplo n.º 16
0
        /// <summary>
        /// Crea los términos que no existan.
        /// El parámetro "arbol" representa el path del término, siendo el último elemento del vector el término a devolver.
        /// </summary>
        /// <param name="termStore"></param>
        /// <param name="termSet"></param>
        /// <param name="arbol"></param>
        /// <returns></returns>
        public static Term CrearNuevosTerminos(ref TermStore termStore, ref TermSet termSet, string[] arbol, int lcid)
        {
            Term   termResult     = null;
            string cadena         = String.Empty;
            string cadenaAnterior = String.Empty;

            for (int j = 0; j <= arbol.Length - 1; j++)
            {
                cadena    += arbol[j];
                termResult = new List <Term>(termSet.GetTerms(arbol[j], false, StringMatchOption.ExactMatch, 100000, false)).Find(c => c.GetPath().ToLower().Equals(cadena.ToLower()));
                if (termResult == null)
                {
                    CrearTermino(ref termStore, ref termSet, arbol, ref termResult, cadenaAnterior, j, lcid);
                }

                cadena         += ";";
                cadenaAnterior += arbol[j] + ";";
            }
            return(termResult);
        }
Exemplo n.º 17
0
        public static string GetTermIdForTerm(string term, Guid termSetId, ClientContext clientContext)
        {
            string termId = string.Empty;

            TaxonomySession tSession = TaxonomySession.GetTaxonomySession(clientContext);
            TermStore       ts       = tSession.GetDefaultSiteCollectionTermStore();
            TermSet         tset     = ts.GetTermSet(termSetId);

            LabelMatchInformation lmi = new LabelMatchInformation(clientContext);

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

            TermCollection termMatches = tset.GetTerms(lmi);


            //tset.CreateTerm()
            clientContext.Load(tSession);
            clientContext.Load(ts);
            clientContext.Load(tset);
            clientContext.Load(termMatches);

            clientContext.ExecuteQuery();

            if (termMatches != null && termMatches.Count() > 0)
            {
                termId = termMatches.First().Id.ToString();
            }
            else
            {
                Term TermAdd = tset.CreateTerm(term, 1033, Guid.NewGuid());
                clientContext.ExecuteQuery();
                clientContext.Load(TermAdd);
                clientContext.ExecuteQuery();
                termId = TermAdd.Id.ToString();
            }


            return(termId);
        }
Exemplo n.º 18
0
        /// <summary>
        /// Updates a multi-value managed metatada column
        /// </summary>
        /// <param name="taxonomyTerms"></param>
        /// <param name="item"></param>
        /// <param name="fieldToUpdate"></param>
        public static void UpdateMultiMMField(string[] taxonomyTerms, 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   multipleManagedMetadataField = item.ParentList.Fields[fieldToUpdate] as TaxonomyField;
            Guid            tsId        = multipleManagedMetadataField.TermSetId;
            Guid            termStoreId = multipleManagedMetadataField.SspId;
            TaxonomySession tSession    = new TaxonomySession(item.ParentList.ParentWeb.Site);
            TermStore       tStore      = tSession.TermStores[termStoreId];
            TermSet         tSet        = tStore.GetTermSet(tsId);
            TaxonomyFieldValueCollection termCollection = new TaxonomyFieldValueCollection(multipleManagedMetadataField);

            //Loop through each value being added to the metadata field
            foreach (string t in taxonomyTerms)
            {
                TermCollection terms = tSet.GetTerms(t, false);
                Term           term  = null;
                //If there are no matching terms in the term store, create one
                if (terms.Count == 0)
                {
                    Console.WriteLine("Creating term in managed metadata, {0}", t);
                    term = tSet.CreateTerm(t, tStore.Languages[0]);
                    tStore.CommitAll();
                }
                else
                {
                    term = terms[0];
                }

                //Add the current term to a term collection
                TaxonomyFieldValue termValue = new TaxonomyFieldValue(multipleManagedMetadataField);
                termValue.TermGuid = term.Id.ToString();
                termValue.Label    = term.Name;
                termCollection.Add(termValue);
            }

            //Add the term collection to the metadata field
            multipleManagedMetadataField.SetFieldValue(item, termCollection);
            item.Update();
        }
Exemplo n.º 19
0
        public static bool UpdateTaxonomyFieldValue(SPSite targetSite, TermSet termSet, TaxonomyFieldValue fieldValue, Dictionary <Guid, TaxonomyFieldValue> mappedValues)
        {
            CommonHelper.ConfirmNotNull(targetSite, "targetSite");
            CommonHelper.ConfirmNotNull(termSet, "termSet");
            CommonHelper.ConfirmNotNull(fieldValue, "fieldValue");
            CommonHelper.ConfirmNotNull(mappedValues, "mappedValues");

            Guid originalGuid = new Guid(fieldValue.TermGuid);
            TaxonomyFieldValue newValue;

            if (mappedValues.TryGetValue(originalGuid, out newValue))
            {
                if (newValue != null && newValue.TermGuid != originalGuid.ToString())
                {
                    fieldValue.TermGuid = newValue.TermGuid;
                    fieldValue.WssId    = newValue.WssId;
                    return(true);
                }
                return(false);
            }
            Term originalTerm = termSet.GetTerm(originalGuid);

            if (originalTerm != null)
            {
                mappedValues.Add(originalGuid, null);
                return(false);
            }
            TermCollection matchedTerms = termSet.GetTerms(fieldValue.Label, false);

            if (matchedTerms.Count > 0)
            {
                mappedValues.Add(originalGuid, fieldValue);
                fieldValue.TermGuid = matchedTerms[0].Id.ToString();
                fieldValue.WssId    = matchedTerms[0].EnsureWssId(targetSite, false);
                return(true);
            }
            mappedValues.Add(originalGuid, null);
            return(false);
        }
Exemplo n.º 20
0
        /// <summary>
        /// Gets a Taxonomy Term by Name
        /// </summary>
        /// <param name="termSetId"></param>
        /// <param name="term"></param>
        /// <param name="clientContext"></param>
        /// <returns></returns>
        public static Term GetTermByName(this Site site, Guid termSetId, string term)
        {
            if (string.IsNullOrEmpty(term))
            {
                throw new ArgumentNullException("term");
            }

            TermCollection         termMatches = null;
            ExceptionHandlingScope scope       = new ExceptionHandlingScope(site.Context);

            string          termId   = string.Empty;
            TaxonomySession tSession = TaxonomySession.GetTaxonomySession(site.Context);
            TermStore       ts       = tSession.GetDefaultSiteCollectionTermStore();
            TermSet         tset     = ts.GetTermSet(termSetId);

            var lmi = new LabelMatchInformation(site.Context);

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

            termMatches = tset.GetTerms(lmi);
            site.Context.Load(tSession);
            site.Context.Load(ts);
            site.Context.Load(tset);
            site.Context.Load(termMatches);

            site.Context.ExecuteQuery();

            if (termMatches.AreItemsAvailable)
            {
                return(termMatches.FirstOrDefault());
            }
            else
            {
                return(null);
            }
        }
Exemplo n.º 21
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();
        }
Exemplo n.º 22
0
        public static TaxonomyFieldValue GetTaxonomyFieldValue(TermSet termSet, string value, bool addIfDoesNotExist, out bool newTermAdded)
        {
            string termVal = TaxonomyItem.NormalizeName((value ?? string.Empty).Trim()); //ReplaceIllegalCharacters((value ?? string.Empty).Trim());
            Term   term    = null;

            newTermAdded = false;

            if (termSet != null)
            {
                if (!string.IsNullOrEmpty(termVal))
                {
                    term = termSet.GetTerms(termVal, termSet.TermStore.DefaultLanguage, true,
                                            StringMatchOption.ExactMatch, 1, false).FirstOrDefault();
                }

                if (term == null && termSet.IsOpenForTermCreation && addIfDoesNotExist)
                {
                    if (!string.IsNullOrEmpty(termVal))
                    {
                        term         = termSet.CreateTerm(termVal, termSet.TermStore.DefaultLanguage);
                        newTermAdded = true;
                        //termSet.TermStore.CommitAll();
                    }
                }

                if (term != null)
                {
                    string termValue = string.Concat(term.GetDefaultLabel(termSet.TermStore.DefaultLanguage),
                                                     TaxonomyField.TaxonomyGuidLabelDelimiter,
                                                     term.Id.ToString());
                    return(TaxonomyFieldControl.GetTaxonomyValue(termValue));
                }
            }

            return(null);
        }
 public Term FindTerm(TermSet termSet, string label)
 {
     termSet.RequireNotNull("termSet");
     return termSet.GetTerms(label, false).FirstOrDefault();
 }
Exemplo n.º 24
0
        private void CreateOrUpdateTerms(TermSet oTerms, SimpleTree <string> data, int lcid)
        {
            if (oTerms == null)
            {
                throw new ArgumentNullException("oTerms");
            }
            if (data == null)
            {
                throw new ArgumentNullException("data");
            }

            var allNodes = SimpleTree <string> .Traverse(data, node => node).ToList();

            allNodes.ForEach(node => node.Clear());
            var currentNodes = TraverseTerms(new SimpleTree <string>("", oTerms.Name), oTerms, lcid, false).ToList();

            // stores terms and controls if they have uniqye key paths in store
            Dictionary <string, Term> termDict = new Dictionary <string, Term>();

            if (currentNodes.Count == 1)
            {
                // create all
                foreach (SimpleTree <string> node in allNodes)
                {
                    if (oTerms.Name == node.Value)
                    {
                        continue;
                    }

                    int level = node.Key.Count(c => c == '.');
                    if (level == 1)
                    {
                        CreateAndAddToDict(oTerms, termDict, node, lcid);
                    }
                    else
                    {
                        CreateAndAddToDict(getParentTerm(node.Key, termDict), termDict, node, lcid);
                    }
                }
            }
            else
            {
                var toDisable = currentNodes.Except(allNodes).ToList();
                var toAdd     = allNodes.Except(currentNodes).ToList();

                foreach (var node in toAdd)
                {
                    if (node.Parent.Value == oTerms.Name)
                    {
                        // check if disabled
                        var terms = oTerms.GetTerms(node.Value, lcid, false, StringMatchOption.ExactMatch, 1, false);
                        if (terms.Count > 0)
                        {
                            terms[0].IsAvailableForTagging = true;
                            termDict.Add(node.Key, terms[0]);
                        }
                        else
                        {
                            CreateAndAddToDict(oTerms, termDict, node, lcid);
                        }
                    }
                    else
                    {
                        // check if disabled
                        var terms = oTerms.GetTerms(node.Value, lcid, false, StringMatchOption.ExactMatch, 1, false);
                        if (terms.Count > 0)
                        {
                            terms[0].IsAvailableForTagging = true;
                            termDict.Add(node.Key, terms[0]);
                        }
                        else
                        {
                            // check in temp dict
                            if (termDict.ContainsKey(node.Parent.Key))
                            {
                                CreateAndAddToDict(getParentTerm(node.Key, termDict), termDict, node, lcid);
                            }
                            else
                            {
                                // get parent from site
                                terms = oTerms.GetTerms(node.Parent.Value, lcid, false, StringMatchOption.ExactMatch, 1, true);
                                if (terms.Count > 0)
                                {
                                    CreateAndAddToDict(terms[0], termDict, node, lcid);
                                }
                            }
                        }
                    }
                }
                foreach (var item in toDisable)
                {
                    var terms = oTerms.GetTerms(item.Value, lcid, false, StringMatchOption.ExactMatch, 1, true);
                    if (terms.Count > 0)
                    {
                        terms[0].IsAvailableForTagging = false;
                    }
                }
            }
        }
Exemplo n.º 25
0
        protected override void ExecuteCmdlet()
        {
            DefaultRetrievalExpressions = new Expression <Func <Term, object> >[] { g => g.Name, g => g.TermsCount, g => g.Id };
            var taxonomySession = TaxonomySession.GetTaxonomySession(ClientContext);
            // Get Term Store
            TermStore termStore = null;

            if (TermStore == null)
            {
                termStore = taxonomySession.GetDefaultSiteCollectionTermStore();
            }
            else
            {
                if (TermStore.StringValue != null)
                {
                    termStore = taxonomySession.TermStores.GetByName(TermStore.StringValue);
                }
                else if (TermStore.IdValue != Guid.Empty)
                {
                    termStore = taxonomySession.TermStores.GetById(TermStore.IdValue);
                }
                else
                {
                    if (TermStore.Item != null)
                    {
                        termStore = TermStore.Item;
                    }
                }
            }

            if (ParameterSetName == ParameterSet_TERM)
            {
                if (Identity.IdValue != Guid.Empty)
                {
                    term = termStore.GetTerm(Identity.IdValue);
                    ClientContext.Load(term, RetrievalExpressions);
                    ClientContext.ExecuteQueryRetry();
                    if (IncludeChildTerms.IsPresent && term.TermsCount > 0)
                    {
                        LoadChildTerms(term);
                    }
                    WriteObject(term);
                }
                else
                {
                    WriteError(new ErrorRecord(new Exception("Insufficient parameters"), "INSUFFICIENTPARAMETERS", ErrorCategory.SyntaxError, this));
                }
            }
            else
            {
                TermGroup termGroup = null;

                if (TermGroup != null && TermGroup.Id != Guid.Empty)
                {
                    termGroup = termStore.Groups.GetById(TermGroup.Id);
                }
                else if (TermGroup != null && !string.IsNullOrEmpty(TermGroup.Name))
                {
                    termGroup = termStore.Groups.GetByName(TermGroup.Name);
                }

                TermSet termSet = null;
                if (TermSet != null)
                {
                    if (TermSet.Id != Guid.Empty)
                    {
                        termSet = termGroup.TermSets.GetById(TermSet.Id);
                    }
                    else if (!string.IsNullOrEmpty(TermSet.Title))
                    {
                        termSet = termGroup.TermSets.GetByName(TermSet.Title);
                    }
                    else
                    {
                        termSet = TermSet.Item;
                    }
                }
                if (Identity != null)
                {
                    term = null;
                    if (Identity.IdValue != Guid.Empty)
                    {
                        term = termStore.GetTerm(Identity.IdValue);
                    }
                    else
                    {
                        var termName = TaxonomyExtensions.NormalizeName(Identity.StringValue);
                        if (!Recursive)
                        {
                            term = termSet.Terms.GetByName(termName);
                        }
                        else
                        {
                            var lmi = new LabelMatchInformation(ClientContext)
                            {
                                TrimUnavailable = true,
                                TermLabel       = termName
                            };

                            var termMatches = termSet.GetTerms(lmi);
                            ClientContext.Load(termMatches);
                            ClientContext.ExecuteQueryRetry();

                            if (termMatches.AreItemsAvailable)
                            {
                                term = termMatches.FirstOrDefault();
                            }
                        }
                    }
                    ClientContext.Load(term, RetrievalExpressions);
                    ClientContext.ExecuteQueryRetry();
                    if (IncludeChildTerms.IsPresent && term.TermsCount > 0)
                    {
                        LoadChildTerms(term);
                    }
                    WriteObject(term);
                }
                else
                {
                    var query = termSet.Terms.IncludeWithDefaultProperties(RetrievalExpressions);
                    var terms = ClientContext.LoadQuery(query);
                    ClientContext.ExecuteQueryRetry();
                    if (IncludeChildTerms.IsPresent)
                    {
                        foreach (var collectionTerm in terms)
                        {
                            if (collectionTerm.TermsCount > 0)
                            {
                                LoadChildTerms(collectionTerm);
                            }
                        }
                    }
                    WriteObject(terms, true);
                }
            }
        }
Exemplo n.º 26
0
        public static TaxonomyFieldValue GetTaxonomyFieldValue(TermSet termSet, string value, bool addIfDoesNotExist, out bool newTermAdded)
        {
            string termVal = TaxonomyItem.NormalizeName((value ?? string.Empty).Trim()); //ReplaceIllegalCharacters((value ?? string.Empty).Trim());
            Term term = null;
            newTermAdded = false;

            if (termSet != null)
            {
                if (!string.IsNullOrEmpty(termVal))
                {
                    term = termSet.GetTerms(termVal, termSet.TermStore.DefaultLanguage, true,
                                                 StringMatchOption.ExactMatch, 1, false).FirstOrDefault();
                }

                if (term == null && termSet.IsOpenForTermCreation && addIfDoesNotExist)
                {
                    if (!string.IsNullOrEmpty(termVal))
                    {
                        term = termSet.CreateTerm(termVal, termSet.TermStore.DefaultLanguage);
                        newTermAdded = true;
                        //termSet.TermStore.CommitAll();
                    }
                }

                if (term != null)
                {
                    string termValue = string.Concat(term.GetDefaultLabel(termSet.TermStore.DefaultLanguage),
                                                          TaxonomyField.TaxonomyGuidLabelDelimiter,
                                                          term.Id.ToString());
                    return TaxonomyFieldControl.GetTaxonomyValue(termValue);
                }
            }

            return null;
        }
Exemplo n.º 27
0
        protected Term FindTermInTermSet(TermSet termSet, TaxonomyTermDefinition termModel)
        {
            Term result = null;

            if (termModel.Id.HasValue)
                result = termSet.GetTerm(termModel.Id.Value);
            else if (!string.IsNullOrEmpty(termModel.Name))
            {
                var termName = NormalizeTermName(termModel.Name);
                result = termSet.GetTerms(termName, termModel.LCID, false).FirstOrDefault();
            }

            return result;
        }
Exemplo n.º 28
0
        protected Term FindTermInTermSet(TermSet termSet, TaxonomyTermDefinition termModel)
        {
            Term result = null;

            var context = termSet.Context;

            if (termModel.Id.HasValue)
            {
                var scope = new ExceptionHandlingScope(context);
                using (scope.StartScope())
                {
                    using (scope.StartTry())
                    {
                        result = termSet.Terms.GetById(termModel.Id.Value);
                        context.Load(result);
                    }

                    using (scope.StartCatch())
                    {

                    }
                }

                context.ExecuteQueryWithTrace();
            }
            else if (!string.IsNullOrEmpty(termModel.Name))
            {
                var terms = termSet.GetTerms(new LabelMatchInformation(context)
                {
                    Lcid = termModel.LCID,
                    TermLabel = termModel.Name,
                    TrimUnavailable = false
                });

                context.Load(terms);
                context.ExecuteQueryWithTrace();

                result = terms.FirstOrDefault();
            }

            if (result != null && result.ServerObjectIsNull == false)
            {
                context.Load(result);
                context.ExecuteQueryWithTrace();

                return result;
            }

            return null;
        }