public void CanAddWebPartsToForms()
        {
            var template = new ProvisioningTemplate();

            FileSystemConnector connector = new FileSystemConnector(resourceFolder + @"\..", "");

            template.Connector = connector;
            var webPart = new WebPart
            {
                Column   = 1,
                Row      = 1,
                Contents = webpartcontents,
                Title    = "Script Editor",
                Order    = 0,
                Zone     = "Main"
            };

            var myfile = new Core.Framework.Provisioning.Model.File()
            {
                Overwrite = false,
                Src       = "EditForm.aspx",
                Folder    = "SitePages/Forms"
            };

            myfile.WebParts.Add(webPart);
            template.Files.Add(myfile);

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

                ctx.Web.EnsureProperties(w => w.ServerRelativeUrl);

                var file = ctx.Web.GetFileByServerRelativeUrl(
                    UrlUtility.Combine(ctx.Web.ServerRelativeUrl,
                                       UrlUtility.Combine("SitePages/Forms", "EditForm.aspx")));
                ctx.Load(file, f => f.Exists);
                ctx.ExecuteQueryRetry();

                // first of all do we even find the form ?
                Assert.IsTrue(file.Exists);
                var webParts = file.GetLimitedWebPartManager(PersonalizationScope.Shared).WebParts;
                ctx.Load(webParts, wp => wp.IncludeWithDefaultProperties(w => w.Id, w => w.WebPart, w => w.WebPart.Title));
                ctx.ExecuteQueryRetry();

                var webPartsArray = webParts.ToArray();
                var webPartExists = false;
                foreach (var webPartDefinition in webPartsArray)
                {
                    if (webPartDefinition.WebPart.Title == "Script Editor")
                    {
                        webPartExists = true;
                        // cleanup after ourselves if we can find the webpart...
                        webPartDefinition.DeleteWebPart();
                    }
                }
                ctx.ExecuteQueryRetry();
                Assert.IsTrue(webPartExists);
            }
        }
示例#2
0
        public void CanProvisionObjects()
        {
            var template = new ProvisioningTemplate();

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

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

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

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

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

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

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

            terms.Add(term1);

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

            termSet.Terms.AddRange(terms);

            termSets.Add(termSet);

            termGroup.TermSets.AddRange(termSets);

            template.TermGroups.Add(termGroup);

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

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

                TaxonomySession session = TaxonomySession.GetTaxonomySession(ctx);

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

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

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


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

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

                Assert.IsTrue(template.TermGroups.Any());
                Assert.IsInstanceOfType(template.TermGroups, typeof(Core.Framework.Provisioning.Model.TermGroupCollection));
            }
        }
 public static void ClassCleanup()
 {
     using (var clientContext = TestCommon.CreateClientContext())
     {
     }
 }
        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(_termSetId);
                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");
            }
        }
        public void ParseTests()
        {
            using (var ctx = TestCommon.CreateClientContext())
            {
                ctx.Load(ctx.Web,
                         w => w.Id,
                         w => w.ServerRelativeUrl,
                         w => w.Title,
                         w => w.AssociatedOwnerGroup.Title,
                         w => w.AssociatedMemberGroup.Title,
                         w => w.AssociatedVisitorGroup.Title,
                         w => w.AssociatedOwnerGroup.Id,
                         w => w.AssociatedMemberGroup.Id,
                         w => w.AssociatedVisitorGroup.Id);
                ctx.Load(ctx.Site, s => s.ServerRelativeUrl);

                var masterCatalog = ctx.Web.GetCatalog((int)ListTemplateType.MasterPageCatalog);
                ctx.Load(masterCatalog, m => m.RootFolder.ServerRelativeUrl);

                var themesCatalog = ctx.Web.GetCatalog((int)ListTemplateType.ThemeCatalog);
                ctx.Load(themesCatalog, t => t.RootFolder.ServerRelativeUrl);

                ctx.ExecuteQueryRetry();

                var currentUser = ctx.Web.EnsureProperty(w => w.CurrentUser);


                var ownerGroupName = ctx.Web.AssociatedOwnerGroup.Title;


                ProvisioningTemplate template = new ProvisioningTemplate();
                template.Parameters.Add("test", "test");

                var parser                 = new TokenParser(ctx.Web, template);
                var siteName               = parser.ParseString("{sitename}");
                var siteId                 = parser.ParseString("{siteid}");
                var site1                  = parser.ParseString("~siTE/test");
                var site2                  = parser.ParseString("{site}/test");
                var sitecol1               = parser.ParseString("~siteCOLLECTION/test");
                var sitecol2               = parser.ParseString("{sitecollection}/test");
                var masterUrl1             = parser.ParseString("~masterpagecatalog/test");
                var masterUrl2             = parser.ParseString("{masterpagecatalog}/test");
                var themeUrl1              = parser.ParseString("~themecatalog/test");
                var themeUrl2              = parser.ParseString("{themecatalog}/test");
                var parameterTest1         = parser.ParseString("abc{parameter:TEST}/test");
                var parameterTest2         = parser.ParseString("abc{$test}/test");
                var associatedOwnerGroup   = parser.ParseString("{associatedownergroup}");
                var associatedVisitorGroup = parser.ParseString("{associatedvisitorgroup}");
                var associatedMemberGroup  = parser.ParseString("{associatedmembergroup}");
                var currentUserId          = parser.ParseString("{currentuserid}");
                var currentUserLoginName   = parser.ParseString("{currentuserloginname}");
                var currentUserFullName    = parser.ParseString("{currentuserfullname}");
                var guid = parser.ParseString("{guid}");
                var associatedOwnerGroupId   = parser.ParseString("{groupid:associatedownergroup}");
                var associatedMemberGroupId  = parser.ParseString("{groupid:associatedmembergroup}");
                var associatedVisitorGroupId = parser.ParseString("{groupid:associatedvisitorgroup}");
                var groupId = parser.ParseString($"{{groupid:{ownerGroupName}}}");

                Assert.IsTrue(site1 == $"{ctx.Web.ServerRelativeUrl}/test");
                Assert.IsTrue(site2 == $"{ctx.Web.ServerRelativeUrl}/test");
                Assert.IsTrue(sitecol1 == $"{ctx.Site.ServerRelativeUrl}/test");
                Assert.IsTrue(sitecol2 == $"{ctx.Site.ServerRelativeUrl}/test");
                Assert.IsTrue(masterUrl1 == $"{masterCatalog.RootFolder.ServerRelativeUrl}/test");
                Assert.IsTrue(masterUrl2 == $"{masterCatalog.RootFolder.ServerRelativeUrl}/test");
                Assert.IsTrue(themeUrl1 == $"{themesCatalog.RootFolder.ServerRelativeUrl}/test");
                Assert.IsTrue(themeUrl2 == $"{themesCatalog.RootFolder.ServerRelativeUrl}/test");
                Assert.IsTrue(parameterTest1 == "abctest/test");
                Assert.IsTrue(parameterTest2 == "abctest/test");
                Assert.IsTrue(associatedOwnerGroup == ctx.Web.AssociatedOwnerGroup.Title);
                Assert.IsTrue(associatedVisitorGroup == ctx.Web.AssociatedVisitorGroup.Title);
                Assert.IsTrue(associatedMemberGroup == ctx.Web.AssociatedMemberGroup.Title);
                Assert.IsTrue(siteName == ctx.Web.Title);
                Assert.IsTrue(siteId == ctx.Web.Id.ToString());
                Assert.IsTrue(currentUserId == currentUser.Id.ToString());
                Assert.IsTrue(currentUserFullName == currentUser.Title);
                Assert.IsTrue(currentUserLoginName == currentUser.LoginName);
                Guid outGuid;
                Assert.IsTrue(Guid.TryParse(guid, out outGuid));
                Assert.IsTrue(int.Parse(associatedOwnerGroupId) == ctx.Web.AssociatedOwnerGroup.Id);
                Assert.IsTrue(int.Parse(associatedMemberGroupId) == ctx.Web.AssociatedMemberGroup.Id);
                Assert.IsTrue(int.Parse(associatedVisitorGroupId) == ctx.Web.AssociatedVisitorGroup.Id);
                Assert.IsTrue(associatedOwnerGroupId == groupId);
            }
        }
