private static NavigationTermSet GetEditableNavigationTermSetByProviderName(
            Web web, ClientRuntimeContext context, String providerName)
        {
            // Get the current taxonomy session and update cache, just in case
            TaxonomySession taxonomySession = TaxonomySession.GetTaxonomySession(web.Context);

            taxonomySession.UpdateCache();

            context.ExecuteQueryRetry();

            // Retrieve the Navigation TermSet for the current web
            NavigationTermSet navigationTermSet = TaxonomyNavigation.GetTermSetForWeb(web.Context,
                                                                                      web, providerName, true);

            context.Load(navigationTermSet);
            context.ExecuteQueryRetry();

            // Retrieve an editable TermSet for the current target navigation
            NavigationTermSet editableNavigationTermSet = navigationTermSet.GetAsEditable(taxonomySession);

            context.Load(editableNavigationTermSet);
            context.ExecuteQueryRetry();

            return(editableNavigationTermSet);
        }
Example #2
0
        static void Main(string[] args)
        {
            Log("\r\nTermSetSync (Client OM): Starting...\r\n");

            // Uncomment this section to create a sample input file.
#if false
            GenerateExampleXmlFile();
#else
            TermSetGoal termSetGoal = LoadTermSetGoal();

            Program.clientContext = new ClientContext(siteUrl);

            TaxonomySession taxonomySession = TaxonomySession.GetTaxonomySession(Program.clientContext);
            taxonomySession.UpdateCache();
            TermStore termStore = taxonomySession.GetDefaultSiteCollectionTermStore();

            TermSet termSet = CreateTermSetAndGroup(termStore, termSetGoal);
            SyncTermSet(termSet, termSetGoal);
#endif

            Log("\r\nThe operation completed successfully.");

            if (Debugger.IsAttached)
            {
                Debugger.Break();
            }
        }
Example #3
0
    public static SiteCollectionModel GetSiteCollectionModel(string url)
    {
        SiteCollectionModel model = new SiteCollectionModel();

        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();
                model.Url = siteCollection.Url;

                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, false);
                clientContext.ExecuteQuery();
                bool siteCollectionHasPrivateGroup = CSOMObjectExists(group);
                model.hasPrivateGroup = siteCollectionHasPrivateGroup;
                model.Termsets        = new Dictionary <Guid, TermsetModel>();
                if (siteCollectionHasPrivateGroup)
                {
                    clientContext.Load(group, g => g.Id, g => g.Name, g => g.TermSets);
                    clientContext.ExecuteQuery();
                    model.GroupId   = group.Id;
                    model.GroupName = group.Name;
                    foreach (var ts in group.TermSets)
                    {
                        TermsetModel termset = new TermsetModel {
                            TermsetId = ts.Id, DisplayName = ts.Name
                        };
                        clientContext.Load(ts.Terms);
                        clientContext.ExecuteQuery();
                        List <TermModel> terms = new List <TermModel>();
                        foreach (Term term in ts.Terms)
                        {
                            TermModel newTerm = new TermModel {
                                TermName = term.Name, TermId = term.Id
                            };
                            LoadChildTerms(term, newTerm, clientContext);
                            terms.Add(newTerm);
                        }
                        termset.TopLevelTerms = terms;
                        model.Termsets.Add(ts.Id, termset);
                    }
                }
            }
            return(model);
        }
    }
Example #4
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();
            }
        }
    }
Example #5
0
        public TermStore GetTermStore(ClientContext context)
        {
            TaxonomySession taxonomySession = TaxonomySession.GetTaxonomySession(context);

            taxonomySession.UpdateCache();
            context.Load(taxonomySession);
            context.ExecuteQuery();

            TermStore termStore = taxonomySession.GetDefaultSiteCollectionTermStore();

            context.Load(termStore, x => x.Groups, x => x.Id, x => x.DefaultLanguage);
            context.ExecuteQuery();

            return(termStore);
        }
