Exemple #1
0
        public void ImportTermSetShouldUpdateSetTest()
        {
            using (var clientContext = TestCommon.CreateClientContext())
            {
                var taxSession = TaxonomySession.GetTaxonomySession(clientContext);
                var termStore  = taxSession.GetDefaultSiteCollectionTermStore();
                clientContext.Load(termStore, s => s.DefaultLanguage);
                clientContext.ExecuteQueryRetry();
                var lcid = termStore.DefaultLanguage;

                var termGroup = termStore.GetGroup(_termGroupId);
                var termSet   = termGroup.CreateTermSet("Test Changes", UpdateTermSetId, lcid);
                termSet.Description = "Initial term set description";
                var retain1 = termSet.CreateTerm("Retain1", lcid, Guid.NewGuid());
                retain1.SetDescription("Test of deletes, adds and update", lcid);
                var update2 = retain1.CreateTerm("Update2", lcid, Guid.NewGuid());
                update2.SetDescription("Initial update2 description", lcid);
                var retain3 = update2.CreateTerm("Retain3", lcid, Guid.NewGuid());
                retain3.SetDescription("Test retaining same term", lcid);
                var delete2 = retain1.CreateTerm("Delete2", lcid, Guid.NewGuid());
                delete2.SetDescription("Term to delete", lcid);
                var delete3 = delete2.CreateTerm("Delete3", lcid, Guid.NewGuid());
                delete3.SetDescription("Child term to delete", lcid);
                clientContext.ExecuteQueryRetry();
            }

            using (var clientContext = TestCommon.CreateClientContext())
            {
                var taxSession = TaxonomySession.GetTaxonomySession(clientContext);
                var termStore  = taxSession.GetDefaultSiteCollectionTermStore();
                var termGroup  = termStore.GetGroup(_termGroupId);

                // Act
                var termSet = termGroup.ImportTermSet(SampleUpdateTermSetPath, UpdateTermSetId, synchroniseDeletions: true, termSetIsOpen: true);
            }

            using (var clientContext = TestCommon.CreateClientContext())
            {
                var taxSession     = TaxonomySession.GetTaxonomySession(clientContext);
                var termStore      = taxSession.GetDefaultSiteCollectionTermStore();
                var createdSet     = termStore.GetTermSet(UpdateTermSetId);
                var allTerms       = createdSet.GetAllTerms();
                var rootCollection = createdSet.Terms;
                clientContext.Load(createdSet);
                clientContext.Load(allTerms);
                clientContext.Load(rootCollection, ts => ts.Include(t => t.Name, t => t.Description, t => t.IsAvailableForTagging));
                clientContext.ExecuteQueryRetry();

                Assert.AreEqual("Updated term set description", createdSet.Description);
                Assert.IsTrue(createdSet.IsOpenForTermCreation);
                Assert.AreEqual(6, allTerms.Count);
                Assert.AreEqual(2, rootCollection.Count);

                var retain1Collection = rootCollection.First(t => t.Name == "Retain1").Terms;
                clientContext.Load(retain1Collection, ts => ts.Include(t => t.Name, t => t.Description, t => t.IsAvailableForTagging));
                clientContext.ExecuteQueryRetry();

                Assert.IsTrue(retain1Collection.Any(t => t.Name == "New2"));
                Assert.IsFalse(retain1Collection.Any(t => t.Name == "Delete2"));
                Assert.AreEqual("Changed description", retain1Collection.First(t => t.Name == "Update2").Description);
                Assert.IsFalse(retain1Collection.First(t => t.Name == "Update2").IsAvailableForTagging);
            }
        }
Exemple #2
0
        private bool IsFieldXmlValid(string fieldXml, TokenParser parser, ClientRuntimeContext context)
        {
            var isValid        = true;
            var leftOverTokens = parser.GetLeftOverTokens(fieldXml);

            if (!leftOverTokens.Any())
            {
                var fieldElement = XElement.Parse(fieldXml);
                if (fieldElement.Attribute("Type").Value == "TaxonomyFieldType")
                {
                    var termStoreIdElement =
                        fieldElement.XPathSelectElement("//ArrayOfProperty/Property[Name='SspId']/Value");
                    if (termStoreIdElement != null)
                    {
                        var termStoreId = Guid.Parse(termStoreIdElement.Value);
                        var taxSession  = TaxonomySession.GetTaxonomySession(context);
                        try
                        {
                            taxSession.EnsureProperty(t => t.TermStores);
                            var store = taxSession.TermStores.GetById(termStoreId);
                            context.Load(store);
                            context.ExecuteQueryRetry();
                            if (store.ServerObjectIsNull.HasValue && !store.ServerObjectIsNull.Value)
                            {
                                var termSetIdElement =
                                    fieldElement.XPathSelectElement("//ArrayOfProperty/Property[Name='TermSetId']/Value");
                                if (termSetIdElement != null)
                                {
                                    var termSetId = Guid.Parse(termSetIdElement.Value);
                                    try
                                    {
                                        var termSet = store.GetTermSet(termSetId);
                                        context.Load(termSet);
                                        context.ExecuteQueryRetry();
                                        isValid = termSet.ServerObjectIsNull.HasValue &&
                                                  !termSet.ServerObjectIsNull.Value;
                                    }
                                    catch (Exception)
                                    {
                                        isValid = false;
                                    }
                                }
                            }
                        }
                        catch (Exception)
                        {
                            isValid = false;
                        }
                    }
                    else
                    {
                        isValid = false;
                    }
                }
            }
            else
            {
                //Some tokens where not replaced
                isValid = false;
            }
            return(isValid);
        }
Exemple #3
0
        protected override void ExecuteCmdlet()
        {
            var taxonomySession = TaxonomySession.GetTaxonomySession(ClientContext);
            // Get Term Store
            var termStore = default(TermStore);

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

            TermGroup termGroup = null;

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

            TermSet termSet;

            if (TermSet.Id != Guid.Empty)
            {
                termSet = termGroup.TermSets.GetById(TermSet.Id);
            }
            else if (!string.IsNullOrEmpty(TermSet.Title))
            {
                termSet = termGroup.TermSets.GetByName(TermSet.Title);
            }
            else
            {
                termSet = TermSet.Item;
            }

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

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

            var customProperties = CustomProperties ?? new Hashtable();

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

            var localCustomProperties = LocalCustomProperties ?? new Hashtable();

            foreach (var key in localCustomProperties.Keys)
            {
                term.SetCustomProperty(key as string, localCustomProperties[key] as string);
            }
            termStore.CommitAll();
            ClientContext.Load(term);
            ClientContext.ExecuteQueryRetry();
            WriteObject(term);
        }
        private void AddTermStoreTokens(Web web)
        {
            TaxonomySession session = TaxonomySession.GetTaxonomySession(web.Context);

            var termStores = session.EnsureProperty(s => s.TermStores);

            foreach (var ts in termStores)
            {
                _tokens.Add(new TermStoreIdToken(web, ts.Name, ts.Id));
            }
            var termStore = session.GetDefaultSiteCollectionTermStore();

            web.Context.Load(termStore);
            web.Context.ExecuteQueryRetry();
            if (!termStore.ServerObjectIsNull.Value)
            {
                web.Context.Load(termStore.Groups,
                                 g => g.Include(
                                     tg => tg.Name,
                                     tg => tg.TermSets.Include(
                                         ts => ts.Name,
                                         ts => ts.Id)
                                     ));
                web.Context.ExecuteQueryRetry();
                foreach (var termGroup in termStore.Groups)
                {
                    foreach (var termSet in termGroup.TermSets)
                    {
                        _tokens.Add(new TermSetIdToken(web, termGroup.Name, termSet.Name, termSet.Id));
                    }
                }
            }

            // SiteCollection TermSets, only when we're not working in app-only
            if (!web.Context.IsAppOnly())
            {
                _tokens.Add(new SiteCollectionTermGroupIdToken(web));
                _tokens.Add(new SiteCollectionTermGroupNameToken(web));

                var site = (web.Context as ClientContext).Site;
                var siteCollectionTermGroup = termStore.GetSiteCollectionGroup(site, true);
                web.Context.Load(siteCollectionTermGroup);
                try
                {
                    web.Context.ExecuteQueryRetry();
                    if (null != siteCollectionTermGroup && !siteCollectionTermGroup.ServerObjectIsNull.Value)
                    {
                        web.Context.Load(siteCollectionTermGroup, group => group.TermSets.Include(ts => ts.Name, ts => ts.Id));
                        web.Context.ExecuteQueryRetry();
                        foreach (var termSet in siteCollectionTermGroup.TermSets)
                        {
                            _tokens.Add(new SiteCollectionTermSetIdToken(web, termSet.Name, termSet.Id));
                        }
                    }
                }
                catch (ServerUnauthorizedAccessException)
                {
                    // If we don't have permission to access the TermGroup, just skip it
                }
                catch (NullReferenceException)
                {
                    // If there isn't a default TermGroup for the Site Collection, we skip the terms in token handler
                }
            }
        }
        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);
        }
        protected override void ExecuteCmdlet()
        {
            var taxonomySession = TaxonomySession.GetTaxonomySession(ClientContext);
            // Get Term Store
            TermStore termStore = null;

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

            var termGroup = TermGroup.GetGroup(termStore);

            if (Identity != null)
            {
                var termSet = Identity.GetTermSet(termGroup);

                ClientContext.Load(termSet, t => t.CustomProperties);
                ClientContext.ExecuteQueryRetry();
                if (termSet.ServerObjectIsNull.Value == false)
                {
                    bool updateRequired = false;
                    if (ParameterSpecified(nameof(Name)))
                    {
                        termSet.Name   = Name;
                        updateRequired = true;
                    }
                    if (ParameterSpecified(nameof(Description)))
                    {
                        termSet.Description = Description;
                        updateRequired      = true;
                    }
                    if (ParameterSpecified(nameof(Owner)))
                    {
                        termSet.Owner  = Owner;
                        updateRequired = true;
                    }
                    if (ParameterSpecified(nameof(Contact)))
                    {
                        termSet.Contact = Contact;
                        updateRequired  = true;
                    }
                    if (ParameterSpecified(nameof(CustomProperties)))
                    {
                        var enumerator = termSet.CustomProperties.GetEnumerator();
                        while (enumerator.MoveNext())
                        {
                            var prop = enumerator.Current;
                            if (!prop.Key.StartsWith("_Sys_"))
                            {
                                termSet.DeleteCustomProperty(prop.Key);
                            }
                        }

                        foreach (var entry in CustomProperties.Cast <DictionaryEntry>().ToDictionary(kvp => (string)kvp.Key, kvp => (string)kvp.Value))
                        {
                            termSet.SetCustomProperty(entry.Key, entry.Value);
                        }
                        updateRequired = true;
                    }
                    if (ParameterSpecified(nameof(StakeholderToAdd)))
                    {
                        termSet.AddStakeholder(StakeholderToAdd);
                        updateRequired = true;
                    }
                    if (ParameterSpecified(nameof(StakeholderToDelete)))
                    {
                        termSet.DeleteStakeholder(StakeholderToDelete);
                        updateRequired = true;
                    }
                    if (ParameterSpecified(nameof(IsAvailableForTagging)))
                    {
                        termSet.IsAvailableForTagging = IsAvailableForTagging;
                        updateRequired = true;
                    }
                    if (ParameterSpecified(nameof(IsOpenForTermCreation)))
                    {
                        termSet.IsOpenForTermCreation = IsOpenForTermCreation;
                        updateRequired = true;
                    }
                    if (ParameterSpecified(nameof(UseForSiteNavigation)))
                    {
                        if (UseForSiteNavigation)
                        {
                            if (!termSet.CustomProperties.ContainsKey("_Sys_Nav_IsNavigationTermSet"))
                            {
                                termSet.SetCustomProperty("_Sys_Nav_IsNavigationTermSet", "True");
                                updateRequired = true;
                            }
                        }
                        else
                        {
                            if (termSet.CustomProperties.ContainsKey("_Sys_Nav_IsNavigationTermSet"))
                            {
                                termSet.DeleteCustomProperty("_Sys_Nav_IsNavigationTermSet");
                                updateRequired = true;
                            }
                        }
                    }
                    if (ParameterSpecified(nameof(UseForFacetedNavigation)))
                    {
                        if (UseForFacetedNavigation)
                        {
                            if (!termSet.CustomProperties.ContainsKey("_Sys_Facet_IsFacetedTermSet"))
                            {
                                termSet.SetCustomProperty("_Sys_Facet_IsFacetedTermSet", "True");
                                updateRequired = true;
                            }
                        }
                        else
                        {
                            if (termSet.CustomProperties.ContainsKey("_Sys_Facet_IsFacetedTermSet"))
                            {
                                termSet.DeleteCustomProperty("_Sys_Facet_IsFacetedTermSet");
                                updateRequired = true;
                            }
                        }
                    }
                    if (ParameterSpecified(nameof(SetTargetPageForTerms)) && ParameterSpecified(nameof(RemoveTargetPageforTerms)))
                    {
                        throw new PSArgumentException("Cannot both set and remove the target page for this termset. Either use SetTargetPageForTerms or RemoveTargetPageForTerms");
                    }
                    else
                    {
                        if (ParameterSpecified(nameof(SetTargetPageForTerms)))
                        {
                            termSet.SetCustomProperty("_Sys_Nav_TargetUrlForChildTerms", SetTargetPageForTerms);
                            updateRequired = true;
                        }
                        if (ParameterSpecified(nameof(RemoveTargetPageforTerms)))
                        {
                            termSet.DeleteCustomProperty("_Sys_Nav_TargetUrlForChildTerms");
                            updateRequired = true;
                        }
                    }

                    if (ParameterSpecified(nameof(SetCatalogItemPageForCategories)) && ParameterSpecified(nameof(RemoveCatalogItemPageForCategories)))
                    {
                        throw new PSArgumentException("Cannot both set and remove the catalog page for this termset. Either use SetCatalogItemPageForCategories or RemoveCatalogItemPageForCategories");
                    }
                    else
                    {
                        if (ParameterSpecified(nameof(SetCatalogItemPageForCategories)))
                        {
                            termSet.SetCustomProperty("_Sys_Nav_CatalogTargetUrlForChildTerms", SetTargetPageForTerms);
                            updateRequired = true;
                        }
                        if (ParameterSpecified(nameof(RemoveCatalogItemPageForCategories)))
                        {
                            termSet.DeleteCustomProperty("_Sys_Nav_CatalogTargetUrlForChildTerms");
                            updateRequired = true;
                        }
                    }

                    if (updateRequired)
                    {
                        termStore.CommitAll();
                        ClientContext.ExecuteQueryRetry();
                    }
                }
                else
                {
                    throw new PSArgumentException("Cannot find termset");
                }
            }
        }