示例#6
0
        public void TransformPagesTest()
        {
            // Local functions
            string titleOverride(string title)
            {
                return($"{title}_1");
            }

            ILayoutTransformator layoutOverride(ClientSidePage cp)
            {
                return(new TestLayout());
            }

            IContentTransformator contentOverride(ClientSidePage cp, PageTransformation pt)
            {
                return(new TestTransformator());
            }

            using (var cc = TestCommon.CreateClientContext())
            {
                var pageTransformator = new PageTransformator(cc);

                //complexwiki
                //demo1
                //wikitext
                //wiki_li
                //webparts.aspx
                //contentbyquery1.aspx
                //how to use this library.aspx
                var pages = cc.Web.GetPages("webparts.aspx");

                foreach (var page in pages)
                {
                    PageTransformationInformation pti = new PageTransformationInformation(page)
                    {
                        // If target page exists, then overwrite it
                        Overwrite = true,

                        // Migrated page gets the name of the original page
                        //TargetPageTakesSourcePageName = false,

                        // Give the migrated page a specific prefix, default is Migrated_
                        //TargetPagePrefix = "Yes_",

                        // Configure the page header, empty value means ClientSidePageHeaderType.None
                        //PageHeader = new ClientSidePageHeader(cc, ClientSidePageHeaderType.None, null),

                        // If the page is a home page then replace with stock home page
                        //ReplaceHomePageWithDefaultHomePage = true,

                        // Replace embedded images and iframes with a placeholder and add respective images and video web parts at the bottom of the page
                        //HandleWikiImagesAndVideos = false,

                        // Callout to your custom code to allow for title overriding
                        //PageTitleOverride = titleOverride,

                        // Callout to your custom layout handler
                        //LayoutTransformatorOverride = layoutOverride,

                        // Callout to your custom content transformator...in case you fully want replace the model
                        //ContentTransformatorOverride = contentOverride,
                    };

                    pageTransformator.Transform(pti);
                }
            }
        }
        public void SetBlankTaxonomyFieldValueTest()
        {
            var fieldName = "Test2_" + DateTime.Now.ToFileTime();

            var fieldId = Guid.NewGuid();

            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(_termSetId);
                clientContext.Load(termSet);
                clientContext.ExecuteQueryRetry();

                // Create taxonomyfield first
                TaxonomyFieldCreationInformation fieldCI = new TaxonomyFieldCreationInformation()
                {
                    Id           = fieldId,
                    DisplayName  = fieldName,
                    InternalName = fieldName,
                    Group        = "Test Fields Group",
                    TaxonomyItem = termSet
                };
                //Add Enterprise keywords field so that we have at least two taxonomy fields in the list
                var keyworkdField = clientContext.Web.Fields.GetByInternalNameOrTitle("TaxKeyword");
                clientContext.Load(keyworkdField, f => f.Id);
                list.Fields.Add(keyworkdField);
                var field = list.CreateTaxonomyField(fieldCI);

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

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

                //First set a valid value in at least two taxonomy fields (same term can be used if one field is the keyword field)
                item.SetTaxonomyFieldValue(fieldId, _termName, _termId);
                item.SetTaxonomyFieldValue(keyworkdField.Id, _termName, _termId);

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

                Assert.AreEqual(2, (item["TaxCatchAll"] as FieldLookupValue[]).Length, "TaxCatchAll does not have 2 entries");
                var value = item[fieldName] as TaxonomyFieldValue;
                Assert.AreEqual(_termId.ToString(), value.TermGuid, "Term not set correctly");

                //Set a blank value in one of the taxonomy fields.
                item.SetTaxonomyFieldValue(fieldId, string.Empty, Guid.Empty);

                var taxonomyField = clientContext.CastTo <TaxonomyField>(field);
                clientContext.Load(taxonomyField, t => t.TextField);
                clientContext.Load(item, i => i[fieldName], i => i["TaxCatchAll"]);
                clientContext.ExecuteQueryRetry();

                var hiddenField = list.Fields.GetById(taxonomyField.TextField);
                clientContext.Load(hiddenField,
                                   f => f.InternalName);
                clientContext.ExecuteQueryRetry();

                Assert.AreEqual(1, (item["TaxCatchAll"] as FieldLookupValue[]).Length, "TaxCatchAll does not have 1 entry");
                object taxonomyFieldValue = item[fieldName];
                object hiddenFieldValue   = item[hiddenField.InternalName];
                Assert.IsNull(taxonomyFieldValue, "taxonomyFieldValue is not null");
                Assert.IsNull(hiddenFieldValue, "hiddenFieldValue is not null");
            }
        }
        public void ParseTests()
        {
            using (var ctx = TestCommon.CreateClientContext())
            {
                ctx.Load(ctx.Web,
                         w => w.Id,
                         w => w.ServerRelativeUrl,
                         w => w.Title,
                         w => w.AssociatedOwnerGroup.Title,
                         w => w.AssociatedMemberGroup.Title,
                         w => w.AssociatedVisitorGroup.Title,
                         w => w.AssociatedOwnerGroup.Id,
                         w => w.AssociatedMemberGroup.Id,
                         w => w.AssociatedVisitorGroup.Id);
                ctx.Load(ctx.Site, s => s.ServerRelativeUrl, s => s.Owner);

                var masterCatalog = ctx.Web.GetCatalog((int)ListTemplateType.MasterPageCatalog);
                ctx.Load(masterCatalog, m => m.RootFolder.ServerRelativeUrl);

                var themesCatalog = ctx.Web.GetCatalog((int)ListTemplateType.ThemeCatalog);
                ctx.Load(themesCatalog, t => t.RootFolder.ServerRelativeUrl);

                var expectedRoleDefinitionId = 1073741826;
                var roleDefinition           = ctx.Web.RoleDefinitions.GetById(expectedRoleDefinitionId);
                ctx.Load(roleDefinition);

                ctx.ExecuteQueryRetry();

                var currentUser = ctx.Web.EnsureProperty(w => w.CurrentUser);


                var ownerGroupName = ctx.Web.AssociatedOwnerGroup.Title;


                ProvisioningTemplate template = new ProvisioningTemplate();
                template.Parameters.Add("test", "test");
                template.Parameters.Add("test2", "test2");
                // Due to the refactoring of the parser only tokens specified in the template are loaded
                template.Parameters.Add("sitename", "{sitename}");
                template.Parameters.Add("siteid", "{siteid}");
                template.Parameters.Add("site", "{site}");
                template.Parameters.Add("sitecollection", "{sitecollection}");
                template.Parameters.Add("masterpagecatalog", "{masterpagecatalog}");
                template.Parameters.Add("themecatalog", "{themecatalog}");
                template.Parameters.Add("associatedownergroup", "{associatedownergroup}");
                template.Parameters.Add("associatedmembergroup", "{associatedmembergroup}");
                template.Parameters.Add("associatedvisitorgroup", "{associatedvisitorgroup}");
                template.Parameters.Add("currentuserid", "{currentuserid}");
                template.Parameters.Add("currentuserloginname", "{currentuserloginname}");
                template.Parameters.Add("currentuserfullname", "{currentuserfullname}");
                template.Parameters.Add("guid", "{guid}");
                template.Parameters.Add("groupid:associatedownergroup", "{groupid:associatedownergroup}");
                template.Parameters.Add("associatedownergroupid", "{associatedownergroupid}");
                template.Parameters.Add("siteowner", "{siteowner}");
                template.Parameters.Add("everyonebutexternalusers", "{everyonebutexternalusers}");
                template.Parameters.Add("roledefinitionid", "{roledefinitionid}");
                template.Parameters.Add("termid", "{termsetid:{parameter:test}:{parameter:test}}");

                var parser = new TokenParser(ctx.Web, template);
                parser.AddToken(new FieldIdToken(ctx.Web, "DemoField", new Guid("7E5E53E4-86C2-4A64-9F2E-FDFECE6219E0")));

                var          siteName                 = parser.ParseString("{sitename}");
                var          siteId                   = parser.ParseString("{siteid}");
                var          site                     = parser.ParseString("{site}/test");
                var          sitecol                  = parser.ParseString("{sitecollection}/test");
                var          masterUrl                = parser.ParseString("{masterpagecatalog}/test");
                var          themeUrl                 = parser.ParseString("{themecatalog}/test");
                var          parameterTest            = parser.ParseString("abc{parameter:TEST}/test");
                var          associatedOwnerGroup     = parser.ParseString("{associatedownergroup}");
                var          associatedVisitorGroup   = parser.ParseString("{associatedvisitorgroup}");
                var          associatedMemberGroup    = parser.ParseString("{associatedmembergroup}");
                var          currentUserId            = parser.ParseString("{currentuserid}");
                var          currentUserLoginName     = parser.ParseString("{currentuserloginname}");
                var          currentUserFullName      = parser.ParseString("{currentuserfullname}");
                var          guid                     = parser.ParseString("{guid}");
                var          associatedOwnerGroupId   = parser.ParseString("{groupid:associatedownergroup}");
                var          associatedMemberGroupId  = parser.ParseString("{groupid:associatedmembergroup}");
                var          associatedVisitorGroupId = parser.ParseString("{groupid:associatedvisitorgroup}");
                var          groupId                  = parser.ParseString($"{{groupid:{ownerGroupName}}}");
                var          siteOwner                = parser.ParseString("{siteowner}");
                var          roleDefinitionId         = parser.ParseString($"{{roledefinitionid:{roleDefinition.Name}}}");
                var          xamlEscapeString         = "{}{0}Id";
                var          parsedXamlEscapeString   = parser.ParseString(xamlEscapeString);
                const string fieldRef                 = @"<FieldRefs><FieldRef Name=""DemoField"" ID=""{7E5E53E4-86C2-4A64-9F2E-FDFECE6219E0}"" /></FieldRefs></Field>";
                var          parsedFieldRef           = parser.ParseString(@"<FieldRefs><FieldRef Name=""DemoField"" ID=""{{fieldid:DemoField}}"" /></FieldRefs></Field>");
                var          everyoneExceptExternals  = parser.ParseString("{everyonebutexternalusers}");



                Assert.IsTrue(site == $"{ctx.Web.ServerRelativeUrl}/test");
                Assert.IsTrue(sitecol == $"{ctx.Site.ServerRelativeUrl}/test");
                Assert.IsTrue(masterUrl == $"{masterCatalog.RootFolder.ServerRelativeUrl}/test");
                Assert.IsTrue(themeUrl == $"{themesCatalog.RootFolder.ServerRelativeUrl}/test");
                Assert.IsTrue(parameterTest == "abctest/test");
                Assert.IsTrue(associatedOwnerGroup == ctx.Web.AssociatedOwnerGroup.Title);
                Assert.IsTrue(associatedVisitorGroup == ctx.Web.AssociatedVisitorGroup.Title);
                Assert.IsTrue(associatedMemberGroup == ctx.Web.AssociatedMemberGroup.Title);
                Assert.IsTrue(siteName == ctx.Web.Title);
                Assert.IsTrue(siteId == ctx.Web.Id.ToString());
                Assert.IsTrue(currentUserId == currentUser.Id.ToString());
                Assert.IsTrue(currentUserFullName == currentUser.Title);
                Assert.IsTrue(currentUserLoginName.Equals(currentUser.LoginName, StringComparison.OrdinalIgnoreCase));
                // Guid token is
                Guid outGuid;
                Assert.IsTrue(Guid.TryParse(guid, out outGuid));
                Assert.IsTrue(int.Parse(associatedOwnerGroupId) == ctx.Web.AssociatedOwnerGroup.Id);
                Assert.IsTrue(int.Parse(associatedMemberGroupId) == ctx.Web.AssociatedMemberGroup.Id);
                Assert.IsTrue(int.Parse(associatedVisitorGroupId) == ctx.Web.AssociatedVisitorGroup.Id);
                Assert.IsTrue(associatedOwnerGroupId == groupId);
                Assert.IsTrue(siteOwner == ctx.Site.Owner.LoginName);
                Assert.IsTrue(roleDefinitionId == expectedRoleDefinitionId.ToString(), $"Role Definition Id was not parsed correctly (expected:{expectedRoleDefinitionId};returned:{roleDefinitionId})");
                Assert.IsTrue(parsedXamlEscapeString == xamlEscapeString);
                Assert.IsTrue(parsedFieldRef.ToUpperInvariant() == fieldRef.ToUpperInvariant());
            }
        }
        public void BasicPublishingPageOnPremisesTest()
        {
            using (var targetClientContext = TestCommon.CreateClientContext("https://bertonline.sharepoint.com/sites/modernizationusermapping"))
            {
                //https://bertonline.sharepoint.com/sites/modernizationtestportal
                //using (var sourceClientContext = TestCommon.CreateClientContext(TestCommon.AppSetting("SPODevSiteUrl")))
                AuthenticationManager authManager = new AuthenticationManager();
                using (var sourceClientContext = authManager.GetOnPremisesContext("https://portal2013.pnp.com/sites/devportal"))
                {
                    //"C:\github\sp-dev-modernization\Tools\SharePoint.Modernization\SharePointPnP.Modernization.Framework.Tests\Transform\Publishing\custompagelayoutmapping.xml"
                    //"C:\temp\mappingtest.xml"
                    var pageTransformator = new PublishingPageTransformator(sourceClientContext, targetClientContext, @"c:\github\zzscratch\pagelayoutmapping.xml");
                    pageTransformator.RegisterObserver(new MarkdownObserver(folder: "c:\\temp", includeVerbose: true));


                    var pages = sourceClientContext.Web.GetPagesFromList("Pages", "bug268");
                    //var pages = sourceClientContext.Web.GetPagesFromList("Pages", folder:"News");

                    foreach (var page in pages)
                    {
                        PublishingPageTransformationInformation pti = new PublishingPageTransformationInformation(page)
                        {
                            // If target page exists, then overwrite it
                            Overwrite = true,

                            // Don't log test runs
                            SkipTelemetry = true,

                            KeepPageCreationModificationInformation = true,

                            PostAsNews      = true,
                            UserMappingFile = @"C:\github\pnpframework\src\lib\PnP.Framework.Modernization.Test\Transform\Mapping\usermapping_sample2.csv",

                            //RemoveEmptySectionsAndColumns = false,

                            // Configure the page header, empty value means ClientSidePageHeaderType.None
                            //PageHeader = new ClientSidePageHeader(cc, ClientSidePageHeaderType.None, null),

                            // Replace embedded images and iframes with a placeholder and add respective images and video web parts at the bottom of the page
                            // HandleWikiImagesAndVideos = false,

                            // Callout to your custom code to allow for title overriding
                            //PageTitleOverride = titleOverride,

                            // Callout to your custom layout handler
                            //LayoutTransformatorOverride = layoutOverride,

                            // Callout to your custom content transformator...in case you fully want replace the model
                            //ContentTransformatorOverride = contentOverride,
                        };

                        pti.MappingProperties["SummaryLinksToQuickLinks"] = "true";
                        pti.MappingProperties["UseCommunityScriptEditor"] = "true";

                        var result = pageTransformator.Transform(pti);
                    }

                    pageTransformator.FlushObservers();
                }
            }
        }
