Exemple #1
0
        public void PageBannerTest()
        {
            using (var cc = TestCommon.CreateClientContext("https://bertonline.sharepoint.com/sites/contosoelectronicsdrones"))
            {
                var pageTransformator = new PageTransformator(cc);

                var pages = cc.Web.GetPages("d95");

                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,

                        // Modernization center setup
                        ModernizationCenterInformation = new ModernizationCenterInformation()
                        {
                            AddPageAcceptBanner = true,
                        },
                    };

                    pageTransformator.Transform(pti);
                }
            }
        }
Exemple #2
0
        public void MetaDataCopyTest()
        {
            using (var cc = TestCommon.CreateClientContext("https://bertonline.sharepoint.com/sites/modernizationtestpages/metadata"))
            {
                var pageTransformator = new PageTransformator(cc);

                var pages = cc.Web.GetPages("meta2");

                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,

                        CopyPageMetadata = true,

                        //KeepPageSpecificPermissions = false,

                        //// Modernization center setup
                        //ModernizationCenterInformation = new ModernizationCenterInformation()
                        //{
                        //    AddPageAcceptBanner = true,
                        //},
                    };

                    pageTransformator.Transform(pti);
                }
            }
        }
Exemple #3
0
        public void FileInRootTest()
        {
            using (var cc = TestCommon.CreateClientContext("https://bertonline.sharepoint.com/sites/projectsitetest"))
            {
                var pageTransformator = new PageTransformator(cc);

                var fileToModernize = cc.Web.GetFileByServerRelativeUrl("/sites/projectsitetest/default.aspx");
                cc.Load(fileToModernize);
                cc.ExecuteQueryRetry();

                PageTransformationInformation pti = new PageTransformationInformation(null)
                {
                    // If target page exists, then overwrite it
                    Overwrite = true,

                    SourceFile = fileToModernize,

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

                    // Modernization center setup
                    //ModernizationCenterInformation = new ModernizationCenterInformation()
                    //{
                    //    AddPageAcceptBanner = true,
                    //},
                };

                var resultingpage = pageTransformator.Transform(pti);
            }
        }
Exemple #4
0
        public void AssetTransfer_CopyAssetToTarget_PagesWithImageWebPartTest()
        {
            //Note: This is more of a system test rather than unit given its dependency on SharePoint

            using (var targetClientContext = TestCommon.CreateClientContext(TestCommon.AppSetting("SPOTargetSiteUrl")))
            {
                using (var sourceClientContext = TestCommon.CreateClientContext(TestCommon.AppSetting("SPODevTeamSiteUrl")))
                {
                    var pageTransformator = new PageTransformator(sourceClientContext, targetClientContext);

                    var pages = sourceClientContext.Web.GetPages("WPP_Image-Asset");

                    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,

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

                        pageTransformator.Transform(pti);
                    }
                }
            }

            Assert.Inconclusive(TestCommon.InconclusiveNoAutomatedChecksMessage);
        }
Exemple #5
0
        public void TransformPagesTest()
        {
            // Local functions
            string titleOverride(string title)
            {
                return($"{title}_1");
            }

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

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

                var pages = cc.Web.GetPages("wiki_l");

                foreach (var page in pages)
                {
                    PageTransformationInformation pti = new PageTransformationInformation(page)
                    {
                        Overwrite = true,
                        //PageTitleOverride = titleOverride,
                        //LayoutTransformatorOverride = layoutOverride,
                    };

                    pageTransformator.Transform(pti);
                }
            }
        }
Exemple #6
0
        public void RunHeaderTest()
        {
            using (var cc = TestCommon.CreateClientContext())
            {
                var pageTransformator = new PageTransformator(cc);

                var pages = cc.Web.GetPages("Detection_");
                //var pages = cc.Web.GetPages("temp2");

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

                            // Don't log test runs
                            SkipTelemetry = 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,
                        };

                        pageTransformator.Transform(pti);
                    }
                    catch (Exception ex)
                    {
                    }
                }
            }
        }
Exemple #7
0
        public void Reporting_CrossSite_WebPartPage_ConsoleObserverTest()
        {
            using (var targetClientContext = TestCommon.CreateClientContext(TestCommon.AppSetting("SPOTargetSiteUrl")))
            {
                using (var sourceClientContext = TestCommon.CreateClientContext())
                {
                    var pageTransformator = new PageTransformator(sourceClientContext, targetClientContext);
                    pageTransformator.RegisterObserver(new ConsoleObserver());

                    var pages = sourceClientContext.Web.GetPages("wpp").Take(1);

                    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,

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

                        pageTransformator.Transform(pti);
                        pageTransformator.FlushObservers();
                    }
                }
            }

            Assert.Inconclusive(TestCommon.InconclusiveNoAutomatedChecksMessage);
        }
Exemple #8
0
        public void WPPerformanceTest()
        {
            using (var cc = TestCommon.CreateClientContext("https://bertonline.sharepoint.com/sites/espctest2"))
            {
                var pageTransformator = new PageTransformator(cc);

                //webparts
                var pages = cc.Web.GetPages("webparts");

                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,

                        // Modernization center setup
                        //ModernizationCenterInformation = new ModernizationCenterInformation()
                        //{
                        //    AddPageAcceptBanner = true,
                        //},
                    };

                    pageTransformator.Transform(pti);
                }
            }
        }
Exemple #9
0
        public void FolderTest()
        {
            using (var cc = TestCommon.CreateClientContext("https://bertonline.sharepoint.com/sites/modernizationtestpages/subsite"))
            {
                var pageTransformator = new PageTransformator(cc);

                var pages = cc.Web.GetPages("page", "Folder1/Sub1");

                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,

                        //TargetPageTakesSourcePageName = true,
                    };

                    pageTransformator.Transform(pti);
                }
            }
        }
Exemple #10
0
        public void CrossSiteTransform_SameSite_WebPartPageTest()
        {
            using (var sourceClientContext = TestCommon.CreateClientContext(TestCommon.AppSetting("SPODevTeamSiteUrl")))
            {
                var pageTransformator = new PageTransformator(sourceClientContext);
                pageTransformator.RegisterObserver(new UnitTestLogObserver());

                var pages = sourceClientContext.Web.GetPages("wpp_with");

                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,

                        // 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 = "Converted_",

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

            Assert.Inconclusive(TestCommon.InconclusiveNoAutomatedChecksMessage);
        }
Exemple #11
0
        static void Main(string[] args)
        {
            using (var cc = new ClientContext("https://bertonline.sharepoint.com/sites/espctest2"))
            {
                SharePointOnlineCredentials creds = new SharePointOnlineCredentials("*****@*****.**", ConvertToSecureString(""));
                cc.Credentials = creds;

                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);
                }
            }
        }
