private static IList<Term> GetTermsForLabelInternal(TermStore termStore, Group termStoreGroup, TermSet termSet, string termLabel)
        {
            if (termStore == null)
            {
                throw new ArgumentNullException("termStore");
            }

            if (termStoreGroup == null)
            {
                throw new ArgumentNullException("termStoreGroup");
            }

            if (termSet == null)
            {
                throw new ArgumentNullException("termSetName");
            }

            if (string.IsNullOrEmpty(termLabel))
            {
                throw new ArgumentNullException("termLabel");
            }

            TermCollection termCollection = termSet.GetAllTerms();
            return termCollection.Where((term) =>
            {
                return term.Labels.Any(label => label.Value == termLabel);
            }).ToList();
        }
Esempio n. 2
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)
            {
            }
        }
 public Term FindTerm(TermSet termSet, Guid termGuid, string nameString)
 {
     termSet.RequireNotNull("termSet");
     nameString.RequireNotNullOrEmpty("nameString");
     Term term = FindTerm(termSet, termGuid) ?? FindTerm(termSet, nameString);
     return term;
 }
        private static void MapTermSet(TermSet currentTermSet, TaxonomyTermSetDefinition termSetModel)
        {
            currentTermSet.Description = termSetModel.Description;

            if (termSetModel.IsOpenForTermCreation.HasValue)
                currentTermSet.IsOpenForTermCreation = termSetModel.IsOpenForTermCreation.Value;

            if (termSetModel.IsAvailableForTagging.HasValue)
                currentTermSet.IsAvailableForTagging = termSetModel.IsAvailableForTagging.Value;
        }
Esempio n. 5
0
        public static Term CreateTerm(this SPSite site, TermSet termset, string name)
        {
            if (termset.Terms.All(x => x.Name != name))
            {
                var term = termset.CreateTerm(name, int.Parse(site.RootWeb.Language.ToString()));
                term.TermStore.CommitAll();
                return term;
            }

            return termset.Terms.FirstOrDefault(x => x.Name == name);
        }
Esempio n. 6
0
        /// <summary>
        /// Initializes a <see cref="TermSetInfo"/> instance from a taxonomy term set.
        /// </summary>
        /// <param name="termSet">The term set</param>
        /// <returns>The easily serializable <see cref="TermSetInfo"/> object</returns>
        public TermSetInfo CreateFromTermSet(TermSet termSet)
        {
            if (termSet == null)
            {
                throw new ArgumentNullException("termSet");
            }

            TermGroupInfo groupInfo = this.CreateFromTermGroup(termSet.Group);

            return new TermSetInfo(termSet.Id, this.GetTermSetLabelsForAllWorkingLanguages(termSet), groupInfo);
        }
Esempio n. 7
0
        public SPOTermSet(TermSet termSet)
            : base(termSet)
        {
            _termSet = termSet;

            if (_termSet.IsPropertyAvailable("Description"))
                SetProp("Description", _termSet.Description, false);
            if (_termSet.IsPropertyAvailable("Contact"))
                SetProp("Contact", _termSet.Contact, false);
            if (_termSet.IsPropertyAvailable("IsOpenForTermCreation"))
                SetProp("IsOpenForTermCreation", _termSet.IsOpenForTermCreation, false);
        }
 private static void AddTerm(ClientContext clientContext, TermSet termSet, string termName, string termNameFrench, string termNameGerman, string termNameSwedish)
 {
     if (!termSet.Terms.Any(t => t.Name.Equals(termName)))
     {
         var term = termSet.CreateTerm(termName, 1033, Guid.NewGuid());
         term.CreateLabel(termNameGerman, 1031, false);
         term.CreateLabel(termNameFrench, 1036, false);
         term.CreateLabel(termNameSwedish, 1053, false);
         term.SetLocalCustomProperty("_Sys_Nav_SimpleLinkUrl", clientContext.Web.ServerRelativeUrl);
         clientContext.ExecuteQuery();
     }
 }
Esempio n. 9
0
        private static void CreateTerms(TermSet termset)
        {
            var lcid = 1033;

            foreach (var term in TermInfos)
            {
                var newTerm = termset.CreateTerm(term.TermName, lcid, Guid.NewGuid());
                newTerm.SetCustomProperty("Format", term.TermFormat);

                CreateSubTerms(term, newTerm);
            }
            string[] order = SetOrder(TermInfos);
            termset.CustomSortOrder = String.Join(":", order);
        }
Esempio n. 10
0
        private static TermSet GetCorrectTermSet(ClientContext ctx, string termName, TermSetCollection termSets)
        {
            //This is a challenge when there is more than one
            if (termSets.Count == 1)
            {
                return(termSets[0]);
            }
            if (termSets.Count == 0)
            {
                return(null);
            }

            TermSet bestMatch    = null;
            var     maxTermCount = 0;

            foreach (var termSet in termSets)
            {
                var terms = termSet.GetAllTerms();
                ctx.Load(terms);
                ctx.Load(termSet.Group, g => g.Name);
                try
                {
                    ctx.ExecuteQueryRetry();

                    if (!termSet.Group.Name.StartsWith("Site Collection"))
                    {
                        if (!string.IsNullOrEmpty(termName))
                        {
                            if (terms.FirstOrDefault(t => t.Name == termName) != null)
                            {
                                return(termSet);
                            }
                        }
                        else
                        {
                            if (terms.Count > maxTermCount || bestMatch == null)
                            {
                                maxTermCount = terms.Count;
                                bestMatch    = termSet;
                            }
                        }
                    }
                }
                catch
                {
                    //ignored
                }
            }
            return(bestMatch);
        }
        private static void MapTermSet(TermSet currentTermSet, TaxonomyTermSetDefinition termSetModel)
        {
            currentTermSet.Description = termSetModel.Description;

            if (termSetModel.IsOpenForTermCreation.HasValue)
            {
                currentTermSet.IsOpenForTermCreation = termSetModel.IsOpenForTermCreation.Value;
            }

            if (termSetModel.IsAvailableForTagging.HasValue)
            {
                currentTermSet.IsAvailableForTagging = termSetModel.IsAvailableForTagging.Value;
            }
        }
Esempio n. 12
0
        public override void WithResolvingModelHost(ModelHostResolveContext modelHostContext)
        {
            var modelHost      = modelHostContext.ModelHost;
            var model          = modelHostContext.Model;
            var childModelType = modelHostContext.ChildModelType;
            var action         = modelHostContext.Action;


            var definition = model.WithAssertAndCast <TaxonomyTermDefinition>("model", value => value.RequireNotNull());

            Term      currentTerm = null;
            TermGroup group       = null;
            TermSet   termSet     = null;
            TermStore termStore   = null;

            TermModelHost localModelHost = new TermModelHost();

            if (modelHost is TermModelHost)
            {
                var h = (modelHost as TermModelHost);

                group     = h.HostGroup;
                termSet   = h.HostTermSet;
                termStore = h.HostTermStore;

                currentTerm = FindTermInTerm(h.HostTerm, definition);

                localModelHost.HostGroup     = group;
                localModelHost.HostTermSet   = termSet;
                localModelHost.HostTerm      = currentTerm;
                localModelHost.HostTermStore = termStore;
            }
            else if (modelHost is TermSetModelHost)
            {
                var h = (modelHost as TermSetModelHost);

                termStore = h.HostTermStore;
                group     = h.HostGroup;
                termSet   = h.HostTermSet;

                currentTerm = FindTermInTermSet(h.HostTermSet, definition);

                localModelHost.HostGroup     = group;
                localModelHost.HostTermSet   = termSet;
                localModelHost.HostTerm      = currentTerm;
                localModelHost.HostTermStore = termStore;
            }

            action(localModelHost);
        }
