Пример #1
0
        //GetItems
        //GetTaxanomy
        public List <SelectListItem> GetTaxanomy(ClientContext context)
        {
            List <SelectListItem> items    = new List <SelectListItem>();
            TermCollection        terms    = null;
            TaxonomySession       taxonomy = TaxonomySession.GetTaxonomySession(context);

            if (taxonomy != null)
            {
                TermStore termStore = taxonomy.GetDefaultKeywordsTermStore();
                if (termStore != null)
                {
                    TermGroup termGroup = termStore.Groups.GetByName(TERMGROUPNAME);
                    TermSet   termSet   = termGroup.TermSets.GetByName(TERMSETNAME);
                    terms = termSet.GetAllTerms();

                    context.Load(terms);
                    context.ExecuteQuery();

                    foreach (var term in terms)
                    {
                        items.Add(new SelectListItem {
                            Text = term.Name, Value = term.Id.ToString()
                        });
                    }
                }
            }
            return(items);
        }
Пример #2
0
        //ModifyItem
        //CreateTermSet
        public void CreateTermSet(ClientContext context)
        {
            //English(Default English Locale ID)
            int lcid = 1033;
            //Get termSession
            TaxonomySession taxonomy = TaxonomySession.GetTaxonomySession(context);

            if (taxonomy != null)
            {
                //Get TermStore
                TermStore termStore = taxonomy.GetDefaultKeywordsTermStore();
                if (termStore != null)
                {
                    //Set TermGroup
                    TermGroup termGroup = termStore.CreateGroup(TERMGROUPNAME, Guid.NewGuid());
                    //Set TermSet
                    TermSet termSetCollection = termGroup.CreateTermSet(TERMSETNAME, Guid.NewGuid(), lcid);
                    //Set Terms
                    termSetCollection.CreateTerm(TERM_ELEKTRONIK, lcid, Guid.NewGuid());
                    termSetCollection.CreateTerm(TERM_FORDON, lcid, Guid.NewGuid());
                    termSetCollection.CreateTerm(TERM_FRITIDOCHHOBBY, lcid, Guid.NewGuid());
                    termSetCollection.CreateTerm(TERM_HYGIENARTIKLAR, lcid, Guid.NewGuid());
                    termSetCollection.CreateTerm(TERM_MÖBLER, lcid, Guid.NewGuid());

                    context.ExecuteQuery();
                }
            }
        }
Пример #3
0
        public void CanProvisionTokenizedTermsTwiceNameMatch()
        {
            var          template      = new ProvisioningTemplate();
            const string termGroupName = "TestProvisioningGroup";
            var          termGroup     = new TermGroup(_termGroupGuid, termGroupName, null);

            const string termSiteName = "TestProvisioningTermSet - {sitename}";
            var          termSet1     = new TermSet(_termSetGuid, termSiteName, null, true, false, null, null);

            var          term1Id   = Guid.NewGuid();
            const string term1Name = "TestProvisioningTerm - {siteid}";
            var          term1     = new Term(term1Id, term1Name, null, null, null, null, null);

            termSet1.Terms.Add(term1);
            termGroup.TermSets.Add(termSet1);
            template.TermGroups.Add(termGroup);

            for (int index = 0; index < 2; index++)
            {
                if (index == 1)
                {
                    // Assign a new ID to the Term to test the name matching logic.
                    term1.Id = Guid.NewGuid();
                }

                using (ClientContext ctx = TestCommon.CreateClientContext())
                {
                    var parser = new TokenParser(ctx.Web, template);
                    new ObjectTermGroups().ProvisionObjects(ctx.Web, template, parser, new ProvisioningTemplateApplyingInformation());
                }

                using (ClientContext ctx = TestCommon.CreateClientContext())
                {
                    TaxonomySession session = TaxonomySession.GetTaxonomySession(ctx);

                    var store = session.GetDefaultKeywordsTermStore();
                    var group = store.GetGroup(_termGroupGuid);
                    var set   = store.GetTermSet(_termSetGuid);

                    ctx.Load(group);
                    ctx.Load(set, s => s.Id, s => s.Name, s => s.Terms);
                    ctx.ExecuteQueryRetry();

                    Assert.IsInstanceOfType(group, typeof(Microsoft.SharePoint.Client.Taxonomy.TermGroup));
                    StringAssert.Matches(group.Name, new Regex(Regex.Escape(termGroupName)));
                    Assert.AreEqual(_termGroupGuid, group.Id);

                    Assert.IsInstanceOfType(set, typeof(Microsoft.SharePoint.Client.Taxonomy.TermSet));
                    Assert.AreEqual(1, set.Terms.Count);
                    Assert.AreEqual(_termSetGuid, set.Id);
                    StringAssert.DoesNotMatch(set.Name, new Regex(Regex.Escape(termSiteName)));

                    var remoteTerm1 = set.Terms[0];
                    Assert.AreEqual(term1Id, remoteTerm1.Id);
                    StringAssert.DoesNotMatch(remoteTerm1.Name, new Regex(Regex.Escape(term1Name)));
                }
            }
        }
Пример #4
0
        public static TermStore GetDefaultKeywordsTermStore(this Site site)
        {
            TaxonomySession session   = TaxonomySession.GetTaxonomySession(site.Context);
            var             termStore = session.GetDefaultKeywordsTermStore();

            site.Context.Load(termStore);
            site.Context.ExecuteQuery();

            return(termStore);
        }
Пример #5
0
 public override string GetReplaceValue()
 {
     if (CacheValue == null)
     {
         TaxonomySession session   = TaxonomySession.GetTaxonomySession(TokenContext);
         var             termStore = session.GetDefaultKeywordsTermStore();
         TokenContext.Load(termStore, t => t.Id);
         TokenContext.ExecuteQueryRetry();
         CacheValue = termStore.Id.ToString();
     }
     return(CacheValue);
 }
Пример #6
0
        public void GetTermSet(TaxonomyTypes taxonomyType, string termSetName, string groupName, bool createIfMissing, out TermStore termStore, out TermSet termSet)
        {
            termSet = null;
            Site site = _clientContext.Site;

            termStore = null;

            TaxonomySession session = TaxonomySession.GetTaxonomySession(_clientContext);

            switch (taxonomyType)
            {
            case TaxonomyTypes.SiteCollection:
                termStore = session.GetDefaultSiteCollectionTermStore();
                break;

            case TaxonomyTypes.Keywords:
                termStore = session.GetDefaultKeywordsTermStore();
                break;

            default:
                throw new Exception("Unexpected Taxonomytype");
            }

            try
            {
                if (termStore != null)
                {
                    _clientContext.Load(termStore);
                    _clientContext.ExecuteQuery();
                    System.Threading.Thread.Sleep(1000);
                    TermGroup termGroup = groupName == null
                    ? termStore.GetSiteCollectionGroup(site, createIfMissing)
                    : termStore.GetTermGroupByName(groupName);

                    System.Threading.Thread.Sleep(1000);
                    if (termGroup == null || termGroup.TermSets == null)
                    {
                        return;
                    }

                    _clientContext.Load(termGroup);
                    _clientContext.Load(termGroup.TermSets);
                    _clientContext.ExecuteQuery();
                    System.Threading.Thread.Sleep(1000);
                    termSet = termGroup.TermSets.FirstOrDefault(ts => ts.Name == termSetName);
                }
            }
            catch (Exception ex)
            {
                throw;
            }
        }
Пример #7
0
        public override TokenParser ProvisionObjects(Web web, Model.ProvisioningTemplate template, TokenParser parser,
                                                     ProvisioningTemplateApplyingInformation applyingInformation)
        {
            using (var scope = new PnPMonitoredScope(this.Name))
            {
                this.reusedTerms = new List <TermGroupHelper.ReusedTerm>();

                TaxonomySession taxSession = TaxonomySession.GetTaxonomySession(web.Context);
                TermStore       termStore  = null;
                TermGroup       siteCollectionTermGroup = null;

                try
                {
                    termStore = taxSession.GetDefaultKeywordsTermStore();
                    web.Context.Load(termStore,
                                     ts => ts.Languages,
                                     ts => ts.DefaultLanguage,
                                     ts => ts.Groups.Include(
                                         tg => tg.Name,
                                         tg => tg.Id,
                                         tg => tg.TermSets.Include(
                                             tset => tset.Name,
                                             tset => tset.Id)));
                    siteCollectionTermGroup = termStore.GetSiteCollectionGroup((web.Context as ClientContext).Site, false);
                    web.Context.Load(siteCollectionTermGroup);
                    web.Context.ExecuteQueryRetry();
                }
                catch (ServerException)
                {
                    // 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(parser);
                }

                SiteCollectionTermGroupNameToken siteCollectionTermGroupNameToken =
                    new SiteCollectionTermGroupNameToken(web);

                foreach (var modelTermGroup in template.TermGroups)
                {
                    this.reusedTerms.AddRange(TermGroupHelper.ProcessGroup(web.Context as ClientContext, taxSession, termStore, modelTermGroup, siteCollectionTermGroup, parser, scope));
                }

                foreach (var reusedTerm in this.reusedTerms)
                {
                    TermGroupHelper.TryReuseTerm(web.Context as ClientContext, reusedTerm.ModelTerm, reusedTerm.Parent, reusedTerm.TermStore, parser, scope);
                }
            }
            return(parser);
        }
