// Create the goal objects in the specified term store
        static void ImportTermSet(TermStore termStore, TermSetGoal termSetGoal)
        {
            Log("Setting up term set \"" + termSetGoal.Name + "\"");
            Group group = termStore.Groups.FirstOrDefault(g => g.Name == termSetGoal.GroupName);

            if (group == null)
            {
                Log("Creating missing group \"" + termSetGoal.GroupName + "\"");
                group = termStore.CreateGroup(termSetGoal.GroupName);
            }

            TermSet termSet = termStore.GetTermSet(termSetGoal.Id);

            if (termSet != null)
            {
                Log("Deleting existing term set \"" + termSetGoal.Name + "\"");
                termSet.Delete();
                termStore.CommitAll();
            }

            Log("Creating new term set \"" + termSetGoal.Name + "\"");
            termSet = group.CreateTermSet(termSetGoal.Name, termSetGoal.Id);
            termStore.CommitAll();

            ImportTerms(termSet, termSetGoal);

            termStore.CommitAll();
        }
Exemplo n.º 2
0
        public static void CreateProductTaxonomy(ClientContext ctx)
        {
            TermStore store = ctx.Site.GetDefaultKeywordsTermStore();
            TermGroup productCategoryGroup = store.GetTermGroupByName("OD2");

            if (productCategoryGroup == null)
            {
                productCategoryGroup = store.CreateTermGroup("OD2", Constants.TAXONOMY_OD2_GROUP_ID.ToGuid(), "Stuff for od2");
            }


            TermSet ts = store.GetTermSet(Constants.TAXONOMY_PRODUCTCAT_TERMSET_ID.ToGuid());

            ctx.Load(ts);
            ctx.ExecuteQuery();
            // if term store does not exist create a new one.
            if (ts.ServerObjectIsNull.Value)
            {
                ts = productCategoryGroup.CreateTermSet("Product Category", Constants.TAXONOMY_PRODUCTCAT_TERMSET_ID.ToGuid(), 1033);
                store.CommitAll();
                ctx.Load(ts);
                ctx.ExecuteQuery();
                ts.CreateTerm("Prod Cat 1", 1033, Guid.NewGuid());
                ts.CreateTerm("Prod Cat 2", 1033, Guid.NewGuid());
                ts.CreateTerm("Prod Cat 3", 1033, Guid.NewGuid());
                ts.CreateTerm("Prod Cat 4", 1033, Guid.NewGuid());

                store.CommitAll();
                ctx.ExecuteQuery();
            }
        }
Exemplo n.º 3
0
    public static void CreateProductCategoriesTermset()
    {
        string termSetName       = "Product Categories";
        var    aspnetHttpContext = System.Web.HttpContext.Current;
        var    spContext         = SharePointContextProvider.Current.GetSharePointContext(aspnetHttpContext);

        using (var clientContext = spContext.CreateUserClientContextForSPHost()) {
            if (clientContext != null)
            {
                Site siteCollection = clientContext.Site;
                clientContext.Load(siteCollection, sc => sc.Url);
                clientContext.ExecuteQuery();

                TaxonomySession taxonomySession = TaxonomySession.GetTaxonomySession(clientContext);
                taxonomySession.UpdateCache();
                clientContext.Load(taxonomySession, ts => ts.TermStores);
                clientContext.ExecuteQuery();
                TermStore termStore        = taxonomySession.TermStores.FirstOrDefault <TermStore>();
                Guid      localTermStoreID = termStore.Id;

                TermGroup group = termStore.GetSiteCollectionGroup(siteCollection, true);
                clientContext.Load(group);
                clientContext.Load(group.TermSets);
                clientContext.ExecuteQuery();


                // make sure it's deleted if exists

                foreach (TermSet termset in group.TermSets)
                {
                    if (termset.Name.Equals(termSetName))
                    {
                        termset.DeleteObject();
                        termStore.CommitAll();
                        clientContext.ExecuteQuery();
                    }
                }

                Guid    termSetId = Guid.NewGuid();
                TermSet tset      = group.CreateTermSet(termSetName, termSetId, 1033);
                termStore.CommitAll();
                clientContext.ExecuteQuery();

                foreach (var term in terms)
                {
                    CreateTopLevelTerm(tset, term);
                }

                termStore.CommitAll();
                clientContext.ExecuteQuery();

                clientContext.ExecuteQuery();
                termStore.CommitAll();
            }
        }
    }
Exemplo n.º 4
0
        public static NavigationTermSet CriarItemNaTermStore(string url, string urlweb, Guid NavTermSetId, Guid TaggingTermSetId)
        {
            SPSite site = new SPSite(url);

            SPWeb web = site.AllWebs[urlweb];

            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);

            termStore.CommitAll();

            NavigationTermSet navTermSet = NavigationTermSet.GetAsResolvedByWeb(termSet, web,
                                                                                StandardNavigationProviderNames.GlobalNavigationTaxonomyProvider);

            termStore.CommitAll();

            navTermSet.IsNavigationTermSet = true;

            navTermSet.TargetUrlForChildTerms.Value = "/en/Pages/default.aspx";

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

            term1.SimpleLinkUrl = "http://h9j/pt/Paginas/default.aspx";
            termStore.CommitAll();

            /*
             * NavigationTerm term2 = navTermSet.CreateTerm("Term 2", NavigationLinkType.FriendlyUrl, Guid.NewGuid());
             *
             * term2.FriendlyUrlSegment.Value = "PAgInicial";
             *
             * term2.TargetUrl.Value = "/en/Pages/default.aspx";
             */


            termStore.CommitAll();

            return(navTermSet);
        }