Example #6
0
        // Retrieved target xml data is not matching with source xml navigation types so changing navigation settings to get correct data.
        public void ChangeNavigationSettings(ClientContext cc, StandardNavigationSource gSource, StandardNavigationSource cSource)
        {
            TaxonomySession taxonomySession = TaxonomySession.GetTaxonomySession(cc);

            taxonomySession.UpdateCache();
            cc.Load(taxonomySession, ts => ts.TermStores);
            cc.ExecuteQueryRetry();

            var navigationSettings = new WebNavigationSettings(cc, cc.Web);

            navigationSettings.GlobalNavigation.Source  = gSource;
            navigationSettings.CurrentNavigation.Source = cSource;
            navigationSettings.Update(taxonomySession);

            try
            {
                cc.ExecuteQueryRetry();
            }
            catch (Exception) // if termset not found then set newly created termset to managed navigation
            {
                TermStore termStore = taxonomySession.GetDefaultSiteCollectionTermStore();
                Microsoft.SharePoint.Client.Taxonomy.TermGroup group   = termStore.GetTermGroupByName("TG_1"); // TG_1 is a term group mentioned in navigation_add_1605.xml
                Microsoft.SharePoint.Client.Taxonomy.TermSet   termset = group.TermSets.GetByName("TS_1_1");   // TS_1_1 is a term set mentioned in navigation_add_1605.xml
                cc.Load(termStore);
                cc.Load(group, g => g.TermSets);
                cc.Load(termset);
                cc.ExecuteQuery();

                if (StandardNavigationSource.TaxonomyProvider == gSource)
                {
                    navigationSettings.GlobalNavigation.TermStoreId = termStore.Id;
                    navigationSettings.GlobalNavigation.TermSetId   = termset.Id;
                }

                if (StandardNavigationSource.TaxonomyProvider == cSource)
                {
                    navigationSettings.CurrentNavigation.TermStoreId = termStore.Id;
                    navigationSettings.CurrentNavigation.TermSetId   = termset.Id;
                }

                navigationSettings.GlobalNavigation.Source  = gSource;
                navigationSettings.CurrentNavigation.Source = cSource;
                navigationSettings.Update(taxonomySession);
                cc.ExecuteQueryRetry();
            }
        }
Example #7
0
        public TermStore GetTermStore()
        {
            TaxonomySession taxonomySession = TaxonomySession.GetTaxonomySession(Ctx);

            taxonomySession.UpdateCache();
            TermStore termStore = taxonomySession.GetDefaultSiteCollectionTermStore();

            Ctx.Load(termStore,
                     termStoreArg => termStoreArg.WorkingLanguage,
                     termStoreArg => termStoreArg.Id,
                     termStoreArg => termStoreArg.Groups.Include(
                         groupArg => groupArg.Id,
                         groupArg => groupArg.Name
                         )
                     );
            Ctx.ExecuteQuery();
            return(termStore);
        }
Example #8
0
        static TermGroup GetSiteCollectionTermGroup(ClientContext clientContext, Site siteCollection)
        {
            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 termGroup        = termStore.GetSiteCollectionGroup(siteCollection, true);

            clientContext.Load(termGroup);
            clientContext.Load(termGroup.TermSets);
            clientContext.ExecuteQuery();
            return(termGroup);
        }
Example #9
0
    public static void CreatePrivateGroup()
    {
        var aspnetHttpContext = System.Web.HttpContext.Current;
        var spContext         = SharePointContextProvider.Current.GetSharePointContext(aspnetHttpContext);

        using (var clientContext = spContext.CreateUserClientContextForSPHost()) {
            if (clientContext != null)
            {
                Site            siteCollection  = clientContext.Site;
                TaxonomySession taxonomySession = TaxonomySession.GetTaxonomySession(clientContext);
                taxonomySession.UpdateCache();
                clientContext.Load(taxonomySession, ts => ts.TermStores);
                clientContext.ExecuteQuery();
                TermStore termStore = taxonomySession.TermStores.FirstOrDefault <TermStore>();
                TermGroup group     = termStore.GetSiteCollectionGroup(siteCollection, true);
                clientContext.ExecuteQuery();
            }
        }
    }
Example #10
0
        public override void ItemAdded(SPItemEventProperties properties)
        {
            base.ItemAdded(properties);
            try
            {
                SPSecurity.RunWithElevatedPrivileges(delegate()
                {
                    SPWeb myWeb = properties.Web;

                    if (properties.ListTitle == "SectionDetails")
                    {
                        #region "Create Termstore Set For Friendly URL"

                        TaxonomySession taxonomySession = new TaxonomySession(myWeb.Site);
                        taxonomySession.UpdateCache();
                        TermStore termStore       = taxonomySession.DefaultSiteCollectionTermStore;
                        Group siteCollectionGroup = termStore.GetSiteCollectionGroup(myWeb.Site, createIfMissing: true);
                        TermSet ts = siteCollectionGroup.TermSets.Where(p => p.Name.ToLower() == "lappia education").FirstOrDefault();
                        if (ts != null)//check term set is exist or not
                        {
                            NavigationTermSet navigationTermSet   = NavigationTermSet.GetAsResolvedByWeb(ts, myWeb, StandardNavigationProviderNames.GlobalNavigationTaxonomyProvider);
                            navigationTermSet.IsNavigationTermSet = true;

                            NavigationTerm subterm = navigationTermSet.CreateTerm(Convert.ToString(properties.ListItem["Title"].ToString()) + ".aspx", NavigationLinkType.FriendlyUrl, Guid.NewGuid());
                            if ((uint)System.Globalization.CultureInfo.CurrentUICulture.LCID == 1033)
                            {
                                subterm.TargetUrl.Value = SPContext.Current.Web.Url + "/Pages/" + Convert.ToString(properties.ListItem["Title"].ToString()) + ".aspx";
                            }
                            else if ((uint)System.Globalization.CultureInfo.CurrentUICulture.LCID == 1035)
                            {
                                subterm.TargetUrl.Value = SPContext.Current.Web.Url + "/Pages/" + Convert.ToString(properties.ListItem["Title"].ToString()) + ".aspx";
                            }
                        }
                        termStore.CommitAll();
                        #endregion
                    }
                });
            }
            catch (Exception ex)
            {
            }
        }