Пример #8
0
        public override TokenParser ProvisionObjects(Tenant tenant, Model.ProvisioningHierarchy hierarchy, string sequenceId, TokenParser parser,
                                                     ProvisioningTemplateApplyingInformation applyingInformation)
        {
            using (var scope = new PnPMonitoredScope(this.Name))
            {
                foreach (var sequence in hierarchy.Sequences)
                {
                    this.reusedTerms = new List <TermGroupHelper.ReusedTerm>();

                    var context = tenant.Context as ClientContext;

                    TaxonomySession taxSession = TaxonomySession.GetTaxonomySession(context);
                    TermStore       termStore  = null;

                    try
                    {
                        termStore = taxSession.GetDefaultKeywordsTermStore();
                        context.Load(termStore,
                                     ts => ts.Languages,
                                     ts => ts.DefaultLanguage,
                                     ts => ts.Groups.Include(
                                         tg => tg.Name,
                                         tg => tg.Id,
                                         tg => tg.TermSets.Include(
                                             tset => tset.Name,
                                             tset => tset.Id)));
                        context.ExecuteQueryRetry();
                    }
                    catch (ServerException)
                    {
                        WriteMessage("Failed to retrieve existing terms", ProvisioningMessageType.Error);

                        return(parser);
                    }

                    foreach (var modelTermGroup in sequence.TermStore.TermGroups)
                    {
                        this.reusedTerms.AddRange(TermGroupHelper.ProcessGroup(context, taxSession, termStore, modelTermGroup, null, parser, scope));
                    }

                    foreach (var reusedTerm in this.reusedTerms)
                    {
                        TermGroupHelper.TryReuseTerm(context, reusedTerm.ModelTerm, reusedTerm.Parent, reusedTerm.TermStore, parser, scope);
                    }
                }
            }
            return(parser);
        }
Пример #9
0
 public override string GetReplaceValue()
 {
     if (CacheValue == null)
     {
         this.Web.EnsureProperty(w => w.Url);
         using (ClientContext context = this.Web.Context.Clone(this.Web.Url))
         {
             TaxonomySession session   = TaxonomySession.GetTaxonomySession(context);
             var             termStore = session.GetDefaultKeywordsTermStore();
             context.Load(termStore, t => t.Id);
             context.ExecuteQueryRetry();
             CacheValue = termStore.Id.ToString();
         }
     }
     return(CacheValue);
 }
        private static Guid AddKeyWord(string label, ClientContext ctx)
        {
            if (string.IsNullOrEmpty(label))
            {
                return(Guid.Empty);
            }

            LogHelper.Log("label : " + label + " ctx:" + ctx);
            TaxonomySession tax    = TaxonomySession.GetTaxonomySession(ctx);
            Guid            TermId = Guid.NewGuid();

            try
            {
                tax.GetDefaultKeywordsTermStore().KeywordsTermSet.CreateTerm(label, 1033, TermId);
                ctx.ExecuteQuery();
                EmptyKeywordsNeedsRefresh = true;
                return(TermId);
            }
            catch (Exception ex)
            {
                LogHelper.Log("failed for label : " + label + " ctx:" + ctx + " tax:" + tax, LogSeverity.Error);
                try
                {
                    //cannot reuse tax because it is stale.
                    TaxonomySession       tax1 = TaxonomySession.GetTaxonomySession(ctx);
                    LabelMatchInformation m    = new LabelMatchInformation(ctx);
                    m.TermLabel       = label;
                    m.TrimUnavailable = true;
                    TermCollection matches = tax1.GetDefaultKeywordsTermStore().KeywordsTermSet.GetTerms(m);
                    ctx.Load(matches);
                    ctx.ExecuteQuery();
                    if (matches.Count > 0)
                    {
                        return(matches[0].Id);
                    }
                    else
                    {
                        return(Guid.Empty);
                    }
                }
                catch (Exception subex)
                {
                    LogHelper.Log(subex.Message + subex.StackTrace, LogSeverity.Error);
                    return(Guid.Empty);
                }
            }
        }
Пример #11
0
        public async Task Default_Keywords_TermStore_gets_resolved()
        {
            var resolver = ManualResolver.ResolveSingle(Resolve.TermStoreKeywordsDefault());
            await ClientContext.ExecuteQueryAsync();

            var termStore = resolver.Value;

            Assert.NotNull(termStore);

            var expected = TaxonomySession.GetDefaultKeywordsTermStore();

            ClientContext.Load(expected, ts => ts.Id);
            ClientContext.Load(termStore, ts => ts.Id);
            await ClientContext.ExecuteQueryAsync();

            Assert.Equal(expected.Id, termStore.Id);
        }
Пример #12
0
 /// <summary>
 /// Loading the Term Group Based on Given Name
 /// </summary>
 /// <param name="clientContext">Client context</param>
 /// <param name="taxonomySession">Taxonomy session</param>
 /// <param name="termGroupName">Term group name </param>
 /// <returns>Term group </returns>
 public static TermGroup LoadTermGroup(ClientContext clientContext, TaxonomySession taxonomySession, string termGroupName)
 {
     TermStore termStore = taxonomySession.GetDefaultKeywordsTermStore();
     clientContext.Load(termStore,
             store => store.Name,
             store => store.Groups.Include(
                 group => group.Name,
                 group => group.TermSets.Include(
                     termSet => termSet.Name,
                     termSet => termSet.Terms.Include(
                         term => term.Name,
                         term => term.CustomProperties
                         )
                 )
             )
     );
     clientContext.ExecuteQuery();
     TermGroup termGroup = termStore.Groups.GetByName(termGroupName);
     return termGroup;
 }
Пример #13
0
        private TermStore GetTermStoreObject(ClientContext ctx)
        {
            TaxonomySession _sourceTaxonomySession = TaxonomySession.GetTaxonomySession(ctx);
            TermStore       _sourceTermStore       = _sourceTaxonomySession.GetDefaultKeywordsTermStore();

            ctx.Load(_sourceTermStore,
                     store => store.Name,
                     store => store.DefaultLanguage,
                     store => store.Groups.Include(
                         group => group.Name, group => group.Id, group => group.Description,
                         group => group.TermSets.Include(
                             termSet => termSet.Name, termSet => termSet.Id,
                             termSet => termSet.Terms.Include(
                                 term => term.Name, term => term.Id)
                             )
                         )
                     );
            ctx.ExecuteQuery();

            return(_sourceTermStore);
        }
Пример #14
0
        /// <summary>
        /// Loading the Term Group Based on Given Name
        /// </summary>
        /// <param name="clientContext">Client context</param>
        /// <param name="taxonomySession">Taxonomy session</param>
        /// <param name="termGroupName">Term group name </param>
        /// <returns>Term group </returns>
        public static TermGroup LoadTermGroup(ClientContext clientContext, TaxonomySession taxonomySession, string termGroupName)
        {
            TermStore termStore = taxonomySession.GetDefaultKeywordsTermStore();

            clientContext.Load(termStore,
                               store => store.Name,
                               store => store.Groups.Include(
                                   group => group.Name,
                                   group => group.TermSets.Include(
                                       termSet => termSet.Name,
                                       termSet => termSet.Terms.Include(
                                           term => term.Name,
                                           term => term.CustomProperties
                                           )
                                       )
                                   )
                               );
            clientContext.ExecuteQuery();
            TermGroup termGroup = termStore.Groups.GetByName(termGroupName);

            return(termGroup);
        }
Пример #15
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
                    {
                        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 !ONPREMISES
                        // 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);
        }