Esempio n. 13
0
        public TermSet CreateTermSet(TermGroup group, string termsetname)
        {
            Ctx.Load(group.TermSets);
            Ctx.ExecuteQuery();
            TermSet set = group.TermSets.FirstOrDefault(x => x.Name == termsetname);

            if (set == null)
            {
                set = group.CreateTermSet(termsetname, Guid.NewGuid(), LCID);
                Ctx.Load(set);
                Ctx.ExecuteQuery();
            }
            return(set);
        }
Esempio n. 14
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();
        }
Esempio n. 15
0
 static Term GetTerm(TermSet termSet, string termName)
 {
     if (termSet != null)
     {
         foreach (Term term in termSet.Terms)
         {
             if (term.GetDefaultLabel(1033) == termName)
             {
                 return(term);
             }
         }
     }
     return(null);
 }
        private TermSet GetTermSetByName(string termSetName, Group termGroup)
        {
            TermSet termSetToReturn = null;

            foreach (TermSet currentTermSet in termGroup.TermSets)
            {
                if (currentTermSet.Name == termSetName)
                {
                    termSetToReturn = currentTermSet;
                    return(termSetToReturn);
                }
            }
            return(termSetToReturn);
        }
Esempio n. 17
0
        private static Term GetTermByName(ClientContext ctx, string issueCategory)
        {
            TermStore store   = ctx.Site.GetDefaultSiteCollectionTermStore();
            TermSet   termSet = store.GetTermSet("{3D4C7DE0-3867-44C3-871A-C36DEC4E1970}".ToGuid());

            TermCollection terms = termSet.Terms;

            ctx.Load(terms);
            ctx.ExecuteQuery();

            Term term = terms.Where(t => t.Name == issueCategory).FirstOrDefault();

            return(term);
        }
Esempio n. 18
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();
        }
Esempio n. 19
0
        private static void ExportTerms(string directoryPath, string groupName, string termsetName, string urlSPSite)
        {
            strExportXml = new StringBuilder();

            using (SPSite site = new SPSite(urlSPSite))
            {
                String fileName = groupName + "-" + termsetName + ".xml";
                fileName = fileName.Replace("/", "").Replace("\\", "").Replace(" ", "");

                // function that return termstore from site.
                termStore = termstorefromWebApp(site);

                Group   group   = termStore.Groups[groupName];
                TermSet termSet = group.TermSets[termsetName];

                String termsetNameFr = String.Empty;
                try
                {
                    PropertyInfo namesProperty = termSet.GetType().GetProperties(BindingFlags.NonPublic | BindingFlags.Instance).Single(pi => pi.Name == "Names");
                    System.Collections.Generic.Dictionary <int, string> names = (System.Collections.Generic.Dictionary <int, string>)namesProperty.GetValue(termSet, null);


                    if (names[1036] != null)
                    {
                        termsetNameFr = names[1036];
                    }
                }
                catch (System.Collections.Generic.KeyNotFoundException)
                {
                }

                strExportXml.Append("<?xml version=\"1.0\" encoding=\"utf-16\" ?>");
                strExportXml.Append("<Groups>");
                strExportXml.Append("<Group Name=\"" + groupName + "\">");
                strExportXml.Append("<TermSet Name=\"" + termsetName + "\" " + "NameFr=\"" + termsetNameFr + "\">");
                strExportXml.Append("<Terms>");

                foreach (Term trm in termSet.Terms)
                {
                    GetTerm(trm);
                }
                strExportXml.Append("</Terms>");
                strExportXml.Append("</TermSet>");
                strExportXml.Append("</Group>");
                strExportXml.Append("</Groups>");
                System.Console.WriteLine("Export Terms");
                FinalExport(directoryPath, fileName);
            }
        }
Esempio n. 20
0
        protected override void ProcessFieldProperties(Field field, FieldDefinition fieldModel)
        {
            var context = CurrentSiteModelHost.HostClientContext;

            var taxFieldModel = fieldModel.WithAssertAndCast <TaxonomyFieldDefinition>("model", value => value.RequireNotNull());
            var taxField      = context.CastTo <TaxonomyField>(field);

            // let base setting be setup
            base.ProcessFieldProperties(taxField, fieldModel);
            context.ExecuteQueryWithTrace();

            var termStore = TaxonomyTermStoreModelHandler.FindTermStore(CurrentSiteModelHost,
                                                                        taxFieldModel.SspName,
                                                                        taxFieldModel.SspId,
                                                                        taxFieldModel.UseDefaultSiteCollectionTermStore);

            if (termStore == null)
            {
                throw new ArgumentNullException("termStore is NULL. Please define SspName, SspId or ensure there is a default term store for the giving site.");
            }

            var storeContext = CurrentSiteModelHost.HostClientContext;

            storeContext.Load(termStore, s => s.Id);
            storeContext.ExecuteQueryWithTrace();

            // TODO
            TermSet termSet = null;

            if (!string.IsNullOrEmpty(taxFieldModel.TermSetName))
            {
                var termSets = termStore.GetTermSetsByName(taxFieldModel.TermSetName, taxFieldModel.TermSetLCID);

                storeContext.Load(termSets);
                storeContext.ExecuteQueryWithTrace();

                termSet = termSets.FirstOrDefault();
            }

            if (termStore != null)
            {
                taxField.SspId = termStore.Id;
            }

            if (termSet != null)
            {
                taxField.TermSetId = termSet.Id;
            }
        }