Example #11
0
        public static string SetReference(ClientContext ctx, TaxonomyFieldValueCollection tax, TaxonomyFieldValue typeDoc, int Id)
        {
            TaxonomySession taxonomySession = TaxonomySession.GetTaxonomySession(ctx);

            taxonomySession.UpdateCache();
            TermStore termStore = taxonomySession.GetDefaultSiteCollectionTermStore();

            ctx.Load(termStore,
                     termStoreArg => termStoreArg.WorkingLanguage,
                     termStoreArg => termStoreArg.Id,
                     termStoreArg => termStoreArg.Groups.Include(
                         groupArg => groupArg.Id,
                         groupArg => groupArg.Name
                         )
                     );
            Guid    catTermId  = new Guid(tax.ElementAt(0).TermGuid);
            TermSet catTermSet = termStore.GetTermSet(new Guid("6792f6c1-20ec-4e10-a1e8-a2c04f2906ec"));
            Term    catTerm    = catTermSet.GetTerm(catTermId);

            ctx.Load(catTermSet);
            ctx.Load(catTerm);
            ctx.Load(catTerm.Labels);
            // ctx.Load(catTerm.Parent.Labels);
            Guid    docTermId  = new Guid(typeDoc.TermGuid);
            TermSet docTermSet = termStore.GetTermSet(new Guid("40ae95fa-353f-4154-a574-65f7297286ca"));
            Term    docTerm    = docTermSet.GetTerm(docTermId);

            ctx.Load(docTermSet);
            ctx.Load(docTerm);
            ctx.Load(docTerm.Labels);
            ctx.ExecuteQuery();
            string reference = catTerm.Labels[1].Value + "/" + docTerm.Labels[1].Value + "/" + Id;

            //if(catTerm.Parent.Labels.Count > 1)
            //{
            //   reference = catTerm.Parent.Labels[1].Value + "/" + catTerm.Labels[1].Value + "/" + docTerm.Labels[1].Value + "/" + Id;
            //}
            return(reference);
        }
        static Dictionary <string, TermSetLookup> GetTermSetsByInternalName(List <TaxonomyField> taxonomyFields)
        {
            Dictionary <string, TermSetLookup> termSetsByInternalName
                = new Dictionary <string, TermSetLookup>(StringComparer.OrdinalIgnoreCase);

            TaxonomySession taxonomySession = TaxonomySession.GetTaxonomySession(Program.clientContext);

            taxonomySession.UpdateCache();

            foreach (TaxonomyField field in taxonomyFields)
            {
                TermStore termStore = taxonomySession.TermStores.GetById(field.SspId);
                TermSet   termSet   = termStore.GetTermSet(field.TermSetId);
                termSetsByInternalName.Add(field.InternalName, new TermSetLookup(field, termSet));
            }

            Program.clientContext.ExecuteQuery();
            foreach (TermSetLookup termSetLookup in termSetsByInternalName.Values)
            {
                termSetLookup.LoadResults();
            }
            return(termSetsByInternalName);
        }
Example #13
0
        static void Main(string[] args)
        {
            string siteUrl = GetSite();

            /* Prompt for Credentials */
            Console.WriteLine("Enter Credentials for {0}", siteUrl);

            string       userName = GetUserName();
            SecureString pwd      = GetPassword();

            /* End Program if no Credentials */
            if (string.IsNullOrEmpty(userName) || (pwd == null))
            {
                return;
            }

            ClientContext cc = new ClientContext(siteUrl);

            cc.AuthenticationMode = ClientAuthenticationMode.Default;
            //For SharePoint Online
            cc.Credentials = new SharePointOnlineCredentials(userName, pwd);
            //For SharePoint Online Dedicated or On-Prem
            //cc.Credentials = new NetworkCredential(userName, pwd);


            try
            {
                Console.WriteLine("Connecting to the site using credentials provided...");
                // Let's ensure that the connectivity works.
                Web web = cc.Web;
                cc.Load(web);
                cc.ExecuteQuery();

                Console.WriteLine("Connecting to the taxonomy store...");
                //Let's connect to the Taxonomy Session. The hierarchy for connection is Taxonomy Session --> Term Store --> Term Group --> Term Set --> Terms
                TaxonomySession taxonomySession = TaxonomySession.GetTaxonomySession(cc);
                taxonomySession.UpdateCache();
                cc.Load(taxonomySession.TermStores);
                cc.ExecuteQuery();

                Console.WriteLine("Starting to create the taxonomy..");

                CreateTaxonomyNavigation(cc, taxonomySession);

                Console.WriteLine("Taxonomy created. Reading the taxonomy...");

                GetMMSTermsFromCloud(cc);

                Console.WriteLine("Taxonomy Operations completed successfully.");
                Console.WriteLine("Press any key to exit the application now......");
                Console.Read();
            }
            catch (Exception ex)
            {
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine(string.Format("Exception!"), ex.ToString());
                Console.WriteLine("Press any key to continue.");
                Console.Read();
                throw;
            }
        }