Пример #16
0
        public override TokenParser ProvisionObjects(Web web, Model.ProvisioningTemplate template, TokenParser parser,
                                                     ProvisioningTemplateApplyingInformation applyingInformation)
        {
            using (var scope = new PnPMonitoredScope(this.Name))
            {
                this.reusedTerms = new List <ReusedTerm>();

                TaxonomySession taxSession = TaxonomySession.GetTaxonomySession(web.Context);
                TermStore       termStore  = null;
                TermGroup       siteCollectionTermGroup = null;

                try
                {
                    termStore = taxSession.GetDefaultKeywordsTermStore();
                    web.Context.Load(termStore,
                                     ts => ts.Languages,
                                     ts => ts.DefaultLanguage,
                                     ts => ts.Groups.Include(
                                         tg => tg.Name,
                                         tg => tg.Id,
                                         tg => tg.TermSets.Include(
                                             tset => tset.Name,
                                             tset => tset.Id)));
                    siteCollectionTermGroup = termStore.GetSiteCollectionGroup((web.Context as ClientContext).Site, false);
                    web.Context.Load(siteCollectionTermGroup);
                    web.Context.ExecuteQueryRetry();
                }
                catch (ServerException)
                {
                    // 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(parser);
                }

                SiteCollectionTermGroupNameToken siteCollectionTermGroupNameToken =
                    new SiteCollectionTermGroupNameToken(web);

                foreach (var modelTermGroup in template.TermGroups)
                {
                    #region Group

                    var newGroup            = false;
                    var normalizedGroupName = TaxonomyItem.NormalizeName(web.Context, modelTermGroup.Name);
                    web.Context.ExecuteQueryRetry();

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

                        if (modelTermGroup.Name == "Site Collection" ||
                            parsedGroupName == siteCollectionTermGroupNameToken.GetReplaceValue() ||
                            modelTermGroup.SiteCollectionTermGroup)
                        {
                            var site = (web.Context as ClientContext).Site;
                            group = termStore.GetSiteCollectionGroup(site, true);
                            web.Context.Load(group, g => g.Name, g => g.Id, g => g.TermSets.Include(
                                                 tset => tset.Name,
                                                 tset => tset.Id));
                            web.Context.ExecuteQueryRetry();
                        }
                        else
                        {
                            var parsedNormalizedGroupName = TaxonomyItem.NormalizeName(web.Context, parsedGroupName);
                            web.Context.ExecuteQueryRetry();

                            group = termStore.Groups.FirstOrDefault(g => g.Name == parsedNormalizedGroupName.Value);

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

                                group.Description = parsedDescription;

#if !ONPREMISES
                                // 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);
                                    }
                                }
#endif

                                termStore.CommitAll();
                                web.Context.Load(group);
                                web.Context.ExecuteQueryRetry();

                                newGroup = true;
                            }
                        }
                    }

                    #endregion

                    #region TermSets

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

                        var normalizedTermSetName = TaxonomyItem.NormalizeName(web.Context, modelTermSet.Name);
                        web.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();
                            }
                            set = group.CreateTermSet(parser.ParseString(modelTermSet.Name), modelTermSet.Id,
                                                      modelTermSet.Language ?? termStore.DefaultLanguage);
                            parser.AddToken(new TermSetIdToken(web, group.Name, modelTermSet.Name, modelTermSet.Id));
                            if (!siteCollectionTermGroup.ServerObjectIsNull.Value)
                            {
                                if (group.Name == siteCollectionTermGroup.Name)
                                {
                                    parser.AddToken((new SiteCollectionTermSetIdToken(web, modelTermSet.Name, modelTermSet.Id)));
                                }
                            }
                            newTermSet                = true;
                            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 = modelTermSet.Owner;
                            }
                            termStore.CommitAll();
                            web.Context.Load(set);
                            web.Context.ExecuteQueryRetry();
                        }

                        web.Context.Load(set, s => s.Terms.Include(t => t.Id, t => t.Name));
                        web.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(web.Context, modelTerm.Name);
                                        web.Context.ExecuteQueryRetry();

                                        term = terms.FirstOrDefault(t => t.Name == normalizedTermName.Value);
                                        if (term == null)
                                        {
                                            var returnTuple = CreateTerm <TermSet>(web, modelTerm, set, termStore, parser, scope);
                                            if (returnTuple != null)
                                            {
                                                modelTerm.Id = returnTuple.Item1;
                                                parser       = returnTuple.Item2;
                                            }
                                        }
                                        else
                                        {
                                            modelTerm.Id = term.Id;
                                        }
                                    }
                                    else
                                    {
                                        modelTerm.Id = term.Id;
                                    }

                                    if (term != null)
                                    {
                                        CheckChildTerms(web, modelTerm, term, termStore, parser, scope);
                                    }
                                }
                                else
                                {
                                    var returnTuple = CreateTerm <TermSet>(web, modelTerm, set, termStore, parser, scope);
                                    if (returnTuple != null)
                                    {
                                        modelTerm.Id = returnTuple.Item1;
                                        parser       = returnTuple.Item2;
                                    }
                                }
                            }
                            else
                            {
                                var returnTuple = CreateTerm <TermSet>(web, modelTerm, set, termStore, parser, scope);
                                if (returnTuple != null)
                                {
                                    modelTerm.Id = returnTuple.Item1;
                                    parser       = returnTuple.Item2;
                                }
                            }
                        }

                        // do we need custom sorting?
                        if (modelTermSet.Terms.Any(t => t.CustomSortOrder > -1))
                        {
                            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();
                            web.Context.ExecuteQueryRetry();
                        }
                    }

                    #endregion
                }

                foreach (var reusedTerm in this.reusedTerms)
                {
                    TryReuseTerm(web, reusedTerm.ModelTerm, reusedTerm.Parent, reusedTerm.TermStore, parser, scope);
                }
            }
            return(parser);
        }
Пример #17
0
        public void CanProvisionReusableTerms()
        {
            var template = new ProvisioningTemplate();

            TermGroup termGroup = new TermGroup(_termGroupGuid, "TestProvisioningGroup", null);

            List <TermSet> termSets = new List <TermSet>();

            TermSet termSet1 = new TermSet(_termSetGuid, "TestProvisioningTermSet1", null, true, false, null, null);
            TermSet termSet2 = new TermSet(_additionalTermSetGuid, "TestProvisioningTermSet2", null, true, false, null, null);

            var sourceTerm = new Term(Guid.NewGuid(), "Source Term 1", null, null, null, null, null)
            {
                IsReused     = true,
                IsSourceTerm = true
            };


            var reusedTerm = new Term(sourceTerm.Id, "Source Term 1", null, null, null, null, null)
            {
                IsReused     = true,
                SourceTermId = sourceTerm.Id
            };


            termSet1.Terms.Add(reusedTerm);
            termSet2.Terms.Add(sourceTerm);

            termSets.Add(termSet1);
            termSets.Add(termSet2);

            termGroup.TermSets.AddRange(termSets);

            template.TermGroups.Add(termGroup);

            using (var ctx = TestCommon.CreateClientContext())
            {
                var parser = new TokenParser(ctx.Web, template);

                new ObjectTermGroups().ProvisionObjects(ctx.Web, template, parser, new ProvisioningTemplateApplyingInformation());

                TaxonomySession session = TaxonomySession.GetTaxonomySession(ctx);

                var store = session.GetDefaultKeywordsTermStore();
                var group = store.GetGroup(_termGroupGuid);
                var set2  = store.GetTermSet(_additionalTermSetGuid);

                ctx.Load(group);
                ctx.Load(set2, s => s.Terms);
                ctx.ExecuteQueryRetry();

                var createdSourceTerm = set2.GetTerm(sourceTerm.Id);
                ctx.Load(createdSourceTerm);
                ctx.ExecuteQueryRetry();

                Assert.IsTrue(createdSourceTerm.IsSourceTerm);
                Assert.IsTrue(createdSourceTerm.IsReused);

                var set1 = store.GetTermSet(_termSetGuid);
                ctx.Load(set1, s => s.Terms);
                ctx.ExecuteQueryRetry();

                var createdReusedTerm = set1.GetTerm(reusedTerm.Id);
                ctx.Load(createdReusedTerm, c => c.SourceTerm, c => c.IsReused);
                ctx.ExecuteQueryRetry();
                Assert.IsTrue(createdReusedTerm.SourceTerm.Id == sourceTerm.Id);
                Assert.IsTrue(createdReusedTerm.IsReused);
            }
        }