Exemple #7
0
        protected void TokenizeManagedNavigationTaxonomyIds(Web web, ManagedNavigation managedNavigation)
        {
            // Replace Taxonomy field references to SspId, TermSetId with tokens
            TaxonomySession session                 = TaxonomySession.GetTaxonomySession(web.Context);
            TermStore       defaultStore            = session.GetDefaultSiteCollectionTermStore();
            var             site                    = (web.Context as ClientContext).Site;
            var             siteCollectionTermGroup = defaultStore.GetSiteCollectionGroup(site, false);

            web.Context.Load(siteCollectionTermGroup, t => t.Name);
            web.Context.ExecuteQueryRetry();
            string siteCollectionTermGroupName = null;

            if (!siteCollectionTermGroup.ServerObjectIsNull.Value)
            {
                siteCollectionTermGroupName = siteCollectionTermGroup.Name;
            }
            web.Context.Load(defaultStore, ts => ts.Name, ts => ts.Id);
            web.Context.ExecuteQueryRetry();

            Guid navigationTermStoreId = Guid.Parse(managedNavigation.TermStoreId);

            if (navigationTermStoreId != Guid.Empty)
            {
                TermStore navigationTermStore = session.TermStores.GetById(navigationTermStoreId);
                web.Context.Load(navigationTermStore, ts => ts.Name, ts => ts.Id);
                web.Context.ExecuteQueryRetry();

                if (!navigationTermStore.ServerObjectIsNull())
                {
                    if (navigationTermStore.Id == defaultStore.Id)
                    {
                        managedNavigation.TermStoreId = "{sitecollectiontermstoreid}";
                    }
                    else
                    {
                        managedNavigation.TermStoreId = $"{{termstoreid:{navigationTermStore.Name}}}";
                    }

                    Guid navigationTermSetId = Guid.Parse(managedNavigation.TermSetId);
                    if (navigationTermSetId != Guid.Empty)
                    {
                        var navigationTermSet = navigationTermStore.GetTermSet(navigationTermSetId);
                        web.Context.Load(navigationTermSet, ts => ts.Name, ts => ts.Id, ts => ts.Group);
                        web.Context.ExecuteQueryRetry();

                        if (!navigationTermSet.ServerObjectIsNull())
                        {
                            if (navigationTermSet.Group.Name == siteCollectionTermGroupName)
                            {
                                managedNavigation.TermSetId = $"{{sitecollectiontermsetid:{navigationTermSet.Name}}}";
                            }
                            else
                            {
                                managedNavigation.TermSetId =
                                    $"{{termsetid:{navigationTermSet.Group.Name}:{navigationTermSet.Name}}}";
                            }
                        }
                    }
                }
            }
        }
        protected override void ExecuteCmdlet()
        {
            DefaultRetrievalExpressions = new Expression <Func <TermSet, object> >[] { g => g.Name, g => g.Id };
            var taxonomySession = TaxonomySession.GetTaxonomySession(ClientContext);
            // Get Term Store
            TermStore termStore = null;

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

            TermGroup termGroup = null;

            if (TermGroup.Id != Guid.Empty)
            {
                termGroup = termStore.Groups.GetById(TermGroup.Id);
            }
            else if (!string.IsNullOrEmpty(TermGroup.Name))
            {
                termGroup = termStore.Groups.GetByName(TermGroup.Name);
            }
            if (Identity != null)
            {
                var termSet = default(TermSet);
                if (Identity.IdValue != Guid.Empty)
                {
                    termSet = termGroup.TermSets.GetById(Identity.IdValue);
                }
                else
                {
                    termSet = termGroup.TermSets.GetByName(Identity.StringValue);
                }
                ClientContext.Load(termSet, RetrievalExpressions);
                ClientContext.ExecuteQueryRetry();
                WriteObject(termSet);
            }
            else
            {
                var query    = termGroup.TermSets.IncludeWithDefaultProperties(RetrievalExpressions);
                var termSets = ClientContext.LoadQuery(query);
                ClientContext.ExecuteQueryRetry();
                WriteObject(termSets, true);
            }
        }