Exemple #12
0
        public void BasicOnlineWikiPage_TermMappingTest()
        {
            using (var targetClientContext = TestCommon.CreateClientContext(TestCommon.AppSetting("SPOTargetSiteUrl")))
            {
                using (var sourceClientContext = TestCommon.CreateClientContext(TestCommon.AppSetting("SPODevTeamSiteUrl")))
                {
                    var pageTransformator = new PageTransformator(sourceClientContext, targetClientContext);
                    //pageTransformator.RegisterObserver(new MarkdownObserver(folder: "c:\\temp", includeVerbose: true));
                    pageTransformator.RegisterObserver(new UnitTestLogObserver());

                    var pages = sourceClientContext.Web.GetPagesFromList("Site Pages", pageNameStartsWith: "Common-WikiPageTest");

                    pages.FailTestIfZero();

                    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,

                            //Permissions are unlikely to work given cross domain
                            KeepPageSpecificPermissions = false,

                            SkipUserMapping       = true,
                            SkipDefaultUrlRewrite = true,
                            SkipUrlRewrite        = true,

                            // Term store mapping
                            TermMappingFile = @"..\..\Transform\Mapping\term_mapping_sample.csv",

                            //Should process default mapping
                            SkipTermStoreMapping = true,

                            CopyPageMetadata = true
                        };

                        Console.WriteLine("SharePoint Version: {0}", pti.SourceVersion);

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

                        var result = pageTransformator.Transform(pti);
                    }

                    pageTransformator.FlushObservers();
                }
            }
        }
Exemple #13
0
        static void Main(string[] args)
        {
            string siteUrl           = "https://contoso.sharepoint.com/sites/mytestsite";
            string userName          = "******";
            AuthenticationManager am = new AuthenticationManager();

            using (var cc = am.GetSharePointOnlineAuthenticatedContextTenant(siteUrl, userName, GetSecureString("Password")))
            {
                var pageTransformator = new PageTransformator(cc);

                // Use below override if you want to apply a filter on the pages to transform
                // var pages = cc.Web.GetPages("webparts.aspx");
                var pages = cc.Web.GetPages();

                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 (default = false)
                        //TargetPageTakesSourcePageName = false,

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

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

                        // If the page is a home page then replace with stock home page (default = false)
                        //ReplaceHomePageWithDefaultHomePage = true,

                        // Replace images and iframes embedded inside a list or table in the wiki text with a placeholder and add respective images and video web parts at the bottom of the page (default = true)
                        //HandleWikiImagesAndVideos = false,
                    };
                    try
                    {
                        Console.WriteLine($"Transforming page {page.FieldValues["FileLeafRef"]}");
                        pageTransformator.Transform(pti);
                    }
                    catch (ArgumentException ex)
                    {
                        Console.WriteLine($"Page {page.FieldValues["FileLeafRef"]} could not be transformed: {ex.Message}");
                    }
                }
            }

            Console.WriteLine("Press enter to continue...");
            Console.ReadLine();
        }
Exemple #14
0
        public void Logging_ErrorTest()
        {
            // Deliberate Error
            var pageTransformator = new PageTransformator(null);

            pageTransformator.RegisterObserver(new UnitTestLogObserver()); // Example of registering an observer, this can be anything really.

            PageTransformationInformation pti = new PageTransformationInformation(null);

            // Should capture a argument exception
            Assert.ThrowsException <ArgumentNullException>(() =>
            {
                pageTransformator.Transform(pti);
            });
        }
Exemple #15
0
        /// <summary>
        /// Different page same test conditions
        /// </summary>
        /// <param name="pageName"></param>
        private void TransformPage(SPPlatformVersion version, string pageNameStartsWith = "Common-WikiPage")
        {
            using (var targetClientContext = TestCommon.CreateClientContext(TestCommon.AppSetting("SPOTargetSiteUrl")))
            {
                using (var sourceClientContext = TestCommon.CreateSPPlatformClientContext(version, TransformType.WikiPage))
                {
                    var pageTransformator = new PageTransformator(sourceClientContext, targetClientContext);
                    pageTransformator.RegisterObserver(new MarkdownObserver(folder: "c:\\temp", includeVerbose: true));
                    pageTransformator.RegisterObserver(new UnitTestLogObserver());

                    var pages = sourceClientContext.Web.GetPages(pageNameStartsWith);

                    pages.FailTestIfZero();

                    foreach (var page in pages)
                    {
                        var pageName = page.FieldValues["FileLeafRef"].ToString();

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

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

                            //Permissions are unlikely to work given cross domain
                            KeepPageSpecificPermissions = false,

                            //Update target to include SP version
                            TargetPageName = TestCommon.UpdatePageToIncludeVersion(version, pageName)
                        };

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

                        var result = pageTransformator.Transform(pti);

                        Assert.IsTrue(!string.IsNullOrEmpty(result));
                    }

                    pageTransformator.FlushObservers();
                }
            }
        }
Exemple #16
0
        public void CacheTest()
        {
            using (var cc = TestCommon.CreateClientContext())
            {
                var pageTransformator = new PageTransformator(cc);

                var pages = cc.Web.GetPages("table_1");

                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,
                    };

                    pageTransformator.Transform(pti);
                }
            }

            using (var cc = TestCommon.CreateClientContext("https://bertonline.sharepoint.com/sites/temp2"))
            {
                var pageTransformator = new PageTransformator(cc);

                var pages = cc.Web.GetPages("demo5");

                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,
                    };

                    pageTransformator.Transform(pti);
                }
            }
        }
Exemple #17
0
        /// <summary>
        /// Different page same test conditions
        /// </summary>
        /// <param name="pageName"></param>
        private void PageToTransform(string pageName)
        {
            using (var targetClientContext = TestCommon.CreateClientContext(TestCommon.AppSetting("SPOTargetSiteUrl")))
            {
                using (var sourceClientContext = TestCommon.CreateOnPremisesClientContext(TestCommon.AppSetting("SPOnPremTeamSiteUrl")))
                {
                    var pageTransformator = new PageTransformator(sourceClientContext, targetClientContext);
                    pageTransformator.RegisterObserver(new MarkdownObserver(folder: "c:\\temp", includeVerbose: true));
                    pageTransformator.RegisterObserver(new UnitTestLogObserver());

                    var pages = sourceClientContext.Web.GetPages(pageName);

                    pages.FailTestIfZero();

                    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,

                            //Permissions are unlikely to work given cross domain
                            KeepPageSpecificPermissions = false,
                        };

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

                        var result = pageTransformator.Transform(pti);
                    }

                    pageTransformator.FlushObservers();

                    //TODO: Add Target Site Page Creation Checking
                }
            }
        }
Exemple #18
0
        public void Reporting_SameSite_WebPartPageTest()
        {
            using (var sourceClientContext = TestCommon.CreateClientContext())
            {
                var pageTransformator = new PageTransformator(sourceClientContext);
                pageTransformator.RegisterObserver(new UnitTestLogObserver()); //Registers the unit test observer to log details for testing

                var pages = sourceClientContext.Web.GetPages("wpp");

                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,

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

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

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

                    pageTransformator.Transform(pti);
                    pageTransformator.FlushObservers();
                }
            }

            Assert.Inconclusive(TestCommon.InconclusiveNoAutomatedChecksMessage);
        }
Exemple #19
0
        public void TransformPagesTest()
        {
            // Local functions
            string titleOverride(string title)
            {
                return($"{title}_1");
            }

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

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

                //complexwiki
                //demo1
                //wikitext
                //wiki_li
                var pages = cc.Web.GetPages("demo17.aspx");

                foreach (var page in pages)
                {
                    PageTransformationInformation pti = new PageTransformationInformation(page)
                    {
                        Overwrite = true,
                        //ReplaceHomePageWithDefaultHomePage = true,
                        //HandleWikiImagesAndVideos = false,
                        //PageTitleOverride = titleOverride,
                        //LayoutTransformatorOverride = layoutOverride,
                    };

                    pageTransformator.Transform(pti);
                }
            }
        }