Esempio n. 21
0
        public static NavigationTermSet CriarItemNaTermStore(string url, string urlweb, Guid NavTermSetId, Guid TaggingTermSetId)
        {
            SPSite site = new SPSite(url);

            SPWeb web = site.AllWebs[url];

            TaxonomySession taxonomySession = new TaxonomySession(site);

            if (taxonomySession.TermStores.Count == 0)
            {
                throw new InvalidOperationException("O Serviço de taxonomia não existe");
            }

            TermStore termStore = taxonomySession.TermStores[0];

            TermSet existingTermSet = termStore.GetTermSet(NavTermSetId);

            if (existingTermSet != null)
            {
                existingTermSet.Delete();
                termStore.CommitAll();
            }


            Group             siteCollectionGroup = termStore.GetSiteCollectionGroup(web.Site);
            TermSet           termSet             = siteCollectionGroup.CreateTermSet("Teste01", NavTermSetId);
            NavigationTermSet navTermSet          = NavigationTermSet.GetAsResolvedByWeb(termSet, web,
                                                                                         StandardNavigationProviderNames.GlobalNavigationTaxonomyProvider);

            navTermSet.IsNavigationTermSet = true;

            navTermSet.TargetUrlForChildTerms.Value = "~site/Pages/Topics/Topic.aspx";

            NavigationTerm term1 = navTermSet.CreateTerm("Term 1", NavigationLinkType.SimpleLink);

            term1.SimpleLinkUrl = "https://ekisiot.sharepoint.com/";

            NavigationTerm term2 = navTermSet.CreateTerm("Term 2", NavigationLinkType.FriendlyUrl);

            NavigationTerm term2a = term2.CreateTerm("Term 2 A", NavigationLinkType.FriendlyUrl);

            NavigationTerm term2b = term2.CreateTerm("Term 2 B", NavigationLinkType.FriendlyUrl);

            NavigationTerm term3 = navTermSet.CreateTerm("Term 3", NavigationLinkType.FriendlyUrl);

            termStore.CommitAll();

            return(navTermSet);
        }
        /// <summary>
        /// Used to create a custom document library and Contoso Content type
        /// </summary>
        /// <param name="ctx">The authenticated ClientContext</param>
        /// <param name="library">The Library to create</param>
        public void CreateContosoDocumentLibrary(ClientContext ctx, Library library)
        {
            //Check the fields
            if (!ctx.Web.FieldExistsById(FLD_CLASSIFICATION_ID))
            {
                TermStore termStore = GetDefaultTermStore(ctx.Web);

                if (termStore == null)
                {
                    throw new NullReferenceException("The default term store is not available.");
                }

                // get the term group and term set
                TermGroup termGroup = termStore.Groups.GetByName(TAXONOMY_GROUP);
                TermSet   termSet   = termGroup.TermSets.GetByName(TAXONOMY_TERMSET_CLASSIFICATION_NAME);
                ctx.Load(termStore);
                ctx.Load(termSet);
                ctx.ExecuteQuery();

                TaxonomyFieldCreationInformation fldCreate = new TaxonomyFieldCreationInformation()
                {
                    Id           = FLD_CLASSIFICATION_ID,
                    InternalName = FLD_CLASSIFICATION_INTERNAL_NAME,
                    DisplayName  = FLD_CLASSIFICATION_DISPLAY_NAME,
                    Group        = FIELDS_GROUP_NAME,
                    TaxonomyItem = termSet,
                };
                ctx.Web.CreateTaxonomyField(fldCreate);
            }

            //check the content type
            if (!ctx.Web.ContentTypeExistsById(CONTOSODOCUMENT_CT_ID))
            {
                ctx.Web.CreateContentType(CONTOSODOCUMENT_CT_NAME,
                                          CT_DESC, CONTOSODOCUMENT_CT_ID,
                                          CT_GROUP);
            }

            //associate fields to content types
            if (!ctx.Web.FieldExistsByNameInContentType(CONTOSODOCUMENT_CT_NAME, FLD_CLASSIFICATION_INTERNAL_NAME))
            {
                ctx.Web.AddFieldToContentTypeById(CONTOSODOCUMENT_CT_ID,
                                                  FLD_CLASSIFICATION_ID.ToString(),
                                                  false);
            }


            CreateLibrary(ctx, library, CONTOSODOCUMENT_CT_ID);
        }
Esempio n. 23
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);
        }
        public override void OnTermSetRunningStart(TermSet termSet)
        {
            termSet.Context.Load(termSet,
                                 s => s.Name);
            termSet.Context.ExecuteQuery();

            TermInfo termInfo = new TermInfo()
            {
                Type = Type.TermSet,
                Name = termSet.Name
            };

            // Write CSV
            managedMetadataFileWriter.WriteRecord(termInfo);
        }
Esempio n. 25
0
        //gavdcodeend 07

        //gavdcodebegin 08
        static void SpCsCsomFindOneTerm(ClientContext spCtx)
        {
            string termStoreName = "Taxonomy_hVIOdhme2obc+5zqZXqqUQ==";

            TaxonomySession myTaxSession = TaxonomySession.GetTaxonomySession(spCtx);
            TermStore       myTermStore  = myTaxSession.TermStores.GetByName(termStoreName);
            TermGroup       myTermGroup  = myTermStore.Groups.GetByName("CsCsomTermGroup");
            TermSet         myTermSet    = myTermGroup.TermSets.GetByName("CsCsomTermSet");
            Term            myTerm       = myTermSet.Terms.GetByName("CsCsomTerm");

            spCtx.Load(myTerm);
            spCtx.ExecuteQuery();

            Console.WriteLine(myTerm.Name);
        }
Esempio n. 26
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);
        }
Esempio n. 27
0
        public XmlDocument Export(TermSet termSet)
        {
            if (termSet == null)
            {
                throw new ArgumentNullException("termSet", "The TermSet object is null.");
            }

            XmlElement termSetElement = AddTermSetElement(null, termSet);

            foreach (Term term in termSet.Terms)
            {
                Export(termSetElement, term);
            }
            return(_xml);
        }
        protected TermSet FindTermSet(Microsoft.SharePoint.Taxonomy.Group termGroup, TaxonomyTermSetDefinition termSetModel)
        {
            TermSet result = null;

            if (termSetModel.Id.HasValue)
            {
                result = termGroup.TermSets.FirstOrDefault(t => t.Id == termSetModel.Id.Value);
            }
            else if (!string.IsNullOrEmpty(termSetModel.Name))
            {
                result = termGroup.TermSets.FirstOrDefault(t => t.Name.ToUpper() == termSetModel.Name.ToUpper());
            }

            return(result);
        }
        private void Export(XmlElement parentElement, TermSet termSet)
        {
            XmlElement termSetElement = GetTermSetElement(parentElement, termSet);
            var        terms          = termSet.Terms;

            if (!termSet.IsObjectPropertyInstantiated("Terms") || !termSet.Terms.AreItemsAvailable)
            {
                _ctx.Load(terms);
                _ctx.ExecuteQuery();
            }
            foreach (Term term in terms)
            {
                Export(termSetElement, term);
            }
        }
Esempio n. 30
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);
        }
        private void CreatePlantTaxonomy(string contextToken, string hostWeb)
        {
            using (var clientContext
                       = TokenHelper.GetClientContextWithContextToken(hostWeb, contextToken, Request.Url.Authority))
            {
                //Create Taxonomy
                //To manage terms, we must create a new Taxonomy Session object
                TaxonomySession session = TaxonomySession.GetTaxonomySession(clientContext);

                //Get the termstore
                //TermStore termstore = session.TermStores["Managed Metadata Service"];
                TermStore termStore = session.GetDefaultSiteCollectionTermStore();

                //Create a term group
                //Group plantsGroup = termstore.CreateGroup("Plants", Guid.NewGuid());
                TermGroup plantsGroup = termStore.CreateGroup("Plants", Guid.NewGuid());

                //Create a term set
                TermSet flowersTermSet = plantsGroup.CreateTermSet("Flowers", Guid.NewGuid(), 1033);

                //Create some terms
                Term tulipsTerm    = flowersTermSet.CreateTerm("Tulips", 1033, Guid.NewGuid());
                Term orchidsTerm   = flowersTermSet.CreateTerm("Orchids", 1033, Guid.NewGuid());
                Term daffodilsTerm = flowersTermSet.CreateTerm("Daffodils", 1033, Guid.NewGuid());

                //Create a child term within the Orchids term
                Term vanillaTerm = orchidsTerm.CreateTerm("Vanilla", 1033, Guid.NewGuid());

                //You should set properties for every term. In this example, we'll
                //do just one for brevity
                vanillaTerm.SetDescription("A common orchid whose pods are used in desserts", 1033);
                //Use CreateLabel to add synomyns and alternates
                vanillaTerm.CreateLabel("Vanilla planifolia", 1033, false);
                vanillaTerm.CreateLabel("Flat-leaved vanilla", 1033, false);

                //When we are finished making changes, we must commit them
                try
                {
                    //termstore.CommitAll();
                    clientContext.ExecuteQuery();
                    resultsLabel.Text = "Taxonomy created successfully";
                }
                catch (Exception ex)
                {
                    resultsLabel.Text = "There was an error: " + ex.Message;
                }
            }
        }