Example #14
0
        internal static List <ReusedTerm> ProcessGroup(ClientContext context, TaxonomySession session, TermStore termStore, Model.TermGroup modelTermGroup, TermGroup siteCollectionTermGroup, TokenParser parser, PnPMonitoredScope scope)
        {
            List <ReusedTerm> reusedTerms = new List <ReusedTerm>();

            SiteCollectionTermGroupNameToken siteCollectionTermGroupNameToken =
                new SiteCollectionTermGroupNameToken(context.Web);

            #region Group

            var newGroup = false;

            var modelGroupName = parser.ParseString(modelTermGroup.Name);

            var normalizedGroupName = TaxonomyItem.NormalizeName(context, modelGroupName);
            context.ExecuteQueryRetry();

            TermGroup group = termStore.Groups.FirstOrDefault(
                g => g.Id == modelTermGroup.Id || g.Name == normalizedGroupName.Value);
            if (group == null)
            {
                var parsedDescription = parser.ParseString(modelTermGroup.Description);

                if (modelTermGroup.Name == "Site Collection" ||
                    modelGroupName == siteCollectionTermGroupNameToken.GetReplaceValue() ||
                    modelTermGroup.SiteCollectionTermGroup)
                {
                    var site = (context as ClientContext).Site;
                    group = termStore.GetSiteCollectionGroup(site, true);
                    context.Load(group, g => g.Name, g => g.Id, g => g.TermSets.Include(
                                     tset => tset.Name,
                                     tset => tset.Id));
                    context.ExecuteQueryRetry();
                }
                else
                {
                    group = termStore.Groups.FirstOrDefault(g => g.Name == normalizedGroupName.Value);

                    if (group == null)
                    {
                        if (modelTermGroup.Id == Guid.Empty)
                        {
                            modelTermGroup.Id = Guid.NewGuid();
                        }
                        group = termStore.CreateGroup(modelGroupName, modelTermGroup.Id);

                        group.Description = parsedDescription;

                        // Handle TermGroup Contributors, if any
                        if (modelTermGroup.Contributors != null && modelTermGroup.Contributors.Count > 0)
                        {
                            foreach (var c in modelTermGroup.Contributors)
                            {
                                group.AddContributor(c.Name);
                            }
                        }

                        // Handle TermGroup Managers, if any
                        if (modelTermGroup.Managers != null && modelTermGroup.Managers.Count > 0)
                        {
                            foreach (var m in modelTermGroup.Managers)
                            {
                                group.AddGroupManager(m.Name);
                            }
                        }

                        termStore.CommitAll();
                        context.Load(group);
                        context.Load(termStore);
                        context.ExecuteQueryRetry();

                        newGroup = true;
                    }
                }
            }
            #endregion

            session.UpdateCache();
            session.Context.ExecuteQueryRetry();
            #region TermSets

            foreach (var modelTermSet in modelTermGroup.TermSets)
            {
                TermSet set        = null;
                var     newTermSet = false;

                var normalizedTermSetName = TaxonomyItem.NormalizeName(context, parser.ParseString(modelTermSet.Name));
                context.ExecuteQueryRetry();
                if (!newGroup)
                {
                    set =
                        group.TermSets.FirstOrDefault(
                            ts => ts.Id == modelTermSet.Id || ts.Name == normalizedTermSetName.Value);
                }
                if (set == null)
                {
                    if (modelTermSet.Id == Guid.Empty)
                    {
                        modelTermSet.Id = Guid.NewGuid();
                    }
                    else
                    {
                        if (CheckIfTermSetIdIsUnique(termStore, modelTermSet.Id) == false)
                        {
                            throw new Exception($"Termset ID {modelTermSet.Id} is already present in termstore");
                        }
                    }
                    var termSetLanguage = modelTermSet.Language.HasValue ? modelTermSet.Language.Value : termStore.DefaultLanguage;
                    set = group.CreateTermSet(normalizedTermSetName.Value, modelTermSet.Id, termSetLanguage);
                    parser.AddToken(new TermSetIdToken(context.Web, group.Name, normalizedTermSetName.Value, modelTermSet.Id));
                    if (siteCollectionTermGroup != null && !siteCollectionTermGroup.ServerObjectIsNull.Value)
                    {
                        if (group.Name == siteCollectionTermGroup.Name)
                        {
                            parser.AddToken((new SiteCollectionTermSetIdToken(context.Web, normalizedTermSetName.Value, modelTermSet.Id)));
                        }
                    }
                    newTermSet = true;
                    if (!string.IsNullOrEmpty(modelTermSet.Description))
                    {
                        set.Description = parser.ParseString(modelTermSet.Description);
                    }
                    set.IsOpenForTermCreation = modelTermSet.IsOpenForTermCreation;
                    set.IsAvailableForTagging = modelTermSet.IsAvailableForTagging;
                    foreach (var property in modelTermSet.Properties)
                    {
                        set.SetCustomProperty(property.Key, parser.ParseString(property.Value));
                    }
                    if (modelTermSet.Owner != null)
                    {
                        set.Owner = parser.ParseString(modelTermSet.Owner);
                    }
                    termStore.CommitAll();
                    context.Load(set);
                    context.ExecuteQueryRetry();
                }

                context.Load(set, s => s.Terms.Include(t => t.Id, t => t.Name));
                context.ExecuteQueryRetry();
                var terms = set.Terms;

                foreach (var modelTerm in modelTermSet.Terms)
                {
                    if (!newTermSet)
                    {
                        if (terms.Any())
                        {
                            var term = terms.FirstOrDefault(t => t.Id == modelTerm.Id);
                            if (term == null)
                            {
                                var normalizedTermName = TaxonomyItem.NormalizeName(context, parser.ParseString(modelTerm.Name));
                                context.ExecuteQueryRetry();

                                term = terms.FirstOrDefault(t => t.Name == normalizedTermName.Value);
                                if (term == null)
                                {
                                    var returnTuple = CreateTerm(context, modelTerm, set, termStore, parser, scope);
                                    if (returnTuple != null)
                                    {
                                        modelTerm.Id = returnTuple.Item1;
                                        parser       = returnTuple.Item2;
                                    }
                                    reusedTerms.AddRange(returnTuple.Item3);
                                }
                                else
                                {
                                    // todo: add handling for reused term?
                                    modelTerm.Id = term.Id;
                                }
                            }
                            else
                            {
                                // todo: add handling for reused term?
                                modelTerm.Id = term.Id;
                            }

                            if (term != null)
                            {
                                CheckChildTerms(context, modelTerm, term, termStore, parser, scope);
                            }
                        }
                        else
                        {
                            var returnTuple = CreateTerm(context, modelTerm, set, termStore, parser, scope);
                            if (returnTuple != null)
                            {
                                modelTerm.Id = returnTuple.Item1;
                                parser       = returnTuple.Item2;
                            }
                            reusedTerms.AddRange(returnTuple.Item3);
                        }
                    }
                    else
                    {
                        var returnTuple = CreateTerm(context, modelTerm, set, termStore, parser, scope);
                        if (returnTuple != null)
                        {
                            modelTerm.Id = returnTuple.Item1;
                            parser       = returnTuple.Item2;
                        }
                        reusedTerms.AddRange(returnTuple.Item3);
                    }
                }

                // do we need custom sorting?
                if (modelTermSet.Terms.Any(t => t.CustomSortOrder > 0))
                {
                    var sortedTerms = modelTermSet.Terms.OrderBy(t => t.CustomSortOrder);

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

                    set.CustomSortOrder = customSortString;
                    termStore.CommitAll();
                    context.ExecuteQueryRetry();
                }
            }

            #endregion

            return(reusedTerms);
        }