Пример #18
0
        public void CanProvisionObjects()
        {
            var template = new ProvisioningTemplate();

            TermGroup termGroup = new TermGroup(_termGroupGuid, "TestProvisioningGroup", null);

            List <TermSet> termSets = new List <TermSet>();

            TermSet termSet = new TermSet(_termSetGuid, "TestProvisioningTermSet", null, true, false, null, null);

            List <Term> terms = new List <Term>();

            var term1 = new Term(Guid.NewGuid(), "TestProvisioningTerm 1", null, null, null, null, null);

            term1.Properties.Add("TestProp1", "Test Value 1");
            term1.LocalProperties.Add("TestLocalProp1", "Test Value 1");
            term1.Labels.Add(new TermLabel()
            {
                Language = 1033, Value = "Testing"
            });

            term1.Terms.Add(new Term(Guid.NewGuid(), "Sub Term 1", null, null, null, null, null));

            terms.Add(term1);

            terms.Add(new Term(Guid.NewGuid(), "TestProvisioningTerm 2", null, null, null, null, null));

            termSet.Terms.AddRange(terms);

            termSets.Add(termSet);

            termGroup.TermSets.AddRange(termSets);

            template.TermGroups.Add(termGroup);

            using (var ctx = TestCommon.CreateClientContext())
            {
                var parser = new TokenParser(ctx.Web, template);

                new ObjectTermGroups().ProvisionObjects(ctx.Web, template, parser, new ProvisioningTemplateApplyingInformation());

                TaxonomySession session = TaxonomySession.GetTaxonomySession(ctx);

                var store = session.GetDefaultKeywordsTermStore();
                var group = store.GetGroup(_termGroupGuid);
                var set   = store.GetTermSet(_termSetGuid);

                ctx.Load(group);
                ctx.Load(set, s => s.Terms);
                ctx.ExecuteQueryRetry();

                Assert.IsInstanceOfType(group, typeof(Microsoft.SharePoint.Client.Taxonomy.TermGroup));
                Assert.IsInstanceOfType(set, typeof(Microsoft.SharePoint.Client.Taxonomy.TermSet));
                Assert.IsTrue(set.Terms.Count == 2);


                var creationInfo = new ProvisioningTemplateCreationInformation(ctx.Web)
                {
                    BaseTemplate = ctx.Web.GetBaseTemplate()
                };

                var template2 = new ProvisioningTemplate();
                template2 = new ObjectTermGroups().ExtractObjects(ctx.Web, template, creationInfo);

                Assert.IsTrue(template.TermGroups.Any());
                Assert.IsInstanceOfType(template.TermGroups, typeof(Core.Framework.Provisioning.Model.TermGroupCollection));
            }
        }
Пример #19
0
        public void CanProvisionReusableTerms()
        {
            var template = new ProvisioningTemplate();

            var termGroup = new TermGroup(_termGroupGuid, "TestProvisioningGroup", null);

            var termSets = new List <TermSet>();

            var termSet1 = new TermSet(_termSetGuid, "TestProvisioningTermSet1", null, true, false, null, null);
            var termSet2 = new TermSet(_additionalTermSetGuid, "TestProvisioningTermSet2", null, true, false, null, null);

            var sourceTerm = new Term(Guid.NewGuid(), "Source Term 1", null, null, null, null, null)
            {
                IsReused     = true,
                IsSourceTerm = true
            };

            var reusedTerm = new Term(sourceTerm.Id, "Source Term 1", null, null, null, null, null)
            {
                IsReused     = true,
                SourceTermId = sourceTerm.Id
            };

            termSet1.Terms.Add(reusedTerm);
            termSet2.Terms.Add(sourceTerm);

            termSets.Add(termSet1);
            termSets.Add(termSet2);

            termGroup.TermSets.AddRange(termSets);

            template.TermGroups.Add(termGroup);

            using (var ctx = TestCommon.CreateClientContext())
            {
                var parser = new TokenParser(ctx.Web, template);

                new ObjectTermGroups().ProvisionObjects(ctx.Web, template, parser, new ProvisioningTemplateApplyingInformation());

                TaxonomySession session = TaxonomySession.GetTaxonomySession(ctx);

                var store = session.GetDefaultKeywordsTermStore();
                var group = store.GetGroup(_termGroupGuid);
                var set2  = store.GetTermSet(_additionalTermSetGuid);

                ctx.Load(group);
                ctx.Load(set2, s => s.Terms);
                ctx.ExecuteQueryRetry();

                var createdSourceTerm = set2.GetTerm(sourceTerm.Id);
                ctx.Load(createdSourceTerm);
                ctx.ExecuteQueryRetry();

                Assert.IsTrue(createdSourceTerm.IsSourceTerm);
                Assert.IsTrue(createdSourceTerm.IsReused);

                var set1 = store.GetTermSet(_termSetGuid);
                ctx.Load(set1, s => s.Terms);
                ctx.ExecuteQueryRetry();

                var createdReusedTerm = set1.GetTerm(reusedTerm.Id);
                ctx.Load(createdReusedTerm,
                         c => c.SourceTerm.Id,
                         c => c.IsReused
                         );
                ctx.ExecuteQueryRetry();

                // createdReusedTerm.SourceTerm.EnsureProperty(s => s.Id);

                Assert.IsTrue(createdReusedTerm.SourceTerm.Id == sourceTerm.Id);
                Assert.IsTrue(createdReusedTerm.IsReused);
            }

            // check result by reading the template again
            using (var ctx = TestCommon.CreateClientContext())
            {
                var result = ctx.Web.GetProvisioningTemplate(new ProvisioningTemplateCreationInformation(ctx.Web)
                {
                    HandlersToProcess    = Handlers.TermGroups,
                    IncludeAllTermGroups = true // without this being true no term groups will be returned
                });

                // note: cannot use TermGroupValidator class to validate the result as XML since the read template contains additional information like Description="", Owner="[...]", differing TermGroup ID etc. which makes the validation fail; so manually compare what's interesting
                var newTermGroups = result.TermGroups.Where(tg => tg.Name == termGroup.Name);
                Assert.AreEqual(1, newTermGroups.Count());

                var newTermGroup = newTermGroups.First();
                Assert.AreEqual(2, newTermGroup.TermSets.Count);
                Assert.AreEqual(1, newTermGroup.TermSets[0].Terms.Count);
                Assert.AreEqual(1, newTermGroup.TermSets[1].Terms.Count);

                // note: this check that the IDs of the source and reused term are the same to document this behavior
                Assert.AreEqual(sourceTerm.Id, newTermGroup.TermSets[0].Terms[0].Id);
                Assert.AreEqual(sourceTerm.Id, newTermGroup.TermSets[1].Terms[0].Id);
                Assert.IsTrue(newTermGroup.TermSets[0].Terms[0].IsReused);
                Assert.IsTrue(newTermGroup.TermSets[1].Terms[0].IsReused);
            }
        }
Пример #20
0
        public void CanProvisionObjects()
        {
            var template = new ProvisioningTemplate();

            var termGroup = new TermGroup(_termGroupGuid, "TestProvisioningGroup", null);

            var termSets = new List <TermSet>();

            var termSet = new TermSet(_termSetGuid, "TestProvisioningTermSet", null, true, false, null, null);

            var terms = new List <Term>();

            var          term1Id   = Guid.NewGuid();
            const string term1Name = "TestProvisioningTerm 1";
            var          term1     = new Term(term1Id, term1Name, null, null, null, null, null);

            term1.Properties.Add("TestProp1", "Test Value 1");
            term1.LocalProperties.Add("TestLocalProp1", "Test Value 1");
            term1.Labels.Add(new TermLabel()
            {
                Language = 1033, Value = "Testing"
            });

            var term1Subterm1Id = Guid.NewGuid();

            term1.Terms.Add(new Term(term1Subterm1Id, "Sub Term 1", null, null, null, null, null));

            terms.Add(term1);

            var          term2Id   = Guid.NewGuid();
            const string term2Name = "TestProvisioningTerm 2";

            terms.Add(new Term(term2Id, term2Name, null, null, null, null, null));

            termSet.Terms.AddRange(terms);

            termSets.Add(termSet);

            termGroup.TermSets.AddRange(termSets);

            template.TermGroups.Add(termGroup);

            using (var ctx = TestCommon.CreateClientContext())
            {
                var parser = new TokenParser(ctx.Web, template);

                new ObjectTermGroups().ProvisionObjects(ctx.Web, template, parser, new ProvisioningTemplateApplyingInformation());

                TaxonomySession session = TaxonomySession.GetTaxonomySession(ctx);

                var store = session.GetDefaultKeywordsTermStore();
                var group = store.GetGroup(_termGroupGuid);
                var set   = store.GetTermSet(_termSetGuid);

                ctx.Load(group);
                ctx.Load(set, s => s.Terms);
                ctx.ExecuteQueryRetry();

                Assert.IsInstanceOfType(group, typeof(Microsoft.SharePoint.Client.Taxonomy.TermGroup));
                Assert.IsInstanceOfType(set, typeof(Microsoft.SharePoint.Client.Taxonomy.TermSet));

                var orderedTerms = set.Terms.OrderBy(t => t.Name, StringComparer.Ordinal).ToArray();
                Assert.AreEqual(2, orderedTerms.Length);

                var remoteTerm1 = orderedTerms[0];
                Assert.AreEqual(term1Id, remoteTerm1.Id);
                StringAssert.Matches(remoteTerm1.Name, new Regex(Regex.Escape(term1Name)));

                var remoteTerm2 = orderedTerms[1];
                Assert.AreEqual(term2Id, remoteTerm2.Id);
                StringAssert.Matches(remoteTerm2.Name, new Regex(Regex.Escape(term2Name)));

                var creationInfo = new ProvisioningTemplateCreationInformation(ctx.Web)
                {
                    BaseTemplate = ctx.Web.GetBaseTemplate()
                };

                var template2 = new ProvisioningTemplate();
                template2 = new ObjectTermGroups().ExtractObjects(ctx.Web, template, creationInfo);

                Assert.IsTrue(template.TermGroups.Any());
                Assert.IsInstanceOfType(template.TermGroups, typeof(PnP.Framework.Provisioning.Model.TermGroupCollection));
            }
        }