Exemplo n.º 5
0
        // Create the TermSetGoal objects in the specified TermStore object.
        static void SyncTermSet(TermStore termStore, TermSetGoal termSetGoal)
        {
            Group group = termStore.Groups.FirstOrDefault(g => g.Name == termSetGoal.GroupName);

            if (group == null)
            {
                Log("* Creating missing group \"" + termSetGoal.GroupName + "\"");
                group = termStore.CreateGroup(termSetGoal.GroupName);
            }

            TermSet termSet = termStore.GetTermSet(termSetGoal.Id);

            if (termSet == null)
            {
                Log("* Creating missing term set \"" + termSetGoal.Name + "\"");
                termSet = group.CreateTermSet(termSetGoal.Name, termSetGoal.Id, lcid);
            }
            else
            {
                if (termSet.Group.Id != group.Id)
                {
                    Log("* Moving term set to group \"" + group.Name + "\"");
                    termSet.Move(group);
                }

                if (termSet.Name != termSetGoal.Name)
                {
                    termSet.Name = termSetGoal.Name;
                }
            }

            termStore.CommitAll();

            // Load the tree of terms as a flat list.
            Dictionary <Guid, Term> termsById = new Dictionary <Guid, Term>();

            foreach (Term term in termSet.GetAllTerms())
            {
                termsById.Add(term.Id, term);
            }

            Log("Step 1: Adds and Moves");
            ProcessAddsAndMoves(termSet, termSetGoal, termsById);

            Log("Step 2: Deletes");
            // Requery the TermSet object to reflect changes to the topology.
            termSet = termStore.GetTermSet(termSetGoal.Id);
            ProcessDeletes(termSet, termSetGoal); // Step 2

            Log("Step 3: Property Updates");
            termSet = termStore.GetTermSet(termSetGoal.Id);
            ProcessPropertyUpdates(termSet, termSetGoal); // Step 3

            termStore.CommitAll();
        }
Exemplo n.º 6
0
        public static NavigationTermSet RecreateSampleNavTermSet(TestContext testContext,
                                                                 TaxonomySession taxonomySession, SPWeb web)
        {
            Console.WriteLine(testContext, "RecreateSampleNavTermSet(): START");

            // Use the first TermStore object in the list.
            if (taxonomySession.TermStores.Count == 0)
            {
                throw new InvalidOperationException("The Taxonomy Service is offline or missing.");
            }

            TermStore termStore = taxonomySession.TermStores[0];

            // Does the TermSet object already exist?
            TermSet existingTermSet = termStore.GetTermSet(TestConfig.NavTermSetId);

            if (existingTermSet != null)
            {
                Console.WriteLine(testContext, "RecreateSampleNavTermSet(): Deleting old TermSet");
                existingTermSet.Delete();
                termStore.CommitAll();
            }

            Console.WriteLine(testContext, "RecreateSampleNavTermSet(): Creating new TermSet");

            // Create a new TermSet object.
            Group   siteCollectionGroup = termStore.GetSiteCollectionGroup(web.Site);
            TermSet termSet             = siteCollectionGroup.CreateTermSet("Navigation Demo", TestConfig.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 = "http://www.bing.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();

            Console.WriteLine(testContext, "RecreateSampleNavTermSet(): FINISH");

            return(navTermSet);
        }
Exemplo n.º 7
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.º 8
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);
        }
Exemplo n.º 9
0
        private static void GenerateDefaultTaxonomyTreeFromXMLFile(SPSite site)
        {
            using (site)
            {
                TaxonomySession taxonomySession = new TaxonomySession(site);
                TermStore       termStore       = taxonomySession.DefaultSiteCollectionTermStore;

                if (termStore != null)
                {
                    TermStore = termStore;

                    var web = site.RootWeb;

                    XmlDocument document = new XmlDocument();
                    SPFile      file     = web.GetFile(String.Format("{0}/{1}", web.Url, valueSource));
                    using (Stream fileStream = file.OpenBinaryStream())
                    {
                        document.Load(fileStream);
                        fileStream.Close();
                    }

                    GetNodes((XmlNode)document.DocumentElement);
                    try
                    {
                        CreateTaxonomyTree();
                        TermStore.CommitAll();
                    }
                    catch (Exception ex)
                    {
                    }
                }
            }
        }
Exemplo n.º 10
0
        protected override void ExecuteCmdlet()
        {
            var taxonomySession = TaxonomySession.GetTaxonomySession(ClientContext);
            // Get Term Store
            TermStore termStore = null;

            if (TermStore == null)
            {
                termStore = taxonomySession.GetDefaultSiteCollectionTermStore();
            }
            else
            {
                termStore = TermStore.GetTermStore(taxonomySession);
            }

            Term term = null;

            if (ParameterSetName == ParameterSet_TERMID)
            {
                term = Identity.GetTerm(ClientContext, termStore, null, false, null);
            }
            else
            {
                var termGroup = TermGroup.GetGroup(termStore);
                var termSet   = TermSet.GetTermSet(termGroup);
                term = Identity.GetTerm(ClientContext, termStore, termSet, false, null);
            }
            if (ShouldProcess($"Delete term {term.Name} with id {term.Id}"))
            {
                term.DeleteObject();
                termStore.CommitAll();
                ClientContext.ExecuteQueryRetry();
            }
        }
Exemplo n.º 11
0
        public void Import(TermStore parentTermStore)
        {
            if (parentTermStore == null)
            {
                throw new ArgumentNullException("parentTermStore", "The parent TermStore object is null.");
            }

            if (_xml.DocumentElement.Name == "Groups")
            {
                XmlNodeList groupNodes = _xml.SelectNodes("./Groups/Group");
                if (groupNodes == null || groupNodes.Count == 0)
                {
                    return;
                }

                foreach (XmlElement groupElement in groupNodes)
                {
                    Import(groupElement, parentTermStore);
                }
            }
            else if (_xml.DocumentElement.Name == "Group")
            {
                Import(_xml.DocumentElement, parentTermStore);
            }
            parentTermStore.CommitAll();
        }