示例#10
0
        public void CrossSiteDelveTransformTest()
        {
            using (var targetClientContext = TestCommon.CreateClientContext(TestCommon.AppSetting("SPOTargetSiteUrl")))
            {
                using (var sourceClientContext = TestCommon.CreateClientContext("https://bertonline.sharepoint.com/portals/personal/bertjansen"))
                {
                    var pageTransformator = new DelvePageTransformator(sourceClientContext, targetClientContext);
                    pageTransformator.RegisterObserver(new UnitTestLogObserver());

                    var pages = sourceClientContext.Web.GetBlogsFromList("Pages", "Delve");

                    foreach (var page in pages)
                    {
                        DelvePageTransformationInformation pti = new DelvePageTransformationInformation(page)
                        {
                            // If target page exists, then overwrite it
                            Overwrite = true,

                            // Don't log test runs
                            SkipTelemetry = true,

                            KeepPageCreationModificationInformation = true,

                            SetAuthorInPageHeader = true,

                            PostAsNews = true,

                            PublishCreatedPage = true,

                            KeepSubTitle = true,

                            //TargetPageFolder = "Blogs",

                            //SkipUserMapping = true,

                            //AddTableListImageAsImageWebPart = true,

                            // Configure the page header, empty value means ClientSidePageHeaderType.None
                            //PageHeader = new ClientSidePageHeader(cc, ClientSidePageHeaderType.None, null),

                            // Replace embedded images and iframes with a placeholder and add respective images and video web parts at the bottom of the page
                            // HandleWikiImagesAndVideos = false,

                            // Callout to your custom code to allow for title overriding
                            //PageTitleOverride = titleOverride,

                            // Callout to your custom layout handler
                            //LayoutTransformatorOverride = layoutOverride,

                            // Callout to your custom content transformator...in case you fully want replace the model
                            //ContentTransformatorOverride = contentOverride,
                        };

                        pti.MappingProperties["SummaryLinksToQuickLinks"] = "true";
                        pti.MappingProperties["UseCommunityScriptEditor"] = "true";

                        var result = pageTransformator.Transform(pti);
                    }
                }
            }

            //Assert.Inconclusive(TestCommon.InconclusiveNoAutomatedChecksMessage);
        }
示例#11
0
        public void CrossSiteBlogTransformTest()
        {
            using (var targetClientContext = TestCommon.CreateClientContext(TestCommon.AppSetting("SPOTargetSiteUrl")))
            {
                using (var sourceClientContext = TestCommon.CreateClientContext("https://bertonline.sharepoint.com/sites/modernizationtestpages/blog"))
                {
                    var pageTransformator = new PageTransformator(sourceClientContext, targetClientContext);
                    pageTransformator.RegisterObserver(new UnitTestLogObserver());

                    var pages = sourceClientContext.Web.GetBlogsFromList(CacheManager.Instance.GetBlogListName(sourceClientContext), "k");

                    foreach (var page in pages)
                    {
                        PageTransformationInformation pti = new PageTransformationInformation(page)
                        {
                            // If target page exists, then overwrite it
                            Overwrite = true,

                            // Don't log test runs
                            SkipTelemetry = true,

                            KeepPageCreationModificationInformation = true,

                            PostAsNews = true,

                            PublishCreatedPage = true,

                            CopyPageMetadata = true,

                            SetAuthorInPageHeader = true,

                            //TargetPageFolder = "Blogs",

                            //SkipUserMapping = true,

                            //AddTableListImageAsImageWebPart = true,

                            // ModernizationCenter options
                            //ModernizationCenterInformation = new ModernizationCenterInformation()
                            //{
                            //    AddPageAcceptBanner = true
                            //},

                            // Migrated page gets the name of the original page
                            //TargetPageTakesSourcePageName = true,

                            // Give the migrated page a specific prefix, default is Migrated_
                            //TargetPagePrefix = "Yes_",

                            // Configure the page header, empty value means ClientSidePageHeaderType.None
                            //PageHeader = new ClientSidePageHeader(cc, ClientSidePageHeaderType.None, null),

                            // If the page is a home page then replace with stock home page
                            //ReplaceHomePageWithDefaultHomePage = true,

                            // Replace embedded images and iframes with a placeholder and add respective images and video web parts at the bottom of the page
                            // HandleWikiImagesAndVideos = false,

                            // Callout to your custom code to allow for title overriding
                            //PageTitleOverride = titleOverride,

                            // Callout to your custom layout handler
                            //LayoutTransformatorOverride = layoutOverride,

                            // Callout to your custom content transformator...in case you fully want replace the model
                            //ContentTransformatorOverride = contentOverride,
                        };

                        pti.MappingProperties["SummaryLinksToQuickLinks"] = "true";
                        pti.MappingProperties["UseCommunityScriptEditor"] = "true";

                        var result = pageTransformator.Transform(pti);
                    }
                }
            }

            //Assert.Inconclusive(TestCommon.InconclusiveNoAutomatedChecksMessage);
        }