Exemple #20
0
        public void CrossSiteTransform_OverwriteOffTest()
        {
            using (var targetClientContext = TestCommon.CreateClientContext(TestCommon.AppSetting("SPOTargetSiteUrl")))
            {
                //Test Requires a test site
                using (var sourceClientContext = TestCommon.CreateClientContext(TestCommon.AppSetting("SPODevTeamSiteUrl")))
                {
                    var pageTransformator = new PageTransformator(sourceClientContext, targetClientContext);
                    pageTransformator.RegisterObserver(new UnitTestLogObserver());

                    var pages = sourceClientContext.Web.GetPages("wpp_with"); //Specific page - aim for one file

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

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

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

                        var result = Assert.ThrowsException <ArgumentException>(() =>
                        {
                            var result1 = pageTransformator.Transform(pti);
                            var result2 = pageTransformator.Transform(pti); //Run twice incase target site didnt have the file in the first place
                        });

                        Assert.IsTrue(result.Message.Contains("Not overwriting - there already exists a page with name"));
                    }
                }
            }
        }
        public void FixPageProperty_NotReallyATest()
        {
            using (var sourceClientContext = TestCommon.CreateClientContext())
            {
                var pageTransformator = new PageTransformator(sourceClientContext);

                var pages = sourceClientContext.Web.GetPages("WPP_Image-Asset-MultipleImages");

                var pageItem = pages.FirstOrDefault();

                if (pageItem != default(ListItem))
                {
                    sourceClientContext.Load(pageItem.File, p => p.ServerRelativeUrl);
                    sourceClientContext.ExecuteQueryRetry();

                    var pageFile = sourceClientContext.Web.GetFileByServerRelativeUrl(pageItem.File.ServerRelativeUrl);
                    sourceClientContext.Load(pageFile, p => p.Properties);
                    pageFile.Properties["vti_setuppath"] = "1033\\STS\\doctemp\\smartpgs\\spstd2.aspx";
                    pageFile.Properties["fixing_layout"] = "1033\\STS\\doctemp\\smartpgs\\spstd2.aspx";
                    pageFile.Update();
                    sourceClientContext.ExecuteQueryRetry();

                    // Try both
                    //page.Properties["vti_setuppath"] = @"1033\STS\doctemp\smartpgs\spstd2.aspx";
                    //page.Update();
                    //sourceClientContext.ExecuteQueryRetry();



                    Assert.IsTrue(true, "File Updated");
                }
                else
                {
                    Assert.Fail("File not found");
                }
            }
        }
Exemple #22
0
        public void Logging_NormalOperationTest()
        {
            using (var sourceClientContext = TestCommon.CreateClientContext())
            {
                var pageTransformator = new PageTransformator(sourceClientContext);
                pageTransformator.RegisterObserver(new UnitTestLogObserver()); // Example of registering an observer, this can be anything really.

                var pages = sourceClientContext.Web.GetPages("wk").Take(1);

                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,

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

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

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

                    pageTransformator.Transform(pti);
                }
            }
        }