Exemplo n.º 12
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.º 13
0
        /// <summary>
        /// Create client terms
        /// </summary>
        /// <param name="TermsData">Data for client terms</param>
        /// <param name="clientContext">Client Context object</param>
        private static void CreateTermsForClients(List <CustomClientGroup> TermsData, ClientContext clientContext)
        {
            TaxonomySession taxonomySession = TaxonomySession.GetTaxonomySession(clientContext);

            clientContext.Load(taxonomySession.TermStores);

            //Execute the query to the server
            clientContext.ExecuteQuery();
            TermStore termStore = taxonomySession.GetDefaultSiteCollectionTermStore();

            clientContext.Load(termStore.Groups);

            //Execute the query to the server
            clientContext.ExecuteQuery();
            foreach (CustomClientGroup cltGroup in TermsData)
            {
                TermGroup group = termStore.Groups.Where(termGroup => termGroup.Name == cltGroup.name).Count() > 0 ? termStore.Groups.GetByName(cltGroup.name) : termStore.CreateGroup(cltGroup.name, Guid.NewGuid());
                if (null != group)
                {
                    TermSet cltTermSet   = group.CreateTermSet(ConfigurationManager.AppSettings["clientterm"], Guid.NewGuid(), 1033);
                    TermSet cltIDTermSet = group.CreateTermSet(ConfigurationManager.AppSettings["clientidterm"], Guid.NewGuid(), 1033);
                    foreach (ClientList clients in cltGroup.clt)
                    {
                        Term clientCustom = cltTermSet.CreateTerm(clients.ClientName, 1033, Guid.NewGuid());
                        cltIDTermSet.CreateTerm(clients.ClientID, 1033, Guid.NewGuid());
                        clientCustom.SetCustomProperty("ClientID", clients.ClientID);
                        clientCustom.SetCustomProperty("ClientURL", clients.ClientURL);
                    }
                }
            }
            termStore.CommitAll();
            clientContext.Load(termStore);
            //Execute the query to the server
            clientContext.ExecuteQuery();
        }
        public void Import(TermStore parentTermStore)
        {
            if (parentTermStore == null || parentTermStore.ServerObjectIsNull.Value)
            {
                throw new ArgumentNullException("parentTermStore", "The parent TermStore object is null.");
            }

            LoadWorkingLanguage(parentTermStore);
            if (_xml.DocumentElement.Name == "Groups")
            {
                XmlNodeList groupNodes = _xml.SelectNodes("./Groups/Group");
                if (groupNodes == null || groupNodes.Count == 0)
                {
                    return;
                }

                foreach (XmlElement groupElement in groupNodes)
                {
                    Import(groupElement, parentTermStore);
                }
            }
            else if (_xml.DocumentElement.Name == "Group")
            {
                Import(_xml.DocumentElement, parentTermStore);
            }
            parentTermStore.CommitAll();
            parentTermStore.Context.ExecuteQuery();
        }
 /// <summary>
 /// An item is being deleted.
 /// </summary>
 public override void ItemDeleting(SPItemEventProperties properties)
 {
     try
     {
         SPSecurity.RunWithElevatedPrivileges(delegate()
         {
             TaxonomySession session       = new TaxonomySession(properties.Web.Site);
             TermStore mainTermStore       = session.TermStores[0];
             Group siteGroup               = mainTermStore.GetSiteCollectionGroup(properties.Web.Site);
             TermSet issuingCompanyTermSet = GetTermSetByName("Issuing Company", siteGroup);
             if (issuingCompanyTermSet != null)
             {
                 string newTerm    = properties.ListItem["Title"].ToString();
                 Term matchingTerm = GetTermByName(newTerm, issuingCompanyTermSet);
                 if (matchingTerm != null)
                 {
                     if (!matchingTerm.IsDeprecated)
                     {
                         matchingTerm.Deprecate(true);
                         mainTermStore.CommitAll();
                     }
                 }
             }
             else
             {
                 throw new Exception("There was an error connecting to the SharePoint Managed Metadata Service");
             }
         });
     }
     catch (Exception taxonomyException)
     {
         properties.ErrorMessage = taxonomyException.Message;
         properties.Status       = SPEventReceiverStatus.CancelWithError;
     }
 }
        // 7.	Crear el código en la función Main que cree los grupos, términos y los enlace para la navegación

        static void Main(string[] args)
        {
            SPSecurity.RunWithElevatedPrivileges(
                () =>
            {
                using (SPSite site = new SPSite("http://" + sphost + "/sites/publicacion"))
                {
                    TaxonomySession session = new TaxonomySession(site);
                    TermStore termStore     = session.TermStores["Managed Metadata Service"];
                    Group group             = CreateGroup(termStore, "Navigation");
                    CreateNavigationTermSet(group, "Intranet");

                    TermSet s_termSet = group.TermSets["Intranet"];
                    CreateNavigationTerms(s_termSet);

                    CreateNavigationTermSet(group, "Team");
                    TermSet t_termSet = group.TermSets["Team"];

                    PinTermSet(s_termSet, t_termSet);
                    termStore.CommitAll();
                }



                using (SPSite site = new SPSite("http://" + sphost + "/sites/publicacion"))

                {
                    SetManagedNavigation(site, "Navigation", "Intranet");
                }
            });
        }
Exemplo n.º 17
0
        public static bool MakeTermSet(TermStore termstore, string _group, string _termset)
        {
            LogHelper logger = LogHelper.Instance;

            bool _result = false;

            try
            {
                SPSecurity.RunWithElevatedPrivileges(delegate()
                {
                    Guid termSetId = Guid.NewGuid();
                    Guid uidStore = GetIdTermStoreGroup(termstore, _group);
                    termstore.GetGroup(uidStore).CreateTermSet(_termset, termSetId, termstore.DefaultLanguage);
                    termstore.CommitAll();
                });

                _result = true;
                logger.Log(string.Format("Set Termini {0} creato nel Gruppo {1}", _termset, _group, LogSeverity.Debug));
            }
            catch (Exception ex)
            {
                _result = false;
                logger.Log(ex.Message + " : " + string.Format("Set Termini {0} non creato nel Gruppo {1}", _termset, _group, LogSeverity.Error));
            }
            return _result;            
        }