Esempio n. 32
0
        protected override void ProcessFieldProperties(SPField field, FieldDefinition fieldModel)
        {
            // let base setting be setup
            base.ProcessFieldProperties(field, fieldModel);

            // process taxonomy field specific properties
            var taxField      = field.WithAssertAndCast <TaxonomyField>("field", value => value.RequireNotNull());
            var taxFieldModel = fieldModel.WithAssertAndCast <TaxonomyFieldDefinition>("model", value => value.RequireNotNull());

            var site = GetCurrentSite();

            taxField.AllowMultipleValues = taxFieldModel.IsMulti;

            if (taxFieldModel.Open.HasValue)
            {
                taxField.Open = taxFieldModel.Open.Value;
            }

            if (taxFieldModel.CreateValuesInEditForm.HasValue)
            {
                taxField.CreateValuesInEditForm = taxFieldModel.CreateValuesInEditForm.Value;
            }

            if (taxFieldModel.IsPathRendered.HasValue)
            {
                taxField.IsPathRendered = taxFieldModel.IsPathRendered.Value;
            }

            TermStore tesmStore = LookupTermStore(site, taxFieldModel);

            if (tesmStore != null)
            {
                taxField.SspId = tesmStore.Id;

                TermSet termSet = LookupTermSet(tesmStore, taxFieldModel);
                Term    term    = LookupTerm(tesmStore, taxFieldModel);

                if (termSet != null)
                {
                    taxField.TermSetId = termSet.Id;
                }

                if (term != null)
                {
                    taxField.AnchorId = term.Id;
                }
            }
        }
Esempio n. 33
0
        public static TaxonomyFieldValueCollection GetTaxonomyFieldValues(SPSite site, Guid sspId, Guid termSetId, IEnumerable <string> values, bool addIfDoesNotExist /*, out bool newTermsAdded*/)
        {
            bool            newTermsAdded;
            TaxonomySession taxonomySession = new TaxonomySession(site);
            TermStore       termStore       = taxonomySession.TermStores[sspId];
            TermSet         termSet         = termStore.GetTermSet(termSetId);

            TaxonomyFieldValueCollection val = GetTaxonomyFieldValues(termSet, values, addIfDoesNotExist, out newTermsAdded);

            if (newTermsAdded)
            {
                termStore.CommitAll();
            }

            return(val);
        }
Esempio n. 34
0
        private XmlElement GetTermSetElement(XmlElement parent, TermSet termSet)
        {
            if (parent == null)
            {
                return(AddTermSetElement(parent, termSet));
            }

            XmlElement termSetElement = parent.SelectSingleNode("./TermSets/TermSet[@Id='" + termSet.Id + "']") as XmlElement;

            if (termSetElement == null)
            {
                termSetElement = AddTermSetElement(parent, termSet);
            }

            return(termSetElement);
        }
Esempio n. 35
0
        private static TermSet CreateTermset(Group group)
        {
            TermSet termset     = null;
            var     termSetLcid = 1033;

            termset = group.CreateTermSet(TermsetInfo.Name, TermsetInfo.TermSetId, termSetLcid);

            if (termset != null)
            {
                return(termset);
            }
            else
            {
                throw new Exception(String.Format("Termset {0} could not be created!", TermsetInfo.Name));
            }
        }
Esempio n. 36
0
    static void CreateTerms(ClientContext clientContext, TermSet termSet) {

      Term termEurope = termSet.CreateTerm("Europe", 1033, Guid.NewGuid());
      termEurope.CreateTerm("United Kingdon", 1033, Guid.NewGuid());
      termEurope.CreateTerm("France", 1033, Guid.NewGuid());
      termEurope.CreateTerm("Spain", 1033, Guid.NewGuid());
      termEurope.CreateTerm("Germany", 1033, Guid.NewGuid());

      Term termNorthAmerica = termSet.CreateTerm("North America", 1033, Guid.NewGuid());
      termNorthAmerica.CreateTerm("Canada", 1033, Guid.NewGuid());
      termNorthAmerica.CreateTerm("United States", 1033, Guid.NewGuid());
      termNorthAmerica.CreateTerm("Mexico", 1033, Guid.NewGuid());

      clientContext.ExecuteQuery();
      termSet.TermStore.CommitAll();

    }
Esempio n. 37
0
        public static TermSet GetParent(TermStore termStore, TermQueryModel model, out Term parentTerm)
        {
            TermSet termSet = null;

            parentTerm = null;

            if (string.IsNullOrEmpty(model.TermSetId))
            {
                parentTerm = termStore.GetTerm(new Guid(model.ParentTermId));
            }
            else
            {
                termSet = termStore.GetTermSet(new Guid(model.TermSetId));
            }

            return(termSet);
        }
Esempio n. 38
0
        public TreeViewTerm(TermSet termSet)
        {
            _parent     = null;
            _term       = null;
            _name       = termSet.Name;
            _guidString = "";

            _children = new TreeViewTermCollection();

            foreach (Term term in termSet.Terms)
            {
                if (term.IsAvailableForTagging)
                {
                    _children.Add(new TreeViewTerm(this, term));
                }
            }
        }
Esempio n. 39
0
        public static TermSet LookupTermSet(ClientRuntimeContext context, TermStore termStore,
                                            string termSetName, Guid?termSetId, int termSetLCID)
        {
            var storeContext = context;

            if (!string.IsNullOrEmpty(termSetName))
            {
                var termSets = termStore.GetTermSetsByName(termSetName, termSetLCID);

                storeContext.Load(termSets);
                storeContext.ExecuteQueryWithTrace();

                return(termSets.FirstOrDefault());
            }

            if (termSetId.HasGuidValue())
            {
                TermSet termSet = null;

                var scope = new ExceptionHandlingScope(storeContext);
                using (scope.StartScope())
                {
                    using (scope.StartTry())
                    {
                        termSet = termStore.GetTermSet(termSetId.Value);
                        storeContext.Load(termSet);
                    }

                    using (scope.StartCatch())
                    {
                    }
                }

                storeContext.ExecuteQueryWithTrace();

                if (termSet != null && termSet.ServerObjectIsNull == false)
                {
                    storeContext.Load(termSet, g => g.Id);
                    storeContext.ExecuteQueryWithTrace();

                    return(termSet);
                }
            }

            return(null);
        }
Esempio n. 40
0
        public void ExportTermSet(TermSet termSet, out XElement termSetElement, bool recurse = true)
        {
            termSetElement = new XElement("TermSet");

            try
            {
                termSetElement.SetAttributeValue("Name", termSet.Name);

                if (recurse)
                {

                    foreach (Term term in termSet.Terms)
                    {
                        XElement termElement;
                        ExportTerm(term, out termElement);
                        termSetElement.Add(termElement);
                    }
                }

            }
            catch (Exception e)
            {
            }
        }