Exemple #23
0
        protected override void ExecuteCmdlet()
        {
            //Fix loading of modernization framework
            FixLocalAssemblyResolving();

            // Load the page to transform
            Identity.Library       = this.Library;
            Identity.Folder        = this.Folder;
            Identity.BlogPage      = this.BlogPage;
            Identity.DelveBlogPage = this.DelveBlogPage;

            if ((this.PublishingPage && this.BlogPage) ||
                (this.PublishingPage && this.DelveBlogPage) ||
                (this.BlogPage && this.DelveBlogPage))
            {
                throw new Exception($"The page is either a blog page, a publishing page or a Delve blog page. Setting PublishingPage, BlogPage and DelveBlogPage to true is not valid.");
            }

            ListItem page = null;

            if (this.PublishingPage)
            {
                page = Identity.GetPage(this.ClientContext.Web, CacheManager.Instance.GetPublishingPagesLibraryName(this.ClientContext));
            }
            else if (this.BlogPage)
            {
                // Blogs don't live in other libraries or sub folders
                Identity.Library = null;
                Identity.Folder  = null;
                page             = Identity.GetPage(this.ClientContext.Web, CacheManager.Instance.GetBlogListName(this.ClientContext));
            }
            else if (this.DelveBlogPage)
            {
                // Blogs don't live in other libraries or sub folders
                Identity.Library = null;
                Identity.Folder  = null;
                page             = Identity.GetPage(this.ClientContext.Web, "pPg");
            }
            else
            {
                if (this.Folder == null || !this.Folder.Equals(rootFolder, StringComparison.InvariantCultureIgnoreCase))
                {
                    page = Identity.GetPage(this.ClientContext.Web, "sitepages");
                }
            }

            if (page == null && (Folder == null || !this.Folder.Equals(rootFolder, StringComparison.InvariantCultureIgnoreCase)))
            {
                throw new Exception($"Page '{Identity?.Name}' does not exist");
            }

            // Publishing specific validation
            if (this.PublishingPage && string.IsNullOrEmpty(this.TargetWebUrl) && TargetConnection == null)
            {
                throw new Exception($"Publishing page transformation is only supported when transformating into another site collection. Use the -TargetWebUrl to specify a modern target site.");
            }

            // Blog specific validation
            if ((this.BlogPage || this.DelveBlogPage) && string.IsNullOrEmpty(this.TargetWebUrl) && TargetConnection == null)
            {
                throw new Exception($"Blog and Delve blog page transformation is only supported when transformating into another site collection. Use the -TargetWebUrl to specify a modern target site.");
            }

            // Load transformation models
            PageTransformation webPartMappingModel = null;

            if (string.IsNullOrEmpty(this.WebPartMappingFile))
            {
                webPartMappingModel = PageTransformator.LoadDefaultWebPartMapping();
                this.WriteVerbose("Using embedded webpartmapping file. Use Export-PnPClientSidePageMapping to get that file in case you want to base your version of the embedded version.");
            }

            // Validate webpartmappingfile
            if (!string.IsNullOrEmpty(this.WebPartMappingFile))
            {
                if (!System.IO.File.Exists(this.WebPartMappingFile))
                {
                    throw new Exception($"Provided webpartmapping file {this.WebPartMappingFile} does not exist");
                }
            }

            if (this.PublishingPage && !string.IsNullOrEmpty(this.PageLayoutMapping) && !System.IO.File.Exists(this.PageLayoutMapping))
            {
                throw new Exception($"Provided pagelayout mapping file {this.PageLayoutMapping} does not exist");
            }

            bool crossSiteTransformation = TargetConnection != null || !string.IsNullOrEmpty(TargetWebUrl);

            // Create target client context (when needed)
            ClientContext targetContext = null;

            if (TargetConnection == null)
            {
                if (!string.IsNullOrEmpty(TargetWebUrl))
                {
                    targetContext = this.ClientContext.Clone(TargetWebUrl);
                }
            }
            else
            {
                targetContext = TargetConnection.Context;
            }


            // Create transformator instance
            PageTransformator           pageTransformator           = null;
            PublishingPageTransformator publishingPageTransformator = null;
            DelvePageTransformator      delvePageTransformator      = null;

            if (!string.IsNullOrEmpty(this.WebPartMappingFile))
            {
                // Using custom web part mapping file
                if (this.PublishingPage)
                {
                    if (!string.IsNullOrEmpty(this.PageLayoutMapping))
                    {
                        // Using custom page layout mapping file + default one (they're merged together)
                        publishingPageTransformator = new PublishingPageTransformator(this.ClientContext, targetContext, this.WebPartMappingFile, this.PageLayoutMapping);
                    }
                    else
                    {
                        // Using default page layout mapping file
                        publishingPageTransformator = new PublishingPageTransformator(this.ClientContext, targetContext, this.WebPartMappingFile, null);
                    }
                }
                else if (this.DelveBlogPage)
                {
                    delvePageTransformator = new DelvePageTransformator(this.ClientContext, targetContext, this.WebPartMappingFile);
                }
                else
                {
                    // Use web part mapping file
                    pageTransformator = new PageTransformator(this.ClientContext, targetContext, this.WebPartMappingFile);
                }
            }
            else
            {
                // Using default web part mapping file
                if (this.PublishingPage)
                {
                    if (!string.IsNullOrEmpty(this.PageLayoutMapping))
                    {
                        // Load and validate the custom mapping file
                        PageLayoutManager pageLayoutManager = new PageLayoutManager();
                        var pageLayoutMappingModel          = pageLayoutManager.LoadPageLayoutMappingFile(this.PageLayoutMapping);

                        // Using custom page layout mapping file + default one (they're merged together)
                        publishingPageTransformator = new PublishingPageTransformator(this.ClientContext, targetContext, webPartMappingModel, pageLayoutMappingModel);
                    }
                    else
                    {
                        // Using default page layout mapping file
                        publishingPageTransformator = new PublishingPageTransformator(this.ClientContext, targetContext, webPartMappingModel, null);
                    }
                }
                else if (this.DelveBlogPage)
                {
                    delvePageTransformator = new DelvePageTransformator(this.ClientContext, targetContext, webPartMappingModel);
                }
                else
                {
                    // Use web part mapping model loaded from embedded mapping file
                    pageTransformator = new PageTransformator(this.ClientContext, targetContext, webPartMappingModel);
                }
            }

            // Setup logging
            if (this.LogType == ClientSidePageTransformatorLogType.File)
            {
                if (this.PublishingPage)
                {
                    publishingPageTransformator.RegisterObserver(new MarkdownObserver(folder: this.LogFolder, includeVerbose: this.LogVerbose, includeDebugEntries: this.LogVerbose));
                }
                else if (this.DelveBlogPage)
                {
                    delvePageTransformator.RegisterObserver(new MarkdownObserver(folder: this.LogFolder, includeVerbose: this.LogVerbose, includeDebugEntries: this.LogVerbose));
                }
                else
                {
                    pageTransformator.RegisterObserver(new MarkdownObserver(folder: this.LogFolder, includeVerbose: this.LogVerbose, includeDebugEntries: this.LogVerbose));
                }
            }
            else if (this.LogType == ClientSidePageTransformatorLogType.SharePoint)
            {
                if (this.PublishingPage)
                {
                    publishingPageTransformator.RegisterObserver(new MarkdownToSharePointObserver(targetContext ?? this.ClientContext, includeVerbose: this.LogVerbose, includeDebugEntries: this.LogVerbose));
                }
                else if (this.DelveBlogPage)
                {
                    delvePageTransformator.RegisterObserver(new MarkdownToSharePointObserver(targetContext ?? this.ClientContext, includeVerbose: this.LogVerbose, includeDebugEntries: this.LogVerbose));
                }
                else
                {
                    pageTransformator.RegisterObserver(new MarkdownToSharePointObserver(targetContext ?? this.ClientContext, includeVerbose: this.LogVerbose, includeDebugEntries: this.LogVerbose));
                }
            }
            else if (this.LogType == ClientSidePageTransformatorLogType.Console)
            {
                if (this.PublishingPage)
                {
                    publishingPageTransformator.RegisterObserver(new ConsoleObserver(includeDebugEntries: this.LogVerbose));
                }
                else if (this.DelveBlogPage)
                {
                    delvePageTransformator.RegisterObserver(new ConsoleObserver(includeDebugEntries: this.LogVerbose));
                }
                else
                {
                    pageTransformator.RegisterObserver(new ConsoleObserver(includeDebugEntries: this.LogVerbose));
                }
            }

            // Clear the client side component cache
            if (this.ClearCache)
            {
                CacheManager.Instance.ClearAllCaches();
            }

            string serverRelativeClientPageUrl = "";

            if (this.PublishingPage)
            {
                // Setup Transformation information
                PublishingPageTransformationInformation pti = new PublishingPageTransformationInformation(page)
                {
                    Overwrite = this.Overwrite,
                    KeepPageSpecificPermissions             = !this.SkipItemLevelPermissionCopyToClientSidePage,
                    PublishCreatedPage                      = !this.DontPublish,
                    KeepPageCreationModificationInformation = this.KeepPageCreationModificationInformation,
                    PostAsNews                             = this.PostAsNews,
                    DisablePageComments                    = this.DisablePageComments,
                    TargetPageName                         = !string.IsNullOrEmpty(this.PublishingTargetPageName) ? this.PublishingTargetPageName : this.TargetPageName,
                    SkipUrlRewrite                         = this.SkipUrlRewriting,
                    SkipDefaultUrlRewrite                  = this.SkipDefaultUrlRewriting,
                    UrlMappingFile                         = this.UrlMappingFile,
                    AddTableListImageAsImageWebPart        = this.AddTableListImageAsImageWebPart,
                    SkipUserMapping                        = this.SkipUserMapping,
                    UserMappingFile                        = this.UserMappingFile,
                    LDAPConnectionString                   = this.LDAPConnectionString,
                    TargetPageFolder                       = this.TargetPageFolder,
                    TargetPageFolderOverridesDefaultFolder = this.TargetPageFolderOverridesDefaultFolder,
                    TermMappingFile                        = TermMappingFile,
                    SkipTermStoreMapping                   = SkipTermStoreMapping,
                    RemoveEmptySectionsAndColumns          = this.RemoveEmptySectionsAndColumns
                };

                // Set mapping properties
                pti.MappingProperties["SummaryLinksToQuickLinks"] = (!SummaryLinksToHtml).ToString().ToLower();
                pti.MappingProperties["UseCommunityScriptEditor"] = UseCommunityScriptEditor.ToString().ToLower();

                try
                {
                    serverRelativeClientPageUrl = publishingPageTransformator.Transform(pti);
                }
                finally
                {
                    // Flush log
                    if (this.LogType != ClientSidePageTransformatorLogType.None && this.LogType != ClientSidePageTransformatorLogType.Console && !this.LogSkipFlush)
                    {
                        publishingPageTransformator.FlushObservers();
                    }
                }
            }
            else if (this.DelveBlogPage)
            {
                // Setup Transformation information
                DelvePageTransformationInformation pti = new DelvePageTransformationInformation(page)
                {
                    Overwrite = this.Overwrite,
                    KeepPageSpecificPermissions             = !this.SkipItemLevelPermissionCopyToClientSidePage,
                    PublishCreatedPage                      = !this.DontPublish,
                    KeepPageCreationModificationInformation = this.KeepPageCreationModificationInformation,
                    SetAuthorInPageHeader                   = this.SetAuthorInPageHeader,
                    PostAsNews                             = this.PostAsNews,
                    DisablePageComments                    = this.DisablePageComments,
                    TargetPageName                         = crossSiteTransformation ? this.TargetPageName : "",
                    SkipUrlRewrite                         = this.SkipUrlRewriting,
                    SkipDefaultUrlRewrite                  = this.SkipDefaultUrlRewriting,
                    UrlMappingFile                         = this.UrlMappingFile,
                    AddTableListImageAsImageWebPart        = this.AddTableListImageAsImageWebPart,
                    SkipUserMapping                        = this.SkipUserMapping,
                    UserMappingFile                        = this.UserMappingFile,
                    LDAPConnectionString                   = this.LDAPConnectionString,
                    TargetPageFolder                       = this.TargetPageFolder,
                    TargetPageFolderOverridesDefaultFolder = this.TargetPageFolderOverridesDefaultFolder,
                    RemoveEmptySectionsAndColumns          = this.RemoveEmptySectionsAndColumns
                };

                // Set mapping properties
                pti.MappingProperties["SummaryLinksToQuickLinks"] = (!SummaryLinksToHtml).ToString().ToLower();
                pti.MappingProperties["UseCommunityScriptEditor"] = UseCommunityScriptEditor.ToString().ToLower();

                try
                {
                    serverRelativeClientPageUrl = delvePageTransformator.Transform(pti);
                }
                finally
                {
                    // Flush log
                    if (this.LogType != ClientSidePageTransformatorLogType.None && this.LogType != ClientSidePageTransformatorLogType.Console && !this.LogSkipFlush)
                    {
                        pageTransformator.FlushObservers();
                    }
                }
            }
            else
            {
                Microsoft.SharePoint.Client.File fileToModernize = null;
                if (this.Folder != null && this.Folder.Equals(rootFolder, StringComparison.InvariantCultureIgnoreCase))
                {
                    // Load the page file from the site root folder
                    var webServerRelativeUrl = this.ClientContext.Web.EnsureProperty(p => p.ServerRelativeUrl);
                    fileToModernize = this.ClientContext.Web.GetFileByServerRelativeUrl($"{webServerRelativeUrl}/{this.Identity.Name}");
                    this.ClientContext.Load(fileToModernize);
                    this.ClientContext.ExecuteQueryRetry();
                }

                // Setup Transformation information
                PageTransformationInformation pti = new PageTransformationInformation(page)
                {
                    SourceFile = fileToModernize,
                    Overwrite  = this.Overwrite,
                    TargetPageTakesSourcePageName      = this.TakeSourcePageName,
                    ReplaceHomePageWithDefaultHomePage = this.ReplaceHomePageWithDefault,
                    KeepPageSpecificPermissions        = !this.SkipItemLevelPermissionCopyToClientSidePage,
                    CopyPageMetadata   = this.CopyPageMetadata,
                    PublishCreatedPage = !this.DontPublish,
                    KeepPageCreationModificationInformation = this.KeepPageCreationModificationInformation,
                    SetAuthorInPageHeader                  = this.SetAuthorInPageHeader,
                    PostAsNews                             = this.PostAsNews,
                    DisablePageComments                    = this.DisablePageComments,
                    TargetPageName                         = crossSiteTransformation ? this.TargetPageName : "",
                    SkipUrlRewrite                         = this.SkipUrlRewriting,
                    SkipDefaultUrlRewrite                  = this.SkipDefaultUrlRewriting,
                    UrlMappingFile                         = this.UrlMappingFile,
                    AddTableListImageAsImageWebPart        = this.AddTableListImageAsImageWebPart,
                    SkipUserMapping                        = this.SkipUserMapping,
                    UserMappingFile                        = this.UserMappingFile,
                    LDAPConnectionString                   = this.LDAPConnectionString,
                    TargetPageFolder                       = this.TargetPageFolder,
                    TargetPageFolderOverridesDefaultFolder = this.TargetPageFolderOverridesDefaultFolder,
                    ModernizationCenterInformation         = new ModernizationCenterInformation()
                    {
                        AddPageAcceptBanner = this.AddPageAcceptBanner
                    },
                    TermMappingFile               = TermMappingFile,
                    SkipTermStoreMapping          = SkipTermStoreMapping,
                    RemoveEmptySectionsAndColumns = this.RemoveEmptySectionsAndColumns
                };

                // Set mapping properties
                pti.MappingProperties["SummaryLinksToQuickLinks"] = (!SummaryLinksToHtml).ToString().ToLower();
                pti.MappingProperties["UseCommunityScriptEditor"] = UseCommunityScriptEditor.ToString().ToLower();

                try
                {
                    serverRelativeClientPageUrl = pageTransformator.Transform(pti);
                }
                finally
                {
                    // Flush log
                    if (this.LogType != ClientSidePageTransformatorLogType.None && this.LogType != ClientSidePageTransformatorLogType.Console && !this.LogSkipFlush)
                    {
                        pageTransformator.FlushObservers();
                    }
                }
            }

            // Output the server relative url to the newly created page
            if (!string.IsNullOrEmpty(serverRelativeClientPageUrl))
            {
                WriteObject(serverRelativeClientPageUrl);
            }
        }
