How to Create Web Part Page in SharePoint 2013/2016/2019 Programmatically using CSOM?

  • Posted by: Softree Technology

Basically, CSOM has not exposed any inbuilt functions which will help us in creating web part page template in SharePoint 2013/2016/2019. By using CSOM functions we can create wiki pages, modern pages and also publishing page but we cannot create web part pages.

In this blog post I am going to use “Web Browser Control” to achieve this task.

By using “Web Browser Control” we can create webpart page in destination page Library. We can create web part page by navigating to this url “<Site Url>+ /_layouts/15/spcf.aspx” and there we can select the webpart page name, page layout type, destination library and then can click the ‘Create’ button internally to create the page in destination library location.

So in this blog post I am going to share all code details how you can invoke to “/_layouts/15/spcf.aspx” page and then how you can set parameter and then submit the page by using “Web Browser Control”.

In this example I am using wpf application so my design page will have the extension as .xaml.

Point-1:

We have to add a web browser control in design page and please make it hidden by default as we are going to use it internally so the end user cannot see this control.

Please refer the below mentioned code for adding “WebBrowserControl” in design or “.xaml” page.

[code lang=”c”]

// adding WebBrowser control in design page
&lt;WebBrowser x:Name=”WebBrowserControlCreatePage” Grid.Row=”0″ Grid.Column=”0″ Height=”10″ Width=”10″ Visibility=”Hidden”/&gt;;

[/code]

Design Page

[code lang=”c”]

&lt;Window x:Class=”WpfApp1.MainWindow”
xmlns=”http://schemas.microsoft.com/winfx/2006/xaml/presentation”
xmlns:x=”http://schemas.microsoft.com/winfx/2006/xaml”
xmlns:d=”http://schemas.microsoft.com/expression/blend/2008″
xmlns:mc=”http://schemas.openxmlformats.org/markup-compatibility/2006″
xmlns:local=”clr-namespace:WpfApp1″
mc:Ignorable=”d”
Title=”MainWindow” Height=”450″ Width=”800″&gt;
&lt;Grid&gt;

&lt;Label x:Name=”lblStatus” HorizontalAlignment=”Center” VerticalAlignment=”Center”&gt;&lt;/Label&gt;
&lt;WebBrowser x:Name=”WebBrowserControlCreatePage” Grid.Row=”0″ Grid.Column=”0″ Height=”10″ Width=”10″ Visibility=”Hidden”/&gt;

&lt;/Grid&gt;
&lt;/Window&gt;

[/code]

Point-2:
In the code behind we have to use the “WebBrowser” control by it’s “x:Name” as mentioned in the desing page. (E.g x:Name=”WebBrowserControlCreatePage” )

[code lang=”c”]

using System;
using System.Text;
using System.Windows;
using System.Threading;
using System.Reflection;
using System.Windows.Controls;

using mshtml;