Exemplo n.º 18
0
        /// <summary>
        /// Creates child terms for the current model term if any exist
        /// </summary>
        /// <param name="web"></param>
        /// <param name="modelTerm"></param>
        /// <param name="term"></param>
        /// <param name="termStore"></param>
        /// <param name="parser"></param>
        /// <param name="scope"></param>
        /// <returns>Updated parser object</returns>
        private TokenParser CreateChildTerms(Web web, Model.Term modelTerm, Term term, TermStore termStore, TokenParser parser, PnPMonitoredScope scope)
        {
            if (modelTerm.Terms.Any())
            {
                foreach (var modelTermTerm in modelTerm.Terms)
                {
                    web.Context.Load(term.Terms);
                    web.Context.ExecuteQueryRetry();
                    var termTerms = term.Terms;
                    if (termTerms.Any())
                    {
                        var termTerm = termTerms.FirstOrDefault(t => t.Id == modelTermTerm.Id);
                        if (termTerm == null)
                        {
                            termTerm = termTerms.FirstOrDefault(t => t.Name == modelTermTerm.Name);
                            if (termTerm == null)
                            {
                                var returnTuple = CreateTerm <Term>(web, modelTermTerm, term, termStore, parser, scope);
                                if (returnTuple != null)
                                {
                                    modelTermTerm.Id = returnTuple.Item1;
                                    parser           = returnTuple.Item2;
                                }
                            }
                            else
                            {
                                modelTermTerm.Id = termTerm.Id;
                            }
                        }
                        else
                        {
                            modelTermTerm.Id = termTerm.Id;
                        }
                    }
                    else
                    {
                        var returnTuple = CreateTerm <Term>(web, modelTermTerm, term, termStore, parser, scope);
                        if (returnTuple != null)
                        {
                            modelTermTerm.Id = returnTuple.Item1;
                            parser           = returnTuple.Item2;
                        }
                    }
                }
                if (modelTerm.Terms.Any(t => t.CustomSortOrder > -1))
                {
                    var sortedTerms = modelTerm.Terms.OrderBy(t => t.CustomSortOrder);

                    var customSortString = sortedTerms.Aggregate(string.Empty, (a, i) => a + i.Id.ToString() + ":");
                    customSortString = customSortString.TrimEnd(new[] { ':' });

                    term.CustomSortOrder = customSortString;
                    termStore.CommitAll();
                }
            }

            return(parser);
        }
Exemplo n.º 19
0
        protected override void ExecuteCmdlet()
        {
            var taxonomySession = TaxonomySession.GetTaxonomySession(ClientContext);
            // Get Term Store
            TermStore termStore = null;

            if (TermStore == null)
            {
                termStore = taxonomySession.GetDefaultSiteCollectionTermStore();
            }
            else
            {
                termStore = TermStore.GetTermStore(taxonomySession);
            }

            var termGroup = TermGroup.GetGroup(termStore);

            if (Id == Guid.Empty)
            {
                Id = Guid.NewGuid();
            }
            var termSet = termGroup.CreateTermSet(Name, Id, Lcid);

            ClientContext.Load(termSet);
            ClientContext.ExecuteQueryRetry();

            termSet.Contact               = Contact;
            termSet.Description           = Description;
            termSet.IsOpenForTermCreation = IsOpenForTermCreation;

            var customProperties = CustomProperties ?? new Hashtable();

            foreach (var key in customProperties.Keys)
            {
                termSet.SetCustomProperty(key as string, customProperties[key] as string);
            }
            if (IsNotAvailableForTagging)
            {
                termSet.IsAvailableForTagging = false;
            }
            if (!string.IsNullOrEmpty(Owner))
            {
                termSet.Owner = Owner;
            }

            if (StakeHolders != null)
            {
                foreach (var stakeHolder in StakeHolders)
                {
                    termSet.AddStakeholder(stakeHolder);
                }
            }

            termStore.CommitAll();
            ClientContext.ExecuteQueryRetry();
            WriteObject(termSet);
        }
Exemplo n.º 20
0
        private static void AplicarOrdenVerdes(SPWeb web, Term term, string guid)
        {
            ResultTable resultTable = RealizarBusqueda(guid);
            int         contador    = 0;
            List <DocumentoSharePoint> primerOrden = OrdenarResultados(resultTable);

            foreach (DocumentoSharePoint doc in primerOrden)
            {
                contador++;
                Console.WriteLine(doc.Path + " " + contador + "/" + primerOrden.Count);
                SPListItem item = web.GetFile(doc.Path).Item;
                if (item.File.CheckOutType == SPFile.SPCheckOutType.None)
                {
                    TaxonomyField campo = (TaxonomyField)item.Fields.GetField(field);
                    int           orden = contador * 100;
                    Console.WriteLine(orden);
                    item[campoOrden] = orden;
                    AplicarTerminoVerdes(term, doc.Path, item, orden);
                }
                else
                {
                    logDesprotegidos.WriteLine("Documento Desprotegido: " + doc.Path);
                }
            }
            if (ramaVirgen)
            {
                var borrables = term.Terms.Select(g => new { Guid = g.Id, Path = g.GetPath() });
                foreach (var borrar in borrables)
                {
                    try
                    {
                        Console.WriteLine("Se borrá: " + borrar.Path);
                        logProceso.WriteLine("Se borrá: " + borrar.Path);
                        termStore.GetTerm(borrar.Guid).Delete();
                        termStore.CommitAll();
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine("Error borrando el siguiente término: " + borrar.Path + " " + ex.Message);
                        logProceso.WriteLine("Error borrando el siguiente término: " + borrar.Path + " " + ex.Message);
                    }
                }
            }
        }
Exemplo n.º 21
0
        private bool CreateStructureForTermSet(TermStore oStore, string termSetName, int lcid = 1045)
        {
            Group   oGroup = oStore.Groups[TermStoreGroupName];
            TermSet oTerms = oGroup.TermSets[termSetName];

            CreateOrUpdateTerms(oTerms, Data[termSetName], lcid);
            oStore.CommitAll();

            return(true);
        }
        public void Import(TaxonomySession ts)
        {
            if (ts == null)
            {
                throw new ArgumentNullException("ts", "The TaxonomySession object is null.");
            }

            XmlNodeList termStoreNodes = _xml.SelectNodes("//TermStore");

            if (termStoreNodes == null || termStoreNodes.Count == 0)
            {
                return;
            }

            var termStores = ts.TermStores;

            _ctx.Load(termStores);
            _ctx.ExecuteQuery();

            foreach (XmlElement termStoreElement in termStoreNodes)
            {
                TermStore termStore = null;
                if (termStoreNodes.Count == 1 && termStores.Count == 1)
                {
                    termStore = termStores[0];
                }
                else
                {
                    string termStoreName = termStoreElement.GetAttribute("Name");

                    termStore = ts.TermStores.GetByName(termStoreName);
                    _ctx.ExecuteQuery();
                    if (termStore == null || termStore.ServerObjectIsNull.Value)
                    {
                        _cmdlet.WriteWarning(string.Format("Unable to locate target Term Store: {0}", termStoreName));
                        continue;
                    }
                }
                LoadWorkingLanguage(termStore);
                _cmdlet.WriteVerbose(string.Format("Importing into Term Store: {0}", termStore.Name));

                XmlNodeList groupNodes = termStoreElement.SelectNodes("./Groups/Group");
                if (groupNodes == null || groupNodes.Count == 0)
                {
                    _cmdlet.WriteWarning("No Group elements were defined in the import file for the Term Store.");
                    continue;
                }
                foreach (XmlElement groupElement in groupNodes)
                {
                    Import(groupElement, termStore);
                }
                termStore.CommitAll();
                termStore.Context.ExecuteQuery();
            }
        }
