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); }
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); } } }
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); } } }
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); } } }
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); }
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); } } }
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); } } }
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) { } } } }
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); } }
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); }
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); } } }
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(); } } }
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(); }
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 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); }); }
/// <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(); } } }
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); } } }
/// <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 } } }
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); }
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); } } }
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); } } }
public void CrossSiteTransformTest() { using (var targetClientContext = TestCommon.CreateClientContext(TestCommon.AppSetting("SPOTargetSiteUrl"))) { using (var sourceClientContext = TestCommon.CreateClientContext()) { var pageTransformator = new PageTransformator(sourceClientContext, targetClientContext); var pages = sourceClientContext.Web.GetPages("wp_"); 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 = "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); }
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(); } } }
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); } } }
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); }
public void RunWPTest() { using (var cc = TestCommon.CreateClientContext()) { var pageTransformator = new PageTransformator(cc); pageTransformator.RegisterObserver(new MarkdownObserver(folder: "c:\\temp", includeVerbose: true, includeDebugEntries: true)); pageTransformator.RegisterObserver(new ConsoleObserver()); var pages = cc.Web.GetPages("wp_"); //var pages = cc.Web.GetPages("pagein", "folder1/sub1"); //var pages = cc.Web.GetPagesFromList("SiteAssets", "loc_", "Folder1"); foreach (var page in pages) { PageTransformationInformation pti = new PageTransformationInformation(page) { // If target page exists, then overwrite it Overwrite = true, // Don't log test runs SkipTelemetry = true, //RemoveEmptySectionsAndColumns = false, // ModernizationCenter options //ModernizationCenterInformation = new ModernizationCenterInformation() //{ // AddPageAcceptBanner = true //}, // Migrated page gets the name of the original page //TargetPageTakesSourcePageName = true, // Give the migrated page a specific prefix, default is Migrated_ //TargetPagePrefix = "Yes_", // Configure the page header, empty value means ClientSidePageHeaderType.None //PageHeader = new ClientSidePageHeader(cc, ClientSidePageHeaderType.None, null), // If the page is a home page then replace with stock home page //ReplaceHomePageWithDefaultHomePage = true, // Replace embedded images and iframes with a placeholder and add respective images and video web parts at the bottom of the page //HandleWikiImagesAndVideos = false, // Callout to your custom code to allow for title overriding //PageTitleOverride = titleOverride, // Callout to your custom layout handler //LayoutTransformatorOverride = layoutOverride, // Callout to your custom content transformator...in case you fully want replace the model //ContentTransformatorOverride = contentOverride, }; pti.MappingProperties["SummaryLinksToQuickLinks"] = "true"; pti.MappingProperties["UseCommunityScriptEditor"] = "true"; pageTransformator.Transform(pti); } pageTransformator.FlushObservers(); } }
public void 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); } } }
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, KeepPageSpecificPermissions = !this.SkipItemLevelPermissionCopyToClientSidePage, CopyPageMetadata = this.CopyPageMetadata, ModernizationCenterInformation = new ModernizationCenterInformation() { AddPageAcceptBanner = this.AddPageAcceptBanner }, }; // Clear the client side component cache if (this.ClearCache) { CacheManager.Instance.ClearClientSideComponents(); CacheManager.Instance.ClearFieldsToCopy(); CacheManager.Instance.ClearBaseTemplate(); } string serverRelativeClientPageUrl = pageTransformator.Transform(pti); // Output the server relative url to the newly created page if (!string.IsNullOrEmpty(serverRelativeClientPageUrl)) { WriteObject(serverRelativeClientPageUrl); } } finally { if (!string.IsNullOrEmpty(tempPath) && System.IO.File.Exists(tempPath)) { System.IO.File.Delete(tempPath); } } }