Exemple #24
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
                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);
                }
            }
        }
Exemple #25
0
        public static async Task <HttpResponseMessage> Run([HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)] HttpRequestMessage req, TraceWriter log)
        {
            DateTime transformationStartDateTime = DateTime.Now;

            // instantiate the telemetry model
            telemetry = new FunctionTelemetry(log);
            if (telemetry != null)
            {
                telemetry.LogTransformationStart();
            }

            try
            {
                log.Info("ModernizePage Azure function is being called");

                string transformedPageUrl = null;

                // Parse and process the query parameters
                string siteUrl = req.GetQueryNameValuePairs().FirstOrDefault(q => string.Compare(q.Key, "SiteUrl", true) == 0).Value;
                string pageUrl = req.GetQueryNameValuePairs().FirstOrDefault(q => string.Compare(q.Key, "PageUrl", true) == 0).Value;

                if (string.IsNullOrEmpty(siteUrl) || string.IsNullOrEmpty(pageUrl))
                {
                    throw new Exception($"Invalid page and/or site url. PageUrl:{pageUrl} SiteUrl:{siteUrl}");
                }

                Uri siteUri = new Uri(siteUrl);

                // is this request authenticated?
                if (Thread.CurrentPrincipal != null &&
                    Thread.CurrentPrincipal.Identity != null &&
                    Thread.CurrentPrincipal.Identity.IsAuthenticated)
                {
                    var issuer = (Thread.CurrentPrincipal as ClaimsPrincipal)?.FindFirst("iss");
                    if (issuer != null && !String.IsNullOrEmpty(issuer.Value))
                    {
                        var issuerValue = issuer.Value.Substring(0, issuer.Value.Length - 1);
                        var tenantId    = issuerValue.Substring(issuerValue.LastIndexOf("/") + 1);
                        var upn         = (Thread.CurrentPrincipal as ClaimsPrincipal)?.FindFirst(ClaimTypes.Upn)?.Value;

                        // Check for multitenant usage of the service. Used for demo purposes or for customers that want to host a
                        // single service for multiple tenants
                        if (!IsAllowedTenant(upn))
                        {
                            throw new Exception($"Tenant {upn.Substring(upn.IndexOf('@') + 1).ToLower()} is not whitelisted for this transformation service endpoint.");
                        }

                        string accessToken = "";
                        // We need to manually retrieve an access token valid for SharePoint from the
                        // received access token used to access this service
                        using (var client = new HttpClient())
                        {
                            // Prepare the AAD OAuth request URI
                            string authority = $"{aadInstance}common";
                            var    tokenUri  = new Uri($"{authority}/oauth2/token");

                            // Grab the access token that was in the request (the one coming from SPFX)
                            log.Verbose($"Parameter: {req.Headers.Authorization.Parameter}");

                            // Prepare the OAuth 2.0 request for an Access Token with the on behalf of flow
                            // https://docs.microsoft.com/en-us/azure/active-directory/develop/v2-oauth2-on-behalf-of-flow
                            var content = new FormUrlEncodedContent(new[]
                            {
                                new KeyValuePair <string, string>("grant_type", "urn:ietf:params:oauth:grant-type:jwt-bearer"),
                                new KeyValuePair <string, string>("client_id", GetAppSetting("CLIENT_ID")),
                                new KeyValuePair <string, string>("client_secret", GetAppSetting("CLIENT_SECRET")),
                                new KeyValuePair <string, string>("assertion", req.Headers.Authorization.Parameter),
                                new KeyValuePair <string, string>("resource", $"https://{siteUri.Authority}"),
                                new KeyValuePair <string, string>("requested_token_use", "on_behalf_of"),
                            });

                            // Make the HTTP request
                            var result = await client.PostAsync(tokenUri, content);

                            string jsonToken = await result.Content.ReadAsStringAsync();

                            // Get back the OAuth 2.0 response
                            var token = JsonConvert.DeserializeObject <OAuthTokenResponse>(jsonToken);

                            if (token != null && !String.IsNullOrEmpty(token.AccessToken))
                            {
                                accessToken = token.AccessToken;
                            }
                            else
                            {
                                log.Error($"Obtaining an access token for SharePoint failed. Request response = {jsonToken}");
                                return(req.CreateResponse(HttpStatusCode.Unauthorized, jsonToken));
                            }
                        }

                        log.Info($"IssuerValue: {issuerValue} tenantId: {tenantId} upn: {upn}");
                        log.Verbose($"accessToken: {accessToken}");

                        if (!string.IsNullOrEmpty(accessToken))
                        {
                            try
                            {
                                log.Info($"Transforming page {pageUrl}");
                                OfficeDevPnP.Core.AuthenticationManager authManager = new OfficeDevPnP.Core.AuthenticationManager();
                                using (ClientContext context = authManager.GetAzureADAccessTokenAuthenticatedContext(siteUrl, accessToken))
                                {
                                    string fileName = System.IO.Path.GetFileName(pageUrl);
                                    var    pages    = context.Web.GetPageToTransform(fileName);

                                    if (pages.Count == 1)
                                    {
                                        log.Verbose($"Page {fileName} was found and will be transformed");

                                        // Load page transformation settings
                                        bool   replaceHomePageWithDefaultHomePage = GetAppSettingBool("ReplaceHomePageWithDefaultHomePage", false);
                                        string targetPagePrefix = GetAppSetting("TargetPagePrefix", "Migrated_");

                                        log.Verbose($"Options used to drive page transformation: TargetPagePrefix={targetPagePrefix} ReplaceHomePageWithDefaultHomePage={replaceHomePageWithDefaultHomePage}");

                                        var pageTransformator             = new PageTransformator(context, "d:\\home\\site\\wwwroot\\webpartmapping.xml");
                                        PageTransformationInformation pti = new PageTransformationInformation(pages[0])
                                        {
                                            // If target page exists, then overwrite it
                                            Overwrite = true,

                                            // Modernization center setup
                                            ModernizationCenterInformation = new ModernizationCenterInformation()
                                            {
                                                AddPageAcceptBanner = true,
                                            },

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

                                            // If the page is a home page then replace with stock home page
                                            ReplaceHomePageWithDefaultHomePage = replaceHomePageWithDefaultHomePage,
                                        };

                                        pageTransformator.Transform(pti);

                                        if (pti.TargetPageTakesSourcePageName)
                                        {
                                            transformedPageUrl = pageUrl;
                                        }
                                        else
                                        {
                                            transformedPageUrl = pageUrl.Replace(fileName, $"{pti.TargetPagePrefix}{fileName}");
                                        }

                                        log.Info($"Page {fileName} was transformed into {transformedPageUrl}");

                                        TimeSpan duration = DateTime.Now.Subtract(transformationStartDateTime);
                                        if (telemetry != null)
                                        {
                                            telemetry.LogTransformationDone(duration);
                                        }

                                        return(req.CreateResponse(HttpStatusCode.OK, $"{transformedPageUrl}"));
                                    }
                                    else
                                    {
                                        throw new Exception($"This function only supports the transformation of a single page. We found {pages.Count} pages for page {fileName}");
                                    }
                                }
                            }
                            catch (Exception ex)
                            {
                                if (telemetry != null)
                                {
                                    telemetry.LogError(ex, "TransformationLoop");
                                }
                                log.Error(ex.ToDetailedString());
                                return(req.CreateResponse(HttpStatusCode.InternalServerError, ex.Message));
                            }
                        }
                        else
                        {
                            throw new Exception("Access token could not be retrieved");
                        }
                    }
                    else
                    {
                        throw new Exception("Issuer value could not be retrieved");
                    }
                }
                else
                {
                    throw new Exception("Request was not having a user identity. Are you using this function in anonymous mode?");
                }
            }
            catch (Exception ex)
            {
                if (telemetry != null)
                {
                    telemetry.LogError(ex, "MainLoop");
                }
                log.Error(ex.ToDetailedString());
                return(req.CreateResponse(HttpStatusCode.BadRequest, ex.Message));
            }
            finally
            {
                if (telemetry != null)
                {
                    telemetry.Flush();
                }
            }
        }