Exemplo n.º 23
0
        protected override void ExecuteCmdlet()
        {
            var taxonomySession = TaxonomySession.GetTaxonomySession(ClientContext);
            // Get Term Store
            TermStore termStore = null;

            if (TermStore == null)
            {
                termStore = taxonomySession.GetDefaultSiteCollectionTermStore();
            }
            else
            {
                termStore = TermStore.GetTermStore(taxonomySession);
            }
            termStore.EnsureProperty(ts => ts.DefaultLanguage);

            TermGroup termGroup = TermGroup.GetGroup(termStore);

            TermSet termSet = TermSet.GetTermSet(termGroup);

            if (Id == Guid.Empty)
            {
                Id = Guid.NewGuid();
            }
            var termName = TaxonomyExtensions.NormalizeName(Name);

            if (!ParameterSpecified(nameof(Lcid)))
            {
                Lcid = termStore.EnsureProperty(ts => ts.DefaultLanguage);
            }

            var term = termSet.CreateTerm(termName, Lcid, Id);

            ClientContext.Load(term);
            ClientContext.ExecuteQueryRetry();
            term.SetDescription(Description, Lcid);

            var customProperties = CustomProperties ?? new Hashtable();

            foreach (var key in customProperties.Keys)
            {
                term.SetCustomProperty(key as string, customProperties[key] as string);
            }

            var localCustomProperties = LocalCustomProperties ?? new Hashtable();

            foreach (var key in localCustomProperties.Keys)
            {
                term.SetLocalCustomProperty(key as string, localCustomProperties[key] as string);
            }
            termStore.CommitAll();
            ClientContext.Load(term);
            ClientContext.ExecuteQueryRetry();
            WriteObject(term);
        }
Exemplo n.º 24
0
        protected override void ExecuteCmdlet()
        {
            var taxonomySession = TaxonomySession.GetTaxonomySession(ClientContext);

            TermStore termStore = null;

            if (TermStore == null)
            {
                termStore = taxonomySession.GetDefaultSiteCollectionTermStore();
            }
            else
            {
                termStore = TermStore.GetTermStore(taxonomySession);
            }


            termStore.EnsureProperty(ts => ts.Languages);

            Term term = null;

            if (ParameterSetName == ParameterSet_BYID)
            {
                term = Term.GetTerm(ClientContext, termStore, null, false, null);
            }
            else
            {
                var termGroup = TermGroup.GetGroup(termStore);
                var termSet   = TermSet.GetTermSet(termGroup);

                term = Term.GetTerm(ClientContext, termStore, termSet, false, null);
            }
            if (term != null)
            {
                term.EnsureProperties(t => t.Name, t => t.Id);
                if (ShouldProcess($"Delete label {Label} for language {Lcid} from Term {term.Name} with id {term.Id}"))
                {
                    var labels = term.GetAllLabels(Lcid);
                    ClientContext.Load(labels);
                    ClientContext.ExecuteQueryRetry();
                    var label = labels.FirstOrDefault(l => l.Value == Label);
                    if (label != null)
                    {
                        label.DeleteObject();
                        termStore.CommitAll();
                        ClientContext.ExecuteQueryRetry();
                    }
                    else
                    {
                        throw new PSArgumentException($"Label {Label} not found for language {Lcid}");
                    }
                }
            }
        }
Exemplo n.º 25
0
        private static void ProcessGroup(XmlNode termGroup)
        {
            if (termGroup != null)
            {
                string strGroupName = termGroup.Attributes["Name"].Value;

                //Get TermStore Groups
                GroupCollection groups = termStore.Groups;

                //Find group that we want to Import to
                Group thisGroup = groups.Where(g => g.Name == strGroupName).SingleOrDefault();

                //Check that group exist
                if (thisGroup != null)
                {
                    //Get Current group
                    group = termStore.GetGroup(thisGroup.Id);
                }
                else //If group doesn't exist, create it
                {
                    group = termStore.CreateGroup(strGroupName);
                    termStore.CommitAll();
                }
                Console.WriteLine(strGroupName);

                ProcessTermSet(termGroup);
            }
        }
Exemplo n.º 26
0
        public static void CriarItemNaTermStore(string url)
        {
            using (SPSite site = new SPSite(url))
            {
                TaxonomySession session = new TaxonomySession(site);

                TermStore termStore = session.TermStores["MMS"];


                Group group1 = termStore.CreateGroup("Links1");

                TermSet termSet1 = group1.CreateTermSet("TermSet1");

                Term term1 = termSet1.CreateTerm("Term1", 1033);

                Term term2 = termSet1.CreateTerm("Term2", 1033);

                Term term3 = termSet1.CreateTerm("Term3", 1033);

                Term term1a = term1.CreateTerm("Term1a", 1033);

                Term term1b = term1.CreateTerm("Term1b", 1033);

                termStore.CommitAll();

                term1.SetDescription("This is term1", 1033);

                term1.CreateLabel("TermOne", 1033, false);

                term1.CreateLabel("FirstTerm", 1033, false);

                termStore.CommitAll();


                term3.Delete();

                termStore.CommitAll();
            }
        }