Exemple #9
0
        public void CanProvisionObjects()
        {
            if (TestCommon.AppOnlyTesting())
            {
                Assert.Inconclusive("Taxonomy tests are not supported when testing using app-only");
            }

            var template     = new ProvisioningTemplate();
            var listInstance = new Core.Framework.Provisioning.Model.ListInstance();

            listInstance.Url          = string.Format("lists/{0}", listName);
            listInstance.Title        = listName;
            listInstance.TemplateType = (int)ListTemplateType.GenericList;
            listInstance.FieldRefs.Add(new FieldRef()
            {
                Id = new Guid("23f27201-bee3-471e-b2e7-b64fd8b7ca38")
            });

            using (var ctx = TestCommon.CreateClientContext())
            {
                //Create term
                var taxSession = TaxonomySession.GetTaxonomySession(ctx);
                var termStore  = taxSession.GetDefaultSiteCollectionTermStore();

                // Termgroup
                termGroupId = Guid.NewGuid();
                var termGroup = termStore.CreateGroup("Test_Group_" + DateTime.Now.ToFileTime(), termGroupId);
                ctx.Load(termGroup);

                var termSet = termGroup.CreateTermSet("Test_Termset_" + DateTime.Now.ToFileTime(), Guid.NewGuid(), 1033);
                ctx.Load(termSet);

                Guid   termId   = Guid.NewGuid();
                string termName = "Test_Term_" + DateTime.Now.ToFileTime();

                termSet.CreateTerm(termName, 1033, termId);

                Dictionary <string, string> dataValues = new Dictionary <string, string>();
                dataValues.Add("Title", "Test");
                dataValues.Add("TaxKeyword", $"{termName}|{termId.ToString()}");
                DataRow dataRow = new DataRow(dataValues);

                listInstance.DataRows.Add(dataRow);

                template.Lists.Add(listInstance);


                var parser = new TokenParser(ctx.Web, template);

                // Create the List
                parser = new ObjectListInstance().ProvisionObjects(ctx.Web, template, parser, new ProvisioningTemplateApplyingInformation());

                // Load DataRows
                new ObjectListInstanceDataRows().ProvisionObjects(ctx.Web, template, parser, new ProvisioningTemplateApplyingInformation());

                var list = ctx.Web.GetListByUrl(listInstance.Url);
                Assert.IsNotNull(list);

                var items = list.GetItems(CamlQuery.CreateAllItemsQuery());
                ctx.Load(items, itms => itms.Include(item => item["Title"], i => i["TaxKeyword"]));
                ctx.ExecuteQueryRetry();

                Assert.IsTrue(items.Count == 1);
                Assert.IsTrue(items[0]["Title"].ToString() == "Test");

                //Validate taxonomy field data
                var value = items[0]["TaxKeyword"] as TaxonomyFieldValueCollection;
                Assert.IsNotNull(value);
                Assert.IsTrue(value[0].WssId > 0, "Term WSS ID not set correctly");
                Assert.AreEqual(termName, value[0].Label, "Term label not set correctly");
                Assert.AreEqual(termId.ToString(), value[0].TermGuid, "Term GUID not set correctly");
            }
        }
        private void AddTermStoreTokens(Web web, List <string> tokenIds)
        {
            if (tokenIds.Contains("termstoreid") || tokenIds.Contains("termsetid") || tokenIds.Contains("sitecollectiontermgroupid") || tokenIds.Contains("sitecollectiontermgroupname") || tokenIds.Contains("sitecollectiontermsetid"))
            {
                TaxonomySession session = TaxonomySession.GetTaxonomySession(web.Context);

                if (tokenIds.Contains("termstoreid"))
                {
                    var termStores = session.EnsureProperty(s => s.TermStores);
                    foreach (var ts in termStores)
                    {
                        _tokens.Add(new TermStoreIdToken(web, ts.Name, ts.Id));
                    }
                }
                var termStore = session.GetDefaultSiteCollectionTermStore();
                web.Context.Load(termStore);
                web.Context.ExecuteQueryRetry();
                if (tokenIds.Contains("termsetid"))
                {
                    if (!termStore.ServerObjectIsNull.Value)
                    {
                        web.Context.Load(termStore.Groups,
                                         g => g.Include(
                                             tg => tg.Name,
                                             tg => tg.TermSets.Include(
                                                 ts => ts.Name,
                                                 ts => ts.Id)
                                             ));
                        web.Context.ExecuteQueryRetry();
                        foreach (var termGroup in termStore.Groups)
                        {
                            foreach (var termSet in termGroup.TermSets)
                            {
                                _tokens.Add(new TermSetIdToken(web, termGroup.Name, termSet.Name, termSet.Id));
                            }
                        }
                    }
                }

                if (tokenIds.Contains("sitecollectiontermgroupid"))
                {
                    _tokens.Add(new SiteCollectionTermGroupIdToken(web));
                }
                if (tokenIds.Contains("sitecollectiontermgroupname"))
                {
                    _tokens.Add(new SiteCollectionTermGroupNameToken(web));
                }

                if (tokenIds.Contains("sitecollectiontermsetid"))
                {
                    var site = (web.Context as ClientContext).Site;
                    var siteCollectionTermGroup = termStore.GetSiteCollectionGroup(site, true);
                    web.Context.Load(siteCollectionTermGroup);
                    try
                    {
                        web.Context.ExecuteQueryRetry();
                        if (null != siteCollectionTermGroup && !siteCollectionTermGroup.ServerObjectIsNull.Value)
                        {
                            web.Context.Load(siteCollectionTermGroup, group => group.TermSets.Include(ts => ts.Name, ts => ts.Id));
                            web.Context.ExecuteQueryRetry();
                            foreach (var termSet in siteCollectionTermGroup.TermSets)
                            {
                                _tokens.Add(new SiteCollectionTermSetIdToken(web, termSet.Name, termSet.Id));
                            }
                        }
                    }
                    catch (ServerUnauthorizedAccessException)
                    {
                        // If we don't have permission to access the TermGroup, just skip it
                        Log.Warning(Constants.LOGGING_SOURCE, CoreResources.TermGroup_No_Access);
                    }
                    catch (NullReferenceException)
                    {
                        // If there isn't a default TermGroup for the Site Collection, we skip the terms in token handler
                    }
                }
            }
        }
        public TokenParser(Web web, ProvisioningTemplate template)
        {
            web.EnsureProperties(w => w.ServerRelativeUrl, w => w.Language);

            _web = web;

            _tokens = new List <TokenDefinition>();

            _tokens.Add(new SiteCollectionToken(web));
            _tokens.Add(new SiteToken(web));
            _tokens.Add(new MasterPageCatalogToken(web));
            _tokens.Add(new SiteCollectionTermStoreIdToken(web));
            _tokens.Add(new KeywordsTermStoreIdToken(web));
            _tokens.Add(new ThemeCatalogToken(web));
            _tokens.Add(new SiteNameToken(web));
            _tokens.Add(new SiteIdToken(web));
            _tokens.Add(new AssociatedGroupToken(web, AssociatedGroupToken.AssociatedGroupType.owners));
            _tokens.Add(new AssociatedGroupToken(web, AssociatedGroupToken.AssociatedGroupType.members));
            _tokens.Add(new AssociatedGroupToken(web, AssociatedGroupToken.AssociatedGroupType.visitors));
            _tokens.Add(new GuidToken(web));
            _tokens.Add(new CurrentUserIdToken(web));
            _tokens.Add(new CurrentUserLoginNameToken(web));
            _tokens.Add(new CurrentUserFullNameToken(web));

            // Add lists
            web.Context.Load(web.Lists, ls => ls.Include(l => l.Id, l => l.Title, l => l.RootFolder.ServerRelativeUrl));
            web.Context.ExecuteQueryRetry();
            foreach (var list in web.Lists)
            {
                _tokens.Add(new ListIdToken(web, list.Title, list.Id));
                _tokens.Add(new ListUrlToken(web, list.Title, list.RootFolder.ServerRelativeUrl.Substring(web.ServerRelativeUrl.Length + 1)));
            }

            // Add ContentTypes
            web.Context.Load(web.ContentTypes, cs => cs.Include(ct => ct.StringId, ct => ct.Name));
            web.Context.ExecuteQueryRetry();
            foreach (var ct in web.ContentTypes)
            {
                _tokens.Add(new ContentTypeIdToken(web, ct.Name, ct.StringId));
            }
            // Add parameters
            foreach (var parameter in template.Parameters)
            {
                _tokens.Add(new ParameterToken(web, parameter.Key, parameter.Value));
            }

            // Add TermSetIds
            TaxonomySession session = TaxonomySession.GetTaxonomySession(web.Context);

            var termStore = session.GetDefaultSiteCollectionTermStore();

            web.Context.Load(termStore);
            web.Context.ExecuteQueryRetry();
            if (!termStore.ServerObjectIsNull.Value)
            {
                web.Context.Load(termStore.Groups,
                                 g => g.Include(
                                     tg => tg.Name,
                                     tg => tg.TermSets.Include(
                                         ts => ts.Name,
                                         ts => ts.Id)
                                     ));
                web.Context.ExecuteQueryRetry();
                foreach (var termGroup in termStore.Groups)
                {
                    foreach (var termSet in termGroup.TermSets)
                    {
                        _tokens.Add(new TermSetIdToken(web, termGroup.Name, termSet.Name, termSet.Id));
                    }
                }
            }

            _tokens.Add(new SiteCollectionTermGroupIdToken(web));
            _tokens.Add(new SiteCollectionTermGroupNameToken(web));

            // Handle resources
            if (template.Localizations.Any())
            {
                // Read all resource keys in a list
                List <Tuple <string, uint, string> > resourceEntries = new List <Tuple <string, uint, string> >();
                foreach (var localizationEntry in template.Localizations)
                {
                    var filePath = localizationEntry.ResourceFile;
                    using (var stream = template.Connector.GetFileStream(filePath))
                    {
                        if (stream != null)
                        {
                            using (ResXResourceReader resxReader = new ResXResourceReader(stream))
                            {
                                foreach (DictionaryEntry entry in resxReader)
                                {
                                    resourceEntries.Add(new Tuple <string, uint, string>(entry.Key.ToString(), (uint)localizationEntry.LCID, entry.Value.ToString()));
                                }
                            }
                        }
                    }
                }

                var uniqueKeys = resourceEntries.Select(k => k.Item1).Distinct();
                foreach (var key in uniqueKeys)
                {
                    var matches = resourceEntries.Where(k => k.Item1 == key);
                    var entries = matches.Select(k => new ResourceEntry()
                    {
                        LCID = k.Item2, Value = k.Item3
                    }).ToList();
                    LocalizationToken token = new LocalizationToken(web, key, entries);

                    _tokens.Add(token);
                }
            }
            var sortedTokens = from t in _tokens
                               orderby t.GetTokenLength() descending
                               select t;

            _tokens = sortedTokens.ToList();
        }
        /// <summary>
        /// 用語セットグループに用語を追加します。
        /// </summary>
        /// <param name="termSetInfo">用語セット情報</param>
        public void AddTerm(TermSetInfo termSetInfo)
        {
            var groupName   = this.GroupName;
            var defaultLcID = this.DefaultLcID;

            this.Extract(cn => {
                var groups = cn.GetGroups();

                var taxonomySession = TaxonomySession.GetTaxonomySession(cn);
                cn.Load(taxonomySession,
                        t => t.TermStores.Include(
                            store => store.Name,
                            store => store.Groups.Include(
                                group => group.Name
                                )
                            )
                        );
                cn.ExecuteQuery();

                var termStore = taxonomySession.GetDefaultSiteCollectionTermStore();

                if (!groups.ContainsKey(groupName))
                {
                    var gp = termStore.CreateGroup(groupName, Guid.NewGuid());
                    var ts = gp.CreateTermSet(termSetInfo.Name, Guid.NewGuid(), defaultLcID);
                    ts.IsOpenForTermCreation = termSetInfo.IsOpenForTermCreation;
                    ts.Description           = termSetInfo.Description;

                    termSetInfo.Terms.ForEach(t => {
                        ts.AddTerm(t.Name, defaultLcID, tm => {
                            tm.SetDescription(t.Description, defaultLcID);
                            tm.IsAvailableForTagging = t.IsAvailableForTagging;
                        });
                    });
                }
                else
                {
                    var gp       = termStore.Groups.GetByName(groupName);
                    var termSets = groups[groupName];
                    if (!termSets.Any(t => t.Name == termSetInfo.Name))
                    {
                        var ts = gp.CreateTermSet(termSetInfo.Name, Guid.NewGuid(), defaultLcID);
                        ts.IsOpenForTermCreation = termSetInfo.IsOpenForTermCreation;
                        ts.Description           = termSetInfo.Description;

                        termSetInfo.Terms.ForEach(t => {
                            ts.AddTerm(t.Name, defaultLcID, tm => {
                                tm.SetDescription(t.Description, defaultLcID);
                                tm.IsAvailableForTagging = t.IsAvailableForTagging;
                            });
                        });
                    }
                    else
                    {
                        var ts = gp.TermSets.GetByName(termSetInfo.Name);
                        ts.IsOpenForTermCreation = termSetInfo.IsOpenForTermCreation;
                        ts.Description           = termSetInfo.Description;

                        var terms = termSets.Single(t => t.Name == termSetInfo.Name).Terms;
                        termSetInfo.Terms.ForEach(t => {
                            if (!terms.Any(v => v.Name == t.Name))
                            {
                                ts.AddTerm(t.Name, defaultLcID, tm => {
                                    tm.SetDescription(t.Description, defaultLcID);
                                    tm.IsAvailableForTagging = t.IsAvailableForTagging;
                                });
                            }
                            else
                            {
                                var tm = ts.Terms.GetByName(t.Name);
                                tm.SetDescription(t.Description, defaultLcID);
                                tm.IsAvailableForTagging = t.IsAvailableForTagging;
                            }
                        });
                    }
                }
                termStore.CommitAll();

                cn.ExecuteQuery();

                return(cn.GetGroups());
            });
        }
        protected override void ExecuteCmdlet()
        {
            var taxonomySession = TaxonomySession.GetTaxonomySession(ClientContext);
            // Get Term Store
            TermStore termStore = null;

            if (TermStore == null)
            {
                termStore = taxonomySession.GetDefaultSiteCollectionTermStore();
            }
            else
            {
                if (TermStore.StringValue != null)
                {
                    termStore = taxonomySession.TermStores.GetByName(TermStore.StringValue);
                }
                else if (TermStore.IdValue != Guid.Empty)
                {
                    termStore = taxonomySession.TermStores.GetById(TermStore.IdValue);
                }
                else
                {
                    if (TermStore.Item != null)
                    {
                        termStore = TermStore.Item;
                    }
                }
            }
            // Get Group
            if (termStore != null)
            {
                TermGroup group = null;
                if (Identity.Id != Guid.Empty)
                {
                    group = termStore.Groups.GetById(Identity.Id);
                }
                else
                {
                    group = termStore.Groups.GetByName(Identity.Title);
                }
                ClientContext.Load(group);
                ClientContext.ExecuteQueryRetry();

                if (group.ServerObjectIsNull.Value != false)
                {
                    bool updateRequired = false;
                    if (ParameterSpecified(nameof(Name)))
                    {
                        group.Name     = Name;
                        updateRequired = true;
                    }
                    if (ParameterSpecified(nameof(Description)))
                    {
                        group.Description = Description;
                        updateRequired    = true;
                    }
                    if (updateRequired)
                    {
                        termStore.CommitAll();
                        ClientContext.ExecuteQuery();
                    }
                    WriteObject(group);
                }
                else
                {
                    throw new PSArgumentException("Group not found");
                }
            }
            else
            {
                WriteError(new ErrorRecord(new ArgumentException("Cannot find termstore"), "INCORRECTTERMSTORE", ErrorCategory.ObjectNotFound, TermStore));
            }
        }
        public static string GetTaxonomyPickerData(ClientContext clientContext, TermSetQueryModel model)
        {
            var pickerTermSet = new PickerTermSetModel();

            if (clientContext != null)
            {
                //Get terms from the 'Keywords' termset for autocomplete suggestions.
                // It might be a good idea to cache these values.

                var taxonomySession = TaxonomySession.GetTaxonomySession(clientContext);
                var termStore       = taxonomySession.GetDefaultSiteCollectionTermStore();

                TermSet termSet = null;

                if (!string.IsNullOrWhiteSpace(model.Id))
                {
                    termSet = termStore.GetTermSet(new Guid(model.Id));
                }
                else if (!string.IsNullOrWhiteSpace(model.Name))
                {
                    var rawTermSets = termStore.GetTermSetsByName(model.Name, model.LCID);
                    termSet = rawTermSets.GetByName(model.Name);
                }
                else if (model.UseHashtags)
                {
                    termSet = termStore.HashTagsTermSet;
                }
                else if (model.UseKeywords)
                {
                    termSet = termStore.KeywordsTermSet;
                }

                clientContext.Load(termSet, ts => ts.Id, ts => ts.IsOpenForTermCreation, ts => ts.CustomSortOrder, ts => ts.Name,
                                   ts => ts.Terms.Include(t => t.PathOfTerm,
                                                          t => t.Id,
                                                          t => t.Labels.Include(l => l.IsDefaultForLanguage, l => l.Value),
                                                          t => t.Name,
                                                          t => t.TermsCount));
                clientContext.ExecuteQuery();

                var allTerms = termSet.GetAllTerms();

                clientContext.Load(allTerms, terms => terms.Include(t => t.PathOfTerm,
                                                                    t => t.Id,
                                                                    t => t.Labels.Include(l => l.IsDefaultForLanguage, l => l.Value),
                                                                    t => t.Name,
                                                                    t => t.TermsCount));
                clientContext.ExecuteQuery();

                pickerTermSet.Id   = termSet.Id.ToString().Replace("{", string.Empty).Replace("}", string.Empty);
                pickerTermSet.Name = termSet.Name;
                pickerTermSet.IsOpenForTermCreation = termSet.IsOpenForTermCreation;
                pickerTermSet.CustomSortOrder       = termSet.CustomSortOrder;
                pickerTermSet.Terms     = new List <PickerTermModel>();
                pickerTermSet.FlatTerms = new List <PickerTermModel>();

                foreach (var term in termSet.Terms.ToList <Term>())
                {
                    pickerTermSet.Terms.Add(GetPickerTerm(term));
                }

                foreach (var term in allTerms.ToList <Term>())
                {
                    pickerTermSet.FlatTerms.Add(GetPickerTerm(term, false));
                }
            }
            return(JsonHelper.Serialize <PickerTermSetModel>(pickerTermSet));
        }
        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;
                                    }
                                }
                                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);
        }