Пример #21
0
        public void ProcessChanges(ClientContext sourceClientContext, ClientContext targetClientContext, List <string> termSetNames)
        {
            List <TermOperation> _list      = new List <TermOperation>();
            DateTime             _startFrom = DateTime.Now.AddYears(-1);

            Console.WriteLine("Opening the taxonomy session");
            TaxonomySession _sourceTaxonomySession = TaxonomySession.GetTaxonomySession(sourceClientContext);
            TermStore       sourceTermStore        = _sourceTaxonomySession.GetDefaultKeywordsTermStore();

            sourceClientContext.Load(sourceTermStore);
            sourceClientContext.ExecuteQuery();

            Console.WriteLine("Reading the changes");
            ChangeInformation _ci = new ChangeInformation(sourceClientContext);

            _ci.StartTime = _startFrom;
            ChangedItemCollection _cic = sourceTermStore.GetChanges(_ci);

            sourceClientContext.Load(_cic);
            sourceClientContext.ExecuteQuery();

            if (_cic.Count > 0)
            {
                bool noError = true;
                // Load up the taxonomy item names.
                TaxonomySession targetTaxonomySession = TaxonomySession.GetTaxonomySession(targetClientContext);
                TermStore       targetTermStore       = targetTaxonomySession.GetDefaultKeywordsTermStore();
                targetClientContext.Load(targetTermStore,
                                         store => store.Name,
                                         store => store.DefaultLanguage,
                                         store => store.Groups.Include(
                                             group => group.Name, group => group.Id));
                targetClientContext.ExecuteQuery();

                foreach (ChangedItem _changeItem in _cic)
                {
                    Guid g = _changeItem.Id;
                    if (_changeItem.ItemType == ChangedItemType.Group)
                    {
                        TermGroup sourceTermGroup = sourceTermStore.GetGroup(_changeItem.Id);
                        sourceClientContext.Load(sourceTermGroup, group => group.Name, group => group.Id, group => group.IsSystemGroup, group => group.Description);
                        sourceClientContext.ExecuteQuery();
                        if (sourceTermGroup.ServerObjectIsNull.Value)
                        {
                            continue;
                        }
                        else
                        {
                            if (sourceTermGroup.IsSystemGroup)
                            {
                                Console.WriteLine("Group \"" + sourceTermGroup.Name + "\" is a system group");
                                continue;
                            }
                        }

                        if (_changeItem.Operation == ChangedOperationType.DeleteObject)
                        {
                            TermGroup targetTermGroup = targetTermStore.GetGroup(_changeItem.Id);
                            targetClientContext.Load(targetTermGroup,
                                                     group => group.Name,
                                                     group => group.Id,
                                                     group => group.TermSets.Include(
                                                         termSet => termSet.Name,
                                                         termSet => termSet.Id));
                            targetClientContext.ExecuteQuery();

                            foreach (TermSet ts in targetTermGroup.TermSets)
                            {
                                Console.WriteLine("Deleting termset: " + ts.Name);
                                TermOperation op = new TermOperation();
                                op.Term      = ts.Name;
                                op.Id        = ts.Id.ToString();
                                op.Operation = "Delete";
                                op.Type      = "TermSet";
                                _list.Add(op);
                                ts.DeleteObject();
                            }

                            Console.WriteLine("Deleting group: " + sourceTermGroup.Name);
                            targetTermGroup.DeleteObject();
                            TermOperation op2 = new TermOperation();
                            op2.Term      = sourceTermGroup.Name;
                            op2.Id        = _changeItem.Id.ToString();
                            op2.Operation = "Delete";
                            op2.Type      = "TermGroup";
                            _list.Add(op2);

                            targetClientContext.ExecuteQuery();
                        }
                        else if (_changeItem.Operation == ChangedOperationType.Add)
                        {
                            TermGroup targetTermGroup = targetTermStore.GetGroup(_changeItem.Id);
                            targetClientContext.Load(targetTermGroup, group => group.Name,
                                                     group => group.Id,
                                                     group => group.TermSets.Include(
                                                         termSet => termSet.Name,
                                                         termSet => termSet.Id));

                            targetClientContext.ExecuteQuery();

                            if (targetTermGroup.ServerObjectIsNull.Value)
                            {
                                TermGroup targetTermGroupTest = targetTermStore.Groups.GetByName(sourceTermGroup.Name);
                                targetClientContext.Load(targetTermGroupTest, group => group.Name);

                                try
                                {
                                    targetClientContext.ExecuteQuery();
                                    if (!targetTermGroupTest.ServerObjectIsNull.Value)
                                    {
                                        if (sourceTermGroup.Name.ToLower() == "system" || sourceTermGroup.Name.ToLower() == "people")
                                        {
                                            Console.WriteLine("Group: " + sourceTermGroup.Name + " already exists");
                                            continue;
                                        }
                                        else
                                        {
                                            InvalidOperationException uEx = new InvalidOperationException("A group named: \"" + sourceTermGroup.Name + "\" already exists but with a different ID. Please delete the term group from the target termstore");
                                            break;
                                        }
                                    }
                                }
                                catch
                                {
                                }

                                Console.WriteLine("Adding group: " + sourceTermGroup.Name);
                                TermGroup _targetTermGroup = targetTermStore.CreateGroup(sourceTermGroup.Name, _changeItem.Id);
                                if (!string.IsNullOrEmpty(sourceTermGroup.Description))
                                {
                                    _targetTermGroup.Description = sourceTermGroup.Description;
                                }
                                targetClientContext.ExecuteQuery();
                                targetTermStore.CommitAll();
                                targetTermStore.RefreshLoad();

                                TermOperation op = new TermOperation();
                                op.Term      = sourceTermGroup.Name;
                                op.Id        = _changeItem.Id.ToString();
                                op.Operation = "Add";
                                op.Type      = "TermGroup";

                                _list.Add(op);
                            }
                        }
                        else if (_changeItem.Operation == ChangedOperationType.Edit)
                        {
                            TermGroup targetTermGroup = targetTermStore.GetGroup(_changeItem.Id);
                            targetClientContext.Load(targetTermGroup,
                                                     group => group.Name,
                                                     group => group.Id,
                                                     group => group.TermSets.Include(
                                                         termSet => termSet.Name,
                                                         termSet => termSet.Id));

                            targetClientContext.ExecuteQuery();
                            if (targetTermGroup.ServerObjectIsNull.Value)
                            {
                                targetTermGroup = targetTermStore.Groups.GetByName(sourceTermGroup.Name);

                                targetClientContext.Load(targetTermGroup, group => group.Name);
                                targetClientContext.ExecuteQuery();
                                if (targetTermGroup.ServerObjectIsNull.Value)
                                {
                                    noError = false;
                                    break;
                                }
                            }

                            if (targetTermGroup.Name != sourceTermGroup.Name)
                            {
                                Console.WriteLine("Modifying group: " + sourceTermGroup.Name);

                                targetTermGroup.Name = sourceTermGroup.Name;
                                TermOperation op = new TermOperation();
                                op.Term      = sourceTermGroup.Name;
                                op.Id        = _changeItem.Id.ToString();
                                op.Operation = "Modify";
                                op.Type      = "TermGroup";

                                _list.Add(op);

                                targetClientContext.ExecuteQuery();
                            }
                        }
                    }

                    if (_changeItem.ItemType == ChangedItemType.TermSet)
                    {
                        TermSet sourceTermset = sourceTermStore.GetTermSet(_changeItem.Id);
                        sourceClientContext.Load(sourceTermset, termset => termset.Name,
                                                 termset => termset.Id,
                                                 termset => termset.Description,
                                                 termset => termset.Contact,
                                                 termset => termset.CustomProperties,
                                                 termset => termset.Group, group => group.Id);
                        sourceClientContext.ExecuteQuery();
                        if (sourceTermset.ServerObjectIsNull.Value)
                        {
                            continue;
                        }
                        if (!termSetNames.Contains(sourceTermset.Name))
                        {
                            continue;
                        }

                        if (_changeItem.Operation == ChangedOperationType.DeleteObject)
                        {
                            TermSet targetTermset = targetTermStore.GetTermSet(_changeItem.Id);
                            targetClientContext.Load(targetTermset);
                            targetClientContext.ExecuteQuery();

                            Console.WriteLine("Deleting termset: " + targetTermset.Name);

                            targetTermset.DeleteObject();
                            targetClientContext.ExecuteQuery();

                            TermOperation op = new TermOperation();
                            op.Term      = targetTermset.Name;
                            op.Id        = _changeItem.Id.ToString();
                            op.Operation = "Delete";
                            op.Type      = "TermSet";

                            _list.Add(op);
                        }
                        else if (_changeItem.Operation == ChangedOperationType.Add)
                        {
                            TermGroup targetTermGroup = targetTermStore.GetGroup(sourceTermset.Group.Id);
                            targetClientContext.Load(targetTermGroup,
                                                     group => group.Name,
                                                     group => group.IsSystemGroup,
                                                     group => group.TermSets.Include(
                                                         termSet => termSet.Name, termSet => termSet.Id));
                            targetClientContext.ExecuteQuery();
                            if (targetTermGroup.ServerObjectIsNull.Value)
                            {
                                //Group may exist with another name
                                targetTermGroup = targetTermStore.Groups.GetByName(sourceTermset.Group.Name);
                                targetClientContext.Load(targetTermGroup,
                                                         group => group.Name,
                                                         group => group.IsSystemGroup,
                                                         group => group.TermSets.Include(
                                                             termSet => termSet.Name, termSet => termSet.Id));
                                targetClientContext.ExecuteQuery();
                                if (targetTermGroup.ServerObjectIsNull.Value)
                                {
                                    noError = false;
                                    break;
                                }
                            }

                            TermSet targetTermSetCheck = targetTermGroup.TermSets.GetByName(sourceTermset.Name);
                            targetClientContext.Load(targetTermSetCheck);

                            try
                            {
                                targetClientContext.ExecuteQuery();
                                if (!targetTermSetCheck.ServerObjectIsNull.Value)
                                {
                                    Console.WriteLine("Termset: " + sourceTermset.Name + " already exists");
                                    continue;
                                }
                            }
                            catch
                            {
                            }
                            Console.WriteLine("Adding termset: " + sourceTermset.Name);
                            targetTermGroup.CreateTermSet(sourceTermset.Name, _changeItem.Id, targetTermStore.DefaultLanguage);
                            TermOperation op = new TermOperation();
                            op.Term      = sourceTermset.Name;
                            op.Id        = _changeItem.Id.ToString();
                            op.Operation = "Add";
                            op.Type      = "TermSet";
                            targetClientContext.ExecuteQuery();
                            targetTermStore.CommitAll();
                            targetTermStore.RefreshLoad();

                            _list.Add(op);
                        }
                        else if (_changeItem.Operation == ChangedOperationType.Edit)
                        {
                            TermGroup targetTermGroup = null;
                            TermSet   sourceTermSet   = sourceTermStore.GetTermSet(_changeItem.Id);
                            sourceClientContext.Load(sourceTermSet, termset => termset.Name);
                            sourceClientContext.ExecuteQuery();

                            TermSet targetTermSet = targetTermStore.GetTermSet(_changeItem.Id);
                            targetClientContext.Load(targetTermSet, termset => termset.Name);
                            targetClientContext.ExecuteQuery();

                            if (targetTermSet.ServerObjectIsNull.Value)
                            {
                                targetTermGroup = targetTermStore.GetGroup(sourceTermset.Group.Id);
                                targetClientContext.Load(targetTermGroup, group => group.Name, group => group.IsSystemGroup);
                                targetClientContext.ExecuteQuery();
                                if (!targetTermGroup.ServerObjectIsNull.Value)
                                {
                                    targetTermSet = targetTermGroup.TermSets.GetByName(sourceTermSet.Name);
                                    targetClientContext.Load(targetTermSet, termset => termset.Name);
                                    targetClientContext.ExecuteQuery();
                                }
                            }

                            if (!targetTermSet.ServerObjectIsNull.Value)
                            {
                                if (targetTermSet.Name != sourceTermSet.Name)
                                {
                                    Console.WriteLine("Modifying termset: " + sourceTermSet.Name);
                                    targetTermSet.Name = sourceTermSet.Name;
                                    TermOperation op = new TermOperation();
                                    op.Term      = sourceTermSet.Name;
                                    op.Id        = _changeItem.Id.ToString();
                                    op.Operation = "Modify";
                                    op.Type      = "TermSet";

                                    _list.Add(op);
                                }
                            }
                            else
                            {
                                Console.WriteLine("Termset: " + sourceTermset.Name + " not found, creating it");
                                targetTermGroup.CreateTermSet(sourceTermset.Name, _changeItem.Id, targetTermStore.DefaultLanguage);
                                TermOperation op = new TermOperation();
                                op.Term      = sourceTermset.Name;
                                op.Id        = _changeItem.Id.ToString();
                                op.Operation = "Add";
                                op.Type      = "TermSet";

                                _list.Add(op);
                            }
                        }
                    }

                    if (_changeItem.ItemType == ChangedItemType.Term)
                    {
                        Term sourceTerm = sourceTermStore.GetTerm(_changeItem.Id);

                        sourceClientContext.Load(sourceTerm,
                                                 term => term.Name,
                                                 term => term.Description,
                                                 term => term.Id,
                                                 term => term.TermSet,
                                                 termset => termset.Id);

                        sourceClientContext.ExecuteQuery();
                        if (!sourceTerm.ServerObjectIsNull.Value)
                        {
                            TermSet sourceTermSet = sourceTermStore.GetTermSet(sourceTerm.TermSet.Id);
                            sourceClientContext.Load(sourceTermSet,
                                                     termset => termset.Name,
                                                     termset => termset.Id,
                                                     termset => termset.Group);
                            sourceClientContext.ExecuteQuery();


                            if (!sourceTermSet.ServerObjectIsNull.Value)
                            {
                                if (!termSetNames.Contains(sourceTermSet.Name))
                                {
                                    continue;
                                }
                            }


                            TermSet targetTermSet = targetTermStore.GetTermSet(sourceTerm.TermSet.Id);
                            targetClientContext.Load(targetTermSet, termset => termset.Name);
                            targetClientContext.ExecuteQuery();
                            if (targetTermSet.ServerObjectIsNull.Value)
                            {
                                noError = false;
                                break;
                            }


                            if (_changeItem.Operation == ChangedOperationType.DeleteObject)
                            {
                                Term targetTerm = targetTermStore.GetTerm(_changeItem.Id);
                                targetClientContext.Load(targetTerm);
                                targetClientContext.ExecuteQuery();

                                Console.WriteLine("Deleting term: " + sourceTerm.Name);

                                targetTerm.DeleteObject();
                                TermOperation op = new TermOperation();
                                op.Term      = sourceTerm.Name;
                                op.Id        = _changeItem.Id.ToString();
                                op.Operation = "Delete";
                                op.Type      = "Term";
                                _list.Add(op);
                            }

                            else if (_changeItem.Operation == ChangedOperationType.Add)
                            {
                                Term targetTerm = targetTermStore.GetTerm(sourceTerm.Id);
                                targetClientContext.Load(targetTerm);
                                targetClientContext.ExecuteQuery();

                                if (targetTerm.ServerObjectIsNull.Value)
                                {
                                    Console.WriteLine("Creating term: " + sourceTerm.Name);

                                    Term _targetTerm = targetTermSet.CreateTerm(sourceTerm.Name, targetTermStore.DefaultLanguage, _changeItem.Id);
                                    if (!string.IsNullOrEmpty(sourceTerm.Description))
                                    {
                                        _targetTerm.SetDescription(sourceTerm.Description, targetTermStore.DefaultLanguage);
                                    }
                                    //GetLabels from Source



                                    targetClientContext.ExecuteQuery();
                                    TermOperation op = new TermOperation();
                                    op.Term      = sourceTerm.Name;
                                    op.Id        = _changeItem.Id.ToString();
                                    op.Operation = "Add";
                                    op.Type      = "Term";

                                    _list.Add(op);
                                }
                            }
                            else if (_changeItem.Operation == ChangedOperationType.Edit)
                            {
                                Term targetTerm = targetTermStore.GetTerm(_changeItem.Id);
                                targetClientContext.Load(targetTerm, term => term.Name);
                                targetClientContext.ExecuteQuery();

                                if (!targetTerm.ServerObjectIsNull.Value)
                                {
                                    if (targetTerm.Name != sourceTerm.Name)
                                    {
                                        targetTerm.Name = sourceTerm.Name;
                                        TermOperation op = new TermOperation();
                                        op.Term      = sourceTerm.Name;
                                        op.Id        = _changeItem.Id.ToString();
                                        op.Operation = "Modify";
                                        op.Type      = "Term";

                                        _list.Add(op);
                                    }
                                }
                                else
                                {
                                    try
                                    {
                                        Term _targetTerm = targetTermSet.CreateTerm(sourceTerm.Name, targetTermStore.DefaultLanguage, _changeItem.Id);
                                        if (!string.IsNullOrEmpty(sourceTerm.Description))
                                        {
                                            _targetTerm.SetDescription(sourceTerm.Description, targetTermStore.DefaultLanguage);
                                        }
                                        targetClientContext.ExecuteQuery();
                                        Console.WriteLine("Term: " + sourceTerm.Name + " not found, creating it");
                                        TermOperation op = new TermOperation();
                                        op.Term      = sourceTerm.Name;
                                        op.Id        = _changeItem.Id.ToString();
                                        op.Operation = "Add";
                                        op.Type      = "Term";
                                        _list.Add(op);
                                    }
                                    catch
                                    {
                                    }
                                }
                            }
                        }
                    }
                }
                if (noError)
                {
                    targetClientContext.ExecuteQuery();
                    targetTermStore.CommitAll();
                }
            }
        }
        public override CanProvisionResult CanProvision(Web web, ProvisioningTemplate template, ProvisioningTemplateApplyingInformation applyingInformation)
        {
            // Prepare the default output
            var result = new CanProvisionResult();

#if !ONPREMISES
            Model.ProvisioningTemplate targetTemplate = null;

            if (template.ParentHierarchy != null)
            {
                // If we have a hierarchy, search for a template with Taxonomy settings, if any
                targetTemplate = template.ParentHierarchy.Templates.FirstOrDefault(t => t.TermGroups.Count > 0);

                if (targetTemplate == null)
                {
                    // or use the first in the hierarchy
                    targetTemplate = template.ParentHierarchy.Templates[0];
                }
            }
            else
            {
                // Otherwise, use the provided template
                targetTemplate = template;
            }


            // Verify if we need the Term Store permissions (i.e. the template contains term groups to provision, or sequences with TermStore settings)
            if ((targetTemplate.TermGroups != null && targetTemplate.TermGroups?.Count > 0) ||
                targetTemplate.ParentHierarchy.Sequences.Any(
                    s => s.TermStore?.TermGroups != null && s.TermStore?.TermGroups?.Count > 0))
            {
                using (var scope = new PnPMonitoredScope(this.Name))
                {
                    try
                    {
                        // Try to access the Term Store
                        TaxonomySession taxSession = TaxonomySession.GetTaxonomySession(web.Context);
                        TermStore       termStore  = taxSession.GetDefaultKeywordsTermStore();
                        web.Context.Load(termStore,
                                         ts => ts.Languages,
                                         ts => ts.DefaultLanguage,
                                         ts => ts.Groups.Include(
                                             tg => tg.Name,
                                             tg => tg.Id,
                                             tg => tg.TermSets.Include(
                                                 tset => tset.Name,
                                                 tset => tset.Id)));
                        var siteCollectionTermGroup = termStore.GetSiteCollectionGroup((web.Context as ClientContext).Site, false);
                        web.Context.Load(siteCollectionTermGroup);
                        web.Context.ExecuteQueryRetry();

                        var termGroupId = Guid.NewGuid();
                        var group       = termStore.CreateGroup($"Temp-{termGroupId.ToString()}", termGroupId);
                        termStore.CommitAll();
                        web.Context.Load(group);
                        web.Context.ExecuteQueryRetry();

                        // Now delete the just created termGroup, to cleanup the Term Store
                        group.DeleteObject();
                        web.Context.ExecuteQueryRetry();
                    }
                    catch (Exception ex)
                    {
                        // And if we fail, raise a CanProvisionIssue
                        result.CanProvision = false;
                        result.Issues.Add(new CanProvisionIssue()
                        {
                            Source              = this.Name,
                            Tag                 = CanProvisionIssueTags.MISSING_TERMSTORE_PERMISSIONS,
                            Message             = CanProvisionIssuesMessages.Term_Store_Not_Admin,
                            ExceptionMessage    = ex.Message,    // Here we have a specific exception
                            ExceptionStackTrace = ex.StackTrace, // Here we have a specific exception
                        });
                    }
                }
            }
#else
            result.CanProvision = false;
#endif
            return(result);
        }