Example #15
0
    public static void CreateCustomerGeographyTermset()
    {
        string termSetName       = "Customer Geography";
        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);

                Term term1 = tset.CreateTerm("Northern Sales Territory", 1033, Guid.NewGuid());
                term1.CreateTerm("New York", 1033, Guid.NewGuid());
                term1.CreateTerm("New Jersey", 1033, Guid.NewGuid());
                term1.CreateTerm("Connecticut", 1033, Guid.NewGuid());

                Term term2 = tset.CreateTerm("Southern Sales Territory", 1033, Guid.NewGuid());
                term2.CreateTerm("Georgia", 1033, Guid.NewGuid());
                term2.CreateTerm("Alalabama", 1033, Guid.NewGuid());
                Term florida = term2.CreateTerm("Florida", 1033, Guid.NewGuid());
                florida.CreateTerm("Jacksonville", 1033, Guid.NewGuid());
                florida.CreateTerm("Tampa", 1033, Guid.NewGuid());
                florida.CreateTerm("Miami", 1033, Guid.NewGuid());
                florida.CreateTerm("Key West", 1033, Guid.NewGuid());


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

                clientContext.ExecuteQuery();
                termStore.CommitAll();
            }
        }
    }
Example #16
0
        public static void RePin()
        {
            Guid termSetGUID       = new Guid("7ab9e8b0-e1e1-4a7c-9b20-d6c5030103df");
            Guid srcTermSetGUID    = new Guid("4d8916d8-e226-45f6-83bd-9f2b134cc264");
            Guid srcDepartmentGUID = new Guid("eea07c73-7e2b-418d-96ff-1a2cdb4eb25c");

            string        siteUrl       = "http://win-f33ohjutmmi/sites/cms";
            ClientContext clientContext = new ClientContext(siteUrl);

            TaxonomySession taxonomySession = TaxonomySession.GetTaxonomySession(clientContext);

            taxonomySession.UpdateCache();

            clientContext.Load(taxonomySession, ts => ts.TermStores);
            clientContext.ExecuteQuery();

            if (taxonomySession.TermStores.Count == 0)
            {
                throw new InvalidOperationException("The Taxonomy Service is offline or missing");
            }

            TermStore termStore = taxonomySession.TermStores[0];

            clientContext.Load(termStore,
                               ts => ts.Name,
                               ts => ts.WorkingLanguage);
            clientContext.ExecuteQuery();

            // Does the TermSet object already exist?
            TermSet   existingTermSet;
            TermGroup siteCollectionGroup;

            siteCollectionGroup = termStore.GetSiteCollectionGroup(clientContext.Site,
                                                                   createIfMissing: true);

            existingTermSet = termStore.GetTermSet(termSetGUID);
            clientContext.Load(existingTermSet);
            clientContext.ExecuteQuery();
            if (!existingTermSet.ServerObjectIsNull.Value)
            {
                existingTermSet.DeleteObject();
                termStore.CommitAll();
                clientContext.ExecuteQuery();
            }

            TermSet termSet = siteCollectionGroup.CreateTermSet("CMSNavigationTermSet", termSetGUID,
                                                                termStore.WorkingLanguage);

            clientContext.Load(termSet);

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

            //*******below code does not work, so commented it out*******//
            //NavigationTermSet navTermSet = NavigationTermSet.GetAsResolvedByWeb(clientContext,
            //    termSet, clientContext.Web, "GlobalNavigationTaxonomyProvider");
            //navTermSet.IsNavigationTermSet = true;
            //termStore.CommitAll();
            //clientContext.ExecuteQuery();
            //*******                                            *******//

            Term srcTerm    = null;
            Term targetTerm = null;

            //get the source termset
            srcTerm = termStore.GetTerm(srcDepartmentGUID);
            clientContext.Load(srcTerm);
            clientContext.ExecuteQuery();

            if (!srcTerm.ServerObjectIsNull.Value)
            {
                targetTerm = termSet.ReuseTermWithPinning(srcTerm);
                targetTerm.CustomSortOrder = srcTerm.CustomSortOrder;
                termStore.CommitAll();
                clientContext.ExecuteQuery();
            }


            WebNavigationSettings navigationSettings = new WebNavigationSettings(clientContext, clientContext.Web);

            //******* this is weird, we have to reset the navigation to something else, then change it back to TaxonomyProvider, this way works.
            navigationSettings.GlobalNavigation.Source
                = StandardNavigationSource.PortalProvider;
            navigationSettings.Update(taxonomySession);
            clientContext.ExecuteQuery();
            //*********************************//

            navigationSettings.GlobalNavigation.Source
                = StandardNavigationSource.TaxonomyProvider;
            navigationSettings.GlobalNavigation.TermStoreId
                = termStore.Id;
            navigationSettings.GlobalNavigation.TermSetId
                = termSet.Id;

            navigationSettings.Update(taxonomySession);
            //clientContext.Load(navigationSettings);
            clientContext.ExecuteQuery();
        }