namespace WpfApp1
{
/// &amp;lt;summary&amp;gt;
/// Interaction logic for MainWindow.xaml
/// &amp;lt;/summary&amp;gt;
public partial class MainWindow : Window
{
bool _isPageLoadedSuccessfully = false;
string _webPartPageName = string.Empty;

public MainWindow()
{
InitializeComponent();

//Please enter the site url where you want to create the web part page
string siteUrl = “http://siteurl”;

//Please enter a valid user name for authentication
string userName = “Testuser”;

//Please enter valid password for the above user
string password = “password”;

string headers = string.Empty;
//const string HTTP = “http://”;

if (userName.Contains(“\\”))
userName = userName.Split(‘\\’)[1];

// please enter page name you want to create
this._webPartPageName = “CreateNewWebPartPage”;

//By navigation to the below url we can create the page programmatically
Application.Current.Dispatcher.Invoke((Action)delegate
{
headers = “Authorization: Basic ” + Convert.ToBase64String(Encoding.ASCII.GetBytes(userName + “:” + password)) + Environment.NewLine;

if (siteUrl.StartsWith(“http://”))
this.WebBrowserControlCreatePage.Navigate(String.Format(“http://{0}:{1}@” + siteUrl.TrimEnd(‘/’).Replace(“http://”, “”) + “/_layouts/15/spcf.aspx”, userName, password), null, null, headers);

#region Navigate to the above refered location
HideScriptErrorPopUp(this.WebBrowserControlCreatePage);
this.WebBrowserControlCreatePage.LoadCompleted += WebBrowserControlCreatePage_LoadCompleted;
#endregion
});

this.lblStatus.Content = “Please wait…Creating page”;
}

#region HideScriptErrorPopUp
private void HideScriptErrorPopUp(WebBrowser webbrowser)
{
try
{
System.Reflection.FieldInfo fldInfo = typeof(WebBrowser).GetField(“_axIWebBrowser2”, BindingFlags.Instance | BindingFlags.NonPublic);

if (fldInfo == null)
return;

object obj = fldInfo.GetValue(webbrowser);
if (obj == null)
return;

obj.GetType().InvokeMember(“Silent”, BindingFlags.SetProperty, null, obj, new object[] { true });
}
catch { }
}
#endregion

// This event will execute after webbrowser control loaded the refered location successfully
#region WebBrowserControlCreatePage_LoadCompleted
private void WebBrowserControlCreatePage_LoadCompleted(object sender, System.Windows.Navigation.NavigationEventArgs e)
{
HTMLDocument htmlDocument = null;

try
{
if (!this._isPageLoadedSuccessfully)
{
htmlDocument = (HTMLDocument)WebBrowserControlCreatePage.Document;
CreateWebPartPage(htmlDocument);
}
}
catch { }
}

// This funtuion will create the webpart programmatically using webbrowser
private void CreateWebPartPage(HTMLDocument htmlDocument)
{
IHTMLElementCollection iHtmlElementColl = null;

try
{
if (!this._isPageLoadedSuccessfully)
{
iHtmlElementColl = htmlDocument.getElementsByTagName(“input”);

foreach (IHTMLElement iHtmlElement in iHtmlElementColl)
{
try
{
if (iHtmlElement.getAttribute(“id”) != null &amp;amp;&amp;amp; iHtmlElement.getAttribute(“id”).ToString().Contains(“onetidListTitle”))
iHtmlElement.setAttribute(“value”, this._webPartPageName, 1);
}
catch { }
}

iHtmlElementColl = htmlDocument.getElementsByTagName(“select”);

foreach (IHTMLElement iHtmlElement in iHtmlElementColl)
{
try
{
if (iHtmlElement.getAttribute(“id”) != null &amp;amp;&amp;amp; iHtmlElement.getAttribute(“id”).ToString().Contains(“onetidWebPartPageTemplate”))
{
var dropdown = ((IHTMLElement)htmlDocument.all.item(“WebPartPageTemplate”));
var dropdownItems = (IHTMLElementCollection)dropdown.children;

foreach (IHTMLElement option in dropdownItems)
{
// Header, Footer, 3 Columns
option.setAttribute(“selected”, “selected”);
break;
}
}

if (iHtmlElement.getAttribute(“id”) != null &amp;amp;&amp;amp; iHtmlElement.getAttribute(“id”).ToString().Contains(“onetidDocLibIDSelect”))
{
var dropdown = ((IHTMLElement)htmlDocument.all.item(“List”));
var dropdownItems = (IHTMLElementCollection)dropdown.children;

foreach (IHTMLElement option in dropdownItems)
{
var value = option.getAttribute(“value”).ToString();

// Please select required library
if (option.innerHTML.ToLower() == “site pages”)
{
option.setAttribute(“selected”, “selected”);
break;
}
}
}
}
catch { }
}

iHtmlElementColl = htmlDocument.getElementsByTagName(“input”);

foreach (IHTMLElement iHtmlElement in iHtmlElementColl)
{
try
{
if (iHtmlElement.getAttribute(“value”) == “Create”)
{
//Internally clicking the OK button to create page
iHtmlElement.click();
this._isPageLoadedSuccessfully = true;
Thread.Sleep(5000);

this.lblStatus.Content = “Page Created Successfully”;
break;
}
}
catch { }
}
}
}
catch { }
}
}
}

[/code]

After the label changed to “Page Created Successfully” you can manually check the “Site Pages” library and there you can find the newly created webpart page as shown in below screenshot.

webpartpagecreation

 

This solution is brought to you by our SharePoint professionals.

Softree Consulting employs SharePoint consultants; we are a technology services provider with the aim to help companies achieve exceptional performance through SharePoint. Our dedicated team of SharePoint consultants has the right bent of mind to understand and execute customer requirements.

Be it SPFx or SharePoint add-in developments, SharePoint 2019 developments, web part developments, migrating from SharePoint 2010/2013 to SharePoint 2013/2016/Office 365, Office 365, SharePoint hosted apps development or something else in SharePoint, we strive to deliver the best

Author: Softree Technology

Leave a Reply