Esempio n. 41
0
        /// <summary>
        /// Wires up MMS field to the specified term set.
        /// </summary>
        /// <param name="list">List to be processed</param>
        /// <param name="field">Field to be wired up</param>
        /// <param name="mmsGroupName">Taxonomy group</param>
        /// <param name="mmsTermSetName">Term set name</param>
        public static void WireUpTaxonomyField(this List list, Field field, TermSet termSet, bool allowMultipleValues = false)
        {
            var clientContext = list.Context as ClientContext;

            if (!termSet.IsPropertyAvailable("TermStore"))
            {
                clientContext.Load(termSet.TermStore);
                clientContext.ExecuteQuery();
            }

            // set the SSP ID and Term Set ID on the taxonomy field
            var taxField = clientContext.CastTo<TaxonomyField>(field);
            taxField.SspId = termSet.TermStore.Id;
            taxField.TermSetId = termSet.Id;
            taxField.AllowMultipleValues = allowMultipleValues;
            taxField.Update();
            clientContext.ExecuteQuery();
        }
Esempio n. 42
0
        /// <summary>
        /// Can be used to create taxonomy field remotely in a list. 
        /// </summary>
        /// <param name="list">List to be processed</param>
        /// <param name="id">Unique Id for the taxonomy field</param>
        /// <param name="internalName">Internal Name of the field</param>
        /// <param name="displayName">Display name</param>
        /// <param name="group">Site column group</param>
        /// <param name="termSet">Taxonomy TermSet</param>
        /// <param name="multiValue">If true, create a multivalue field</param>
        /// <returns>New taxonomy field</returns>
        public static Field CreateTaxonomyField(this List list, Guid id, string internalName, string displayName, string group, TermSet termSet, bool multiValue = false)
        {
            internalName.ValidateNotNullOrEmpty("internalName");
            displayName.ValidateNotNullOrEmpty("displayName");
            termSet.ValidateNotNullOrEmpty("termSet");

            try
            {
                var _field = list.CreateField(id, internalName, multiValue ? "TaxonomyFieldTypeMulti" : "TaxonomyFieldType", true, displayName, group, "ShowField=\"Term1033\"");

                WireUpTaxonomyField(list, _field, termSet, multiValue);
                _field.Update();

                list.Context.ExecuteQuery();

                return _field;
            }
            catch (Exception)
            {
                ///If there is an exception the hidden field might be present
                FieldCollection _fields = list.Fields;
                list.Context.Load(_fields, fc => fc.Include(f => f.Id, f => f.InternalName));
                list.Context.ExecuteQuery();
                var _hiddenField = id.ToString().Replace("-", "");

                var _field = _fields.FirstOrDefault(f => f.InternalName == _hiddenField);
                if (_field != null)
                {
                    _field.Hidden = false; // Cannot delete a hidden column
                    _field.Update();
                    _field.DeleteObject();
                    list.Context.ExecuteQuery();
                }
                throw;
            }
        }
 public static Field CreateTaxonomyField(this List list, Guid id, string internalName, string displayName, string group, TermSet termSet, bool multiValue = false)
 {
     TaxonomyFieldCreationInformation fieldCI = new TaxonomyFieldCreationInformation()
     {
         Id = id,
         InternalName = internalName,
         DisplayName = displayName,
         Required = false,
         Group = group,
         MultiValue = multiValue,
         TaxonomyItem = termSet
     };
     return list.CreateTaxonomyField(fieldCI);
 }
        private static IList<Term> GetTermsForTermSetInternal(TermStore termStore, Group termStoreGroup, TermSet termSet)
        {
            if (termStore == null)
            {
                throw new ArgumentNullException("termStore");
            }

            if (termStoreGroup == null)
            {
                throw new ArgumentNullException("termStoreGroup");
            }

            if (termSet == null)
            {
                throw new ArgumentNullException("termSet");
            }

            IList<Term> termsList = new List<Term>();

            if (termSet.Terms.Any())
            {
                // If custom sort order is set, build term list in sorted order
                var customSortOrder = termSet.CustomSortOrder;
                if (!string.IsNullOrEmpty(customSortOrder))
                {
                    var terms = termSet.Terms.ToList();
                    var sortedIds = customSortOrder.Split(':').Select(id => new Guid(id)).ToList();
                    foreach (var sortedId in sortedIds)
                    {
                        var sortedTerm = terms.SingleOrDefault(term => term.Id.Equals(sortedId));
                        if (sortedTerm != null)
                        {
                            termsList.Add(sortedTerm);
                        }
                    }
                }
                else
                {
                    termsList = termSet.Terms.ToList();
                }
            }

            return termsList;
        }