Exemple #26
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();
            }
        }
Exemple #27
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);
        }
Exemple #28
0
        protected override void ExecuteCmdlet()
        {
            string tempPath = null;

            try
            {
                //Fix loading of modernization framework
                FixAssemblyResolving();

                // Load the page to transform
                var page = Identity.GetPage(this.ClientContext.Web);

                if (page == null)
                {
                    throw new Exception($"Page '{Identity?.Name}' does not exist");
                }

                if (string.IsNullOrEmpty(this.WebPartMappingFile))
                {
                    // Load the default one from resources
                    string webpartMappingFileContents = WebPartMappingLoader.LoadFile("SharePointPnP.PowerShell.Commands.ClientSidePages.webpartmapping.xml");

                    // Save the file to a temp location
                    tempPath = System.IO.Path.GetTempFileName();
                    System.IO.File.WriteAllText(tempPath, webpartMappingFileContents);
                    this.WebPartMappingFile = tempPath;

                    this.WriteVerbose("Using embedded webpartmapping file (https://github.com/SharePoint/PnP-PowerShell/blob/master/Commands/ClientSidePages/webpartmapping.xml)");
                }

                // Validate webpartmappingfile
                if (!string.IsNullOrEmpty(this.WebPartMappingFile))
                {
                    if (!System.IO.File.Exists(this.WebPartMappingFile))
                    {
                        throw new Exception($"Provided webpartmapping file {this.WebPartMappingFile} does not exist");
                    }
                }

                // Create transformator instance
                PageTransformator pageTransformator = new PageTransformator(this.ClientContext, this.WebPartMappingFile);

                // Setup Transformation information
                PageTransformationInformation pti = new PageTransformationInformation(page)
                {
                    Overwrite = this.Overwrite,
                    TargetPageTakesSourcePageName      = this.TakeSourcePageName,
                    ReplaceHomePageWithDefaultHomePage = this.ReplaceHomePageWithDefault,
                    ModernizationCenterInformation     = new ModernizationCenterInformation()
                    {
                        AddPageAcceptBanner = this.AddPageAcceptBanner
                    },
                };

                string serverRelativeClientPageUrl = pageTransformator.Transform(pti);

                ClientSidePagePipeBind cpb = new ClientSidePagePipeBind(System.IO.Path.GetFileName(serverRelativeClientPageUrl));
                var clientSidePage         = cpb.GetPage(this.ClientContext);

                if (clientSidePage != null)
                {
                    WriteObject(clientSidePage);
                }
            }
            finally
            {
                if (!string.IsNullOrEmpty(tempPath) && System.IO.File.Exists(tempPath))
                {
                    System.IO.File.Delete(tempPath);
                }
            }
        }