Exemple #16
0
        public void CleanUp()
        {
            using (var ctx = TestCommon.CreateClientContext())
            {
                bool isDirty = false;

                var list = ctx.Web.GetListByUrl(string.Format("lists/{0}", listName));
                if (list == null)
                {
                    list = ctx.Web.GetListByUrl(listName);
                }
                if (list != null)
                {
                    list.DeleteObject();
                    isDirty = true;
                }

                // Clean all data row test list instances, also after a previous test case failed.
                DeleteDataRowLists(ctx);

                // first delete content types
                var contentTypes = ctx.LoadQuery(ctx.Web.ContentTypes);
                ctx.ExecuteQueryRetry();
                var testContentTypes = contentTypes.Where(l => l.Name.StartsWith("Test_", StringComparison.OrdinalIgnoreCase));
                foreach (var ctype in testContentTypes)
                {
                    ctype.DeleteObject();
                    isDirty = true;
                }

                var field           = ctx.Web.GetFieldById <FieldText>(fieldId);                 // Guid matches ID in field caml.
                var calculatedField = ctx.Web.GetFieldById <FieldCalculated>(calculatedFieldId); // Guid matches ID in field caml.

                if (field != null)
                {
                    field.DeleteObject();
                    isDirty = true;
                }
                if (calculatedField != null)
                {
                    calculatedField.DeleteObject();
                    isDirty = true;
                }

                if (isDirty)
                {
                    ctx.ExecuteQueryRetry();
                }

                if (!TestCommon.AppOnlyTesting())
                {
                    // Clean up Taxonomy
                    if (!Guid.Empty.Equals(termGroupId))
                    {
                        var taxSession = TaxonomySession.GetTaxonomySession(ctx);
                        var termStore  = taxSession.GetDefaultSiteCollectionTermStore();
                        var termGroup  = termStore.GetGroup(termGroupId);
                        ctx.ExecuteQueryRetry();
                        isDirty = false;
                        if (!termGroup.ServerObjectIsNull.Value)
                        {
                            var termSets = termGroup.TermSets;
                            ctx.Load(termSets);
                            ctx.ExecuteQueryRetry();
                            foreach (var termSet in termSets)
                            {
                                termSet.DeleteObject();
                            }
                            termGroup.DeleteObject();
                            isDirty = true;
                        }
                        if (isDirty)
                        {
                            ctx.ExecuteQueryRetry();
                        }
                    }
                }
            }
        }
        /// <summary>
        /// Attempts to reuse the model term. If the term does not yet exists it will return
        /// false for the first part of the the return tuple. this will notify the system
        /// that the term should be created instead of re-used.
        /// </summary>
        /// <param name="web"></param>
        /// <param name="modelTerm"></param>
        /// <param name="parent"></param>
        /// <param name="termStore"></param>
        /// <param name="parser"></param>
        /// <param name="scope"></param>
        /// <returns></returns>
        private TryReuseTermResult TryReuseTerm(Web web, Model.Term modelTerm, TaxonomyItem parent, TermStore termStore, TokenParser parser, PnPMonitoredScope scope)
        {
            if (!modelTerm.IsReused)
            {
                return new TryReuseTermResult()
                       {
                           Success = false, UpdatedParser = parser
                       }
            }
            ;
            if (modelTerm.Id == Guid.Empty)
            {
                return new TryReuseTermResult()
                       {
                           Success = false, UpdatedParser = parser
                       }
            }
            ;

            // Since we're reusing terms ensure the previous terms are committed
            termStore.CommitAll();
            web.Context.ExecuteQueryRetry();

            // Try to retrieve a matching term from the website also marked from re-use.
            var taxonomySession = TaxonomySession.GetTaxonomySession(web.Context);

            web.Context.Load(taxonomySession);
            web.Context.ExecuteQueryRetry();

            if (taxonomySession.ServerObjectIsNull())
            {
                return(new TryReuseTermResult()
                {
                    Success = false, UpdatedParser = parser
                });
            }

            var  freshTermStore  = taxonomySession.GetDefaultKeywordsTermStore();
            Term preExistingTerm = freshTermStore.GetTerm(modelTerm.Id);

            try
            {
                web.Context.Load(preExistingTerm);
                web.Context.ExecuteQueryRetry();

                if (preExistingTerm.ServerObjectIsNull())
                {
                    preExistingTerm = null;
                }
            }
            catch (Exception)
            {
                preExistingTerm = null;
            }

            // If the matching term is not found, return false... we can't re-use just yet
            if (preExistingTerm == null)
            {
                return(new TryReuseTermResult()
                {
                    Success = false, UpdatedParser = parser
                });
            }
            // if the matching term is found re-use, create child terms, and return true
            else
            {
                // Reuse term
                Term createdTerm = null;
                if (parent is TermSet)
                {
                    createdTerm = ((TermSet)parent).ReuseTerm(preExistingTerm, false);
                }
                else if (parent is Term)
                {
                    createdTerm = ((Term)parent).ReuseTerm(preExistingTerm, false);
                }

                if (modelTerm.IsSourceTerm)
                {
                    preExistingTerm.ReassignSourceTerm(createdTerm);
                }

                // Set labels and shared properties just in case we're on the source term
                if (modelTerm.IsSourceTerm)
                {
                    if (modelTerm.Labels.Any())
                    {
                        CreateTermLabels(modelTerm, termStore, parser, scope, createdTerm);
                    }

                    if (modelTerm.Properties.Any())
                    {
                        SetTermCustomProperties(modelTerm, parser, createdTerm);
                    }
                }

                if (modelTerm.LocalProperties.Any())
                {
                    SetTermLocalCustomProperties(modelTerm, parser, createdTerm);
                }

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

                // Create any child terms
                parser = this.CreateChildTerms(web, modelTerm, createdTerm, termStore, parser, scope);

                // Return true, because our TryReuseTerm attempt succeeded!
                return(new TryReuseTermResult()
                {
                    Success = true, UpdatedParser = parser
                });
            }
        }
Exemple #18
0
        protected override void ExecuteCmdlet()
        {
            var taxonomySession = TaxonomySession.GetTaxonomySession(ClientContext);
            // Get Term Store
            var termStore = default(TermStore);

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

            var termGroup = default(TermGroup);

            if (TermGroup != null)
            {
                if (!string.IsNullOrEmpty(TermGroup.Name))
                {
                    termGroup = termStore.Groups.GetByName(TermGroup.Name);
                }
                else if (TermGroup.Id != Guid.Empty)
                {
                    termGroup = termStore.Groups.GetById(TermGroup.Id);
                }
            }
            if (Id == Guid.Empty)
            {
                Id = Guid.NewGuid();
            }
            var termSet = termGroup.CreateTermSet(Name, Id, Lcid);

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

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

            var customProperties = CustomProperties ?? new Hashtable();

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

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

            termStore.CommitAll();
            ClientContext.ExecuteQueryRetry();
            WriteObject(termSet);
        }