示例#12
0
        private void ProcessBaseTemplates(List <BaseTemplate> templates, bool deleteSites, bool createSites)
        {
            using (var tenantCtx = TestCommon.CreateTenantClientContext())
            {
                tenantCtx.RequestTimeout = Timeout.Infinite;
                Tenant tenant = new Tenant(tenantCtx);

#if !ONPREMISES
                if (deleteSites)
                {
                    // First delete all template site collections when in SPO
                    foreach (var template in templates)
                    {
                        string siteUrl = GetSiteUrl(template);

                        try
                        {
                            Console.WriteLine("Deleting existing site {0}", siteUrl);
                            tenant.DeleteSiteCollection(siteUrl, false);
                        }
                        catch { }
                    }
                }

                if (createSites)
                {
                    // Create site collections
                    foreach (var template in templates)
                    {
                        string siteUrl = GetSiteUrl(template);

                        Console.WriteLine("Creating site {0}", siteUrl);

                        bool siteExists = false;
                        if (template.SubSiteTemplate.Length > 0)
                        {
                            siteExists = tenant.SiteExists(siteUrl);
                        }

                        if (!siteExists)
                        {
                            tenant.CreateSiteCollection(new Entities.SiteEntity()
                            {
                                Lcid           = 1033,
                                TimeZoneId     = 4,
                                SiteOwnerLogin = (TestCommon.Credentials as SharePointOnlineCredentials).UserName,
                                Title          = "Template Site",
                                Template       = template.Template,
                                Url            = siteUrl,
                            }, true, true);
                        }

                        if (template.SubSiteTemplate.Length > 0)
                        {
                            using (ClientContext ctx = TestCommon.CreateClientContext())
                            {
                                using (var sitecolCtx = ctx.Clone(siteUrl))
                                {
                                    sitecolCtx.Web.Webs.Add(new WebCreationInformation()
                                    {
                                        Title    = string.Format("template{0}", template.SubSiteTemplate),
                                        Language = 1033,
                                        Url      = string.Format("template{0}", template.SubSiteTemplate.Replace("#", "")),
                                        UseSamePermissionsAsParentSite = true
                                    });
                                    sitecolCtx.ExecuteQueryRetry();
                                }
                            }
                        }
                    }
                }
#endif
            }

            // Export the base templates
            using (ClientContext ctx = TestCommon.CreateClientContext())
            {
                foreach (var template in templates)
                {
                    string siteUrl = GetSiteUrl(template, false);

                    // Export the base templates
                    using (ClientContext cc = ctx.Clone(siteUrl))
                    {
                        cc.RequestTimeout = Timeout.Infinite;

                        // Specify null as base template since we do want "everything" in this case
                        ProvisioningTemplateCreationInformation creationInfo = new ProvisioningTemplateCreationInformation(cc.Web);
                        creationInfo.BaseTemplate = null;
                        // Do not extract the home page for the base templates
                        creationInfo.HandlersToProcess ^= Handlers.PageContents;

                        // Override the save name. Case is online site collection provisioned using blankinternetcontainer#0 which returns
                        // blankinternet#0 as web template using CSOM/SSOM API
                        string templateName = template.Template;
                        if (template.SaveAsTemplate.Length > 0)
                        {
                            templateName = template.SaveAsTemplate;
                        }

                        ProvisioningTemplate p = cc.Web.GetProvisioningTemplate(creationInfo);
                        if (template.SubSiteTemplate.Length > 0)
                        {
                            p.Id = String.Format("{0}template", template.SubSiteTemplate.Replace("#", ""));
                        }
                        else
                        {
                            p.Id = String.Format("{0}template", templateName.Replace("#", ""));
                        }

                        // Cleanup before saving
                        p.Security.AdditionalAdministrators.Clear();

                        // persist the template using the XML provider
                        XMLFileSystemTemplateProvider provider = new XMLFileSystemTemplateProvider(".", "");
                        if (template.SubSiteTemplate.Length > 0)
                        {
                            provider.SaveAs(p, String.Format("{0}Template.xml", template.SubSiteTemplate.Replace("#", "")));
                        }
                        else
                        {
                            provider.SaveAs(p, String.Format("{0}Template.xml", templateName.Replace("#", "")));
                        }
                    }
                }
            }
        }
示例#13
0
        public void RunWPTest()
        {
            using (var cc = TestCommon.CreateClientContext())
            {
                var pageTransformator = new PageTransformator(cc);
                pageTransformator.RegisterObserver(new MarkdownObserver(folder: "c:\\temp", includeVerbose: true, includeDebugEntries: true));
                pageTransformator.RegisterObserver(new ConsoleObserver());

                var pages = cc.Web.GetPages("wp_");
                //var pages = cc.Web.GetPages("pagein", "folder1/sub1");
                //var pages = cc.Web.GetPagesFromList("SiteAssets", "loc_", "Folder1");
                foreach (var page in pages)
                {
                    PageTransformationInformation pti = new PageTransformationInformation(page)
                    {
                        // If target page exists, then overwrite it
                        Overwrite = true,

                        // Don't log test runs
                        SkipTelemetry = true,

                        //RemoveEmptySectionsAndColumns = false,

                        // ModernizationCenter options
                        //ModernizationCenterInformation = new ModernizationCenterInformation()
                        //{
                        //    AddPageAcceptBanner = true
                        //},

                        // Migrated page gets the name of the original page
                        //TargetPageTakesSourcePageName = true,

                        // Give the migrated page a specific prefix, default is Migrated_
                        //TargetPagePrefix = "Yes_",

                        // Configure the page header, empty value means ClientSidePageHeaderType.None
                        //PageHeader = new ClientSidePageHeader(cc, ClientSidePageHeaderType.None, null),

                        // If the page is a home page then replace with stock home page
                        //ReplaceHomePageWithDefaultHomePage = true,

                        // Replace embedded images and iframes with a placeholder and add respective images and video web parts at the bottom of the page
                        //HandleWikiImagesAndVideos = false,

                        // Callout to your custom code to allow for title overriding
                        //PageTitleOverride = titleOverride,

                        // Callout to your custom layout handler
                        //LayoutTransformatorOverride = layoutOverride,

                        // Callout to your custom content transformator...in case you fully want replace the model
                        //ContentTransformatorOverride = contentOverride,
                    };

                    pti.MappingProperties["SummaryLinksToQuickLinks"] = "true";
                    pti.MappingProperties["UseCommunityScriptEditor"] = "true";

                    pageTransformator.Transform(pti);
                }

                pageTransformator.FlushObservers();
            }
        }
        public void CanProvisionObjectsRequiredField()
        {
            XMLTemplateProvider provider = new XMLFileSystemTemplateProvider(resourceFolder, "");
            var template = provider.GetTemplate(resourceFolder + "/" + fileName);
            FileSystemConnector connector = new FileSystemConnector(resourceFolder, "");

            template.Connector = connector;
            // replace whatever files is in the template with a file we control
            template.Files.Clear();
            template.Files.Add(new Core.Framework.Provisioning.Model.File()
            {
                Overwrite = true, Src = fileName, Folder = "Lists/ProjectDocuments"
            });

            using (var ctx = TestCommon.CreateClientContext())
            {
                var parser = new TokenParser(ctx.Web, template);
                new ObjectField(FieldAndListProvisioningStepHelper.Step.ListAndStandardFields).ProvisionObjects(ctx.Web, template, parser,
                                                                                                                new ProvisioningTemplateApplyingInformation());
                new ObjectContentType(FieldAndListProvisioningStepHelper.Step.ListAndStandardFields).ProvisionObjects(ctx.Web, template, parser,
                                                                                                                      new ProvisioningTemplateApplyingInformation());
                new ObjectListInstance(FieldAndListProvisioningStepHelper.Step.ListAndStandardFields).ProvisionObjects(ctx.Web, template, parser,
                                                                                                                       new ProvisioningTemplateApplyingInformation());
                new ObjectListInstance(FieldAndListProvisioningStepHelper.Step.ListSettings).ProvisionObjects(ctx.Web, template, parser,
                                                                                                              new ProvisioningTemplateApplyingInformation());

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


                ctx.Web.EnsureProperties(w => w.ServerRelativeUrl);

                var file = ctx.Web.GetFileByServerRelativeUrl(
                    UrlUtility.Combine(ctx.Web.ServerRelativeUrl,
                                       UrlUtility.Combine("Lists/ProjectDocuments", fileName)));
                ctx.Load(file, f => f.Exists);
                ctx.ExecuteQueryRetry();
                Assert.IsTrue(file.Exists);

                // cleanup for artifacts specific to this test
                foreach (var list in template.Lists)
                {
                    ctx.Web.GetListByUrl(list.Url).DeleteObject();
                }

                foreach (var ct in template.ContentTypes)
                {
                    ctx.Web.GetContentTypeById(ct.Id).DeleteObject();
                }

                var idsToDelete = new List <Guid>();
                foreach (var field in ctx.Web.Fields)
                {
                    if (field.Group == "My Columns")
                    {
                        idsToDelete.Add(field.Id);
                    }
                }
                foreach (var guid in idsToDelete)
                {
                    ctx.Web.GetFieldById <Microsoft.SharePoint.Client.Field>(guid).DeleteObject();
                }
                ctx.ExecuteQueryRetry();
            }
        }
示例#15
0
        public void CanProvisionObjects()
        {
            var template = new ProvisioningTemplate();

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

            var termSets = new List <TermSet>();

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

            var terms = new List <Term>();

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

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

            var term1Subterm1Id = Guid.NewGuid();

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

            terms.Add(term1);

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

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

            termSet.Terms.AddRange(terms);

            termSets.Add(termSet);

            termGroup.TermSets.AddRange(termSets);

            template.TermGroups.Add(termGroup);

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

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

                TaxonomySession session = TaxonomySession.GetTaxonomySession(ctx);

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

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

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

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

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

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

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

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

                Assert.IsTrue(template.TermGroups.Any());
                Assert.IsInstanceOfType(template.TermGroups, typeof(PnP.Framework.Provisioning.Model.TermGroupCollection));
            }
        }