Exemplo n.º 27
0
        // 4.	En el evento, en la activación de la feature, activar las etiquetas SEO.

        public override void FeatureActivated(SPFeatureReceiverProperties properties)
        {
            SPSite site = (SPSite)properties.Feature.Parent;

            using (SPWeb web = site.RootWeb)
            {
                // configure SEO properties for the home page (does not use Navigation Term SEO properites)
                SPListItem welcomePage = web.GetListItem(web.RootFolder.WelcomePage);
                // Aqui hay 3 Resources descritos en Resources.resx
                welcomePage["SeoBrowserTitle"]    = Resources.SeoBrowserTitle;
                welcomePage["SeoMetaDescription"] = Resources.SeoDescription;
                welcomePage["SeoKeywords"]        = Resources.SeoKeywords;
                welcomePage["SeoRobotsNoIndex"]   = false.ToString();
                welcomePage.SystemUpdate();

                // configure SEO propertie on all navigation terms associated with Welcome Pages

                TaxonomySession taxSession = new TaxonomySession(site, updateCache: true);
                TermStore       termStore  = taxSession.DefaultSiteCollectionTermStore;
                Group           termGroup  = termStore.GetSiteCollectionGroup(site, true);

                // locate the navigation term set for the site collection (there can be only one)
                foreach (TermSet termSet in termGroup.TermSets)
                {
                    NavigationTermSet navTermSet = NavigationTermSet.GetAsResolvedByWeb(termSet, site.RootWeb, StandardNavigationProviderNames.GlobalNavigationTaxonomyProvider);
                    if (navTermSet.IsNavigationTermSet)
                    {
                        // determine which navigation nodes are associated with Welcome Page content types
                        foreach (NavigationTerm navTerm in navTermSet.Terms)
                        {
                            string     pageUrl  = SPUtility.GetServerRelativeUrlFromPrefixedUrl(navTerm.TargetUrl.Value);
                            SPListItem pageItem = web.GetListItem(pageUrl);
                            if (pageItem.ContentType.Name == "Welcome Page")
                            {
                                // set the SEO properties on the Navigation Term (all will have same SEO tags)
                                Term term = termSet.GetTerm(navTerm.Id);
                                term.SetLocalCustomProperty("_Sys_Seo_PropBrowserTitle", Resources.SeoBrowserTitle);
                                term.SetLocalCustomProperty("_Sys_Seo_PropDescription", Resources.SeoDescription);
                                term.SetLocalCustomProperty("_Sys_Seo_PropKeywords", Resources.SeoKeywords);
                                term.SetLocalCustomProperty("_Sys_Seo_PropSiteNoIndex", false.ToString());
                            }
                        }

                        break;
                    }
                }

                termStore.CommitAll();
                web.Update();
            }
        }
Exemplo n.º 28
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;
            Group     group       = null;
            TermSet   termSet     = null;
            TermStore termStore   = null;
            SPSite    hostSite    = null;

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

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

                currentTerm = FindTermInTerm(h.HostTerm, definition);
            }
            else if (modelHost is TermSetModelHost)
            {
                var h = (modelHost as TermSetModelHost);

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

                currentTerm = FindTermInTermSet(h.HostTermSet, definition);
            }

            action(new TermModelHost
            {
                HostGroup     = group,
                HostTermSet   = termSet,
                HostTerm      = currentTerm,
                HostTermStore = termStore,
                HostSite      = hostSite
            });

            termStore.CommitAll();
        }
Exemplo n.º 29
0
        /// <summary>
        /// Create practice group terms
        /// </summary>
        /// <param name="TermsData">Practice group, SAOL and AOL data</param>
        /// <param name="clientContext">Client context object</param>
        private static void CreatePGTerms(List <CustomTermGroup> TermsData, ClientContext clientContext)
        {
            TaxonomySession taxonomySession = TaxonomySession.GetTaxonomySession(clientContext);

            clientContext.Load(taxonomySession.TermStores);

            //Execute the query to the server
            clientContext.ExecuteQuery();
            TermStore termStore = taxonomySession.GetDefaultSiteCollectionTermStore();

            clientContext.Load(termStore.Groups);

            //Execute the query to the server
            clientContext.ExecuteQuery();

            foreach (CustomTermGroup termGroup in TermsData)
            {
                TermGroup group   = termStore.Groups.Where(groupProperties => groupProperties.Name == termGroup.name).Count() > 0 ? termStore.Groups.GetByName(termGroup.name) : termStore.CreateGroup(termGroup.name, Guid.NewGuid());
                TermSet   pracGrp = group.CreateTermSet(ConfigurationManager.AppSettings["pgterm"], Guid.NewGuid(), 1033);
                foreach (CustomPracticeGroup pg in termGroup.Pg)
                {
                    if (!string.IsNullOrWhiteSpace(pg.name))
                    {
                        Console.WriteLine("Creating practice group " + pg.name);
                        Term pgTermSet = pracGrp.CreateTerm(pg.name, 1033, Guid.NewGuid());
                        if (pg.properties.ContainsKey("PGFolders") && !string.IsNullOrWhiteSpace(pg.properties["PGFolders"]))
                        {
                            pgTermSet.SetCustomProperty("FolderNames", pg.properties["PGFolders"]);
                        }
                        foreach (CustomAreaOfLaw aol in pg.Aol)
                        {
                            if (!string.IsNullOrWhiteSpace(aol.name))
                            {
                                Console.WriteLine("\tCreating area of law " + aol.name);
                                Term AOLTerm = pgTermSet.CreateTerm(aol.name, 1033, Guid.NewGuid());
                                if (aol.properties.ContainsKey("AOLFolders") && !string.IsNullOrWhiteSpace(aol.properties["AOLFolders"]))
                                {
                                    AOLTerm.SetCustomProperty("FolderNames", aol.properties["AOLFolders"]);
                                }
                                CustomArea(aol, AOLTerm);
                            }
                        }
                    }
                }
            }
            termStore.CommitAll();
            clientContext.Load(termStore);
            //Execute the query to the server
            clientContext.ExecuteQuery();
        }
        protected void Button1_Click(object sender, EventArgs e)
        {
            TaxonomySession session      = new TaxonomySession(SPContext.Current.Site);
            TermStore       termStore    = session.TermStores[0];
            Group           myGroup      = termStore.CreateGroup("Training");
            TermSet         topicTermSet = myGroup.CreateTermSet("Topics");

            string[] topics = new string[] { "CRM", "SharePoint", "End User", "Developer", "IT Administrator", "Introduction", "Advanced" };
            foreach (string topic in topics)
            {
                Term newTerm = topicTermSet.CreateTerm(topic, 1033);
            }
            termStore.CommitAll();
        }
        private void Import(XmlElement groupElement, TermStore parentTermStore)
        {
            string groupName = groupElement.GetAttribute("Name");
            Guid groupId = new Guid(groupElement.GetAttribute("Id"));
            LoadWorkingLanguage(parentTermStore);

            TermGroup group = null;
            ExceptionHandlingScope scope = new ExceptionHandlingScope(_ctx);
            using (scope.StartScope())
            {
                using (scope.StartTry())
                {
                    group = parentTermStore.Groups.GetByName(groupName);
                    _ctx.Load(group);
                }
                using (scope.StartCatch())
                {
                }
            }
            _ctx.ExecuteQuery();

            if (group == null || group.ServerObjectIsNull == null || group.ServerObjectIsNull.Value)
            {
                _cmdlet.WriteVerbose(string.Format("Creating Group: {0}", groupName));

                group = parentTermStore.CreateGroup(groupName, groupId);
                group.Description = groupElement.GetAttribute("Description");
                group.Context.ExecuteQuery();
                parentTermStore.CommitAll();
                parentTermStore.Context.ExecuteQuery();
            }
            XmlNodeList termSetNodes = groupElement.SelectNodes("./TermSets/TermSet");
            if (termSetNodes != null && termSetNodes.Count > 0)
            {
                foreach (XmlElement termSetElement in termSetNodes)
                {
                    Import(termSetElement, group);
                }
            }
        }