Esempio n. 45
0
        private static bool ImportTermSetLineImport(IList<string> entries, TermSet importTermSet, int lcid, int lineNumber, IDictionary<Guid, object> importedTermIds)
        {
            TermSetItem parentTermSetItem = null;
            Term term = null;
            int num = 0;
            bool success = true;
            bool result = false;
            bool termCreated = false;
            bool changed = false;
            if (entries == null || entries.Count <= 5)
            {
                return false;
            }
            num = 0;
            checked
            {
                string termName = null;
                Guid termId = Guid.Empty;
                // Find matching existing terms
                while (num < entries.Count - 5 && success)
                {
                    string termNameEntry = entries[5 + num];
                    if (string.IsNullOrEmpty(termNameEntry))
                    {
                        if (termCreated)
                        {
                            result = true;
                        }
                        break;
                    }
                    termName = null;
                    termId = Guid.Empty;
                    // Accept extended format of "Name|Guid", noting that | is not an allowed character in the term name
                    if (termNameEntry.Contains(TaxonomyGuidLabelDelimiter))
                    {
                        var split = termNameEntry.Split(new string[] { TaxonomyGuidLabelDelimiter }, StringSplitOptions.None);
                        termName = split[0];
                        termId = new Guid(split[1]);
                    }
                    else
                    {
                        termName = termNameEntry;
                    }
                    // Process the entry
                    if (termName.Length > 255)
                    {
                        termName = termName.Substring(0, 255);
                    }
                    termName = NormalizeName(termName);
                    try
                    {
                        ValidateName(termName, "name");
                    }
                    catch (ArgumentNullException)
                    {
                        Log.Error(Constants.LOGGING_SOURCE, CoreResources.TaxonomyExtension_ImportErrorName0Line1, new object[]
						{
							termName,
							lineNumber
						});
                        success = false;
                        break;
                    }
                    catch (ArgumentException)
                    {
                        Log.Error(Constants.LOGGING_SOURCE, CoreResources.TaxonomyExtension_ImportErrorName0Line1, new object[]
						{
							termName,
							lineNumber
						});
                        success = false;
                        break;
                    }
                    if (term == null)
                    {
                        parentTermSetItem = importTermSet;
                    }
                    else
                    {
                        parentTermSetItem = term;
                    }
                    term = null;
                    if (!parentTermSetItem.IsObjectPropertyInstantiated("Terms"))
                    {
                        parentTermSetItem.Context.Load(parentTermSetItem, i => i.Terms.Include(t => t.Id, t => t.Name, t => t.Description, t => t.IsAvailableForTagging));
                        parentTermSetItem.Context.ExecuteQueryRetry();
                    }
                    foreach (Term current in parentTermSetItem.Terms)
                    {
                        if (termId != Guid.Empty && current.Id == termId)
                        {
                            term = current;
                            break;
                        }
                        if (current.Name == termName)
                        {
                            term = current;
                            break;
                        }
                    }
                    if (term == null && parentTermSetItem != null)
                    {
                        if (termId == Guid.Empty)
                        {
                            termId = Guid.NewGuid();
                        }
                        Log.Info(Constants.LOGGING_SOURCE, CoreResources.TaxonomyExtension_CreateTerm01UnderParent2, termName, termId, parentTermSetItem.Name);
                        term = parentTermSetItem.CreateTerm(termName, lcid, termId);
                        parentTermSetItem.Context.Load(parentTermSetItem, i => i.Terms.Include(t => t.Id, t => t.Name, t => t.Description, t => t.IsAvailableForTagging));
                        parentTermSetItem.Context.Load(term, t => t.Id, t => t.Name, t => t.Description, t => t.IsAvailableForTagging);
                        parentTermSetItem.Context.ExecuteQueryRetry();
                        termCreated = true;
                        if (num == entries.Count - 5 - 1)
                        {
                            result = true;
                        }
                    }
                    if (term != null)
                    {
                        importedTermIds[term.Id] = null;
                    }
                    num++;
                }
                if (success && term != null)
                {
                    try
                    {
                        if (!string.IsNullOrEmpty(entries[3]))
                        {
                            var isAvailableForTagging = bool.Parse(entries[3]);
                            if (term.IsAvailableForTagging != isAvailableForTagging)
                            {
                                Log.Debug(Constants.LOGGING_SOURCE, "Setting IsAvailableForTagging = {1} for term '{0}'.", term.Name, isAvailableForTagging);
                                term.IsAvailableForTagging = isAvailableForTagging;
                                changed = true;
                            }
                        }
                        else
                        {
                            Log.Debug(Constants.LOGGING_SOURCE, "The available for tagging entry on line {0} is null or empty.", new object[]
							{
								lineNumber
							});
                        }
                    }
                    catch (ArgumentNullException)
                    {
                        Log.Error(Constants.LOGGING_SOURCE, CoreResources.TaxonomyExtension_ImportErrorTaggingLine0, new object[]
						{
							lineNumber
						});
                        success = false;
                    }
                    catch (FormatException)
                    {
                        Log.Error(Constants.LOGGING_SOURCE, CoreResources.TaxonomyExtension_ImportErrorTaggingLine0, new object[]
						{
							lineNumber
						});
                        success = false;
                    }
                    string description = entries[4];
                    if (description.Length > 1000)
                    {
                        description = description.Substring(0, 1000);
                    }
                    if (!string.IsNullOrEmpty(description))
                    {
                        try
                        {
                            ValidateDescription(description, "description");
                            if (term.Description != description)
                            {
                                Log.Debug(Constants.LOGGING_SOURCE, "Updating description for term '{0}'.", term.Name);
                                term.SetDescription(description, lcid);
                                changed = true;
                            }
                        }
                        catch (ArgumentException)
                        {
                            Log.Error(Constants.LOGGING_SOURCE, CoreResources.TaxonomyExtension_ImportErrorDescription0Line1, new object[]
							{
								description,
								lineNumber
							});
                            success = false;
                        }
                    }
                    if (term.Name != termName)
                    {
                        Log.Debug(Constants.LOGGING_SOURCE, "Updating name for term '{0}'.", term.Name);
                        term.Name = termName;
                        changed = true;
                    }
                    if (!success)
                    {
                        result = false;
                        Guid id = term.Id;
                        try
                        {
                            Log.Debug(Constants.LOGGING_SOURCE, "Was an issue; deleting");
                            term.DeleteObject();
                            changed = true;
                        }
                        catch (Exception ex)
                        {
                            Log.Error(Constants.LOGGING_SOURCE, CoreResources.TaxonomyExtension_ImportErrorDeleteId0Line1, new object[]
							{
								id,
								lineNumber
							}, ex.Message);
                        }
                    }
                    if (changed)
                    {
                        Log.Debug(Constants.LOGGING_SOURCE, "Updating term {0}", term.Id);
                        parentTermSetItem.Context.ExecuteQueryRetry();
                    }
                }
                return result || changed;
            }
        }
        private static Term GetTermForLabelInternal(TermStore termStore, Group termStoreGroup, TermSet termSet, string termLabel)
        {
            Term term = null;
            IList<Term> terms = GetTermsForLabelInternal(termStore, termStoreGroup, termSet, termLabel);

            if (terms.Count > 1)
            {
                // More than one hit, we'd prefer a root term
                term = terms.FirstOrDefault(maybeRootTerm => maybeRootTerm.IsRoot);
            }

            // A root term was not found, let's just use the first one we find
            if (term == null)
            {
                term = terms.FirstOrDefault();
            }

            return term;
        }
 public static Term CreateTerm(TermSet termSet, Guid termGuid, string nameString, int LCID)
 {
     termSet.RequireNotNull("termSet");
     nameString.RequireNotNullOrEmpty("nameString");
     Term newTerm = null;
     if (!Guid.Empty.Equals(termGuid))
     {
         newTerm = termSet.CreateTerm(nameString, LCID, termGuid);
     }
     else
     {
         newTerm = termSet.CreateTerm(nameString, LCID);
     }
     return newTerm;
 }
 private static IList<TaxonomyValue> GetTaxonomyValuesForLabelInternal(TermStore termStore, Group termStoreGroup, TermSet termSet, string termLabel)
 {
     IList<Term> terms = GetTermsForLabelInternal(termStore, termStoreGroup, termSet, termLabel);
     return terms.Select(term => new TaxonomyValue(term)).ToList();
 }
        private static TaxonomyValue GetTaxonomyValueForLabelInternal(TermStore termStore, Group termStoreGroup, TermSet termSet, string termLabel)
        {
            Term term = GetTermForLabelInternal(termStore, termStoreGroup, termSet, termLabel);

            TaxonomyValue value = null;
            if (term != null)
            {
                value = new TaxonomyValue(term);
            }

            return value;
        }
 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);
 }
        public static Term LookupTerm(ClientContext clientContext, TermStore termStore,
            TermSet termSet,
            TaxonomyFieldDefinition termModel)
        {
            var context = clientContext;
            var site = clientContext.Site;

            Term result = null;

            TermGroup currenGroup = null;

            var termGroupName = termModel.TermGroupName;
            var termGroupId = termModel.TermGroupId;
            var isSiteCollectionGroup = termModel.IsSiteCollectionGroup;

            if (!string.IsNullOrEmpty(termGroupName))
            {
                currenGroup = termStore.Groups.GetByName(termGroupName);

                context.Load(currenGroup);
                context.ExecuteQueryWithTrace();
            }
            else if (termGroupId != null && termGroupId.HasGuidValue())
            {
                currenGroup = termStore.Groups.GetById(termGroupId.Value);

                context.Load(currenGroup);
                context.ExecuteQueryWithTrace();
            }
            else if (isSiteCollectionGroup == true)
            {
                currenGroup = termStore.GetSiteCollectionGroup(site, false);

                context.Load(currenGroup);
                context.ExecuteQueryWithTrace();
            }

            if (currenGroup != null)
            {
                if (termModel.TermId.HasValue)
                {
                    // by ID, the only one match

                    var scope = new ExceptionHandlingScope(context);
                    using (scope.StartScope())
                    {
                        using (scope.StartTry())
                        {
                            result = termStore.GetTerm(termModel.TermId.Value);
                            context.Load(result);
                        }

                        using (scope.StartCatch())
                        {

                        }
                    }

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

                    context.Load(terms, t => t.Include(
                                                i => i.Id,
                                                i => i.Name,
                                                i => i.TermSet,
                                                i => i.TermSet.Group,
                                                i => i.TermSet.Group.Name
                                                ));
                    context.ExecuteQueryWithTrace();

                    result = terms.FirstOrDefault(t => t.TermSet.Group.Name == currenGroup.Name);

                    if ( (result == null) && (termSet != null ))
                        // sometimes label match information does not return the term 
                    {
                        var allTerms = termSet.GetAllTerms();
                        context.Load(allTerms, t => t.Include(
                                                    i => i.Id,
                                                    i => i.Name,
                                                    i => i.TermSet,
                                                    i => i.TermSet.Group,
                                                    i => i.TermSet.Group.Name,
                                                    i => i.Labels
                                                    ));
                        context.ExecuteQueryWithTrace();

                        result = allTerms.FirstOrDefault(t => (t.TermSet.Group.Name == currenGroup.Name) && (t.Labels.Any(l=>l.Value == termModel.TermName && l.Language == termModel.TermLCID)));
                    }
                }
            }

            else
            {

                if (termModel.TermId.HasValue)
                {
                    var scope = new ExceptionHandlingScope(context);
                    using (scope.StartScope())
                    {
                        using (scope.StartTry())
                        {
                            result = termStore.GetTerm(termModel.TermId.Value);
                            context.Load(result);
                        }

                        using (scope.StartCatch())
                        {

                        }
                    }

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

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

                    result = terms.FirstOrDefault();

                    if ((result == null) && (termSet != null))
                        // sometimes label match information does not return the termset 
                    {
                        var allTerms = termSet.GetAllTerms();
                        context.Load(allTerms, t => t.Include(
                            i => i.Id,
                            i => i.Name,
                            i => i.TermSet,
                            i => i.TermSet.Group,
                            i => i.TermSet.Group.Name,
                            i => i.Labels
                            ));
                        context.ExecuteQueryWithTrace();

                        result =
                            allTerms.FirstOrDefault(
                                t => (t.Labels.Any(l=>l.Value == termModel.TermName && l.Language == termModel.TermLCID)));

                    }

                }
                }

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

                return result;
            }

            return null;
        }