示例#16
0
        public void CleanUp()
        {
            using (var ctx = TestCommon.CreateClientContext())
            {
                var memberGroup = ctx.Web.AssociatedMemberGroup;
                ctx.Load(memberGroup);
                ctx.Load(ctx.Web, w => w.Url);
                ctx.ExecuteQueryRetry();
#if !ONPREMISES
                AllowScripting(ctx.Web.Url, !originalIsNoScriptSite);
#endif
                if (memberGroup.ServerObjectIsNull == false)
                {
                    foreach (var user in admins)
                    {
                        try
                        {
                            ctx.Web.RemoveUserFromGroup(memberGroup.Title, user.LoginName);
                        }
                        catch (ServerException)
                        {
                        }
                    }
                }

                var siteGroups = ctx.Web.SiteGroups;
                ctx.Load(siteGroups, sg => sg.Include(g => g.Title));
                ctx.ExecuteQueryRetry();
                IList <Group> groupsToRemove = new List <Group>();

                foreach (var group in siteGroups)
                {
                    if (group.Title.StartsWith("Test_"))
                    {
                        groupsToRemove.Add(group);
                    }
                }
                if (groupsToRemove.Count > 0)
                {
                    foreach (var group in groupsToRemove)
                    {
                        ctx.Web.SiteGroups.Remove(group);
                    }
                    ctx.ExecuteQueryRetry();
                }
                Web web = ctx.Web;

                //ConditionalScope associatedOwnerScope = new ConditionalScope(ctx, () => web.AssociatedOwnerGroup.ServerObjectIsNull == false);
                //using (associatedOwnerScope.StartScope())
                //{
                //    ctx.Load(web, w => w.AssociatedOwnerGroup.Id);
                //}

                //ConditionalScope associatedMemberScope = new ConditionalScope(ctx, () => web.AssociatedMemberGroup.ServerObjectIsNull == false);
                //using (associatedMemberScope.StartScope())
                //{
                //    ctx.Load(web, w => w.AssociatedMemberGroup.Id);
                //}

                //ConditionalScope associatedVisitorScope = new ConditionalScope(ctx, () => web.AssociatedVisitorGroup.ServerObjectIsNull == false);
                //using (associatedVisitorScope.StartScope())
                //{
                //    ctx.Load(web, w => w.AssociatedVisitorGroup.Id);
                //}

                //ctx.ExecuteQuery();

                bool webIsDirty = false;

                if (originalAssociatedOwnerGroupId > 0)
                {
                    web.AssociatedOwnerGroup = web.SiteGroups.GetById(originalAssociatedOwnerGroupId);
                    webIsDirty = true;
                }

                if (originalAssociatedMemberGroupId > 0)
                {
                    web.AssociatedMemberGroup = web.SiteGroups.GetById(originalAssociatedMemberGroupId);
                    webIsDirty = true;
                }

                if (originalAssociatedVisitorGroupId > 0)
                {
                    web.AssociatedVisitorGroup = web.SiteGroups.GetById(originalAssociatedVisitorGroupId);
                    webIsDirty = true;
                }

                if (webIsDirty)
                {
                    web.Update();
                }

                var websToDelete = new List <Web>();
                try {
                    var subWebs = ctx.Web.Webs; // this call fails in NoScript sites
                    ctx.Load(subWebs, wc => wc.Include(w => w.Title, w => w.ServerRelativeUrl));
                    ctx.ExecuteQueryRetry();

                    foreach (var subWeb in subWebs)
                    {
                        if (subWeb.Title.StartsWith("Test_"))
                        {
                            websToDelete.Add(subWeb);
                        }
                    }
                } catch (Exception e)
                {
                    Console.WriteLine("Error while accessing subwebs: " + e.ToDetailedString());
                }

                foreach (var webToDelete in websToDelete)
                {
                    Console.WriteLine("Deleting site {0}", webToDelete.ServerRelativeUrl);
                    webToDelete.DeleteObject();
                    try
                    {
                        ctx.ExecuteQueryRetry();
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine("Exception cleaning up: {0}", ex);
                    }
                }
            }
        }
示例#17
0
        public void CanProvisionReusableTerms()
        {
            var template = new ProvisioningTemplate();

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

            var termSets = new List <TermSet>();

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

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

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

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

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

            termGroup.TermSets.AddRange(termSets);

            template.TermGroups.Add(termGroup);

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

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

                TaxonomySession session = TaxonomySession.GetTaxonomySession(ctx);

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

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

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

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

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

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

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

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

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

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

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

                // note: this check that the IDs of the source and reused term are the same to document this behavior
                Assert.AreEqual(sourceTerm.Id, newTermGroup.TermSets[0].Terms[0].Id);
                Assert.AreEqual(sourceTerm.Id, newTermGroup.TermSets[1].Terms[0].Id);
                Assert.IsTrue(newTermGroup.TermSets[0].Terms[0].IsReused);
                Assert.IsTrue(newTermGroup.TermSets[1].Terms[0].IsReused);
            }
        }
示例#18
0
        public void CanProvisionAssociatedGroups()
        {
            ProvisioningTemplate template = new ProvisioningTemplate();

            template.Security.AssociatedOwnerGroup   = ownerGroupName;
            template.Security.AssociatedMemberGroup  = memberGroupName;
            template.Security.AssociatedVisitorGroup = visitorGroupName;
            template.Security.SiteGroups.Add(new SiteGroup()
            {
                Title = ownerGroupName
            });
            template.Security.SiteGroups.Add(new SiteGroup()
            {
                Title = memberGroupName
            });
            template.Security.SiteGroups.Add(new SiteGroup()
            {
                Title = visitorGroupName
            });
            foreach (var user in admins)
            {
                template.Security.AdditionalMembers.Add(new User()
                {
                    Name = user.LoginName
                });
            }

            using (var ctx = TestCommon.CreateClientContext())
            {
                InitializeAssociatedGroups(ctx);
                Web web = ctx.Web;

                var parser = new TokenParser(ctx.Web, template);
                new ObjectSiteSecurity().ProvisionObjects(web, template, parser, new ProvisioningTemplateApplyingInformation());

                ctx.Load(web,
                         w => w.AssociatedOwnerGroup.Id,
                         w => w.AssociatedMemberGroup.Id,
                         w => w.AssociatedVisitorGroup.Id);
                ctx.ExecuteQueryRetry();

                Assert.AreEqual(ownerGroupId, web.AssociatedOwnerGroup.Id, "Associated owner group ID mismatch.");
                Assert.AreEqual(memberGroupId, web.AssociatedMemberGroup.Id, "Associated member group ID mismatch.");
                Assert.AreEqual(visitorGroupId, web.AssociatedVisitorGroup.Id, "Associated visitor group ID mismatch.");
                IEnumerable <AssociatedGroupToken> associatedGroupTokens = parser.Tokens.Where(t => t.GetType() == typeof(AssociatedGroupToken)).Cast <AssociatedGroupToken>();

                AssociatedGroupToken associatedOwnerGroupToken   = associatedGroupTokens.FirstOrDefault(t => t.GroupType == AssociatedGroupToken.AssociatedGroupType.owners);
                AssociatedGroupToken associatedMemberGroupToken  = associatedGroupTokens.FirstOrDefault(t => t.GroupType == AssociatedGroupToken.AssociatedGroupType.members);
                AssociatedGroupToken associatedVisitorGroupToken = associatedGroupTokens.FirstOrDefault(t => t.GroupType == AssociatedGroupToken.AssociatedGroupType.visitors);

                Assert.IsNotNull(associatedOwnerGroupToken);
                Assert.IsNotNull(associatedMemberGroupToken);
                Assert.IsNotNull(associatedVisitorGroupToken);

                Assert.AreEqual(ownerGroupName, associatedOwnerGroupToken.GetReplaceValue());
                Assert.AreEqual(memberGroupName, associatedMemberGroupToken.GetReplaceValue());
                Assert.AreEqual(visitorGroupName, associatedVisitorGroupToken.GetReplaceValue());

                foreach (var user in admins)
                {
                    var existingUser = web.AssociatedMemberGroup.Users.GetByLoginName(user.LoginName);
                    ctx.Load(existingUser);
                    ctx.ExecuteQueryRetry();
                    Assert.IsNotNull(existingUser);
                }
            }
        }
示例#19
0
        public void ReorderContentTypesTest()
        {
            using (var clientContext = TestCommon.CreateClientContext())
            {
                var web = clientContext.Web;
                clientContext.Load(web, w => w.ContentTypes);
                clientContext.ExecuteQueryRetry();

                // create content types
                var documentCtype = web.ContentTypes.FirstOrDefault(ct => ct.Name == "Document");
                var newCtypeInfo1 = new ContentTypeCreationInformation()
                {
                    Name = "Test_ContentType1",
                    ParentContentType = documentCtype,
                    Group             = "Test content types",
                    Description       = "This is a test content type"
                };
                var newCtypeInfo2 = new ContentTypeCreationInformation()
                {
                    Name = "Test_ContentType2",
                    ParentContentType = documentCtype,
                    Group             = "Test content types",
                    Description       = "This is a test content type"
                };
                var newCtypeInfo3 = new ContentTypeCreationInformation()
                {
                    Name = "Test_ContentType3",
                    ParentContentType = documentCtype,
                    Group             = "Test content types",
                    Description       = "This is a test content type"
                };

                var newCtype1 = web.ContentTypes.Add(newCtypeInfo1);
                var newCtype2 = web.ContentTypes.Add(newCtypeInfo2);
                var newCtype3 = web.ContentTypes.Add(newCtypeInfo3);
                clientContext.Load(newCtype1);
                clientContext.Load(newCtype2);
                clientContext.Load(newCtype3);
                clientContext.ExecuteQueryRetry();

                var newList = new ListCreationInformation()
                {
                    TemplateType = (int)ListTemplateType.DocumentLibrary,
                    Title        = DOC_LIB_TITLE,
                    Url          = "TestLibrary"
                };

                var doclib = clientContext.Web.Lists.Add(newList);
                doclib.ContentTypesEnabled = true;
                doclib.ContentTypes.AddExistingContentType(newCtype1);
                doclib.ContentTypes.AddExistingContentType(newCtype2);
                doclib.ContentTypes.AddExistingContentType(newCtype3);
                doclib.Update();
                clientContext.Load(doclib.ContentTypes);
                clientContext.ExecuteQueryRetry();

                var expectedIds = new string[] {
                    newCtype3.Name,
                    newCtype1.Name,
                    newCtype2.Name,
                    documentCtype.Name
                };

                doclib.ReorderContentTypes(expectedIds);
                var reorderedCtypes = clientContext.LoadQuery(doclib.ContentTypes);
                clientContext.ExecuteQueryRetry();

                var actualIds = reorderedCtypes.Except(
                    // remove the folder content type
                    reorderedCtypes.Where(ct => ct.Id.StringValue.StartsWith("0x012000"))
                    ).Select(ct => ct.Name).ToArray();

                CollectionAssert.AreEqual(expectedIds, actualIds);
            }
        }