Пример #23
0
        public override TokenParser ProvisionObjects(Web web, Model.ProvisioningTemplate template, TokenParser parser, ProvisioningTemplateApplyingInformation applyingInformation)
        {
            using (var scope = new PnPMonitoredScope(this.Name))
            {
                TaxonomySession taxSession = TaxonomySession.GetTaxonomySession(web.Context);

                var termStore = taxSession.GetDefaultKeywordsTermStore();

                web.Context.Load(termStore,
                                 ts => ts.DefaultLanguage,
                                 ts => ts.Groups.Include(
                                     tg => tg.Name,
                                     tg => tg.Id,
                                     tg => tg.TermSets.Include(
                                         tset => tset.Name,
                                         tset => tset.Id)));
                web.Context.ExecuteQueryRetry();

                SiteCollectionTermGroupNameToken siteCollectionTermGroupNameToken = new SiteCollectionTermGroupNameToken(web);
                foreach (var modelTermGroup in template.TermGroups)
                {
                    #region Group

                    var newGroup = false;

                    TermGroup group = termStore.Groups.FirstOrDefault(
                        g => g.Id == modelTermGroup.Id || g.Name == modelTermGroup.Name);
                    if (group == null)
                    {
                        if (modelTermGroup.Name == "Site Collection" ||
                            parser.ParseString(modelTermGroup.Name) == siteCollectionTermGroupNameToken.GetReplaceValue() ||
                            modelTermGroup.SiteCollectionTermGroup)
                        {
                            var site = (web.Context as ClientContext).Site;
                            group = termStore.GetSiteCollectionGroup(site, true);
                            web.Context.Load(group, g => g.Name, g => g.Id, g => g.TermSets.Include(
                                                 tset => tset.Name,
                                                 tset => tset.Id));
                            web.Context.ExecuteQueryRetry();
                        }
                        else
                        {
                            var parsedGroupName = parser.ParseString(modelTermGroup.Name);
                            group = termStore.Groups.FirstOrDefault(g => g.Name == parsedGroupName);

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

                                group.Description = modelTermGroup.Description;

                                #if !ONPREMISES
                                // 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);
                                    }
                                }
                                #endif

                                termStore.CommitAll();
                                web.Context.Load(group);
                                web.Context.ExecuteQueryRetry();

                                newGroup = true;
                            }
                        }
                    }

                    #endregion

                    #region TermSets

                    foreach (var modelTermSet in modelTermGroup.TermSets)
                    {
                        TermSet set        = null;
                        var     newTermSet = false;
                        if (!newGroup)
                        {
                            set = group.TermSets.FirstOrDefault(ts => ts.Id == modelTermSet.Id || ts.Name == modelTermSet.Name);
                        }
                        if (set == null)
                        {
                            if (modelTermSet.Id == Guid.Empty)
                            {
                                modelTermSet.Id = Guid.NewGuid();
                            }
                            set = group.CreateTermSet(parser.ParseString(modelTermSet.Name), modelTermSet.Id, modelTermSet.Language ?? termStore.DefaultLanguage);
                            parser.AddToken(new TermSetIdToken(web, group.Name, modelTermSet.Name, modelTermSet.Id));
                            newTermSet                = true;
                            set.Description           = 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 = modelTermSet.Owner;
                            }
                            termStore.CommitAll();
                            web.Context.Load(set);
                            web.Context.ExecuteQueryRetry();
                        }

                        web.Context.Load(set, s => s.Terms.Include(t => t.Id, t => t.Name));
                        web.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)
                                    {
                                        term = terms.FirstOrDefault(t => t.Name == modelTerm.Name);
                                        if (term == null)
                                        {
                                            var returnTuple = CreateTerm <TermSet>(web, modelTerm, set, termStore, parser, scope);
                                            modelTerm.Id = returnTuple.Item1;
                                            parser       = returnTuple.Item2;
                                        }
                                        else
                                        {
                                            modelTerm.Id = term.Id;
                                        }
                                    }
                                    else
                                    {
                                        modelTerm.Id = term.Id;
                                    }
                                }
                                else
                                {
                                    var returnTuple = CreateTerm <TermSet>(web, modelTerm, set, termStore, parser, scope);
                                    modelTerm.Id = returnTuple.Item1;
                                    parser       = returnTuple.Item2;
                                }
                            }
                            else
                            {
                                var returnTuple = CreateTerm <TermSet>(web, modelTerm, set, termStore, parser, scope);
                                modelTerm.Id = returnTuple.Item1;
                                parser       = returnTuple.Item2;
                            }
                        }

                        // do we need custom sorting?
                        if (modelTermSet.Terms.Any(t => t.CustomSortOrder > -1))
                        {
                            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();
                            web.Context.ExecuteQueryRetry();
                        }
                    }

                    #endregion
                }
            }
            return(parser);
        }