Exemple #29
0
        protected override void ExecuteCmdlet()
        {
            //Fix loading of modernization framework
            FixLocalAssemblyResolving();

            // Load the page to transform
            Identity.Library = this.Library;
            Identity.Folder  = this.Folder;

            ListItem page = null;

            if (this.PublishingPage)
            {
                page = Identity.GetPage(this.ClientContext.Web, CacheManager.Instance.GetPublishingPagesLibraryName(this.ClientContext));
            }
            else
            {
                if (this.Folder == null || !this.Folder.Equals(rootFolder, StringComparison.InvariantCultureIgnoreCase))
                {
                    page = Identity.GetPage(this.ClientContext.Web, "sitepages");
                }
            }

            if (page == null && !this.Folder.Equals(rootFolder, StringComparison.InvariantCultureIgnoreCase))
            {
                throw new Exception($"Page '{Identity?.Name}' does not exist");
            }

            // Publishing specific validation
            if (this.PublishingPage && string.IsNullOrEmpty(this.TargetWebUrl) && TargetConnection == null)
            {
                throw new Exception($"Publishing page transformation is only supported when transformating into another site collection. Use the -TargetWebUrl to specify a modern target site.");
            }

            // Load transformation models
            PageTransformation webPartMappingModel = null;

            if (string.IsNullOrEmpty(this.WebPartMappingFile))
            {
                // Load xml mapping data
                XmlSerializer xmlMapping = new XmlSerializer(typeof(PageTransformation));

                // Load the default one from resources into a model, no need for persisting this file
                string webpartMappingFileContents = WebPartMappingLoader.LoadFile("SharePointPnP.PowerShell.Commands.ClientSidePages.webpartmapping.xml");

                using (var stream = GenerateStreamFromString(webpartMappingFileContents))
                {
                    webPartMappingModel = (PageTransformation)xmlMapping.Deserialize(stream);
                }

                this.WriteVerbose("Using embedded webpartmapping file. Use Export-PnPClientSidePageMapping to get that file in case you want to base your version of the embedded version.");
            }

            // Validate webpartmappingfile
            if (!string.IsNullOrEmpty(this.WebPartMappingFile))
            {
                if (!System.IO.File.Exists(this.WebPartMappingFile))
                {
                    throw new Exception($"Provided webpartmapping file {this.WebPartMappingFile} does not exist");
                }
            }

            if (this.PublishingPage && !string.IsNullOrEmpty(this.PageLayoutMapping) && !System.IO.File.Exists(this.PageLayoutMapping))
            {
                throw new Exception($"Provided pagelayout mapping file {this.PageLayoutMapping} does not exist");
            }

            // Create target client context (when needed)
            ClientContext targetContext = null;

            if (TargetConnection == null)
            {
                if (!string.IsNullOrEmpty(TargetWebUrl))
                {
                    targetContext = this.ClientContext.Clone(TargetWebUrl);
                }
            }
            else
            {
                targetContext = TargetConnection.Context;
            }


            // Create transformator instance
            PageTransformator           pageTransformator           = null;
            PublishingPageTransformator publishingPageTransformator = null;

            if (!string.IsNullOrEmpty(this.WebPartMappingFile))
            {
                // Using custom web part mapping file
                if (this.PublishingPage)
                {
                    if (!string.IsNullOrEmpty(this.PageLayoutMapping))
                    {
                        // Using custom page layout mapping file + default one (they're merged together)
                        publishingPageTransformator = new PublishingPageTransformator(this.ClientContext, targetContext, this.WebPartMappingFile, this.PageLayoutMapping);
                    }
                    else
                    {
                        // Using default page layout mapping file
                        publishingPageTransformator = new PublishingPageTransformator(this.ClientContext, targetContext, this.WebPartMappingFile, null);
                    }
                }
                else
                {
                    // Use web part mapping file
                    pageTransformator = new PageTransformator(this.ClientContext, targetContext, this.WebPartMappingFile);
                }
            }
            else
            {
                // Using default web part mapping file
                if (this.PublishingPage)
                {
                    if (!string.IsNullOrEmpty(this.PageLayoutMapping))
                    {
                        // Load and validate the custom mapping file
                        PageLayoutManager pageLayoutManager = new PageLayoutManager();
                        var pageLayoutMappingModel          = pageLayoutManager.LoadPageLayoutMappingFile(this.PageLayoutMapping);

                        // Using custom page layout mapping file + default one (they're merged together)
                        publishingPageTransformator = new PublishingPageTransformator(this.ClientContext, targetContext, webPartMappingModel, pageLayoutMappingModel);
                    }
                    else
                    {
                        // Using default page layout mapping file
                        publishingPageTransformator = new PublishingPageTransformator(this.ClientContext, targetContext, webPartMappingModel, null);
                    }
                }
                else
                {
                    // Use web part mapping model loaded from embedded mapping file
                    pageTransformator = new PageTransformator(this.ClientContext, targetContext, webPartMappingModel);
                }
            }

            // Setup logging
            if (this.LogType == ClientSidePageTransformatorLogType.File)
            {
                if (this.PublishingPage)
                {
                    publishingPageTransformator.RegisterObserver(new MarkdownObserver(folder: this.LogFolder, includeVerbose: this.LogVerbose, includeDebugEntries: this.LogVerbose));
                }
                else
                {
                    pageTransformator.RegisterObserver(new MarkdownObserver(folder: this.LogFolder, includeVerbose: this.LogVerbose, includeDebugEntries: this.LogVerbose));
                }
            }
            else if (this.LogType == ClientSidePageTransformatorLogType.SharePoint)
            {
                if (this.PublishingPage)
                {
                    publishingPageTransformator.RegisterObserver(new MarkdownToSharePointObserver(targetContext ?? this.ClientContext, includeVerbose: this.LogVerbose, includeDebugEntries: this.LogVerbose));
                }
                else
                {
                    pageTransformator.RegisterObserver(new MarkdownToSharePointObserver(targetContext ?? this.ClientContext, includeVerbose: this.LogVerbose, includeDebugEntries: this.LogVerbose));
                }
            }

            // Clear the client side component cache
            if (this.ClearCache)
            {
                CacheManager.Instance.ClearAllCaches();
            }

            string serverRelativeClientPageUrl = "";

            if (this.PublishingPage)
            {
                // Setup Transformation information
                PublishingPageTransformationInformation pti = new PublishingPageTransformationInformation(page)
                {
                    Overwrite = this.Overwrite,
                    KeepPageSpecificPermissions = !this.SkipItemLevelPermissionCopyToClientSidePage,
                    PublishCreatedPage          = !this.DontPublish,
                    DisablePageComments         = this.DisablePageComments,
                    TargetPageName = this.PublishingTargetPageName,
                    SkipUrlRewrite = this.SkipUrlRewriting
                };

                // Set mapping properties
                pti.MappingProperties["SummaryLinksToQuickLinks"] = (!SummaryLinksToHtml).ToString().ToLower();
                pti.MappingProperties["UseCommunityScriptEditor"] = UseCommunityScriptEditor.ToString().ToLower();

                serverRelativeClientPageUrl = publishingPageTransformator.Transform(pti);
            }
            else
            {
                Microsoft.SharePoint.Client.File fileToModernize = null;
                if (this.Folder != null && this.Folder.Equals(rootFolder, StringComparison.InvariantCultureIgnoreCase))
                {
                    // Load the page file from the site root folder
                    var webServerRelativeUrl = this.ClientContext.Web.EnsureProperty(p => p.ServerRelativeUrl);
                    fileToModernize = this.ClientContext.Web.GetFileByServerRelativeUrl($"{webServerRelativeUrl}/{this.Identity.Name}");
                    this.ClientContext.Load(fileToModernize);
                    this.ClientContext.ExecuteQueryRetry();
                }

                // Setup Transformation information
                PageTransformationInformation pti = new PageTransformationInformation(page)
                {
                    SourceFile = fileToModernize,
                    Overwrite  = this.Overwrite,
                    TargetPageTakesSourcePageName      = this.TakeSourcePageName,
                    ReplaceHomePageWithDefaultHomePage = this.ReplaceHomePageWithDefault,
                    KeepPageSpecificPermissions        = !this.SkipItemLevelPermissionCopyToClientSidePage,
                    CopyPageMetadata               = this.CopyPageMetadata,
                    PublishCreatedPage             = !this.DontPublish,
                    DisablePageComments            = this.DisablePageComments,
                    SkipUrlRewrite                 = this.SkipUrlRewriting,
                    ModernizationCenterInformation = new ModernizationCenterInformation()
                    {
                        AddPageAcceptBanner = this.AddPageAcceptBanner
                    },
                };

                // Set mapping properties
                pti.MappingProperties["SummaryLinksToQuickLinks"] = (!SummaryLinksToHtml).ToString().ToLower();
                pti.MappingProperties["UseCommunityScriptEditor"] = UseCommunityScriptEditor.ToString().ToLower();

                serverRelativeClientPageUrl = pageTransformator.Transform(pti);
            }

            // Flush log
            if (this.LogType != ClientSidePageTransformatorLogType.None)
            {
                if (!this.LogSkipFlush)
                {
                    if (this.PublishingPage)
                    {
                        publishingPageTransformator.FlushObservers();
                    }
                    else
                    {
                        pageTransformator.FlushObservers();
                    }
                }
            }

            // Output the server relative url to the newly created page
            if (!string.IsNullOrEmpty(serverRelativeClientPageUrl))
            {
                WriteObject(serverRelativeClientPageUrl);
            }
        }
