internal void RemoveEmptyTextParts(ClientSidePage targetPage) { var textParts = targetPage.Controls.Where(p => p.Type == typeof(OfficeDevPnP.Core.Pages.ClientSideText)); if (textParts != null && textParts.Any()) { HtmlParser parser = new HtmlParser(new HtmlParserOptions() { IsEmbedded = true }); foreach (var textPart in textParts.ToList()) { using (var document = parser.Parse(((OfficeDevPnP.Core.Pages.ClientSideText)textPart).Text)) { if (document.FirstChild != null && string.IsNullOrEmpty(document.FirstChild.TextContent)) { LogInfo(LogStrings.TransformRemovingEmptyWebPart, LogStrings.Heading_RemoveEmptyTextParts); // Drop text part targetPage.Controls.Remove(textPart); } } } } }
private static ClientSidePage EnsureRepostPage(PnPClientContext context, string pageName) { ClientSidePage repostPage = null; try { // Check if the repost already exists repostPage = ClientSidePage.Load(context, pageName); LogInfo($" Found existing news link: {pageName}"); } catch (ArgumentException ex) { if (ex.Message.Contains("does not exist")) { // If it doesn't, create it repostPage = context.Web.AddClientSidePage(pageName); repostPage.LayoutType = ClientSidePageLayoutType.RepostPage; repostPage.Save(pageName); repostPage = ClientSidePage.Load(context, pageName); LogInfo($" Created news link: {pageName}"); } else { throw; } } catch (Exception ex) { LogError("Unable to retrieve or add repost page", ex); } return(repostPage); }
/// <summary> /// Instantiates the content transformator /// </summary> /// <param name="page">Client side page that will be updates</param> /// <param name="pageTransformation">Transformation information</param> public ContentTransformator(ClientSidePage page, PageTransformation pageTransformation) { this.page = page ?? throw new ArgumentException("Page cannot be null"); this.pageTransformation = pageTransformation ?? throw new ArgumentException("pageTransformation cannot be null"); this.functionProcessor = new FunctionProcessor(this.page, this.pageTransformation); this.siteTokens = CreateSiteTokenList(page.Context); }
public static void AddSectionAndAddWebpart() { OfficeDevPnP.Core.AuthenticationManager authenticationManager = new OfficeDevPnP.Core.AuthenticationManager(); using (binderSiteClientContext = authenticationManager.GetSharePointOnlineAuthenticatedContextTenant(binderSiteUrl, userName, passWord)) { //Create a page or get the existing page string pageName = "POCSiteProvisioning.aspx"; ClientSidePage page = ClientSidePage.Load(binderSiteClientContext, pageName); //var page = binderSiteClientContext.Web.AddClientSidePage("POCAppProvisioning.aspx", true); // Add Section page.AddSection(CanvasSectionTemplate.ThreeColumn, 5); // get the available web parts - this collection will include OOTB and custom SPFx web parts.. page.Save(); // Get all the available webparts var components = page.AvailableClientSideComponents(); // add the named web part.. var webPartToAdd = components.Where(wp => wp.ComponentType == 1 && wp.Name == "HeroControl").FirstOrDefault(); if (webPartToAdd != null) { ClientSideWebPart clientWp = new ClientSideWebPart(webPartToAdd) { Order = 1 }; //Add the WebPart to the page with appropriate section page.AddControl(clientWp, page.Sections[1].Columns[1]); } // the save method creates the page if one doesn't exist with that name in this site.. page.Save(); } }
/// <summary> /// Instantiates the function processor. Also loads the defined add-ons /// </summary> /// <param name="page">Client side page for which we're executing the functions/selectors as part of the mapping</param> /// <param name="pageTransformation">Webpart mapping information</param> public FunctionProcessor(ClientSidePage page, PageTransformation pageTransformation) { this.page = page; this.pageTransformation = pageTransformation; // instantiate default built in functions class this.addOnTypes = new List <AddOnType>(); this.builtInFunctions = Activator.CreateInstance(typeof(BuiltIn), this.page.Context); // instantiate the custom function classes (if there are) foreach (var addOn in this.pageTransformation.AddOns) { try { string path = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, addOn.Assembly); var assembly = Assembly.LoadFile(path); var customType = assembly.GetType(addOn.Type); var instance = Activator.CreateInstance(customType, this.page.Context); this.addOnTypes.Add(new AddOnType() { Name = addOn.Name, Assembly = assembly, Instance = instance, Type = customType, }); } catch (Exception ex) { // TODO: Add logging throw; } } }
public void AddClientSideWebPartTest() { using (var scope = new PSTestScope(true)) { using (var ctx = TestCommon.CreateClientContext()) { ctx.Web.AddClientSidePage(PageAddWebPartTestName, true); var results = scope.ExecuteCommand("Add-PnPClientSideWebPart", new CommandParameter("Page", PageAddWebPartTestName), new CommandParameter("DefaultWebPartType", DefaultClientSideWebParts.Image), new CommandParameter("WebPartProperties", new Hashtable() { { "imageSourceType", 2 }, { "siteId", "c827cb03-d059-4956-83d0-cd60e02e3b41" }, { "webId", "9fafd7c0-e8c3-4a3c-9e87-4232c481ca26" }, { "listId", "78d1b1ac-7590-49e7-b812-55f37c018c4b" }, { "uniqueId", "3C27A419-66D0-4C36-BF24-BD6147719052" }, { "imgWidth", 500 }, { "imgHeight", 235 } } )); var page = ClientSidePage.Load(ctx, PageAddWebPartTestName); Assert.AreEqual(page.Controls.Count, 1); } } }
/// <summary> /// Get's the clientside components from cache or if needed retrieves and caches them /// </summary> /// <param name="page">Page to grab the components for</param> /// <returns></returns> public List <ClientSideComponent> GetClientSideComponents(ClientSidePage page) { Guid webId = page.Context.Web.EnsureProperty(o => o.Id); if (siteToComponentMapping.ContainsKey(webId)) { // Components are cached for this site, get the component key if (siteToComponentMapping.TryGetValue(webId, out string componentKey)) { if (clientSideComponents.TryGetValue(componentKey, out List <ClientSideComponent> componentList)) { return(componentList); } } } // Ok, so nothing in cache so it seems, so let's get the components var componentsToAdd = page.AvailableClientSideComponents().ToList(); // calculate the componentkey string componentKeyToCache = Sha256(JsonConvert.SerializeObject(componentsToAdd)); // store the retrieved data in cache if (siteToComponentMapping.TryAdd(webId, componentKeyToCache)) { // Since the components list is big and often the same across webs we only store it in cache if it's different if (!clientSideComponents.ContainsKey(componentKeyToCache)) { clientSideComponents.TryAdd(componentKeyToCache, componentsToAdd); } } return(componentsToAdd); }
internal void RemoveEmptySectionsAndColumns(ClientSidePage targetPage) { foreach (var section in targetPage.Sections.ToList()) { // First remove all empty sections if (section.Controls.Count == 0) { targetPage.Sections.Remove(section); } } // Remove empty columns foreach (var section in targetPage.Sections) { if (section.Type == CanvasSectionTemplate.TwoColumn || section.Type == CanvasSectionTemplate.TwoColumnLeft || section.Type == CanvasSectionTemplate.TwoColumnRight) { var emptyColumn = section.Columns.Where(p => p.Controls.Count == 0).FirstOrDefault(); if (emptyColumn != null) { // drop the empty column and change to single column section section.Columns.Remove(emptyColumn); section.Type = CanvasSectionTemplate.OneColumn; section.Columns.First().ResetColumn(0, 12); } } else if (section.Type == CanvasSectionTemplate.ThreeColumn) { var emptyColumns = section.Columns.Where(p => p.Controls.Count == 0); if (emptyColumns != null) { if (emptyColumns.Any() && emptyColumns.Count() == 2) { // drop the two empty columns and change to single column section foreach (var emptyColumn in emptyColumns.ToList()) { section.Columns.Remove(emptyColumn); } section.Type = CanvasSectionTemplate.OneColumn; section.Columns.First().ResetColumn(0, 12); } else if (emptyColumns.Any() && emptyColumns.Count() == 1) { // Remove the empty column and change to two column section section.Columns.Remove(emptyColumns.First()); section.Type = CanvasSectionTemplate.TwoColumn; int i = 0; foreach (var column in section.Columns) { column.ResetColumn(i, 6); i++; } } } } } }
/// <summary> /// Instantiates the content transformator /// </summary> /// <param name="page">Client side page that will be updates</param> /// <param name="pageTransformation">Transformation information</param> public ContentTransformator(ClientContext sourceClientContext, ClientSidePage page, PageTransformation pageTransformation, Dictionary <string, string> mappingProperties) { this.page = page ?? throw new ArgumentException("Page cannot be null"); this.pageTransformation = pageTransformation ?? throw new ArgumentException("pageTransformation cannot be null"); this.globalTokens = CreateGlobalTokenList(page.Context, mappingProperties); this.functionProcessor = new FunctionProcessor(sourceClientContext, this.page, this.pageTransformation); this.sourceClientContext = sourceClientContext; this.isCrossSiteTransfer = IsCrossSiteTransfer(); }
protected override void ExecuteCmdlet() { ClientSidePage clientSidePage = Identity?.GetPage(ClientContext); if (clientSidePage == null) { // If the client side page object cannot be found throw new Exception($"Page {Identity?.Name} cannot be found."); } // We need to have the page name, if not found, raise an error string name = ClientSidePageUtilities.EnsureCorrectPageName(Name ?? Identity?.Name); if (name == null) { throw new Exception("Insufficient arguments to update a client side page"); } clientSidePage.LayoutType = LayoutType; clientSidePage.Save(name); // If a specific promote type is specified, promote the page as Home or Article or ... switch (PromoteAs) { case ClientSidePagePromoteType.HomePage: clientSidePage.PromoteAsHomePage(); break; case ClientSidePagePromoteType.NewsArticle: clientSidePage.PromoteAsNewsArticle(); break; case ClientSidePagePromoteType.None: default: break; } if (MyInvocation.BoundParameters.ContainsKey("CommentsEnabled")) { if (CommentsEnabled) { clientSidePage.EnableComments(); } else { clientSidePage.DisableComments(); } } if (Publish) { clientSidePage.Publish(PublishMessage); } WriteObject(clientSidePage); }
private void CleanupPageIfExists(ClientContext ctx, string pageName) { try { pageName = pageName.EndsWith(".aspx") ? pageName : pageName + ".aspx"; var p = ClientSidePage.Load(ctx, pageName); p.Delete(); } catch (Exception) { } }
/// <summary> /// Write the report to SharePoint /// </summary> /// <param name="clearLogData">Also clear the log data</param> public override void Flush(bool clearLogData) { try { if (_clientContext == null) { throw new ArgumentNullException("ClientContext is null"); } var report = GenerateReportWithSummaryAtTop(includeHeading: false); // Dont want to assume locality here string logRunTime = _reportDate.ToString().Replace('/', '-').Replace(":", "-").Replace(" ", "-"); string logFileName = $"Page-Transformation-Report-{logRunTime}{_reportFileName}"; logFileName = logFileName + ".aspx"; var targetFolder = this.EnsureDestination(); var pageName = $"{targetFolder.Name}/{logFileName}"; var reportPage = this._clientContext.Web.AddClientSidePage(pageName); reportPage.PageTitle = base._includeVerbose ? LogStrings.Report_ModernisationReport : LogStrings.Report_ModernisationSummaryReport; var componentsToAdd = CacheManager.Instance.GetClientSideComponents(reportPage); ClientSideComponent baseControl = null; var webPartName = ClientSidePage.ClientSideWebPartEnumToName(DefaultClientSideWebParts.MarkDown); baseControl = componentsToAdd.FirstOrDefault(p => p.Name.Equals(webPartName, StringComparison.InvariantCultureIgnoreCase)); var jsonRpt = JsonConvert.SerializeObject(report, new JsonSerializerSettings { StringEscapeHandling = StringEscapeHandling.EscapeHtml }); var jsonDecoded = GetMarkdownJsonProperties(jsonRpt); PnP.Framework.Pages.ClientSideWebPart mdWebPart = new PnP.Framework.Pages.ClientSideWebPart(baseControl) { PropertiesJson = jsonDecoded }; // This should only have one web part on the page reportPage.AddControl(mdWebPart); reportPage.Save(pageName); reportPage.DisableComments(); // Cleardown all logs Logs.RemoveRange(0, Logs.Count); Console.WriteLine($"Report saved as: {pageName}"); } catch (Exception ex) { Console.WriteLine("Error writing to log file: {0} {1}", ex.Message, ex.StackTrace); } }
internal CanvasSection(ClientSidePage page) { if (page == null) { throw new ArgumentNullException("Passed page cannot be null"); } this.page = page; this.zoneEmphasis = 0; Order = 0; }
public List <ClientSideWebPart> GetWebPart(ClientSidePage page) { if (page == null) { throw new ArgumentException(nameof(page)); } if (!string.IsNullOrEmpty(_title)) { return(page.Controls.Where(c => c.GetType() == typeof(ClientSideWebPart) && ((ClientSideWebPart)c).Title.Equals(_title, StringComparison.InvariantCultureIgnoreCase)).Cast <ClientSideWebPart>().ToList()); } return(page.Controls.Where(c => c.GetType() == typeof(ClientSideWebPart) && c.InstanceId == _instanceId).Cast <ClientSideWebPart>().ToList()); }
/// <summary> /// Instantiates the function processor. Also loads the defined add-ons /// </summary> /// <param name="page">Client side page for which we're executing the functions/selectors as part of the mapping</param> /// <param name="pageTransformation">Webpart mapping information</param> public FunctionProcessor(ClientContext sourceClientContext, ClientSidePage page, PageTransformation pageTransformation, BaseTransformationInformation baseTransformationInformation, IList <ILogObserver> logObservers = null) { this.page = page; this.pageTransformation = pageTransformation; //Register any existing observers if (logObservers != null) { foreach (var observer in logObservers) { base.RegisterObserver(observer); } } // instantiate default built in functions class this.addOnTypes = new List <AddOnType>(); this.builtInFunctions = Activator.CreateInstance(typeof(BuiltIn), baseTransformationInformation, this.page.Context, sourceClientContext, this.page, base.RegisteredLogObservers); // instantiate the custom function classes (if there are) foreach (var addOn in this.pageTransformation.AddOns) { try { string path = ""; if (addOn.Assembly.Contains("\\") && System.IO.File.Exists(addOn.Assembly)) { path = addOn.Assembly; } else { path = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, addOn.Assembly); } var assembly = Assembly.LoadFile(path); var customType = assembly.GetType(addOn.Type); var instance = Activator.CreateInstance(customType, this.page.Context); this.addOnTypes.Add(new AddOnType() { Name = addOn.Name, Assembly = assembly, Instance = instance, Type = customType, }); } catch (Exception ex) { LogError(LogStrings.Error_FailedToInitiateCustomFunctionClasses, LogStrings.Heading_FunctionProcessor, ex); throw; } } }
/// <summary> /// Creates a layout transformator instance /// </summary> /// <param name="page">Client side page that will be receive the created layout</param> public PublishingLayoutTransformator(ClientSidePage page, IList <ILogObserver> logObservers = null) { // Register observers if (logObservers != null) { foreach (var observer in logObservers) { base.RegisterObserver(observer); } } this.page = page; }
public ClientSidePagePipeBind(ClientSidePage page) { _page = page; if (page.PageListItem != null) { File file = page.PageListItem.EnsureProperty(li => li.File); _name = file.EnsureProperty(f => f.Name); } else { _name = page.PageTitle; } }
private static void ModifyPage(ClientContext siteContext, string pageName) { ClientSidePage page = ClientSidePage.Load(siteContext, pageName); ClientSideText txt1 = new ClientSideText() { Text = "Hello world 2!" }; page.AddControl(txt1, 0); page.Save(pageName); Console.WriteLine("Page successfully modified."); }
private static void CreatePage(ClientContext siteContext, string pageName) { ClientSidePage page = new ClientSidePage(siteContext); ClientSideText txt1 = new ClientSideText() { Text = "Hello world!" }; page.AddControl(txt1, 0); page.Save(pageName); Console.WriteLine("Page successfully created."); }
public PublishingMetadataTransformator(PublishingPageTransformationInformation publishingPageTransformationInformation, ClientContext sourceClientContext, ClientContext targetClientContext, ClientSidePage page, PageLayout publishingPageLayoutModel, IList <ILogObserver> logObservers = null) { // Register observers if (logObservers != null) { foreach (var observer in logObservers) { base.RegisterObserver(observer); } } this.publishingPageTransformationInformation = publishingPageTransformationInformation; this.sourceClientContext = sourceClientContext; this.targetClientContext = targetClientContext; this.page = page; this.pageLayoutMappingModel = publishingPageLayoutModel; }
public MyCustomFunctions(BaseTransformationInformation baseTransformationInformation, ClientContext pageClientContext, ClientContext sourceClientContext, ClientSidePage clientSidePage, IList <ILogObserver> logObservers) : base(pageClientContext) { if (logObservers != null) { foreach (var observer in logObservers) { base.RegisterObserver(observer); } } // This is an optional property, in cross site transfer the two contexts would be different. this.sourceClientContext = sourceClientContext; this.clientSidePage = clientSidePage; this.baseTransformationInformation = baseTransformationInformation; this.urlTransformator = new UrlTransformator(baseTransformationInformation, this.sourceClientContext, this.clientContext, base.RegisteredLogObservers); this.userTransformator = new UserTransformator(baseTransformationInformation, this.sourceClientContext, this.clientContext, base.RegisteredLogObservers); }
public void RemoveClientSidePageTest() { using (var scope = new PSTestScope(true)) { using (var ctx = TestCommon.CreateClientContext()) { ctx.Web.AddClientSidePage(PageRemoveTestName, true); scope.ExecuteCommand("Remove-PnPClientSidePage", new CommandParameter("Identity", PageRemoveTestName), new CommandParameter("Force")); var p = ClientSidePage.Load(ctx, PageRemoveTestName); } } }
public PublishingMetadataTransformator(PublishingPageTransformationInformation publishingPageTransformationInformation, ClientContext sourceClientContext, ClientContext targetClientContext, ClientSidePage page, PageLayout publishingPageLayoutModel, PublishingPageTransformation publishingPageTransformation, IList <ILogObserver> logObservers = null) { // Register observers if (logObservers != null) { foreach (var observer in logObservers) { base.RegisterObserver(observer); } } this.publishingPageTransformationInformation = publishingPageTransformationInformation; this.targetClientContext = targetClientContext; this.page = page; this.pageLayoutMappingModel = publishingPageLayoutModel; this.publishingPageTransformation = publishingPageTransformation; this.functionProcessor = new PublishingFunctionProcessor(publishingPageTransformationInformation.SourcePage, sourceClientContext, targetClientContext, this.publishingPageTransformation, publishingPageTransformationInformation as BaseTransformationInformation, base.RegisteredLogObservers); }
/// <summary> /// Adds the controls. /// </summary> /// <param name="sourceContext">The source context.</param> /// <param name="newModernPage">The new modern page.</param> /// <param name="pageName">Name of the page.</param> private void AddControls(ClientContext sourceContext, ClientSidePage newModernPage, string pageName) { try { var sourcePage = ClientSidePage.Load(sourceContext, pageName); //newModernPage.Controls; var controlsCollection = sourcePage.Controls; foreach (var control in controlsCollection) { newModernPage.AddControl(control); //var webparttoadd = newmodernpage.instantiatedefaultwebpart(defaultclientsidewebparts.) } newModernPage.Save(); } catch (Exception ex) { ConsoleOperations.WriteToConsole("Problem with adding controls to page", ConsoleColor.Yellow); } }
/// <summary> /// Instantiates the content transformator /// </summary> /// <param name="page">Client side page that will be updates</param> /// <param name="pageTransformation">Transformation information</param> public ContentTransformator(ClientContext sourceClientContext, ClientSidePage page, PageTransformation pageTransformation, BaseTransformationInformation transformationInformation, IList <ILogObserver> logObservers = null) : base() { //Register any existing observers if (logObservers != null) { foreach (var observer in logObservers) { base.RegisterObserver(observer); } } this.page = page ?? throw new ArgumentException("Page cannot be null"); this.pageTransformation = pageTransformation ?? throw new ArgumentException("pageTransformation cannot be null"); this.globalTokens = CreateGlobalTokenList(page.Context, transformationInformation.MappingProperties); this.functionProcessor = new FunctionProcessor(sourceClientContext, this.page, this.pageTransformation, transformationInformation, base.RegisteredLogObservers); this.sourceClientContext = sourceClientContext; this.isCrossSiteTransfer = IsCrossSiteTransfer(); }
private static void AddCustomSPFxWebPart(ClientContext siteContext, string wpName, string pageName, int wpOrder) { ClientSidePage page = new ClientSidePage(siteContext); var components = page.AvailableClientSideComponents(); var webPartToAdd = components.Where(wp => wp.ComponentType == 1 && wp.Name == wpName).FirstOrDefault(); if (webPartToAdd != null) { ClientSideWebPart clientWp = new ClientSideWebPart(webPartToAdd) { Order = wpOrder }; page.AddControl(clientWp); } page.Save(pageName); }
public void SetClientSidePageTest() { using (var scope = new PSTestScope(true)) { using (var ctx = TestCommon.CreateClientContext()) { ctx.Web.AddClientSidePage(PageSetTestName, true); var results = scope.ExecuteCommand("Set-PnPClientSidePage", new CommandParameter("Identity", PageSetTestName), new CommandParameter("LayoutType", ClientSidePageLayoutType.Home), new CommandParameter("Name", PageSet2TestName)); var page = ClientSidePage.Load(ctx, PageSet2TestName); Assert.IsTrue(page.LayoutType == ClientSidePageLayoutType.Home); } } }
public void AddClientSidePageSectionTest() { using (var scope = new PSTestScope(true)) { using (var ctx = TestCommon.CreateClientContext()) { ctx.Web.AddClientSidePage(PageAddSectionTestName, true); var results = scope.ExecuteCommand("Add-PnPClientSidePageSection", new CommandParameter("Page", PageAddSectionTestName), new CommandParameter("SectionTemplate", CanvasSectionTemplate.ThreeColumn), new CommandParameter("Order", 10)); var page = ClientSidePage.Load(ctx, PageAddSectionTestName); Assert.IsTrue(page.Sections[0].Columns.Count == 3); } } }
internal ClientSidePage GetPage(ClientContext ctx) { if (_page != null) { return(_page); } else if (!string.IsNullOrEmpty(_name)) { try { return(ClientSidePage.Load(ctx, Name)); } catch (ArgumentException) { return(null); } } else { return(null); } }
/// <summary> /// Default constructor /// </summary> public WikiHtmlTransformator(ClientContext sourceContext, ClientSidePage page, BaseTransformationInformation basePageTransformationInformation, IList <ILogObserver> logObservers = null) { //Register any existing observers if (logObservers != null) { foreach (var observer in logObservers) { base.RegisterObserver(observer); } } this.sourceContext = sourceContext; this.page = page; this.mappingProperties = basePageTransformationInformation.MappingProperties; // Instantiate BuiltIn functions class this.builtInFunctions = new BuiltIn(basePageTransformationInformation, this.page.Context, this.sourceContext, this.page, base.RegisteredLogObservers); // Instantiate the AngleSharp Html parser parser = new HtmlParser(new HtmlParserOptions() { IsEmbedded = true }); }