示例#20
0
        public async Task CanExportAndImportAssociatedGroupsProperlyInNewNoScriptSite()
        {
            if (TestCommon.AppOnlyTesting())
            {
                Assert.Inconclusive("Site creation requires owner, so this will not yet work in app-only");
            }

            var newCommSiteUrl = "";
            var newSiteTitle   = "Comm Site Test - Groups";
            var loginName      = "";
            ProvisioningTemplate template;

            using (var clientContext = TestCommon.CreateClientContext())
            {
                // get the template from real site as this produced the template that lead to too many groups being created which lead to #2127
                var creationInfo = new ProvisioningTemplateCreationInformation(clientContext.Web);
                creationInfo.HandlersToProcess = Handlers.SiteSecurity;
                template = clientContext.Web.GetProvisioningTemplate();

                var user = clientContext.Web.CurrentUser;
                clientContext.Load(user);
                clientContext.ExecuteQueryRetry();
                loginName = user.LoginName;
                template.Security.AdditionalMembers.Add(new User()
                {
                    Name = loginName
                });
                template.Security.AdditionalOwners.Add(new User()
                {
                    Name = loginName
                });
                template.Security.AdditionalVisitors.Add(new User()
                {
                    Name = loginName
                });

                newCommSiteUrl = await CreateCommunicationSite(clientContext, newSiteTitle);
            }
            try
            {
                using (var ctx = TestCommon.CreateClientContext(newCommSiteUrl))
                {
                    Web web = ctx.Web;

                    var parser = new TokenParser(ctx.Web, template);
                    new ObjectSiteSecurity().ProvisionObjects(web, template, parser, new ProvisioningTemplateApplyingInformation());

                    await WaitForAsyncGroupTitleChangeWithTimeout(ctx);

                    ctx.Load(web,
                             w => w.SiteGroups,
                             w => w.AssociatedOwnerGroup.Users,
                             w => w.AssociatedOwnerGroup.Title,
                             w => w.AssociatedMemberGroup.Users,
                             w => w.AssociatedMemberGroup.Title,
                             w => w.AssociatedVisitorGroup.Users,
                             w => w.AssociatedVisitorGroup.Title);
                    ctx.ExecuteQueryRetry();

                    Assert.AreEqual(3, web.SiteGroups.Count, "Unexpected number of groups found");
                    Assert.AreEqual(1, web.AssociatedVisitorGroup.Users.Count(u => u.LoginName == loginName));
                    Assert.AreEqual(1, web.AssociatedMemberGroup.Users.Count(u => u.LoginName == loginName));
                    Assert.AreEqual(1, web.AssociatedOwnerGroup.Users.Count(u => u.LoginName == loginName));
                    Assert.AreEqual(newSiteTitle + " Visitors", web.AssociatedVisitorGroup.Title);
                    Assert.AreEqual(newSiteTitle + " Members", web.AssociatedMemberGroup.Title);
                    Assert.AreEqual(newSiteTitle + " Owners", web.AssociatedOwnerGroup.Title);
                }
            } finally
            {
                using (var clientContext = TestCommon.CreateTenantClientContext())
                {
                    var tenant = new Tenant(clientContext);
                    tenant.DeleteSiteCollection(newCommSiteUrl, false);
                }
            }
        }
        public void Initialize()
        {
            if (!TestCommon.AppOnlyTesting())
            {
                Console.WriteLine("TaxonomyExtensionsTests.Initialise");
                // 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();

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

                    // Termgroup
                    // Does the termgroup exist?
                    var termGroup = termStore.GetGroup(_termGroupId);
                    clientContext.Load(termGroup, g => g.Id);
                    clientContext.ExecuteQueryRetry();

                    // Create if non existant
                    if (termGroup.ServerObjectIsNull.Value)
                    {
                        termGroup = termStore.CreateGroup(_termGroupName, _termGroupId);
                        clientContext.Load(termGroup);
                        clientContext.ExecuteQueryRetry();
                    }

                    // Termset
                    // Does the termset exist?
                    var termSet = termStore.GetTermSet(_termSetId);
                    clientContext.Load(termSet, ts => ts.Id);
                    clientContext.ExecuteQueryRetry();

                    // Create if non existant
                    if (termSet.ServerObjectIsNull.Value)
                    {
                        termSet = termGroup.CreateTermSet(_termSetName, _termSetId, 1033);
                        clientContext.Load(termSet);
                        clientContext.ExecuteQueryRetry();
                    }

                    // Term
                    // Does the term exist?
                    var term = termStore.GetTerm(_termId);
                    clientContext.Load(term, t => t.Id);
                    clientContext.ExecuteQueryRetry();

                    // Create if non existant
                    if (term.ServerObjectIsNull.Value)
                    {
                        term = termSet.CreateTerm(_termName, 1033, _termId);
                        clientContext.ExecuteQueryRetry();
                    }
                    else
                    {
                        var label = term.GetDefaultLabel(1033);
                        clientContext.ExecuteQueryRetry();
                        _termName = label.Value;
                    }

                    // List
                    ListCreationInformation listCI = new ListCreationInformation();
                    listCI.TemplateType = (int)ListTemplateType.GenericList;
                    listCI.Title        = "Test_List_" + DateTime.Now.ToFileTime();
                    var list = clientContext.Web.Lists.Add(listCI);
                    clientContext.Load(list);
                    clientContext.ExecuteQueryRetry();
                    _listId = list.Id;
                }
            }
            else
            {
                Assert.Inconclusive("Taxonomy tests are not supported when testing using app-only");
            }
        }
示例#22
0
        public async Task CanMapAssociatedGroupsToExistingOnesInNewScriptSite()
        {
            if (TestCommon.AppOnlyTesting())
            {
                Assert.Inconclusive("Site creation requires owner, so this will not yet work in app-only");
            }

            var newCommSiteUrl = string.Empty;

            ProvisioningTemplate template = new ProvisioningTemplate();

            template.Security.AssociatedOwnerGroup   = "These names shouldn't matter";
            template.Security.AssociatedMemberGroup  = "Site Members";
            template.Security.AssociatedVisitorGroup = "Dummy Visitors";
            // note: there are explicitly no SiteGroups defined

            using (var clientContext = TestCommon.CreateClientContext())
            {
                newCommSiteUrl = await CreateCommunicationSite(clientContext, "Dummy", true);
            }

            try
            {
                using (var ctx = TestCommon.CreateClientContext(newCommSiteUrl))
                {
                    ctx.Load(ctx.Web,
                             w => w.AssociatedOwnerGroup.Id,
                             w => w.AssociatedMemberGroup.Id,
                             w => w.AssociatedVisitorGroup.Id);
                    ctx.ExecuteQuery();
                    var oldOwnerGroupId   = ctx.Web.AssociatedOwnerGroup.Id;
                    var oldMemberGroupId  = ctx.Web.AssociatedMemberGroup.Id;
                    var oldVisitorGroupId = ctx.Web.AssociatedVisitorGroup.Id;

                    var parser = new TokenParser(ctx.Web, template);
                    new ObjectSiteSecurity().ProvisionObjects(ctx.Web, template, parser, new ProvisioningTemplateApplyingInformation());
                    await WaitForAsyncGroupTitleChangeWithTimeout(ctx);

                    ctx.Load(ctx.Web,
                             w => w.AssociatedOwnerGroup.Id,
                             w => w.AssociatedMemberGroup.Id,
                             w => w.AssociatedVisitorGroup.Id);
                    ctx.ExecuteQuery();
                    var newOwnerGroupId   = ctx.Web.AssociatedOwnerGroup.Id;
                    var newMemberGroupId  = ctx.Web.AssociatedMemberGroup.Id;
                    var newVisitorGroupId = ctx.Web.AssociatedVisitorGroup.Id;

                    Assert.AreEqual(oldOwnerGroupId, newOwnerGroupId, "Unexpected new associated owner group");
                    Assert.AreEqual(oldMemberGroupId, newMemberGroupId, "Unexpected new associated member group");
                    Assert.AreEqual(oldVisitorGroupId, newVisitorGroupId, "Unexpected new associated visitor group");
                }
            }
            finally
            {
                using (var clientContext = TestCommon.CreateTenantClientContext())
                {
                    var tenant = new Tenant(clientContext);
                    tenant.DeleteSiteCollection(newCommSiteUrl, false);
                }
            }
        }
        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);
            }
        }