Exemple #19
0
        public override TokenParser ProvisionObjects(Web web, ProvisioningTemplate template, TokenParser parser, ProvisioningTemplateApplyingInformation applyingInformation)
        {
            using (var scope = new PnPMonitoredScope(this.Name))
            {
                if (template.Navigation != null)
                {
                    if (!WebSupportsProvisionNavigation(web, template))
                    {
                        scope.LogDebug(CoreResources.Provisioning_ObjectHandlers_Navigation_Context_web_is_not_publishing);
                        return(parser);
                    }

                    // Check if this is not a noscript site as navigation features are not supported
                    bool isNoScriptSite = web.IsNoScriptSite();

                    // Retrieve the current web navigation settings
                    var navigationSettings = new WebNavigationSettings(web.Context, web);
                    web.Context.Load(navigationSettings, ns => ns.CurrentNavigation, ns => ns.GlobalNavigation);
                    web.Context.ExecuteQueryRetry();

                    navigationSettings.AddNewPagesToNavigation       = template.Navigation.AddNewPagesToNavigation;
                    navigationSettings.CreateFriendlyUrlsForNewPages = template.Navigation.CreateFriendlyUrlsForNewPages;

                    if (!isNoScriptSite)
                    {
                        navigationSettings.Update(TaxonomySession.GetTaxonomySession(web.Context));
                        web.Context.ExecuteQueryRetry();
                    }

                    if (template.Navigation.GlobalNavigation != null)
                    {
                        switch (template.Navigation.GlobalNavigation.NavigationType)
                        {
                        case GlobalNavigationType.Inherit:
                            navigationSettings.GlobalNavigation.Source = StandardNavigationSource.InheritFromParentWeb;
                            web.Navigation.UseShared = true;
                            break;

                        case GlobalNavigationType.Managed:
                            if (template.Navigation.GlobalNavigation.ManagedNavigation == null)
                            {
                                throw new ApplicationException(CoreResources.Provisioning_ObjectHandlers_Navigation_missing_global_managed_navigation);
                            }
                            navigationSettings.GlobalNavigation.Source      = StandardNavigationSource.TaxonomyProvider;
                            navigationSettings.GlobalNavigation.TermStoreId = Guid.Parse(parser.ParseString(template.Navigation.GlobalNavigation.ManagedNavigation.TermStoreId));
                            navigationSettings.GlobalNavigation.TermSetId   = Guid.Parse(parser.ParseString(template.Navigation.GlobalNavigation.ManagedNavigation.TermSetId));
                            web.Navigation.UseShared = false;
                            break;

                        case GlobalNavigationType.Structural:
                        default:
                            if (template.Navigation.GlobalNavigation.StructuralNavigation == null)
                            {
                                throw new ApplicationException(CoreResources.Provisioning_ObjectHandlers_Navigation_missing_global_structural_navigation);
                            }
                            navigationSettings.GlobalNavigation.Source = StandardNavigationSource.PortalProvider;
                            web.Navigation.UseShared = false;

                            break;
                        }

                        if (!isNoScriptSite)
                        {
                            navigationSettings.Update(TaxonomySession.GetTaxonomySession(web.Context));
                            web.Context.ExecuteQueryRetry();
                        }

                        // Need to set navigation nodes after update navigation settings
                        if (template.Navigation.GlobalNavigation.NavigationType == GlobalNavigationType.Structural)
                        {
                            ProvisionGlobalStructuralNavigation(web,
                                                                template.Navigation.GlobalNavigation.StructuralNavigation, parser, applyingInformation.ClearNavigation, scope);
                        }
                    }

                    if (template.Navigation.CurrentNavigation != null)
                    {
                        switch (template.Navigation.CurrentNavigation.NavigationType)
                        {
                        case CurrentNavigationType.Inherit:
                            navigationSettings.CurrentNavigation.Source = StandardNavigationSource.InheritFromParentWeb;
                            break;

                        case CurrentNavigationType.Managed:
                            if (template.Navigation.CurrentNavigation.ManagedNavigation == null)
                            {
                                throw new ApplicationException(CoreResources.Provisioning_ObjectHandlers_Navigation_missing_current_managed_navigation);
                            }
                            navigationSettings.CurrentNavigation.Source      = StandardNavigationSource.TaxonomyProvider;
                            navigationSettings.CurrentNavigation.TermStoreId = Guid.Parse(parser.ParseString(template.Navigation.CurrentNavigation.ManagedNavigation.TermStoreId));
                            navigationSettings.CurrentNavigation.TermSetId   = Guid.Parse(parser.ParseString(template.Navigation.CurrentNavigation.ManagedNavigation.TermSetId));
                            break;

                        case CurrentNavigationType.StructuralLocal:
                            if (!isNoScriptSite)
                            {
                                web.SetPropertyBagValue(NavigationShowSiblings, "false");
                            }
                            if (template.Navigation.CurrentNavigation.StructuralNavigation == null)
                            {
                                throw new ApplicationException(CoreResources.Provisioning_ObjectHandlers_Navigation_missing_current_structural_navigation);
                            }
                            navigationSettings.CurrentNavigation.Source = StandardNavigationSource.PortalProvider;

                            break;

                        case CurrentNavigationType.Structural:
                        default:
                            if (!isNoScriptSite)
                            {
                                web.SetPropertyBagValue(NavigationShowSiblings, "true");
                            }
                            if (template.Navigation.CurrentNavigation.StructuralNavigation == null)
                            {
                                throw new ApplicationException(CoreResources.Provisioning_ObjectHandlers_Navigation_missing_current_structural_navigation);
                            }
                            navigationSettings.CurrentNavigation.Source = StandardNavigationSource.PortalProvider;

                            break;
                        }

                        if (!isNoScriptSite)
                        {
                            navigationSettings.Update(TaxonomySession.GetTaxonomySession(web.Context));
                            web.Context.ExecuteQueryRetry();
                        }

                        // Need to set navigation nodes after update navigation settings
                        if (template.Navigation.CurrentNavigation.NavigationType == CurrentNavigationType.Structural ||
                            template.Navigation.CurrentNavigation.NavigationType == CurrentNavigationType.StructuralLocal)
                        {
                            ProvisionCurrentStructuralNavigation(web,
                                                                 template.Navigation.CurrentNavigation.StructuralNavigation, parser, applyingInformation.ClearNavigation, scope);
                        }
                    }

                    if (template.Navigation.SearchNavigation != null)
                    {
                        var structuralNavigation = new StructuralNavigation();
                        structuralNavigation.NavigationNodes.AddRange(template.Navigation.SearchNavigation.NavigationNodes);
                        structuralNavigation.RemoveExistingNodes = template.Navigation.SearchNavigation.RemoveExistingNodes;
                        ProvisionSearchNavigation(web, structuralNavigation, parser, applyingInformation.ClearNavigation, scope);
                    }
                }
            }

            return(parser);
        }
Exemple #20
0
        /// <summary>
        /// Updates navigation settings for the current web
        /// </summary>
        /// <param name="web">Web to process</param>
        /// <param name="navigationSettings">Navigation settings to update</param>
        public static void UpdateNavigationSettings(this Web web, AreaNavigationEntity navigationSettings)
        {
            //Read all the properties of the web
            web.Context.Load(web, w => w.AllProperties);
            web.Context.ExecuteQueryRetry();

            if (!ArePublishingFeaturesActivated(web.AllProperties))
            {
                throw new ArgumentException("Structural navigation settings are only supported for publishing sites");
            }

            // Use publishing CSOM API to switch between managed metadata and structural navigation
            var taxonomySession = TaxonomySession.GetTaxonomySession(web.Context);

            web.Context.Load(taxonomySession);
            web.Context.ExecuteQueryRetry();
            var webNav = new WebNavigationSettings(web.Context, web);

            if (navigationSettings.GlobalNavigation.InheritFromParentWeb)
            {
                if (web.IsSubSite())
                {
                    webNav.GlobalNavigation.Source = StandardNavigationSource.InheritFromParentWeb;
                }
                else
                {
                    throw new ArgumentException("Cannot inherit global navigation on root site.");
                }
            }
            else if (!navigationSettings.GlobalNavigation.ManagedNavigation)
            {
                webNav.GlobalNavigation.Source = StandardNavigationSource.PortalProvider;
            }
            else
            {
                webNav.GlobalNavigation.Source = StandardNavigationSource.TaxonomyProvider;
            }

            if (navigationSettings.CurrentNavigation.InheritFromParentWeb)
            {
                if (web.IsSubSite())
                {
                    webNav.CurrentNavigation.Source = StandardNavigationSource.InheritFromParentWeb;
                }
                else
                {
                    throw new ArgumentException("Cannot inherit current navigation on root site.");
                }
            }
            else if (!navigationSettings.CurrentNavigation.ManagedNavigation)
            {
                webNav.CurrentNavigation.Source = StandardNavigationSource.PortalProvider;
            }
            else
            {
                webNav.CurrentNavigation.Source = StandardNavigationSource.TaxonomyProvider;
            }

            // If managed metadata navigation is used, set settings related to page creation
            if (navigationSettings.GlobalNavigation.ManagedNavigation || navigationSettings.CurrentNavigation.ManagedNavigation)
            {
                webNav.AddNewPagesToNavigation       = navigationSettings.AddNewPagesToNavigation;
                webNav.CreateFriendlyUrlsForNewPages = navigationSettings.CreateFriendlyUrlsForNewPages;
            }

            webNav.Update(taxonomySession);
            web.Context.ExecuteQueryRetry();

            //Read all the properties of the web again after the above update
            web.Context.Load(web, w => w.AllProperties);
            web.Context.ExecuteQueryRetry();

            if (!navigationSettings.GlobalNavigation.ManagedNavigation)
            {
                var globalNavigationIncludeType = MapToNavigationIncludeTypes(navigationSettings.GlobalNavigation);
                web.AllProperties[GlobalNavigationIncludeTypes] = globalNavigationIncludeType;
                web.AllProperties[GlobalDynamicChildLimit]      = navigationSettings.GlobalNavigation.MaxDynamicItems;
            }

            if (!navigationSettings.CurrentNavigation.ManagedNavigation)
            {
                var currentNavigationIncludeType = MapToNavigationIncludeTypes(navigationSettings.CurrentNavigation);
                web.AllProperties[CurrentNavigationIncludeTypes] = currentNavigationIncludeType;
                web.AllProperties[CurrentDynamicChildLimit]      = navigationSettings.CurrentNavigation.MaxDynamicItems;

                // Call web.update before the IsSubSite call as this might do an ExecuteQuery. Without the update called the changes will be lost
                web.Update();
                // For the current navigation there's an option to show the sites siblings in structural navigation
                if (web.IsSubSite())
                {
                    web.AllProperties[NavigationShowSiblings] = navigationSettings.CurrentNavigation.ShowSiblings.ToString();
                }
            }

            // if there's either global or current structural navigation then update the sorting settings
            if (!navigationSettings.GlobalNavigation.ManagedNavigation || !navigationSettings.CurrentNavigation.ManagedNavigation)
            {
                // If there's automatic sorting or pages are shown with automatic page sorting then we can set all sort options
                if ((navigationSettings.Sorting == StructuralNavigationSorting.Automatically) ||
                    (navigationSettings.Sorting == StructuralNavigationSorting.ManuallyButPagesAutomatically && (navigationSettings.GlobalNavigation.ShowPages || navigationSettings.CurrentNavigation.ShowPages)))
                {
                    // All sort options can be set
                    web.AllProperties[NavigationOrderingMethod]         = (int)navigationSettings.Sorting;
                    web.AllProperties[NavigationAutomaticSortingMethod] = (int)navigationSettings.SortBy;
                    web.AllProperties[NavigationSortAscending]          = navigationSettings.SortAscending.ToString();
                }
                else
                {
                    // if pages are not shown we can set sorting to either automatic or manual
                    if (!navigationSettings.GlobalNavigation.ShowPages && !navigationSettings.CurrentNavigation.ShowPages)
                    {
                        if (navigationSettings.Sorting == StructuralNavigationSorting.ManuallyButPagesAutomatically)
                        {
                            throw new ArgumentException("Sorting can only be set to StructuralNavigationSorting.ManuallyButPagesAutomatically when ShowPages has been selected in either the global or current structural navigation settings");
                        }
                    }

                    web.AllProperties[NavigationOrderingMethod] = (int)navigationSettings.Sorting;
                }
            }

            //Persist all property updates at once
            web.Update();
            web.Context.ExecuteQueryRetry();
        }
        public ListItemCreator GetListItemCreator(ListItem listItem)
        {
            var itemCreator = new ListItemCreator()
            {
                FieldValues = new List <ListItemFieldValue>()
            };

            List.EnsureProperties(l => l.Fields);

            //{67df98f4-9dec-48ff-a553-29bece9c5bf4} is Attachments
            var attachmentsFieldId = Guid.Parse("{67df98f4-9dec-48ff-a553-29bece9c5bf4}");

            foreach (var field in List.Fields)
            {
                if (listItem.FieldValuesForEdit.FieldValues.ContainsKey(field.InternalName) &&
                    !string.IsNullOrEmpty(listItem.FieldValuesForEdit[field.InternalName]) &&
                    ((!field.Hidden &&
                      !field.ReadOnlyField &&
                      field.Id != attachmentsFieldId) ||
                     field.InternalName == "ContentTypeId") ||
                    field.InternalName == "PublishingPageLayout")
                {
                    try
                    {
                        var fieldValuePair = new ListItemFieldValue()
                        {
                            FieldName = field.InternalName,
                            Value     = TokenizeUrls(Web, listItem.FieldValuesForEdit[field.InternalName]),
                            FieldType = field.TypeAsString ?? String.Empty
                        };
                        if (fieldValuePair.FieldType == "DateTime" && fieldValuePair.Value != null)
                        {
                            fieldValuePair.Value =
                                (new DateTimeOffset(DateTime.Parse(fieldValuePair.Value))).UtcDateTime.ToString(
                                    "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fff'Z'");
                        }
                        if (fieldValuePair.FieldType.StartsWith("TaxonomyField"))
                        {
                            if (TaxonomySession == null)
                            {
                                TaxonomySession = TaxonomySession.GetTaxonomySession(ClientContext);
                                TermStore       = TaxonomySession.GetDefaultSiteCollectionTermStore();
                            }
                            if (!_taxonomyFields.ContainsKey(fieldValuePair.FieldName))
                            {
                                _taxonomyFields[fieldValuePair.FieldName] =
                                    ClientContext.CastTo <TaxonomyField>(field);

                                ClientContext.Load(_taxonomyFields[fieldValuePair.FieldName], tx => tx.TermSetId);
                                ClientContext.ExecuteQueryRetry();
                            }
                            if (!_termSetNames.ContainsKey(
                                    _taxonomyFields[fieldValuePair.FieldName].TermSetId))
                            {
                                var termSet =
                                    TermStore.GetTermSet(_taxonomyFields[fieldValuePair.FieldName].TermSetId);

                                ClientContext.Load(termSet, ts => ts.Name);
                                ClientContext.ExecuteQueryRetry();
                                _termSetNames[_taxonomyFields[fieldValuePair.FieldName].TermSetId] = termSet.Name;
                            }

                            fieldValuePair.Value =
                                $"{{@TermSet:{_termSetNames[_taxonomyFields[fieldValuePair.FieldName].TermSetId]}}}|{{@Terms:{fieldValuePair.Value}}} ";
                        }

                        itemCreator.FieldValues.Add(fieldValuePair);
                    }
                    catch
                    {
                        // ignored
                    }
                }
            }

            //Some catalog items don't have a content type (composed looks)
            //No idea why
            if (listItem.ContentType.ServerObjectIsNull != true)
            {
                //Actual content type name is required for versions of CSOM that don't support ContentTypeId
                //If the package also includes the ContentType the ID will not be the same between sites
                //Note this is a read-only field
                var contentTypeValuePair = new ListItemFieldValue()
                {
                    FieldName = "ContentType",
                    Value     = listItem.ContentType.Name,
                    FieldType = "ContentType"
                };
                itemCreator.FieldValues.Add(contentTypeValuePair);
            }

            return(itemCreator);
        }
        public TokenParser(Web web, ProvisioningTemplate template)
        {
            web.EnsureProperties(w => w.ServerRelativeUrl);

            _web = web;

            _tokens = new List <TokenDefinition>();

            _tokens.Add(new SiteCollectionToken(web));
            _tokens.Add(new SiteToken(web));
            _tokens.Add(new MasterPageCatalogToken(web));
            _tokens.Add(new SiteCollectionTermStoreIdToken(web));
            _tokens.Add(new KeywordsTermStoreIdToken(web));
            _tokens.Add(new ThemeCatalogToken(web));
            _tokens.Add(new SiteNameToken(web));
            _tokens.Add(new SiteIdToken(web));
            _tokens.Add(new AssociatedGroupToken(web, AssociatedGroupToken.AssociatedGroupType.owners));
            _tokens.Add(new AssociatedGroupToken(web, AssociatedGroupToken.AssociatedGroupType.members));
            _tokens.Add(new AssociatedGroupToken(web, AssociatedGroupToken.AssociatedGroupType.visitors));
            // Add lists
            web.Context.Load(web.Lists, ls => ls.Include(l => l.Id, l => l.Title, l => l.RootFolder.ServerRelativeUrl));
            web.Context.ExecuteQueryRetry();
            foreach (var list in web.Lists)
            {
                _tokens.Add(new ListIdToken(web, list.Title, list.Id));
                _tokens.Add(new ListUrlToken(web, list.Title, list.RootFolder.ServerRelativeUrl.Substring(web.ServerRelativeUrl.Length + 1)));
            }

            // Add parameters
            foreach (var parameter in template.Parameters)
            {
                _tokens.Add(new ParameterToken(web, parameter.Key, parameter.Value));
            }

            // Add TermSetIds
            TaxonomySession session = TaxonomySession.GetTaxonomySession(web.Context);

            var termStore = session.GetDefaultSiteCollectionTermStore();

            web.Context.Load(termStore);
            web.Context.ExecuteQueryRetry();
            if (!termStore.ServerObjectIsNull.Value)
            {
                web.Context.Load(termStore.Groups,
                                 g => g.Include(
                                     tg => tg.Name,
                                     tg => tg.TermSets.Include(
                                         ts => ts.Name,
                                         ts => ts.Id)
                                     ));
                web.Context.ExecuteQueryRetry();
                foreach (var termGroup in termStore.Groups)
                {
                    foreach (var termSet in termGroup.TermSets)
                    {
                        _tokens.Add(new TermSetIdToken(web, termGroup.Name, termSet.Name, termSet.Id));
                    }
                }
            }

            _tokens.Add(new SiteCollectionTermGroupIdToken(web));
            _tokens.Add(new SiteCollectionTermGroupNameToken(web));

            var sortedTokens = from t in _tokens
                               orderby t.GetTokenLength() descending
                               select t;

            _tokens = sortedTokens.ToList();
        }
        internal static TermStore FindTermStore(Site site,
                                                string termStoreName,
                                                Guid?termStoreId,
                                                bool?useDefaultSiteCollectionTermStore)
        {
            var       clientContext = site.Context;
            TermStore termStore     = null;

            lock (_storeCacheLock)
            {
                var key = string.Format("{0}-{1}-{2}",
                                        clientContext.GetHashCode(),
                                        clientContext.GetHashCode(),
                                        string.Format("{0}-{1}-{2}", termStoreName, termStoreId, useDefaultSiteCollectionTermStore))
                          .ToLower();

                if (!_storeCache.ContainsKey(key))
                {
                    TraceService.VerboseFormat((int)LogEventId.ModelProvisionCoreCall, "First call to TermStore with cache key: [{0}]", key);

                    var session = TaxonomySession.GetTaxonomySession(clientContext);
                    var client  = clientContext;

                    if (useDefaultSiteCollectionTermStore == true)
                    {
                        TraceService.Verbose((int)LogEventId.ModelProvisionCoreCall, "Resolving Term Store as useDefaultSiteCollectionTermStore");

                        termStore = session.GetDefaultSiteCollectionTermStore();
                    }
                    else
                    {
                        if (termStoreId.HasValue && termStoreId != default(Guid))
                        {
                            TraceService.VerboseFormat((int)LogEventId.ModelProvisionCoreCall, "Resolving Term Store by ID: [{0}]", termStoreId.Value);
                            termStore = session.TermStores.GetById(termStoreId.Value);
                        }
                        else if (!string.IsNullOrEmpty(termStoreName))
                        {
                            TraceService.VerboseFormat((int)LogEventId.ModelProvisionCoreCall, "Resolving Term Store by Name: [{0}]", termStoreName);
                            termStore = session.TermStores.GetByName(termStoreName);
                        }
                    }

                    if (termStore != null)
                    {
                        client.Load(termStore, s => s.Id);
                        client.Load(termStore, s => s.Name);

                        client.ExecuteQueryWithTrace();
                    }


                    _storeCache.Add(key, termStore);
                }
                else
                {
                    TraceService.VerboseFormat((int)LogEventId.ModelProvisionCoreCall, "Resolving term store from internal cache with cache key: [{0}]", key);
                }

                return(_storeCache[key]);
            }

            return(termStore);
        }