Exemplo n.º 32
0
        private void CreateTargetNewTermGroup(ClientContext sourceClientContext, ClientContext targetClientContext, TermGroup sourceTermGroup, TermStore targetTermStore)
        {
            try
            {
                this._destinationTermGroup = targetTermStore.CreateGroup(sourceTermGroup.Name, sourceTermGroup.Id);
                if(!string.IsNullOrEmpty(sourceTermGroup.Description))
                {
                    this._destinationTermGroup.Description = sourceTermGroup.Description;
                }
                TermOperation _op = new TermOperation();
                _op.Term = sourceTermGroup.Name;
                _op.Id = sourceTermGroup.Id.ToString();
                _op.Operation = "Add";
                _op.Type = "TermGroup";
                this._termStoreOperations.Add(_op);
     
                TermSetCollection _sourceTermSetCollection = sourceTermGroup.TermSets;
                if (_sourceTermSetCollection.Count > 0)
                {
                    foreach (TermSet _sourceTermSet in _sourceTermSetCollection)
                    {
                        sourceClientContext.Load(_sourceTermSet,
                                                  set => set.Name,
                                                  set => set.Description,
                                                  set => set.Id,
                                                  set => set.Terms.Include(
                                                            term => term.Name,
                                                            term => term.Id),
                                                            term => term.Description,
                                                            term => term.Contact);
                                                   

                        sourceClientContext.ExecuteQuery();
                        
                        TermSet _targetTermSet = _destinationTermGroup.CreateTermSet(_sourceTermSet.Name, _sourceTermSet.Id, targetTermStore.DefaultLanguage);
                        if(!string.IsNullOrEmpty(_sourceTermSet.Description))
                        {
                             _targetTermSet.Description = _sourceTermSet.Description;
                        }
                        foreach(Term _sourceTerm in _sourceTermSet.Terms)
                        {
                             Term _targetTerm = _targetTermSet.CreateTerm(_sourceTerm.Name, targetTermStore.DefaultLanguage, _sourceTerm.Id);
                             _op = new TermOperation();
                             _op.Term = _sourceTerm.Name;
                             _op.Id = _sourceTerm.Id.ToString();
                             _op.Operation = "Add";
                             _op.Type = "Term";
                             this._termStoreOperations.Add(_op);
                        }
                    }

                }
                try
                {
                    targetClientContext.ExecuteQuery();
                    targetTermStore.CommitAll();
                }
                catch
                {
                    throw;
                }
               
            }
            catch
            {
                throw;
            }
        }
        private void Import(XmlElement groupElement, TermStore parentTermStore)
        {
            string groupName = groupElement.GetAttribute("Name");
            Group group = null;
            if (bool.Parse(groupElement.GetAttribute("IsSiteCollectionGroup")))
            {
                XmlNodeList siteCollectionIdNodes = groupElement.SelectNodes("./SiteCollectionAccessIds/SiteCollectionAccessId");
                if (siteCollectionIdNodes != null)
                {
                    foreach (XmlElement siteCollectionIdElement in siteCollectionIdNodes)
                    {
                        SPSite site = null;
                        if (!string.IsNullOrEmpty(siteCollectionIdElement.GetAttribute("Url")))
                        {
                            try
                            {
                                site = new SPSite(siteCollectionIdElement.GetAttribute("Url"));
                            }
                            catch
                            {
                                Logger.WriteWarning("Unable to locate a Site Collection at {0}", siteCollectionIdElement.GetAttribute("Url"));
                            }
                        }
                        else
                        {
                            try
                            {
                                site = new SPSite(new Guid(siteCollectionIdElement.GetAttribute("Id")));
                            }
                            catch
                            {
                                Logger.WriteWarning("Unable to locate a Site Collection with ID {0}", siteCollectionIdElement.GetAttribute("Id"));
                            }
                        }
                        if (site != null)
                        {
                            try
                            {
                                if (group == null)
                                {
                                    group = parentTermStore.GetSiteCollectionGroup(site);
                                }
                                if (group != null && group.IsSiteCollectionGroup)
                                {
                                    group.AddSiteCollectionAccess(site.ID);
                                }
                            }
                            catch (MissingMethodException)
                            {
                                Logger.WriteWarning("Unable to retrieve or add Site Collection group. SharePoint 2010 Service Pack 1 or greater is required. ID={0}, Url={1}", siteCollectionIdElement.GetAttribute("Id"), siteCollectionIdElement.GetAttribute("Url"));
                            }
                            finally
                            {
                                site.Dispose();
                            }
                        }
                    }
                }
            }
            try
            {
                if (group == null)
                    group = parentTermStore.Groups[groupName];
            }
            catch (ArgumentException) {}

            if (group == null)
            {
                Logger.Write("Creating Group: {0}", groupName);
            #if SP2010
                group = parentTermStore.CreateGroup(groupName);
            #else
                // Updated provided by John Calvert
                if (!string.IsNullOrEmpty(groupElement.GetAttribute("Id")))
                {
                    Guid id = new Guid(groupElement.GetAttribute("Id"));
                    group = parentTermStore.CreateGroup(groupName, id);
                }
                else
                    group = parentTermStore.CreateGroup(groupName);
                // End update
            #endif
                group.Description = groupElement.GetAttribute("Description");
            }
            parentTermStore.CommitAll();//TEST

            XmlNodeList termSetNodes = groupElement.SelectNodes("./TermSets/TermSet");
            if (termSetNodes != null && termSetNodes.Count > 0)
            {
                foreach (XmlElement termSetElement in termSetNodes)
                {
                    Import(termSetElement, group);
                }
            }
        }
        public void Import(TermStore parentTermStore)
        {
            if (parentTermStore == null)
                throw new ArgumentNullException("parentTermStore", "The parent TermStore object is null.");

            if (_xml.DocumentElement.Name == "Groups")
            {
                XmlNodeList groupNodes = _xml.SelectNodes("./Groups/Group");
                if (groupNodes == null || groupNodes.Count == 0)
                    return;

                foreach (XmlElement groupElement in groupNodes)
                {
                    Import(groupElement, parentTermStore);
                }
            }
            else if (_xml.DocumentElement.Name == "Group")
            {
                Import(_xml.DocumentElement, parentTermStore);
            }
            parentTermStore.CommitAll();
        }