Пример #24
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);
                    var             termStore = session.GetDefaultSiteCollectionTermStore();
                    web.Context.Load(termStore, t => t.Id, t => t.DefaultLanguage, t => t.OrphanedTermsTermSet);
                    web.Context.ExecuteQueryRetry();

                    var 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 = string.Format("SiteCollectionGroupId{0}", termStore.Id);

                    var siteCollectionTermGroupId = web.GetPropertyBagValueString(propertyBagKey, "");

                    Guid termGroupGuid = Guid.Empty;
                    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.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
                        };

                        foreach (var termSet in termGroup.TermSets.Where(ts => ts.Id != orphanedTermsTermSetId))
                        {
                            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)
                            {
                                modelTermSet.Properties.Add(property.Key, property.Value);
                            }
                            modelTermGroup.TermSets.Add(modelTermSet);
                        }

                        template.TermGroups.Add(modelTermGroup);
                    }
                }
            }
            return(template);
        }
Пример #25
0
        public static TaxonomyItem GetTaxonomyItemByPath(this Site site, string path, string delimiter = "|")
        {
            var context = site.Context;

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

            var pathSplit = path.Split(new string[] { delimiter }, StringSplitOptions.RemoveEmptyEntries);

            TaxonomySession tSession = TaxonomySession.GetTaxonomySession(context);
            TermStore       ts       = tSession.GetDefaultKeywordsTermStore();

            var groups = context.LoadQuery(ts.Groups);

            context.ExecuteQuery();

            var group = groups.FirstOrDefault(l => l.Name.Equals(pathSplit[0], StringComparison.CurrentCultureIgnoreCase));

            if (group == null)
            {
                return(null);
            }
            if (pathSplit.Length == 1)
            {
                return(group);
            }

            var termSets = context.LoadQuery(group.TermSets);

            context.ExecuteQuery();

            var termSet = termSets.FirstOrDefault(l => l.Name.Equals(pathSplit[1], StringComparison.CurrentCultureIgnoreCase));

            if (termSet == null)
            {
                return(null);
            }
            if (pathSplit.Length == 2)
            {
                return(termSet);
            }

            Term term = null;

            for (int i = 2; i < pathSplit.Length; i++)
            {
                IEnumerable <Term> termColl = context.LoadQuery(i == 2 ? termSet.Terms : term.Terms);
                context.ExecuteQuery();

                term = termColl.FirstOrDefault(l => l.Name.Equals(pathSplit[i], StringComparison.OrdinalIgnoreCase));

                if (term == null)
                {
                    return(null);
                }
            }

            return(term);
        }