示例#24
0
        public async Task CanCreateNewAssociatedGroupsInNewScriptSite_CreateNewAssociatedGroup()
        {
            if (TestCommon.AppOnlyTesting())
            {
                Assert.Inconclusive("Site creation requires owner, so this will not yet work in app-only");
            }

            var newCommSiteUrl = string.Empty;

            ProvisioningTemplate template    = new ProvisioningTemplate();
            SiteGroup            ownersGroup = new SiteGroup()
            {
                Title = string.Format("Test_New Group_{0}", DateTime.Now.Ticks),
            };

            template.Security.SiteGroups.Add(ownersGroup);
            template.Security.AssociatedOwnerGroup = ownersGroup.Title;

            using (var clientContext = TestCommon.CreateClientContext())
            {
                newCommSiteUrl = await CreateCommunicationSite(clientContext, "Dummy", true);
            }

            try
            {
                using (var ctx = TestCommon.CreateClientContext(newCommSiteUrl))
                {
                    LoadAssociatedOwnerGroupsData(ctx);
                    var oldOwnerGroupId   = ctx.Web.AssociatedOwnerGroup.Id;
                    var oldMemberGroupId  = ctx.Web.AssociatedMemberGroup.Id;
                    var oldVisitorGroupId = ctx.Web.AssociatedVisitorGroup.Id;
                    var oldSiteGroupCount = ctx.Web.SiteGroups.Count;

                    var parser = new TokenParser(ctx.Web, template);
                    new ObjectSiteSecurity().ProvisionObjects(ctx.Web, template, parser, new ProvisioningTemplateApplyingInformation());
                    await WaitForAsyncGroupTitleChangeWithTimeout(ctx);

                    LoadAssociatedOwnerGroupsData(ctx, true);
                    var newOwnerGroupId    = ctx.Web.AssociatedOwnerGroup.Id;
                    var newMemberGroupId   = ctx.Web.AssociatedMemberGroup.Id;
                    var newVisitorGroupId  = ctx.Web.AssociatedVisitorGroup.Id;
                    var newSiteGroupsCount = ctx.Web.SiteGroups.Count;
                    var group = ctx.Web.SiteGroups.First(sg => sg.Title == ownersGroup.Title);

                    Assert.AreEqual(group.Id, newOwnerGroupId, "Expected owners group to change");
                    Assert.AreEqual(oldMemberGroupId, newMemberGroupId, "Expected members group to stay the same");
                    Assert.AreEqual(oldVisitorGroupId, newVisitorGroupId, "Expected visitors group to stay the same");
                    Assert.AreEqual(oldSiteGroupCount + 1, newSiteGroupsCount, "Expected only one group to be created");

                    // and apply a second time to be sure this works as well
                    new ObjectSiteSecurity().ProvisionObjects(ctx.Web, template, parser, new ProvisioningTemplateApplyingInformation());
                    LoadAssociatedOwnerGroupsData(ctx, true);
                    Assert.AreEqual(newOwnerGroupId, ctx.Web.AssociatedOwnerGroup.Id, "Expected owners group to stay the same");
                    Assert.AreEqual(newMemberGroupId, ctx.Web.AssociatedMemberGroup.Id, "Expected members group to stay the same");
                    Assert.AreEqual(newVisitorGroupId, ctx.Web.AssociatedVisitorGroup.Id, "Expected visitors group to stay the same");
                    Assert.AreEqual(newSiteGroupsCount, ctx.Web.SiteGroups.Count, "Expected no new groups to be created");
                }
            }
            finally
            {
                using (var clientContext = TestCommon.CreateTenantClientContext())
                {
                    var tenant = new Tenant(clientContext);
                    tenant.DeleteSiteCollection(newCommSiteUrl, false);
                }
            }
        }
        public void RegexSpecialCharactersTests()
        {
            using (var ctx = TestCommon.CreateClientContext())
            {
                ctx.Load(ctx.Web, w => w.Id, w => w.ServerRelativeUrl, w => w.Title, w => w.AssociatedOwnerGroup.Title, w => w.AssociatedMemberGroup.Title, w => w.AssociatedVisitorGroup.Title);
                ctx.Load(ctx.Site, s => s.ServerRelativeUrl);

                ctx.ExecuteQueryRetry();

                var currentUser = ctx.Web.EnsureProperty(w => w.CurrentUser);

                ProvisioningTemplate template = new ProvisioningTemplate();
                template.Parameters.Add("test(T)", "test");

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

                var web = ctx.Web;

                var contentTypeName = "Test CT (TC) [TC].$";
                var contentTypeId   = "0x010801006439AECCDEAE4db2A422A3A04C79CC83";
                var listGuid        = Guid.NewGuid();
                var listTitle       = @"List (\,*+?|{[()^$.#";
                var listUrl         = "Lists/TestList";
                var webPartTitle    = @"Webpart (\*+?|{[()^$.#";
                var webPartId       = Guid.NewGuid();
                var termSetName     = @"Test TermSet (\*+?{[()^$.#";
                var termGroupName   = @"Group Name (\*+?{[()^$.#";
                var termStoreName   = @"Test TermStore (\*+?{[()^$.#";
                var termSetId       = Guid.NewGuid();
                var termStoreId     = Guid.NewGuid();


                // Use fake data
                parser.AddToken(new ContentTypeIdToken(web, contentTypeName, contentTypeId));
                parser.AddToken(new ListIdToken(web, listTitle, listGuid));
                parser.AddToken(new ListUrlToken(web, listTitle, listUrl));
                parser.AddToken(new WebPartIdToken(web, webPartTitle, webPartId));
                parser.AddToken(new TermSetIdToken(web, termGroupName, termSetName, termSetId));
                parser.AddToken(new TermStoreIdToken(web, termStoreName, termStoreId));

                var resolvedContentTypeId = parser.ParseString($"{{contenttypeid:{contentTypeName}}}");
                var resolvedListId        = parser.ParseString($"{{listid:{listTitle}}}");
                var resolvedListUrl       = parser.ParseString($"{{listurl:{listTitle}}}");

                var parameterExpectedResult = $"abc{"test"}/test";
                var parameterTest1          = parser.ParseString("abc{parameter:TEST(T)}/test");
                var parameterTest2          = parser.ParseString("abc{$test(T)}/test");
                var resolvedWebpartId       = parser.ParseString($"{{webpartid:{webPartTitle}}}");
                var resolvedTermSetId       = parser.ParseString($"{{termsetid:{termGroupName}:{termSetName}}}");
                var resolvedTermStoreId     = parser.ParseString($"{{termstoreid:{termStoreName}}}");


                Assert.IsTrue(contentTypeId == resolvedContentTypeId);
                Assert.IsTrue(listUrl == resolvedListUrl);
                Guid outGuid;
                Assert.IsTrue(Guid.TryParse(resolvedListId, out outGuid));
                Assert.IsTrue(parameterTest1 == parameterExpectedResult);
                Assert.IsTrue(parameterTest2 == parameterExpectedResult);
                Assert.IsTrue(Guid.TryParse(resolvedWebpartId, out outGuid));
                Assert.IsTrue(Guid.TryParse(resolvedTermSetId, out outGuid));
                Assert.IsTrue(Guid.TryParse(resolvedTermStoreId, out outGuid));
            }
        }
示例#26
0
        public async Task CanCreateNewAssociatedGroupsInNewScriptSite_AfterAsyncRename()
        {
            if (TestCommon.AppOnlyTesting())
            {
                Assert.Inconclusive("Site creation requires owner, so this will not yet work in app-only");
            }

            var newCommSiteUrl = string.Empty;
            var siteTitle      = "Dummy";

            ProvisioningTemplate template    = new ProvisioningTemplate();
            SiteGroup            ownersGroup = new SiteGroup()
            {
                // this should map to existing group
                Title = siteTitle + " Owners",
            };

            template.Security.SiteGroups.Add(ownersGroup);
            template.Security.AssociatedOwnerGroup = ownersGroup.Title;

            using (var clientContext = TestCommon.CreateClientContext())
            {
                newCommSiteUrl = await CreateCommunicationSite(clientContext, siteTitle, true);
            }

            try
            {
                using (var ctx = TestCommon.CreateClientContext(newCommSiteUrl))
                {
                    LoadAssociatedOwnerGroupsData(ctx);
                    var oldOwnerGroupId   = ctx.Web.AssociatedOwnerGroup.Id;
                    var oldMemberGroupId  = ctx.Web.AssociatedMemberGroup.Id;
                    var oldVisitorGroupId = ctx.Web.AssociatedVisitorGroup.Id;
                    var oldGroupCount     = ctx.Web.SiteGroups.Count;

                    var parser = new TokenParser(ctx.Web, template);
                    // wait for async rename
                    await WaitForAsyncGroupTitleChangeWithTimeout(ctx);

                    // now provision - new site titles are in place
                    new ObjectSiteSecurity().ProvisionObjects(ctx.Web, template, parser, new ProvisioningTemplateApplyingInformation());

                    LoadAssociatedOwnerGroupsData(ctx);
                    var newOwnerGroupId   = ctx.Web.AssociatedOwnerGroup.Id;
                    var newMemberGroupId  = ctx.Web.AssociatedMemberGroup.Id;
                    var newVisitorGroupId = ctx.Web.AssociatedVisitorGroup.Id;
                    var newGroupCount     = ctx.Web.SiteGroups.Count;

                    Assert.AreEqual(oldOwnerGroupId, newOwnerGroupId, "Expected owners group to stay the same");
                    Assert.AreEqual(oldMemberGroupId, newMemberGroupId, "Expected members group to stay the same");
                    Assert.AreEqual(oldVisitorGroupId, newVisitorGroupId, "Expected visitors group to stay the same");
                    Assert.AreEqual(oldGroupCount, newGroupCount, "Expected no new groups to be created");
                }
            }
            finally
            {
                using (var clientContext = TestCommon.CreateTenantClientContext())
                {
                    var tenant = new Tenant(clientContext);
                    tenant.DeleteSiteCollection(newCommSiteUrl, false);
                }
            }
        }