Example #17
0
    public void ConfigureTaxonomyNavigation()
    {
        ClientContext   clientContext   = new ClientContext(TestConfig.ServerUrl);
        TaxonomySession taxonomySession = TaxonomySession.GetTaxonomySession(clientContext);

        taxonomySession.UpdateCache();

        NavigationTermSet termSet = DemoUtilities.RecreateSampleNavTermSet(
            this.TestContext, clientContext, taxonomySession, clientContext.Web);

        // Clear out any old settings
        WebNavigationSettings webNavigationSettings = new WebNavigationSettings(clientContext, clientContext.Web);

        webNavigationSettings.ResetToDefaults();
        webNavigationSettings.Update(taxonomySession);

        TaxonomyNavigation.FlushSiteFromCache(clientContext, clientContext.Site);
        clientContext.ExecuteQuery();

        this.WaitForSync();

        // Verify the TermSet is not running
        NavigationTermSet      actualTermSet;
        ExceptionHandlingScope scope = new ExceptionHandlingScope(clientContext);

        using (scope.StartScope())
        {
            using (scope.StartTry())
            {
                actualTermSet = TaxonomyNavigation.GetTermSetForWeb(clientContext, clientContext.Web,
                                                                    "GlobalNavigationTaxonomyProvider", includeInheritedSettings: true);
            }
            using (scope.StartCatch())
            {
            }
        }
        clientContext.ExecuteQuery();

        Assert.IsTrue(actualTermSet.ServerObjectIsNull.Value);

        // Assign the new settings
        webNavigationSettings = new WebNavigationSettings(clientContext, clientContext.Web);

        clientContext.Load(webNavigationSettings,
                           w => w.GlobalNavigation,
                           w => w.CurrentNavigation
                           );
        clientContext.Load(termSet,
                           ts => ts.TermStoreId,
                           ts => ts.Id
                           );
        clientContext.ExecuteQuery();

        // GlobalNavigation = top menu (aka "top nav")
        // CurrentNavigation = left menu (aka "quick launch")
        webNavigationSettings.GlobalNavigation.Source      = StandardNavigationSource.TaxonomyProvider;
        webNavigationSettings.GlobalNavigation.TermStoreId = termSet.TermStoreId;
        webNavigationSettings.GlobalNavigation.TermSetId   = termSet.Id;
        webNavigationSettings.Update(taxonomySession);

        TaxonomyNavigation.FlushSiteFromCache(clientContext, clientContext.Site);
        clientContext.ExecuteQuery();

        this.WaitForSync();

        actualTermSet = TaxonomyNavigation.GetTermSetForWeb(clientContext, clientContext.Web,
                                                            "GlobalNavigationTaxonomyProvider", includeInheritedSettings: true);
        clientContext.Load(actualTermSet, ts => ts.Id);
        clientContext.ExecuteQuery();

        Assert.AreEqual(termSet.Id, actualTermSet.Id);
    }