Esempio n. 52
0
 /// <summary>
 /// Wires up MMS field to the specified term set.
 /// </summary>
 /// <param name="list">List to be processed</param>
 /// <param name="field">Field to be wired up</param>
 /// <param name="termSet">Taxonomy TermSet</param>
 /// <param name="multiValue">Term set name</param>
 public static void WireUpTaxonomyField(this List list, Field field, TermSet termSet, bool multiValue = false)
 {
     WireUpTaxonomyFieldInternal(field, termSet, multiValue);
 }
 public static Term FindTerm(TermSet termSet, Guid termGuid, string nameString)
 {
     termSet.RequireNotNull("termSet");
     nameString.RequireNotNullOrEmpty("nameString");
     Term term = termSet.Terms.FirstOrDefault(t => t.Id.Equals(termGuid) || t.Name.Equals(nameString));
     return term;
 }
        private static IList<TaxonomyValue> GetTaxonomyValuesForTermSetInternal(TermStore termStore, Group termStoreGroup, TermSet termSet)
        {
            IList<TaxonomyValue> termsList = new List<TaxonomyValue>();
            IList<Term> terms = GetTermsForTermSetInternal(termStore, termStoreGroup, termSet);

            if (terms != null && terms.Count > 0)
            {
                termsList = terms.Select(term => new TaxonomyValue(term)).ToList();
            }

            return termsList;
        }
Esempio n. 55
0
 private static void ImportTermSetRemoveExtraTerms(TermSet termSet, IDictionary<Guid, object> importedTermIds)
 {
     Log.Debug(Constants.LOGGING_SOURCE, "Removing extra terms");
     var termsToDelete = new List<Term>();
     var allTerms = termSet.GetAllTerms();
     termSet.Context.Load(allTerms, at => at.Include(t => t.Id, t => t.Name));
     termSet.Context.ExecuteQueryRetry();
     foreach (var term in allTerms)
     {
         if (!importedTermIds.ContainsKey(term.Id))
         {
             termsToDelete.Add(term);
         }
     }
     foreach (var termToDelete in termsToDelete)
     {
         try
         {
             Log.Info(Constants.LOGGING_SOURCE, CoreResources.TaxonomyExtension_DeleteTerm01, termToDelete.Name, termToDelete.Id);
             termToDelete.DeleteObject();
             termSet.Context.ExecuteQueryRetry();
         }
         catch (ServerException ex)
         {
             if (ex.Message.StartsWith("Taxonomy item instantiation failed."))
             {
                 // This is a sucky way to check if the term was already deleted
                 Log.Debug(Constants.LOGGING_SOURCE, "Term id {0} already deleted.", termToDelete.Id);
             }
             else
             {
                 throw;
             }
         }
     }
 }
        public static TaxonomyField CreateMangedMetadataSiteColumn(SPWeb web, string fieldName, TermSet termSet, string GroupName)
        {
            web.RequireNotNull("web");
            fieldName.RequireNotNullOrEmpty("fieldName");
            termSet.RequireNotNull("termSet");

            if (web.Fields.ContainsField(fieldName))
            {
                return web.Fields[fieldName] as TaxonomyField;
            }

            TaxonomyField field = web.Fields.CreateNewField("TaxonomyFieldType", fieldName) as TaxonomyField;
            field.SspId = termSet.TermStore.Id;
            field.TermSetId = termSet.Id;
            field.TargetTemplate = string.Empty;
            ///field.AllowMultipleValues = true;
            // field.CreateValuesInEditForm = true;
            field.Open = true;
            field.AnchorId = Guid.Empty;
            field.Group = !string.IsNullOrEmpty(GroupName) ? GroupName : "Managed Metadata";
            web.Fields.Add(field);
            web.Update();
            return web.Fields[fieldName] as TaxonomyField;
        }
 public static Term LookupTerm(SiteModelHost currentSiteModelHost, TermStore termStore,
     TermSet termSet,
     TaxonomyFieldDefinition termModel)
 {
     return LookupTerm(currentSiteModelHost.HostClientContext, termStore, termSet, termModel);
 }