示例#27
0
        public void CanProvisionReusableTerms()
        {
            var template = new ProvisioningTemplate();

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

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

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

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


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


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

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

            termGroup.TermSets.AddRange(termSets);

            template.TermGroups.Add(termGroup);

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

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

                TaxonomySession session = TaxonomySession.GetTaxonomySession(ctx);

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

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

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

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

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

                var createdReusedTerm = set1.GetTerm(reusedTerm.Id);
                ctx.Load(createdReusedTerm, c => c.SourceTerm, c => c.IsReused);
                ctx.ExecuteQueryRetry();
                Assert.IsTrue(createdReusedTerm.SourceTerm.Id == sourceTerm.Id);
                Assert.IsTrue(createdReusedTerm.IsReused);
            }
        }
示例#28
0
        public async Task CanMapToExistingGroupsInNewScriptSite()
        {
            if (TestCommon.AppOnlyTesting())
            {
                Assert.Inconclusive("Site creation requires owner, so this will not yet work in app-only");
            }

            var newCommSiteUrl = string.Empty;

            ProvisioningTemplate template = new ProvisioningTemplate();
            // check setting of owner group with a configuration that would also create the group
            var       ownerGroupTitle = string.Format("Test_New OWNER Group_{0}", DateTime.Now.Ticks);
            SiteGroup ownerGroup      = new SiteGroup()
            {
                Title = ownerGroupTitle
            };

            template.Security.AssociatedOwnerGroup = ownerGroup.Title;
            template.Security.SiteGroups.Add(ownerGroup);

            // check setting of member group with a configuration that only works if the group already exists in the web
            var memberGroupTitle = string.Format("Test_New MEMBER Group_{0}", DateTime.Now.Ticks);

            template.Security.AssociatedMemberGroup = memberGroupTitle;

            using (var clientContext = TestCommon.CreateClientContext())
            {
                newCommSiteUrl = await CreateCommunicationSite(clientContext, "Dummy", true);
            }

            try
            {
                using (var ctx = TestCommon.CreateClientContext(newCommSiteUrl))
                {
                    // pre-create owner and member group to test mapping
                    ctx.Web.SiteGroups.Add(new GroupCreationInformation()
                    {
                        Title = ownerGroupTitle
                    });
                    ctx.Web.SiteGroups.Add(new GroupCreationInformation()
                    {
                        Title = memberGroupTitle
                    });
                    ctx.ExecuteQueryRetry();
                    ctx.Load(ctx.Web, w => w.SiteGroups.Include(
                                 g => g.Id,
                                 g => g.Title),
                             w => w.AssociatedVisitorGroup);
                    ctx.ExecuteQueryRetry();
                    var newOwnerGroup  = ctx.Web.SiteGroups.First(g => g.Title == ownerGroupTitle);
                    var newMemberGroup = ctx.Web.SiteGroups.First(g => g.Title == memberGroupTitle);
                    var oldAssociatedVisitorGroupId = ctx.Web.AssociatedVisitorGroup.Id;

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

                    LoadAssociatedOwnerGroupsData(ctx, true);
                    var associatedOwnerGroupId   = ctx.Web.AssociatedOwnerGroup.Id;
                    var associatedMemberGroupId  = ctx.Web.AssociatedMemberGroup.Id;
                    var associatedVisitorGroupId = ctx.Web.AssociatedVisitorGroup.Id;

                    Assert.AreEqual(newOwnerGroup.Id, associatedOwnerGroupId, "Expected owners group to change");
                    Assert.AreEqual(newMemberGroup.Id, associatedMemberGroupId, "Expected members group to change");
                    Assert.AreEqual(oldAssociatedVisitorGroupId, associatedVisitorGroupId, "Expected visitors group to stay the same");
                }
            }
            finally
            {
                using (var clientContext = TestCommon.CreateTenantClientContext())
                {
                    var tenant = new Tenant(clientContext);
                    tenant.DeleteSiteCollection(newCommSiteUrl, false);
                }
            }
        }
示例#29
0
        public void CleanUp()
        {
            Console.WriteLine("BrandingExtensionsTests.CleanUp");

            if (System.IO.File.Exists(customColorFilePath))
            {
                System.IO.File.Delete(customColorFilePath);
            }
            if (System.IO.File.Exists(customBackgroundFilePath))
            {
                System.IO.File.Delete(customBackgroundFilePath);
            }

            using (var context = TestCommon.CreateClientContext())
            {
                var web = context.Web;

                // Remove composed looks from server
                List      themeGallery = web.GetCatalog((int)ListTemplateType.DesignCatalog);
                CamlQuery query        = new CamlQuery();
                string    camlString   = @"
                    <View>
                        <Query>                
                            <Where>
                                <Contains>
                                    <FieldRef Name='Name' />
                                    <Value Type='Text'>Test_</Value>
                                </Contains>
                            </Where>
                        </Query>
                    </View>";
                query.ViewXml = camlString;
                var found = themeGallery.GetItems(query);
                web.Context.Load(found);
                web.Context.ExecuteQueryRetry();
                Console.WriteLine("{0} matching looks found to delete", found.Count);
                var looksToDelete = found.ToList();
                foreach (var item in looksToDelete)
                {
                    Console.WriteLine("Delete look item '{0}'", item["Name"]);
                    item.DeleteObject();
                    context.ExecuteQueryRetry();
                }

                // Remove Theme Files
                List             themesList  = web.GetCatalog((int)ListTemplateType.ThemeCatalog);
                Folder           rootFolder  = themesList.RootFolder;
                FolderCollection rootFolders = rootFolder.Folders;
                web.Context.Load(rootFolder);
                web.Context.Load(rootFolders, f => f.Where(folder => folder.Name == "15"));
                web.Context.ExecuteQueryRetry();

                Folder folder15 = rootFolders.FirstOrDefault();

                try
                {
                    Microsoft.SharePoint.Client.File customColorFile = folder15.Files.GetByUrl("custom.spcolor");
                    customColorFile.DeleteObject();
                    context.ExecuteQueryRetry();
                }
                catch (Exception ex)
                {
                    Console.WriteLine("Exception cleaning up: {0}", ex);
                }

                try
                {
                    Microsoft.SharePoint.Client.File customBackgroundFile = folder15.Files.GetByUrl("custombg.jpg");
                    customBackgroundFile.DeleteObject();
                    context.ExecuteQueryRetry();
                }
                catch (Exception ex)
                {
                    Console.WriteLine("Exception cleaning up: {0}", ex);
                }

                // Remove webs
                var webCollection1 = web.Webs;
                context.Load(webCollection1, wc => wc.Include(w => w.Title, w => w.ServerRelativeUrl));
                context.ExecuteQueryRetry();
                var websToDelete = new List <Web>();
                foreach (var web1 in webCollection1)
                {
                    if (web1.Title.StartsWith("Test_"))
                    {
                        var webCollection2 = web1.Webs;
                        context.Load(webCollection2, wc => wc.Include(w => w.Title, w => w.ServerRelativeUrl));
                        context.ExecuteQueryRetry();
                        var childrenToDelete = new List <Web>(webCollection2);
                        foreach (var web2 in childrenToDelete)
                        {
                            Console.WriteLine("Deleting site {0}", web2.ServerRelativeUrl);
                            web2.DeleteObject();
                            context.ExecuteQueryRetry();
                        }
                        websToDelete.Add(web1);
                    }
                }

                foreach (var web1 in websToDelete)
                {
                    Console.WriteLine("Deleting site {0}", web1.ServerRelativeUrl);
                    web1.DeleteObject();
                    try
                    {
                        context.ExecuteQueryRetry();
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine("Exception cleaning up: {0}", ex);
                    }
                }

                // Remove pagelayouts
                List   masterPageGallery             = context.Web.GetCatalog((int)ListTemplateType.MasterPageCatalog);
                Folder rootFolderInMasterPageGallery = masterPageGallery.RootFolder;
                context.Load(rootFolderInMasterPageGallery, f => f.ServerRelativeUrl);
                context.ExecuteQueryRetry();

                try
                {
                    var fileServerRelativeUrl = UrlUtility.Combine(rootFolderInMasterPageGallery.ServerRelativeUrl, publishingPageWithoutExtension);
                    var file = context.Web.GetFileByServerRelativeUrl(String.Format("{0}.aspx", fileServerRelativeUrl));
                    context.Load(file);
                    context.ExecuteQueryRetry();
                    file.DeleteObject();
                    context.ExecuteQueryRetry();

                    fileServerRelativeUrl = UrlUtility.Combine(rootFolderInMasterPageGallery.ServerRelativeUrl, "test/test", publishingPageWithoutExtension);
                    file = context.Web.GetFileByServerRelativeUrl(String.Format("{0}.aspx", fileServerRelativeUrl));
                    context.Load(file);
                    context.ExecuteQueryRetry();
                    file.DeleteObject();
                    context.ExecuteQueryRetry();
                }
                catch (Exception ex)
                {
                    Console.WriteLine("Exception cleaning up: {0}", ex);
                }
            }

            Teardown();
        }
 public void Initialize()
 {
     clientContext      = TestCommon.CreateClientContext();
     sitecollectionName = sitecollectionNamePrefix + Guid.NewGuid().ToString();
 }