In the earlier article, we saw how to create the Custom page Layout using the Design Manager. In this article, as a continuation, let us see, how to create a Page using that Layout programmatically using CSOM.
The Code is straight forward. As usual, I have created a console to test this functionality.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.SharePoint.Client;
using System.Security;
using Microsoft.Online.SharePoint.TenantAdministration;
using OfficeDevPnP.Core;
using Microsoft.SharePoint.Client.Publishing;
namespace Console.Office365
{
class Program
{
static void Main(string[] args)
{
CreatePageWithCustomLayout();
}
public static void CreatePageWithCustomLayout()
{
OfficeDevPnP.Core.AuthenticationManager authMgr = new OfficeDevPnP.Core.AuthenticationManager();
string siteUrl = "https://*****.sharepoint.com/sites/PublishingSite/";
string userName = "Sathish@*****.onmicrosoft.com";
string password = "************";
using (var ctx = authMgr.GetSharePointOnlineAuthenticatedContextTenant(siteUrl, userName, password))
{
Web web = ctx.Web;
ctx.Load(web);
ctx.ExecuteQueryRetry();
var layout = web.GetPageLayoutListItemByName("MyPageLayout");
ctx.Load(layout);
ctx.Load(layout, l => l.DisplayName);
ctx.ExecuteQueryRetry();
PublishingWeb publishingWeb = PublishingWeb.GetPublishingWeb(ctx, web);
ctx.Load(publishingWeb);
PublishingPageInformation publishingPageInfo = new PublishingPageInformation();
publishingPageInfo.Name = "MyPage2.aspx";
publishingPageInfo.PageLayoutListItem = layout;
PublishingPage publishingPage = publishingWeb.AddPublishingPage(publishingPageInfo);
//publishingPage.ListItem.File.CheckOut();
ctx.Load(publishingPage);
ctx.Load(publishingPage.ListItem.File);
ctx.ExecuteQueryRetry();
ListItem listItem = publishingPage.ListItem;
listItem["MySiteColumn"] = "Test";
listItem.Update();
publishingPage.ListItem.File.CheckIn(string.Empty, CheckinType.MajorCheckIn);
publishingPage.ListItem.File.Publish(string.Empty);
ctx.Load(publishingPage);
ctx.ExecuteQueryRetry();
}
}
}
}
Happy Coding,
Sathish Nadarajan.
Leave a comment