Пример #26
0
        public override void ProvisionObjects(Microsoft.SharePoint.Client.Web web, Model.ProvisioningTemplate template, ProvisioningTemplateApplyingInformation applyingInformation)
        {
            Log.Info(Constants.LOGGING_SOURCE_FRAMEWORK_PROVISIONING, CoreResources.Provisioning_ObjectHandlers_TermGroups);

            TaxonomySession taxSession = TaxonomySession.GetTaxonomySession(web.Context);

            var termStore = taxSession.GetDefaultKeywordsTermStore();

            web.Context.Load(termStore,
                             ts => ts.DefaultLanguage,
                             ts => ts.Groups.Include(
                                 tg => tg.Name,
                                 tg => tg.Id,
                                 tg => tg.TermSets.Include(
                                     tset => tset.Name,
                                     tset => tset.Id)));
            web.Context.ExecuteQueryRetry();

            foreach (var modelTermGroup in template.TermGroups)
            {
                #region Group

                var newGroup = false;

                TermGroup group = termStore.Groups.FirstOrDefault(g => g.Id == modelTermGroup.Id);
                if (group == null)
                {
                    group = termStore.Groups.FirstOrDefault(g => g.Name == modelTermGroup.Name);

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

                        group.Description = modelTermGroup.Description;

                        termStore.CommitAll();
                        web.Context.Load(group);
                        web.Context.ExecuteQueryRetry();

                        newGroup = true;
                    }
                }

                #endregion

                #region TermSets

                foreach (var modelTermSet in modelTermGroup.TermSets)
                {
                    TermSet set        = null;
                    var     newTermSet = false;
                    if (!newGroup)
                    {
                        set = group.TermSets.FirstOrDefault(ts => ts.Id == modelTermSet.Id);
                        if (set == null)
                        {
                            set = group.TermSets.FirstOrDefault(ts => ts.Name == modelTermSet.Name);
                        }
                    }
                    if (set == null)
                    {
                        if (modelTermSet.Id == Guid.Empty)
                        {
                            modelTermSet.Id = Guid.NewGuid();
                        }
                        set = group.CreateTermSet(modelTermSet.Name.ToParsedString(), modelTermSet.Id, modelTermSet.Language ?? termStore.DefaultLanguage);
                        TokenParser.AddToken(new TermSetIdToken(web, modelTermGroup.Name, modelTermSet.Name, modelTermSet.Id));
                        newTermSet = true;
                        set.IsOpenForTermCreation = modelTermSet.IsOpenForTermCreation;
                        set.IsAvailableForTagging = modelTermSet.IsAvailableForTagging;
                        foreach (var property in modelTermSet.Properties)
                        {
                            set.SetCustomProperty(property.Key, property.Value);
                        }
                        if (modelTermSet.Owner != null)
                        {
                            set.Owner = modelTermSet.Owner;
                        }
                        termStore.CommitAll();
                        web.Context.Load(set);
                        web.Context.ExecuteQueryRetry();
                    }

                    web.Context.Load(set, s => s.Terms.Include(t => t.Id, t => t.Name));
                    web.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)
                                {
                                    term = terms.FirstOrDefault(t => t.Name == modelTerm.Name);
                                    if (term == null)
                                    {
                                        modelTerm.Id = CreateTerm <TermSet>(web, modelTerm, set, termStore);
                                    }
                                    else
                                    {
                                        modelTerm.Id = term.Id;
                                    }
                                }
                                else
                                {
                                    modelTerm.Id = term.Id;
                                }
                            }
                            else
                            {
                                modelTerm.Id = CreateTerm <TermSet>(web, modelTerm, set, termStore);
                            }
                        }
                        else
                        {
                            modelTerm.Id = CreateTerm <TermSet>(web, modelTerm, set, termStore);
                        }
                    }

                    // do we need custom sorting?
                    if (modelTermSet.Terms.Any(t => t.CustomSortOrder > -1))
                    {
                        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();
                        web.Context.ExecuteQueryRetry();
                    }
                }

                #endregion
            }
        }