Example #18
0
        public override Model.ProvisioningTemplate ExtractObjects(Web web, Model.ProvisioningTemplate template, ProvisioningTemplateCreationInformation creationInfo)
        {
            using (var scope = new PnPMonitoredScope(this.Name))
            {
                if (creationInfo.IncludeSiteCollectionTermGroup || creationInfo.IncludeAllTermGroups)
                {
                    // Find the site collection termgroup, if any
                    TaxonomySession session = TaxonomySession.GetTaxonomySession(web.Context);

                    TermStore termStore = null;

                    try
                    {
                        // Refresh / Update the taxonomy Cache to prevent errors using the same session for creating and getting terms
                        session.UpdateCache();
                        web.Context.ExecuteQueryRetry();

                        termStore = session.GetDefaultSiteCollectionTermStore();
                        web.Context.Load(termStore, t => t.Id, t => t.DefaultLanguage, t => t.OrphanedTermsTermSet);
                        web.Context.ExecuteQueryRetry();
                    }
                    catch (ServerException)
                    {
                        // Skip the exception and go to the next check
                    }

                    if (null == termStore || termStore.ServerObjectIsNull())
                    {
                        // If the GetDefaultSiteCollectionTermStore method call fails ... raise a specific Warning
                        WriteMessage(CoreResources.Provisioning_ObjectHandlers_TermGroups_Wrong_Configuration, ProvisioningMessageType.Warning);

                        // and exit skipping the current handler
                        return(template);
                    }

                    var orphanedTermsTermSetId = default(Guid);
                    if (!termStore.OrphanedTermsTermSet.ServerObjectIsNull())
                    {
                        termStore.OrphanedTermsTermSet.EnsureProperty(ts => ts.Id);
                        orphanedTermsTermSetId = termStore.OrphanedTermsTermSet.Id;
                        if (termStore.ServerObjectIsNull.Value)
                        {
                            termStore = session.GetDefaultKeywordsTermStore();
                            web.Context.Load(termStore, t => t.Id, t => t.DefaultLanguage);
                            web.Context.ExecuteQueryRetry();
                        }
                    }

                    var propertyBagKey = $"SiteCollectionGroupId{termStore.Id}";

                    // Ensure to grab the property from the rootweb
                    var site = (web.Context as ClientContext).Site;
                    web.Context.Load(site, s => s.RootWeb);
                    web.Context.ExecuteQueryRetry();

                    var siteCollectionTermGroupId = site.RootWeb.GetPropertyBagValueString(propertyBagKey, "");

                    Guid termGroupGuid;
                    Guid.TryParse(siteCollectionTermGroupId, out termGroupGuid);

                    List <TermGroup> termGroups = new List <TermGroup>();
                    if (creationInfo.IncludeAllTermGroups)
                    {
                        web.Context.Load(termStore.Groups, groups => groups.Include(tg => tg.Name,
                                                                                    tg => tg.Id,
                                                                                    tg => tg.Description,
                                                                                    tg => tg.TermSets.IncludeWithDefaultProperties(ts => ts.CustomSortOrder)));
                        web.Context.ExecuteQueryRetry();
                        termGroups = termStore.Groups.ToList();
                    }
                    else
                    {
                        if (termGroupGuid != Guid.Empty)
                        {
                            var termGroup = termStore.GetGroup(termGroupGuid);
                            web.Context.Load(termGroup,
                                             tg => tg.Name,
                                             tg => tg.Id,
                                             tg => tg.Description,
                                             tg => tg.TermSets.IncludeWithDefaultProperties(ts => ts.Description, ts => ts.CustomSortOrder));

                            web.Context.ExecuteQueryRetry();

                            termGroups = new List <TermGroup>()
                            {
                                termGroup
                            };
                        }
                    }

                    foreach (var termGroup in termGroups)
                    {
                        Boolean isSiteCollectionTermGroup = termGroupGuid != Guid.Empty && termGroup.Id == termGroupGuid;

                        var modelTermGroup = new Model.TermGroup
                        {
                            Name                    = isSiteCollectionTermGroup ? "{sitecollectiontermgroupname}" : termGroup.Name,
                            Id                      = isSiteCollectionTermGroup ? Guid.Empty : termGroup.Id,
                            Description             = termGroup.Description,
                            SiteCollectionTermGroup = isSiteCollectionTermGroup
                        };

#if !SP2013 && !SP2016
                        // If we need to include TermGroups security
                        if (creationInfo.IncludeTermGroupsSecurity)
                        {
                            termGroup.EnsureProperties(tg => tg.ContributorPrincipalNames, tg => tg.GroupManagerPrincipalNames);

                            // Extract the TermGroup contributors
                            modelTermGroup.Contributors.AddRange(
                                from c in termGroup.ContributorPrincipalNames
                                select new Model.User {
                                Name = c
                            });

                            // Extract the TermGroup managers
                            modelTermGroup.Managers.AddRange(
                                from m in termGroup.GroupManagerPrincipalNames
                                select new Model.User {
                                Name = m
                            });
                        }
#endif

                        web.EnsureProperty(w => w.Url);

                        foreach (var termSet in termGroup.TermSets)
                        {
                            // Do not include the orphan term set
                            if (termSet.Id == orphanedTermsTermSetId)
                            {
                                continue;
                            }

                            // Extract all other term sets
                            var modelTermSet = new Model.TermSet();
                            modelTermSet.Name = termSet.Name;
                            if (!isSiteCollectionTermGroup)
                            {
                                modelTermSet.Id = termSet.Id;
                            }
                            modelTermSet.IsAvailableForTagging = termSet.IsAvailableForTagging;
                            modelTermSet.IsOpenForTermCreation = termSet.IsOpenForTermCreation;
                            modelTermSet.Description           = termSet.Description;
                            modelTermSet.Terms.AddRange(GetTerms <TermSet>(web.Context, termSet, termStore.DefaultLanguage, isSiteCollectionTermGroup));
                            foreach (var property in termSet.CustomProperties)
                            {
                                if (property.Key.Equals("_Sys_Nav_AttachedWeb_SiteId", StringComparison.InvariantCultureIgnoreCase))
                                {
                                    modelTermSet.Properties.Add(property.Key, "{sitecollectionid}");
                                }
                                else if (property.Key.Equals("_Sys_Nav_AttachedWeb_WebId", StringComparison.InvariantCultureIgnoreCase))
                                {
                                    modelTermSet.Properties.Add(property.Key, "{siteid}");
                                }
                                else
                                {
                                    modelTermSet.Properties.Add(property.Key, Tokenize(property.Value, web.Url, web));
                                }
                            }
                            modelTermGroup.TermSets.Add(modelTermSet);
                        }

                        template.TermGroups.Add(modelTermGroup);
                    }
                }
            }
            return(template);
        }
Example #19
0
    public static void CreateSimpleTermset()
    {
        string termSetName       = "My Termset";
        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);

                Term term1 = tset.CreateTerm("Term 1", 1033, Guid.NewGuid());
                term1.CreateTerm("Child A", 1033, Guid.NewGuid());
                term1.CreateTerm("Child B", 1033, Guid.NewGuid());
                term1.CreateTerm("Child C", 1033, Guid.NewGuid());

                Term term2 = tset.CreateTerm("Term 2", 1033, Guid.NewGuid());
                term2.CreateTerm("Child D", 1033, Guid.NewGuid());
                term2.CreateTerm("Child E", 1033, Guid.NewGuid());
                term2.CreateTerm("Child F", 1033, Guid.NewGuid());

                Term term3 = tset.CreateTerm("Term 3", 1033, Guid.NewGuid());
                term3.CreateTerm("Child G", 1033, Guid.NewGuid());
                term3.CreateTerm("Child H", 1033, Guid.NewGuid());
                term3.CreateTerm("Child I", 1033, Guid.NewGuid());


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

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