Exemple #24
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())
            {
                TokenParser.Initialize(ctx.Web, template);

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

                TaxonomySession session = TaxonomySession.GetTaxonomySession(ctx);

                var store = session.GetDefaultSiteCollectionTermStore();

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

                ctx.Load(group);
                ctx.Load(set, ts => ts.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().CreateEntities(ctx.Web, template, creationInfo);

                Assert.IsTrue(template.TermGroups.Any());
                Assert.IsInstanceOfType(template.TermGroups, typeof(List <TermGroup>));
            }
        }
        public void Initialize()
        {
            // Let's do webhook testing for both app-only as credential flows
            using (var clientContext = TestCommon.CreateClientContext())
            {
                var list = clientContext.Web.CreateList(ListTemplateType.DocumentLibrary, "Test_list_" + DateTime.Now.ToFileTime(), false);
                list.EnsureProperty(p => p.Id);
                webHookListId = list.Id;
            }

            if (!TestCommon.AppOnlyTesting())
            {
                /*** Make sure that the user defined in the App.config has permissions to Manage Terms ***/
                // Create some taxonomy groups and terms
                using (var clientContext = TestCommon.CreateClientContext())
                {
                    _termGroupName  = "Test_Group_" + DateTime.Now.ToFileTime();
                    _termSetName    = "Test_Termset_" + DateTime.Now.ToFileTime();
                    _termName       = "Test_Term_" + DateTime.Now.ToFileTime();
                    _textFieldName  = "Test_Text_Field_" + DateTime.Now.ToFileTime();
                    _textFieldName2 = "Test_Text_Field2_" + DateTime.Now.ToFileTime();

                    _termGroupId = Guid.NewGuid();
                    _termSetId   = Guid.NewGuid();
                    _termId      = Guid.NewGuid();

                    // Termgroup
                    var taxSession = TaxonomySession.GetTaxonomySession(clientContext);
                    var termStore  = taxSession.GetDefaultSiteCollectionTermStore();
                    var termGroup  = termStore.CreateGroup(_termGroupName, _termGroupId);
                    clientContext.Load(termGroup);
                    clientContext.ExecuteQueryRetry();

                    // Termset
                    var termSet = termGroup.CreateTermSet(_termSetName, _termSetId, 1033);
                    clientContext.Load(termSet);
                    clientContext.ExecuteQueryRetry();

                    // Term
                    termSet.CreateTerm(_termName, 1033, _termId);
                    clientContext.ExecuteQueryRetry();

                    // List

                    _textFieldId  = Guid.NewGuid();
                    _textFieldId2 = Guid.NewGuid();

                    var fieldCI = new FieldCreationInformation(FieldType.Text)
                    {
                        Id           = _textFieldId,
                        InternalName = _textFieldName,
                        DisplayName  = "Test Text Field",
                        Group        = "Test Group"
                    };

                    var fieldCI2 = new FieldCreationInformation(FieldType.Text)
                    {
                        Id           = _textFieldId2,
                        InternalName = _textFieldName2,
                        DisplayName  = "Test Text Field 2",
                        Group        = "Test Group"
                    };

                    var textfield  = clientContext.Web.CreateField(fieldCI);
                    var textfield2 = clientContext.Web.CreateField(fieldCI2);

                    var list = clientContext.Web.CreateList(ListTemplateType.DocumentLibrary, "Test_list_" + DateTime.Now.ToFileTime(), false);

                    var field = clientContext.Web.Fields.GetByInternalNameOrTitle("TaxKeyword"); // Enterprise Metadata

                    list.Fields.Add(field);
                    list.Fields.Add(textfield);
                    list.Fields.Add(textfield2);

                    list.Update();
                    clientContext.Load(list);
                    clientContext.ExecuteQueryRetry();

                    _listId = list.Id;
                }
            }
            else
            {
                using (var clientContext = TestCommon.CreateClientContext())
                {
                    _textFieldName  = "Test_Text_Field_" + DateTime.Now.ToFileTime();
                    _textFieldName2 = "Test_Text_Field2_" + DateTime.Now.ToFileTime();

                    // List
                    _textFieldId  = Guid.NewGuid();
                    _textFieldId2 = Guid.NewGuid();

                    var fieldCI = new FieldCreationInformation(FieldType.Text)
                    {
                        Id           = _textFieldId,
                        InternalName = _textFieldName,
                        DisplayName  = "Test Text Field",
                        Group        = "Test Group"
                    };

                    var fieldCI2 = new FieldCreationInformation(FieldType.Text)
                    {
                        Id           = _textFieldId2,
                        InternalName = _textFieldName2,
                        DisplayName  = "Test Text Field 2",
                        Group        = "Test Group"
                    };

                    var textfield  = clientContext.Web.CreateField(fieldCI);
                    var textfield2 = clientContext.Web.CreateField(fieldCI2);

                    var list = clientContext.Web.CreateList(ListTemplateType.DocumentLibrary, "Test_list_" + DateTime.Now.ToFileTime(), false);

                    list.Fields.Add(textfield);
                    list.Fields.Add(textfield2);

                    list.Update();
                    clientContext.Load(list);
                    clientContext.ExecuteQueryRetry();

                    _listId = list.Id;
                }
            }
        }
        protected override void ExecuteCmdlet()
        {
            List <string> exportedTerms;

            if (ParameterSetName == "TermSet")
            {
                if (Delimiter != "|" && Delimiter == ";#")
                {
                    throw new Exception("Restricted delimiter specified");
                }
                if (!string.IsNullOrEmpty(TermStoreName))
                {
                    var taxSession = TaxonomySession.GetTaxonomySession(ClientContext);
                    var termStore  = taxSession.TermStores.GetByName(TermStoreName);
                    exportedTerms = ClientContext.Site.ExportTermSet(TermSetId.Id, IncludeID, termStore, Delimiter, Lcid);
                }
                else
                {
                    exportedTerms = ClientContext.Site.ExportTermSet(TermSetId.Id, IncludeID, Delimiter, Lcid);
                }
            }
            else
            {
                exportedTerms = ClientContext.Site.ExportAllTerms(IncludeID, Delimiter);
            }

            if (Path == null)
            {
                WriteObject(exportedTerms);
            }
            else
            {
                if (!System.IO.Path.IsPathRooted(Path))
                {
                    Path = System.IO.Path.Combine(SessionState.Path.CurrentFileSystemLocation.Path, Path);
                }

                System.Text.Encoding textEncoding = System.Text.Encoding.Unicode;
                switch (Encoding)
                {
                case Encoding.ASCII:
                {
                    textEncoding = System.Text.Encoding.ASCII;
                    break;
                }

                case Encoding.BigEndianUnicode:
                {
                    textEncoding = System.Text.Encoding.BigEndianUnicode;
                    break;
                }

                case Encoding.UTF32:
                {
                    textEncoding = System.Text.Encoding.UTF32;
                    break;
                }

                case Encoding.UTF7:
                {
                    textEncoding = System.Text.Encoding.UTF7;
                    break;
                }

                case Encoding.UTF8:
                {
                    textEncoding = System.Text.Encoding.UTF8;
                    break;
                }

                case Encoding.Unicode:
                {
                    textEncoding = System.Text.Encoding.Unicode;
                    break;
                }
                }

                if (File.Exists(Path))
                {
                    if (Force || ShouldContinue(string.Format(Resources.File0ExistsOverwrite, Path), Resources.Confirm))
                    {
                        File.WriteAllLines(Path, exportedTerms, textEncoding);
                    }
                }
                else
                {
                    File.WriteAllLines(Path, exportedTerms, textEncoding);
                }
            }
        }