Exemplo n.º 35
0
        private static void ImportTerms(string filePath, string urlSPSite)
        {
            using (SPSite site = new SPSite(urlSPSite))
            {
                // function that return termstore from site.
                termStore = termstorefromWebApp(site);

                XmlDocument doc = new XmlDocument();
                doc.Load(filePath);
                XmlNode termGroup = doc.SelectSingleNode("/Groups/Group");
                ProcessGroup(termGroup);
                termStore.CommitAll();
            }
        }
        public void Import(TermStore parentTermStore)
        {
            if (parentTermStore == null || parentTermStore.ServerObjectIsNull.Value)
                throw new ArgumentNullException("parentTermStore", "The parent TermStore object is null.");

            LoadWorkingLanguage(parentTermStore);
            if (_xml.DocumentElement.Name == "Groups")
            {
                XmlNodeList groupNodes = _xml.SelectNodes("./Groups/Group");
                if (groupNodes == null || groupNodes.Count == 0)
                    return;

                foreach (XmlElement groupElement in groupNodes)
                {
                    Import(groupElement, parentTermStore);
                }
            }
            else if (_xml.DocumentElement.Name == "Group")
            {
                Import(_xml.DocumentElement, parentTermStore);
            }
            parentTermStore.CommitAll();
            parentTermStore.Context.ExecuteQuery();
        }
Exemplo n.º 37
0
        private void DeleteGroupIfExists(TermStore defaultSiteCollectionTermStore, Guid testGroupId)
        {
            Group existingTestGroup = defaultSiteCollectionTermStore.GetGroup(testGroupId);
            if (existingTestGroup != null)
            {
                foreach (var termSet in existingTestGroup.TermSets)
                {
                    termSet.Delete();
                }

                existingTestGroup.Delete();
                defaultSiteCollectionTermStore.CommitAll();
            }
        }
Exemplo n.º 38
0
        private void DeleteTermGroupsImplementation(ClientContext cc, TermStore termStore)
        {
            cc.Load(termStore.Groups, p => p.Include(t => t.Name, t => t.TermSets.Include(s => s.Name, s => s.Terms.Include(q => q.IsDeprecated, q => q.ReusedTerms))));
            cc.ExecuteQueryRetry();

            foreach (var termGroup in termStore.Groups.ToList())
            {
                DeleteTermGroupImplementation(cc, termGroup);
            }

            var siteCollectionGroup = termStore.GetSiteCollectionGroup(cc.Site, true);
            cc.Load(siteCollectionGroup, t => t.Name, t => t.TermSets.Include(s => s.Name, s => s.Terms.Include(q => q.IsDeprecated, q => q.ReusedTerms)));
            cc.ExecuteQueryRetry();
            DeleteTermGroupImplementation(cc, siteCollectionGroup, true);

            termStore.CommitAll();
            termStore.UpdateCache();
            cc.ExecuteQueryRetry();
        }
Exemplo n.º 39
0
        private static void AddLanguages(ClientContext clientContext, TermStore termStore)
        {
            clientContext.Load(clientContext.Web, w => w.ServerRelativeUrl);
            clientContext.Load(termStore, ts => ts.Languages);
            clientContext.ExecuteQuery();

            var languages = new int[] { 1031, 1033, 1036, 1053 };
            Array.ForEach(languages, l =>
            {
                if (!termStore.Languages.Contains(l))
                    termStore.AddLanguage(l);
            });

            termStore.CommitAll();
            clientContext.ExecuteQuery();
        }
        private TermSet CreateTermSet(TermStore termStore, Guid termSetID, SPWeb currentWeb, TermStoreType tsType)
        {
            //termSet is null. Create new termSet, and set the property in the property bag.
            Group siteCollectionGroup = termStore.GetSiteCollectionGroup(currentWeb.Site);
            //Group navTermsGroup = termStore.Groups["Navigation"]; //TODO: Get this from configuration or passed in.

            string termStoreName = (tsType == TermStoreType.Global) ? string.Format("Global_Nav_For{0}", termSetID) : string.Format("Local_Nav_For{0}", termSetID);
            TermSet newTermSet = siteCollectionGroup.CreateTermSet(termStoreName, termSetID);

            NavigationTermSet navTermSet = NavigationTermSet.GetAsResolvedByWeb(newTermSet, currentWeb, StandardNavigationProviderNames.GlobalNavigationTaxonomyProvider);

            navTermSet.IsNavigationTermSet = true;
            navTermSet.TargetUrlForChildTerms.Value = "~site/SitePages/Home.aspx";

            uint langID = (uint) currentWeb.Locale.LCID;

            string webTemplateID = Convert.ToString(currentWeb.Site.RootWeb.AllProperties["MARTA.WebTemplateID"]);
            string termStoreType = (tsType == TermStoreType.Global) ? "Global" : "Local";
            string termMap = SPUtility.GetLocalizedString(string.Format("$Resources:MARTANavigation,{0}_{1}", webTemplateID, termStoreType) , "MARTANavigation", langID);
            string relativeURL = currentWeb.Site.ServerRelativeUrl;

            BuildNavTerms(navTermSet, termMap, relativeURL);

            termStore.CommitAll();

            return newTermSet;
            //Add this to the property bag of the web as well.
        }