Esempio n. 58
0
        private void ProcessSubTerms(ClientContext sourceClientContext, ClientContext targetClientContext, TermSet targetTermSet, Term targetTerm, Term sourceTerm, List<int> languagesToProcess, int defaultLanguage)
        {
            TermCollection sourceTerms = sourceTerm.Terms;
            sourceClientContext.Load(sourceTerms, terms => terms.Include(
                                                              term => term.Name,
                                                              term => term.Description,
                                                              term => term.Id,
                                                              term => term.IsDeprecated,
                                                              term => term.IsAvailableForTagging,
                                                              term => term.LocalCustomProperties,
                                                              term => term.CustomProperties,
                                                              term => term.Labels.Include(label => label.Value, label => label.Language, label => label.IsDefaultForLanguage),
                                                              term => term.TermSet, termset => termset.Id));
            sourceClientContext.ExecuteQuery();
            foreach (Term subSourceTerm in sourceTerm.Terms)
            {
                Term reusedTerm = targetTerm.TermStore.GetTerm(subSourceTerm.Id);
                targetClientContext.Load(reusedTerm);
                targetClientContext.ExecuteQuery();

                Term childTargetTerm;
                if (reusedTerm.ServerObjectIsNull.Value)
                {

                    childTargetTerm = targetTerm.CreateTerm(subSourceTerm.Name, defaultLanguage, subSourceTerm.Id);
                    targetClientContext.Load(childTargetTerm, term => term.IsDeprecated,
                                                              term => term.CustomProperties,
                                                              term => term.LocalCustomProperties);
                    targetClientContext.ExecuteQuery();
                    UpdateTerm(sourceClientContext, targetClientContext, subSourceTerm, childTargetTerm, languagesToProcess);
                }
                else
                {
                    childTargetTerm = targetTerm.ReuseTerm(reusedTerm, false);
                }

                targetClientContext.Load(childTargetTerm);
                targetClientContext.ExecuteQuery();

                targetTermSet.TermStore.UpdateCache();

                ProcessSubTerms(sourceClientContext, targetClientContext, targetTermSet, childTargetTerm, subSourceTerm, languagesToProcess, defaultLanguage);
            }
        }
        private static IList<Term> GetTermsForTermSetInternal(TermStore termStore, Group termStoreGroup, TermSet termSet)
        {
            if (termStore == null)
            {
                throw new ArgumentNullException("termStore");
            }

            if (termStoreGroup == null)
            {
                throw new ArgumentNullException("termStoreGroup");
            }

            if (termSet == null)
            {
                throw new ArgumentNullException("termSet");
            }

            IList<Term> termsList = new List<Term>();

            if (termSet.Terms.Count() > 0)
            {
                termsList = termSet.Terms.Cast<Term>().ToList();
            }

            return termsList;
        }
        /// <summary>
        /// Load practice group term set from term store 
        /// </summary>
        /// <param name="termSet">Term set containing term set data</param>
        /// <param name="customPropertyName">Custom property name</param>
        /// <returns>Term sets</returns>
        internal static TermSets GetPracticeGroupTermSetHierarchy(TermSet termSet, string customPropertyName)
        {
            TermSets tempTermSet = new TermSets();
            string practiceGroupCustomPropertyFolderNames = ConfigurationManager.AppSettings["PracticeGroupCustomPropertyFolderNames"];
            string areaCustomPropertyFolderNames = ConfigurationManager.AppSettings["AreaCustomPropertyFolderNames"];
            string subAreaCustomPropertyFolderNames = ConfigurationManager.AppSettings["SubAreaCustomPropertyFolderNames"];
            string subAreaCustomPropertyisNoFolderStructurePresent = ConfigurationManager.AppSettings["SubAreaCustomPropertyisNoFolderStructurePresent"];
            string subAreaOfLawDocumentTemplates = ConfigurationManager.AppSettings["SubAreaOfLawDocumentTemplates"];

            try
            {
                tempTermSet.Name = termSet.Name;
                ////Retrieve the Terms - level 1
                tempTermSet.PGTerms = new List<PracticeGroupTerm>();
                TermCollection termColl = termSet.Terms;
                foreach (Term term in termColl)
                {
                    PracticeGroupTerm tempTermPG = new PracticeGroupTerm();
                    tempTermPG.TermName = term.Name;
                    tempTermPG.Id = Convert.ToString(term.Id, CultureInfo.InvariantCulture);
                    tempTermPG.ParentTermName = termSet.Name;
                    /////Retrieve the custom property for Terms at level 1
                    foreach (KeyValuePair<string, string> customProperty in term.CustomProperties)
                    {
                        tempTermPG.FolderNames = (customProperty.Key.Equals(practiceGroupCustomPropertyFolderNames, StringComparison.OrdinalIgnoreCase)) ? customProperty.Value : string.Empty;
                    }
                    tempTermSet.PGTerms.Add(tempTermPG);
                    ///// Retrieve the Terms - level 2
                    tempTermPG.AreaTerms = new List<AreaTerm>();
                    TermCollection termCollArea = term.Terms;
                    foreach (Term termArea in termCollArea)
                    {
                        AreaTerm tempTermArea = new AreaTerm();
                        tempTermArea.TermName = termArea.Name;
                        tempTermArea.Id = Convert.ToString(termArea.Id, CultureInfo.InvariantCulture);
                        tempTermArea.ParentTermName = term.Name;
                        /////Retrieve the custom property for Terms at level 2
                        foreach (KeyValuePair<string, string> customProperty in termArea.CustomProperties)
                        {
                            tempTermArea.FolderNames = (customProperty.Key.Equals(areaCustomPropertyFolderNames, StringComparison.OrdinalIgnoreCase)) ? customProperty.Value : string.Empty;
                        }
                        tempTermPG.AreaTerms.Add(tempTermArea);
                        /////Retrieve the Terms - level 3
                        tempTermArea.SubareaTerms = new List<SubareaTerm>();
                        TermCollection termCollSubArea = termArea.Terms;
                        foreach (Term termSubArea in termCollSubArea)
                        {
                            SubareaTerm tempTermSubArea = new SubareaTerm();
                            tempTermSubArea.TermName = termSubArea.Name;
                            tempTermSubArea.Id = Convert.ToString(termSubArea.Id, CultureInfo.InvariantCulture);
                            tempTermSubArea.ParentTermName = termArea.Name;
                            /////Retrieve the custom property for Terms at level 3

                            tempTermSubArea.DocumentTemplates = string.Empty;
                            foreach (KeyValuePair<string, string> customProperty in termSubArea.CustomProperties)
                            {
                                if (customProperty.Key.Equals(customPropertyName, StringComparison.OrdinalIgnoreCase))
                                {
                                    tempTermSubArea.ContentTypeName = customProperty.Value;
                                }
                                else if (customProperty.Key.Equals(subAreaCustomPropertyFolderNames, StringComparison.OrdinalIgnoreCase))
                                {
                                    tempTermSubArea.FolderNames = customProperty.Value;
                                }
                                else if (customProperty.Key.Equals(subAreaCustomPropertyisNoFolderStructurePresent, StringComparison.OrdinalIgnoreCase))
                                {
                                    tempTermSubArea.IsNoFolderStructurePresent = customProperty.Value;
                                }
                                else if (customProperty.Key.Equals(subAreaOfLawDocumentTemplates, StringComparison.OrdinalIgnoreCase))
                                {
                                    tempTermSubArea.DocumentTemplates = customProperty.Value;
                                }
                            }
                            tempTermArea.SubareaTerms.Add(tempTermSubArea);
                        }
                    }
                }
            }
            catch (Exception exception)
            {
                DisplayAndLogError(errorFilePath, "Message: " + exception.Message + "\nStacktrace: " + exception.StackTrace);
                tempTermSet = null;
            }
            return tempTermSet;
        }