Exemple #27
0
        public TokenParser(Web web, ProvisioningTemplate template)
        {
            web.EnsureProperties(w => w.ServerRelativeUrl, w => w.Language);

            _web = web;

            _tokens = new List <TokenDefinition>();

            _tokens.Add(new SiteCollectionToken(web));
            _tokens.Add(new SiteCollectionIdToken(web));
            _tokens.Add(new SiteToken(web));
            _tokens.Add(new MasterPageCatalogToken(web));
            _tokens.Add(new SiteCollectionTermStoreIdToken(web));
            _tokens.Add(new KeywordsTermStoreIdToken(web));
            _tokens.Add(new ThemeCatalogToken(web));
            _tokens.Add(new SiteNameToken(web));
            _tokens.Add(new SiteIdToken(web));
            _tokens.Add(new SiteOwnerToken(web));
            _tokens.Add(new AssociatedGroupToken(web, AssociatedGroupToken.AssociatedGroupType.owners));
            _tokens.Add(new AssociatedGroupToken(web, AssociatedGroupToken.AssociatedGroupType.members));
            _tokens.Add(new AssociatedGroupToken(web, AssociatedGroupToken.AssociatedGroupType.visitors));
            _tokens.Add(new GuidToken(web));
            _tokens.Add(new DateNowToken(web));
            _tokens.Add(new CurrentUserIdToken(web));
            _tokens.Add(new CurrentUserLoginNameToken(web));
            _tokens.Add(new CurrentUserFullNameToken(web));
            _tokens.Add(new AuthenticationRealmToken(web));

            // Add lists
            web.Context.Load(web.Lists, ls => ls.Include(l => l.Id, l => l.Title, l => l.RootFolder.ServerRelativeUrl, l => l.Views));
            web.Context.ExecuteQueryRetry();
            foreach (var list in web.Lists)
            {
                _tokens.Add(new ListIdToken(web, list.Title, list.Id));
                _tokens.Add(new ListUrlToken(web, list.Title, list.RootFolder.ServerRelativeUrl.Substring(web.ServerRelativeUrl.Length + 1)));

                foreach (var view in list.Views)
                {
                    _tokens.Add(new ListViewIdToken(web, list.Title, view.Title, view.Id));
                }
            }

            if (web.IsSubSite())
            {
                // Add lists from rootweb
                var rootWeb = (web.Context as ClientContext).Site.RootWeb;
                rootWeb.EnsureProperty(w => w.ServerRelativeUrl);
                rootWeb.Context.Load(rootWeb.Lists, ls => ls.Include(l => l.Id, l => l.Title, l => l.RootFolder.ServerRelativeUrl));
                rootWeb.Context.ExecuteQueryRetry();
                foreach (var rootList in rootWeb.Lists)
                {
                    // token already there? Skip the list
                    if (web.Lists.FirstOrDefault(l => l.Title == rootList.Title) == null)
                    {
                        _tokens.Add(new ListIdToken(web, rootList.Title, rootList.Id));
                        _tokens.Add(new ListUrlToken(web, rootList.Title, rootList.RootFolder.ServerRelativeUrl.Substring(rootWeb.ServerRelativeUrl.Length + 1)));
                    }
                }
            }

            // Add ContentTypes
            web.Context.Load(web.AvailableContentTypes, cs => cs.Include(ct => ct.StringId, ct => ct.Name));
            web.Context.ExecuteQueryRetry();
            foreach (var ct in web.AvailableContentTypes)
            {
                _tokens.Add(new ContentTypeIdToken(web, ct.Name, ct.StringId));
            }
            // Add parameters
            foreach (var parameter in template.Parameters)
            {
                _tokens.Add(new ParameterToken(web, parameter.Key, parameter.Value));
            }

            // Add TermSetIds
            TaxonomySession session = TaxonomySession.GetTaxonomySession(web.Context);

            var termStores = session.EnsureProperty(s => s.TermStores);

            foreach (var ts in termStores)
            {
                _tokens.Add(new TermStoreIdToken(web, ts.Name, ts.Id));
            }
            var termStore = session.GetDefaultSiteCollectionTermStore();

            web.Context.Load(termStore);
            web.Context.ExecuteQueryRetry();
            if (!termStore.ServerObjectIsNull.Value)
            {
                web.Context.Load(termStore.Groups,
                                 g => g.Include(
                                     tg => tg.Name,
                                     tg => tg.TermSets.Include(
                                         ts => ts.Name,
                                         ts => ts.Id)
                                     ));
                web.Context.ExecuteQueryRetry();
                foreach (var termGroup in termStore.Groups)
                {
                    foreach (var termSet in termGroup.TermSets)
                    {
                        _tokens.Add(new TermSetIdToken(web, termGroup.Name, termSet.Name, termSet.Id));
                    }
                }
            }

            _tokens.Add(new SiteCollectionTermGroupIdToken(web));
            _tokens.Add(new SiteCollectionTermGroupNameToken(web));

            // SiteCollection TermSets, only when we're not working in app-only
            if (!web.Context.IsAppOnly())
            {
                var site = (web.Context as ClientContext).Site;
                var siteCollectionTermGroup = termStore.GetSiteCollectionGroup(site, true);
                web.Context.Load(siteCollectionTermGroup);
                try
                {
                    web.Context.ExecuteQueryRetry();
                    if (null != siteCollectionTermGroup && !siteCollectionTermGroup.ServerObjectIsNull.Value)
                    {
                        web.Context.Load(siteCollectionTermGroup, group => group.TermSets.Include(ts => ts.Name, ts => ts.Id));
                        web.Context.ExecuteQueryRetry();
                        foreach (var termSet in siteCollectionTermGroup.TermSets)
                        {
                            _tokens.Add(new SiteCollectionTermSetIdToken(web, termSet.Name, termSet.Id));
                        }
                    }
                }
                catch (NullReferenceException)
                {
                    // If there isn't a default TermGroup for the Site Collection, we skip the terms in token handler
                }
            }

            // Fields
            var fields = web.Fields;

            web.Context.Load(fields, flds => flds.Include(f => f.Title, f => f.InternalName));
            web.Context.ExecuteQueryRetry();
            foreach (var field in fields)
            {
                _tokens.Add(new FieldTitleToken(web, field.InternalName, field.Title));
            }

            if (web.IsSubSite())
            {
                // SiteColumns from rootsite
                var rootWeb     = (web.Context as ClientContext).Site.RootWeb;
                var siteColumns = rootWeb.Fields;
                web.Context.Load(siteColumns, flds => flds.Include(f => f.Title, f => f.InternalName));
                web.Context.ExecuteQueryRetry();
                foreach (var field in siteColumns)
                {
                    _tokens.Add(new FieldTitleToken(rootWeb, field.InternalName, field.Title));
                }
            }

            // Handle resources
            if (template.Localizations.Any())
            {
                // Read all resource keys in a list
                List <Tuple <string, uint, string> > resourceEntries = new List <Tuple <string, uint, string> >();
                foreach (var localizationEntry in template.Localizations)
                {
                    var filePath = localizationEntry.ResourceFile;
                    using (var stream = template.Connector.GetFileStream(filePath))
                    {
                        if (stream != null)
                        {
                            using (ResXResourceReader resxReader = new ResXResourceReader(stream))
                            {
                                foreach (DictionaryEntry entry in resxReader)
                                {
                                    resourceEntries.Add(new Tuple <string, uint, string>(entry.Key.ToString(), (uint)localizationEntry.LCID, entry.Value.ToString()));
                                }
                            }
                        }
                    }
                }

                var uniqueKeys = resourceEntries.Select(k => k.Item1).Distinct();
                foreach (var key in uniqueKeys)
                {
                    var matches = resourceEntries.Where(k => k.Item1 == key);
                    var entries = matches.Select(k => new ResourceEntry()
                    {
                        LCID = k.Item2, Value = k.Item3
                    }).ToList();
                    LocalizationToken token = new LocalizationToken(web, key, entries);

                    _tokens.Add(token);
                }
            }

            // OOTB Roledefs
            web.EnsureProperty(w => w.RoleDefinitions.Include(r => r.RoleTypeKind));
            foreach (var roleDef in web.RoleDefinitions.AsEnumerable().Where(r => r.RoleTypeKind != RoleType.None))
            {
                _tokens.Add(new RoleDefinitionToken(web, roleDef));
            }

            // Groups
            web.EnsureProperty(w => w.SiteGroups.Include(g => g.Title, g => g.Id));
            foreach (var siteGroup in web.SiteGroups)
            {
                _tokens.Add(new GroupIdToken(web, siteGroup.Title, siteGroup.Id));
            }
            web.EnsureProperty(w => w.AssociatedVisitorGroup).EnsureProperties(g => g.Id, g => g.Title);
            web.EnsureProperty(w => w.AssociatedMemberGroup).EnsureProperties(g => g.Id, g => g.Title);
            web.EnsureProperty(w => w.AssociatedOwnerGroup).EnsureProperties(g => g.Id, g => g.Title);

            if (!web.AssociatedVisitorGroup.ServerObjectIsNull.Value)
            {
                _tokens.Add(new GroupIdToken(web, "associatedvisitorgroup", web.AssociatedVisitorGroup.Id));
            }
            if (!web.AssociatedMemberGroup.ServerObjectIsNull.Value)
            {
                _tokens.Add(new GroupIdToken(web, "associatedmembergroup", web.AssociatedMemberGroup.Id));
            }
            if (!web.AssociatedOwnerGroup.ServerObjectIsNull.Value)
            {
                _tokens.Add(new GroupIdToken(web, "associatedownergroup", web.AssociatedOwnerGroup.Id));
            }
            var sortedTokens = from t in _tokens
                               orderby t.GetTokenLength() descending
                               select t;

            _tokens = sortedTokens.ToList();
        }