Exemple #30
0
        protected override void ExecuteCmdlet()
        {
            //Fix loading of modernization framework
            FixAssemblyResolving();

            // Load the page to transform
            var page = Identity.GetPage(this.ClientContext.Web);

            if (page == null)
            {
                throw new Exception($"Page '{Identity?.Name}' does not exist");
            }

            PageTransformation webPartMappingModel = null;

            if (string.IsNullOrEmpty(this.WebPartMappingFile))
            {
                // Load xml mapping data
                XmlSerializer xmlMapping = new XmlSerializer(typeof(PageTransformation));

                // Load the default one from resources into a model, no need for persisting this file
                string webpartMappingFileContents = WebPartMappingLoader.LoadFile("SharePointPnP.PowerShell.Commands.ClientSidePages.webpartmapping.xml");

                using (var stream = GenerateStreamFromString(webpartMappingFileContents))
                {
                    webPartMappingModel = (PageTransformation)xmlMapping.Deserialize(stream);
                }

                this.WriteVerbose("Using embedded webpartmapping file (https://github.com/SharePoint/PnP-PowerShell/blob/master/Commands/ClientSidePages/webpartmapping.xml)");
            }

            // Validate webpartmappingfile
            if (!string.IsNullOrEmpty(this.WebPartMappingFile))
            {
                if (!System.IO.File.Exists(this.WebPartMappingFile))
                {
                    throw new Exception($"Provided webpartmapping file {this.WebPartMappingFile} does not exist");
                }
            }

            // Create target client context (when needed)
            ClientContext targetContext = null;

            if (!string.IsNullOrEmpty(TargetWebUrl))
            {
                targetContext = this.ClientContext.Clone(TargetWebUrl);
            }

            // Create transformator instance
            PageTransformator pageTransformator = null;

            if (!string.IsNullOrEmpty(this.WebPartMappingFile))
            {
                // Use web part mapping file
                pageTransformator = new PageTransformator(this.ClientContext, targetContext, this.WebPartMappingFile);
            }
            else
            {
                // Use web part mapping model loaded from embedded mapping file
                pageTransformator = new PageTransformator(this.ClientContext, targetContext, webPartMappingModel);
            }

            // Setup Transformation information
            PageTransformationInformation pti = new PageTransformationInformation(page)
            {
                Overwrite = this.Overwrite,
                TargetPageTakesSourcePageName      = this.TakeSourcePageName,
                ReplaceHomePageWithDefaultHomePage = this.ReplaceHomePageWithDefault,
                KeepPageSpecificPermissions        = !this.SkipItemLevelPermissionCopyToClientSidePage,
                CopyPageMetadata = this.CopyPageMetadata,
                ModernizationCenterInformation = new ModernizationCenterInformation()
                {
                    AddPageAcceptBanner = this.AddPageAcceptBanner
                },
            };

            // Set mapping properties
            pti.MappingProperties["SummaryLinksToQuickLinks"] = (!SummaryLinksToHtml).ToString().ToLower();
            pti.MappingProperties["UseCommunityScriptEditor"] = UseCommunityScriptEditor.ToString().ToLower();

            // Clear the client side component cache
            if (this.ClearCache)
            {
                CacheManager.Instance.ClearAllCaches();
            }

            string serverRelativeClientPageUrl = pageTransformator.Transform(pti);

            // Output the server relative url to the newly created page
            if (!string.IsNullOrEmpty(serverRelativeClientPageUrl))
            {
                WriteObject(serverRelativeClientPageUrl);
            }
        }