Exemple #28
0
        public static async Task <HttpResponseMessage> Run([HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)] HttpRequestMessage req, TraceWriter log)
        {
            log.Info("C# HTTP trigger function processed a request.");
            log.Info(ConfigurationManager.AppSettings["clientID"]);
            string authenticationToken = await helper.getSharePointToken(log, ConfigurationManager.AppSettings["tenantURL"]);

            try
            {
                using (var clientContext = helper.GetClientContext(ConfigurationManager.AppSettings["tenantURL"], authenticationToken))
                {
                    TaxonomySession taxonomySession = TaxonomySession.GetTaxonomySession(clientContext);
                    //taxonomySession.UpdateCache();
                    TermStore termStore = taxonomySession.GetDefaultSiteCollectionTermStore();
                    clientContext.Load(termStore, store => store.Name, store => store.Groups.Where(g => g.IsSystemGroup == false && g.IsSiteCollectionGroup == false).Include(group => group.Id, group => group.Name, group => group.Description, group => group.IsSiteCollectionGroup, group => group.IsSystemGroup, group => group.TermSets.Include(termSet => termSet.Id, termSet => termSet.Name, termSet => termSet.Description, termSet => termSet.CustomProperties, termSet => termSet.Terms.Include(t => t.Id, t => t.Description, t => t.Name, t => t.IsDeprecated, t => t.Parent, t => t.Labels, t => t.LocalCustomProperties, t => t.IsSourceTerm, t => t.IsRoot, t => t.IsKeyword, t => t.TermsCount, t => t.CustomProperties,
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            t => t.Terms.Include(t1 => t1.Id, t1 => t1.Description, t1 => t1.Name, t1 => t1.IsDeprecated, t1 => t1.Parent, t1 => t1.Labels, t1 => t1.LocalCustomProperties, t1 => t1.IsSourceTerm, t1 => t1.IsRoot, t1 => t1.IsKeyword, t1 => t1.TermsCount, t1 => t1.CustomProperties,
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                 t1 => t1.Terms.Include(t2 => t2.Id, t2 => t2.Description, t2 => t2.Name, t2 => t2.IsDeprecated, t2 => t2.Parent, t2 => t2.Labels, t2 => t2.LocalCustomProperties, t2 => t2.IsSourceTerm, t2 => t2.IsRoot, t2 => t2.IsKeyword, t2 => t2.TermsCount, t2 => t2.CustomProperties,
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        t2 => t2.Terms.Include(t3 => t3.Id, t3 => t3.Description, t3 => t3.Name, t3 => t3.IsDeprecated, t3 => t3.Parent, t3 => t3.Labels, t3 => t3.LocalCustomProperties, t3 => t3.IsSourceTerm, t3 => t3.IsRoot, t3 => t3.IsKeyword, t3 => t3.TermsCount, t3 => t3.CustomProperties, t3 => t3.Terms.Include(t4 => t4.Id, t4 => t4.Description, t4 => t4.Name, t4 => t4.IsDeprecated, t4 => t4.Parent, t4 => t4.Labels, t4 => t4.LocalCustomProperties, t4 => t4.IsSourceTerm, t4 => t4.IsRoot, t4 => t4.IsKeyword, t4 => t4.TermsCount, t4 => t4.CustomProperties))))
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            ))));

                    clientContext.ExecuteQuery();
                    ITATermStore itaTermStore = new ITATermStore();
                    itaTermStore.ITATermGroupList = new List <ITATermGroup>();
                    TermGroupCollection allGroups = termStore.Groups;
                    log.Info("Total Groups " + allGroups.Count.ToString());

                    foreach (var termGroup in allGroups)
                    {
                        log.Info("Group Name " + termGroup.Name);
                        ITATermGroup grp = new ITATermGroup();
                        grp.Id   = termGroup.Id;
                        grp.Name = termGroup.Name != null ? termGroup.Name : "";
                        //TermGroup specific logic goes here
                        grp.TermSets = new List <ITATermSets>();
                        foreach (var termSet in termGroup.TermSets)
                        {
                            log.Info("Termset Name : " + termSet.Name);
                            ITATermSets itaTermSet = new ITATermSets();
                            itaTermSet.Id   = termSet.Id != null ? termSet.Id : new Guid();
                            itaTermSet.Name = termSet.Name != null ? termSet.Name : "";
                            itaTermSet.Type = termSet.GetType().ToString();

                            if (termSet.CustomProperties != null)
                            {
                                itaTermSet.CustomProps = new List <ITATermProperty>();
                                foreach (var customProps in termSet.CustomProperties)
                                {
                                    itaTermSet.CustomProps.Add(new ITATermProperty()
                                    {
                                        key = customProps.Key, value = customProps.Value
                                    });
                                }
                            }

                            itaTermSet.Terms = new List <ITATerms>();
                            //TermSet specific logic goes here
                            foreach (var term in termSet.Terms)
                            {
                                log.Info("Term Name " + term.Name);
                                ITATerms itaTerm = new ITATerms();
                                itaTerm.Name = term.Name != null ? term.Name : "";
                                itaTerm.Id   = term.Id != null ? term.Id : new Guid();
                                //Microsoft.SharePoint.Client.Publishing.Navigation.NavigationTerm abc = term;
                                itaTerm.Type = term.GetType().ToString();
                                if (term.Labels.Count > 0)
                                {
                                    itaTerm.Labels = new List <string>();
                                    foreach (var label in term.Labels)
                                    {
                                        itaTerm.Labels.Add(label.Value);
                                    }
                                }
                                if (term.CustomProperties.Count > 0)
                                {
                                    itaTerm.CustomProps = new List <ITATermProperty>();
                                    foreach (var prop in term.CustomProperties)
                                    {
                                        itaTerm.CustomProps.Add(new ITATermProperty()
                                        {
                                            key = prop.Key, value = prop.Value
                                        });
                                    }
                                }

                                getSubTerms(term, itaTerm, log);

                                itaTermSet.Terms.Add(itaTerm);
                            }
                            grp.TermSets.Add(itaTermSet);
                        }
                        itaTermStore.ITATermGroupList.Add(grp);
                    }

                    string output   = JsonConvert.SerializeObject(itaTermStore);
                    var    response = req.CreateResponse(HttpStatusCode.OK);
                    response.Content = new StringContent(output, Encoding.UTF8, "application/json");
                    return(response);
                }
            }
            catch (Exception ex)
            {
                return(req.CreateResponse(HttpStatusCode.OK, "Errorx : " + ex.Message));
            }
        }
        public static async Task <HttpResponseMessage> Run([HttpTrigger(AuthorizationLevel.Function, "post")] GetTermPropertyRequest request, TraceWriter log)
        {
            string siteUrl = request.SiteURL;

            try
            {
                if (string.IsNullOrWhiteSpace(request.SiteURL))
                {
                    throw new ArgumentException("Parameter cannot be null", "SiteURL");
                }
                if (string.IsNullOrWhiteSpace(request.TermGUID))
                {
                    throw new ArgumentException("Parameter cannot be null", "TermGUID");
                }
                if (string.IsNullOrWhiteSpace(request.PropertyName))
                {
                    throw new ArgumentException("Parameter cannot be null", "PropertyName");
                }
                if (string.IsNullOrWhiteSpace(request.FallbackValue))
                {
                    request.FallbackValue = "";
                }
                var clientContext = await ConnectADAL.GetClientContext(siteUrl, log);

                TaxonomySession taxonomySession = TaxonomySession.GetTaxonomySession(clientContext);
                clientContext.Load(taxonomySession);
                clientContext.ExecuteQueryRetry();
                TermStore termStore = taxonomySession.GetDefaultSiteCollectionTermStore();
                var       term      = termStore.GetTerm(new Guid(request.TermGUID));
                clientContext.Load(term, t => t.LocalCustomProperties);
                clientContext.ExecuteQueryRetry();
                var propertyValue = string.Empty;
                do
                {
                    if (term.LocalCustomProperties.Keys.Contains(request.PropertyName))
                    {
                        propertyValue = term.LocalCustomProperties[request.PropertyName];
                    }
                    else
                    {
                        term = term.Parent;
                        clientContext.Load(term, t => t.LocalCustomProperties);
                        clientContext.ExecuteQueryRetry();
                    }
                } while (string.IsNullOrWhiteSpace(propertyValue));

                var getTermPropertyResponse = new GetTermPropertyResponse
                {
                    PropertyValue = propertyValue
                };
                return(await Task.FromResult(new HttpResponseMessage(HttpStatusCode.OK)
                {
                    Content = new ObjectContent <GetTermPropertyResponse>(getTermPropertyResponse, new JsonMediaTypeFormatter())
                }));
            }
            catch (Exception)
            {
                var getTermPropertyResponse = new GetTermPropertyResponse
                {
                    PropertyValue = request.FallbackValue
                };
                return(await Task.FromResult(new HttpResponseMessage(HttpStatusCode.OK)
                {
                    Content = new ObjectContent <GetTermPropertyResponse>(getTermPropertyResponse, new JsonMediaTypeFormatter())
                }));
            }
        }
Exemple #30
0
        public void SetTaxonomyFieldMultiValueTest()
        {
            var fieldName = "TaxKeyword";

            using (var clientContext = TestCommon.CreateClientContext())
            {
                // Retrieve list
                var list = clientContext.Web.Lists.GetById(_listId);
                clientContext.Load(list);
                clientContext.ExecuteQueryRetry();

                // Retrieve Termset
                TaxonomySession session = TaxonomySession.GetTaxonomySession(clientContext);
                var             termSet = session.GetDefaultSiteCollectionTermStore().GetTermSet(_termSet1Id);
                clientContext.Load(termSet);
                clientContext.ExecuteQueryRetry();

                //Add Enterprise keywords field
                var keyworkdField = clientContext.Web.Fields.GetByInternalNameOrTitle(fieldName);
                clientContext.Load(keyworkdField, f => f.Id);
                list.Fields.Add(keyworkdField);

                //Create second term
                var taxSession = TaxonomySession.GetTaxonomySession(clientContext);
                var termStore  = taxSession.GetDefaultSiteCollectionTermStore();

                Guid   term2Id   = Guid.NewGuid();
                string term2Name = "Test_Term_" + DateTime.Now.ToFileTime();

                var term2 = termStore.GetTerm(term2Id);
                clientContext.Load(term2, t => t.Id);
                clientContext.ExecuteQueryRetry();

                // Create if non existant
                if (term2.ServerObjectIsNull.Value)
                {
                    term2 = termSet.CreateTerm(term2Name, 1033, term2Id);
                    clientContext.ExecuteQueryRetry();
                }
                else
                {
                    var label2 = term2.GetDefaultLabel(1033);
                    clientContext.ExecuteQueryRetry();
                    term2Name = label2.Value;
                }

                // Create Item
                ListItemCreationInformation itemCi = new ListItemCreationInformation();

                var item = list.AddItem(itemCi);
                item.Update();
                clientContext.Load(item);
                clientContext.ExecuteQueryRetry();

                item.SetTaxonomyFieldValues(keyworkdField.Id, new List <KeyValuePair <Guid, string> > {
                    new KeyValuePair <Guid, string>(_termId, _termName),
                    new KeyValuePair <Guid, string>(term2Id, term2Name)
                });

                clientContext.Load(item, i => i[fieldName]);
                clientContext.ExecuteQueryRetry();

                var value = item[fieldName] as TaxonomyFieldValueCollection;

                Assert.IsNotNull(value);
                Assert.AreEqual(2, value.Count, "Taxonomy value count mismatch");
                Assert.IsTrue(value[0].WssId > 0, "Term WSS ID not set correctly");
                Assert.IsTrue(value[1].WssId > 0, "Term2 WSS ID not set correctly");
                Assert.AreEqual(_termName, value[0].Label, "Term label not set correctly");
                Assert.AreEqual(term2Name, value[1].Label, "Term2 label not set correctly");
                Assert.AreEqual(_termId.ToString(), value[0].TermGuid, "Term GUID not set correctly");
                Assert.AreEqual(term2Id.ToString(), value[1].TermGuid, "Term2 GUID not set correctly");
            }
        }