Site Designs in SharePoint online


Site designs is newly introduced feature in SharePoint online. With the help of site designs, users can install lists, libraries, add-ins, SPFx web parts, themes at the time of site creation. Following things are possible with site design.

  • Create new list in SharePoint
  • Define a new site column
  • Define a new content type
  • Add a navigation link
  • Apply a theme
  • Set a site logo (only possible for communication sites)
  • Join a hub site
  • Install add-in or solution
  • Register a new extension
  • Add users to SharePoint groups
  • Trigger a flow
  • Configure regional settings

Installing site designs

Site design consists of two things,

  • Site script
  • Site design

Site script is a json file which contains set of actions to perform. You need to register this site script in SharePoint online, which will return you Id of the installed script. Using this script id, need to create a site design.

Install site designs with PowerShell

Site scripts can be installed using PowerShell.

Get ready with json file

Json file will contains actions to perform. Each action will be defined with key verb.

Examples of verbs:

  • createSPList
  • addSPField
  • createSiteColumn
  • createContentType
  • addSiteColumn
  • addNavLink etc.

Sample site script


  "$schema": "schema.json",

  "actions": [  


      "verb": "createSPList",

      "listName": "Customer Tracking",

      "templateType": 100,

      "subactions": [


          "verb": "SetDescription",

          "description": "List of Customers and Orders"



          "verb": "addSPField",

          "fieldType": "Text",

          "displayName": "Customer Name",

          "isRequired": false,

          "addToDefaultView": true



          "verb": "addSPField",

          "fieldType": "Number",

          "displayName": "Requisition Total",

          "addToDefaultView": true,

          "isRequired": true



          "verb": "addSPField",

           "fieldType": "User",

          "displayName": "Contact",

          "addToDefaultView": true,

          "isRequired": true



          "verb": "addSPField",

          "fieldType": "Note",

          "displayName": "Meeting Notes",

          "isRequired": false





  "version": 1


Create site design:

  • create json file and save into your local machine and copy the file location path.
  • Open SharePoint online management shell and connect to your SharePoint tenant with
Connect-SPOServicec -Url "https://<yourdomain>"
  • Execute below command to add site script to SharePoint
Get-Content 'c:\scripts\constructions.json' -Raw | Add-SPOSiteScript -Title "Construction Site Script"
  • Once you execute the above command, it will output as below
Id: 99FBD978-E0F9-460B-B65A-F3EA88572787

Title: Construction Site Script



Version: 0
  • Execute below command to add site design based on output Id.
Add-SPOSiteDesign -Title "Construction Template" -WebTemplate "64" -SiteScripts "99FBD978-E0F9-460B-B65A-F3EA88572787" -Description "Construction site template with lists and libraries"

Note: Here -WebTemplate parameter will take template number for modern sites. 64 is for modern team site, 68 is for communication site.

  • Above command execution will give below output

Id: BFAA61B5-DD1B-488B-B7FF-EF026D523EFB

Title: Construction Template

WebTemplate: 64

SiteScriptIds: {99FBD978-E0F9-460B-B65A-F3EA88572787}

Description: Construction site template with lists and libraries



Is Default: false

Version: 1

Remove site designs with PowerShell

To remove site designs, first remove site design, then remove site script.

To get the installed site designs in site execute below command

  • To get all installed site designs
  • To get your site design
Get-SPOSiteDesign | Where-Object {$_.Title -eq "<Title of your site design>"}
  • Above command will give you the details along with id of the site design. Copy the Id of the site design .
  • Remove site design by executing below command
Remove-SPOSiteDesign -Identity "<id of the installed site design>"
  • Get the installed site script id by executing following command
Get-SPOSiteScript  | Where-Object {$_.Titlel -eq "<Title of your site script>" }
  • Above command will give you the details along with the Id. Copy the Id of the site script
  • Execute below command to remove site script from the site
Remove-SPOSiteScript -Identity "<your site script id>"

Upload image to sharepoint library using FileReader

I am pretty much tired to get solution for uploading image to picture library. But finally achieved it.

I hope it will be useful to someone.

Idea behind implementation

  1. Your browser should support FileReader API.
  2.  Read the contents are buffer by using “readAsArrayBuffer” function which is belongs to “FileReader”.
  3. On load of file (image), just pass the file input control result to your REST query.

Upload image with in sharepoint site (not in app)

function uploadFileUsingRest() {
var fileInput = document.getElementById('myFile');
var reader = new FileReader();
reader.onload = function (e) {
function PerformUploadAction(filename, fileData) {
url: _spPageContextInfo.webAbsoluteUr + "/_api/web/getfolderbyserverrelativeurl('ImagesLibrary')/files/add(url='" + filename + "', overwrite=true)",
method: "POST",
binaryStringRequestBody: true,
headers: {
"accept": "application/json; odata=verbose",
"X-RequestDigest": $("#__REQUESTDIGEST").val(),
"content-type":"application/json; odata=verbose"
success: function (data) {
console.log("Success! Your Picture was uploaded to SharePoint.");
error: function onQueryErrorAQ(xhr, ajaxOptions, thrownError) {
console.log('Error:\n' + xhr.status + '\n' + thrownError + '\n' + xhr.responseText);
  • Don’t forget to add processData:false in your ajax parameters.
  • This code will not work in sharepoint apps (sharepoint hosted app).

Upload image using sharepoint app

function uploadFileUsingRest() {
var reader = new FileReader();
reader.onload = function (result) {
var fileData = '';
var byteArray = new Uint8Array(;
for (var i = 0; i &lt; byteArray.byteLength; i++) {
fileData = fileData + String.fromCharCode(byteArray[i]);
PerformUploadAction(fileInput.files[0].name, fileData, uploadToFolder);
function PerformUploadAction(filename, fileData, uploadToFolder) {
executor = new SP.RequestExecutor(appweburl);
var targetUrl = appweburl + "/_api/SP.AppContextSite(@target)/web/lists/getByTitle('" + libraryToSearch + "')/RootFolder/folders(@TargetFolderName)/Files/add(url=@TargetFileName,overwrite='true')?@target='" + mysiteUrl + "'&amp;@TargetFileName='" + filename + "'&amp;@TargetFolderName='" + uploadToFolder + "'";
url: targetUrl,
headers: { Accept: "application/json;odata=verbose", "content-type": "application/json;odata=verbose" },
method: "POST",
contentType: "application/json;odata=verbose",
binaryStringRequestBody: true,
body: fileData,
async: false,
success: function(){
error: function(){

Happy coding… 🙂

Log exception in sharepoint using Windows event Log

When ever any exception occurs in sharepoint it will be logged in Logs directory of sharepoint. But when ever we are writing the coding solutions it is better to log our exceptions in some place. So, today I want to show, how to log the entry in the windows event viewer.

We will create with an EventLog class. Following is the solution.

public static void LogException(Exception ex)
         if (!EventLog.SourceExists("MySPSource"))
               EventLog.CreateEventSource("MySPSource", "Application");

         EventLog eventLog = new EventLog();
         eventLog.Source = "MySPSource";
         string message = string.Format("Exception Detail: {0}{1}Stack Trace: Exception occurred {2}", ex.Message.Trim(), Environment.NewLine, ex.StackTrace.Trim());
         eventLog.WriteEntry(message, EventLogEntryType.Error);
   catch (Exception)



Deploy Infopath with backend code in sharepoint 2010

I was so much struggled to deploy a infopath form into a sharepoint 2010 which is having backend code to connect database. Finally got the solution. I want to share this because it will definitely helpful to you.


Deploy a Infopath 2010 form which connecting to the Database into sharepoint server.


1. Infopath 2010.

2. Sql server 2008 with northwind database (what ever you required).

3. Sharepoint server 2010. (it should be server only)


1. Create infopath form and write backend code in code editor.

2. Complie the solution. Get the dll.

3.  Publish the infopath form with administrator approved.

4. Create a feature with and deploy into shareoint server.

5. Activating  feature in  site collection.


1. Create infopath form with backend code:

Open the infopath blank form and click on design. It will open a new form. Insert any design template what you needed. Drag and drop the textboxes and button into the form layout.


Change the control ids of text boxes and buttons if needed. Double Click on the button. In the ribbon you will see the Properties tab under Control Tools section is in visible state. If not visible select manually in ribbon. Click on custom code.

We want to connect to database. But here the opened visual studio kind tool doesn’t have a reference of  System.Data. To enable this add a reference to System.Data by right click on reference add reference. Now add the following code in your code editor.  Before pasting this code into your code editor please make sure the names/control ids of buttons and text boxes.

using Microsoft.Office.InfoPath;
using System;
using System.Xml;
using System.Xml.XPath;
using System.Web;
using System.Data;
using System.Data.SqlClient;

namespace NWInfopath
 public partial class FormCode
 public void InternalStartup()
 ((ButtonEvent)EventManager.ControlEvents["CTRL6_5"]).Clicked += new ClickedEventHandler(CTRL6_5_Clicked);
 ((ButtonEvent)EventManager.ControlEvents["CTRL7_5"]).Clicked += new ClickedEventHandler(CTRL7_5_Clicked);

public void CTRL6_5_Clicked(object sender, ClickedEventArgs e)
 SqlConnection sqlconn = null;
 SqlCommand sqlcmd = null;
 SqlDataReader rdr;
 XPathNavigator empid = this.MainDataSource.CreateNavigator().SelectSingleNode("/my:myFields/my:txtEmpid", this.NamespaceManager);
 XPathNavigator empLastName = this.MainDataSource.CreateNavigator().SelectSingleNode("/my:myFields/my:txtLastName", this.NamespaceManager);
 XPathNavigator empFirstName = this.MainDataSource.CreateNavigator().SelectSingleNode("/my:myFields/my:txtFirstName", this.NamespaceManager);
 XPathNavigator empTitle = this.MainDataSource.CreateNavigator().SelectSingleNode("/my:myFields/my:txtTitle", this.NamespaceManager);
 XPathNavigator empCity = this.MainDataSource.CreateNavigator().SelectSingleNode("/my:myFields/my:txtCity", this.NamespaceManager);
 int intEmpID = Convert.ToInt32(empid.Value);
 XPathNavigator resultBox = this.MainDataSource.CreateNavigator().SelectSingleNode("/my:myFields/my:result", this.NamespaceManager);
 using (sqlconn = new SqlConnection())
 sqlconn.ConnectionString = "Data Source=locat;Initial Catalog=Northwind;Integrated Security=true";
 string executeQuery = "Select [LastName],[FirstName],[Title],[City] from MYEmployees where [EmployeeID]=" + intEmpID;
 sqlcmd = new SqlCommand(executeQuery, sqlconn);
 rdr = sqlcmd.ExecuteReader();
 while (rdr.Read())
 catch (Exception ex)
 resultBox.SetValue("Exception occurred" + ex.Message);

public void CTRL7_5_Clicked(object sender, ClickedEventArgs e)
 SqlConnection sqlconn = null;
 SqlCommand sqlcmd = null;
 SqlDataReader rdr;
 XPathNavigator empid = this.MainDataSource.CreateNavigator().SelectSingleNode("/my:myFields/my:txtEmpid", this.NamespaceManager);
 XPathNavigator empLastName = this.MainDataSource.CreateNavigator().SelectSingleNode("/my:myFields/my:txtLastName", this.NamespaceManager);
 XPathNavigator empFirstName = this.MainDataSource.CreateNavigator().SelectSingleNode("/my:myFields/my:txtFirstName", this.NamespaceManager);
 XPathNavigator empTitle = this.MainDataSource.CreateNavigator().SelectSingleNode("/my:myFields/my:txtTitle", this.NamespaceManager);
 XPathNavigator empCity = this.MainDataSource.CreateNavigator().SelectSingleNode("/my:myFields/my:txtCity", this.NamespaceManager);
 XPathNavigator resultBox = this.MainDataSource.CreateNavigator().SelectSingleNode("/my:myFields/my:result", this.NamespaceManager);

 using (sqlconn = new SqlConnection())
 sqlconn.ConnectionString = "Data Source=local;Initial Catalog=Northwind;Integrated Security=true";
 string executeQuery = "insert into MYEmployees(EmployeeID,LastName,FirstName,Title,City) values("+empid.Value+",'" + empLastName.Value.ToString() + "','" + empFirstName.Value.ToString() + "','" + empTitle.Value.ToString() + "','" + empCity.Value.ToString() + "')";
 sqlcmd = new SqlCommand(executeQuery, sqlconn);
 int result = sqlcmd.ExecuteNonQuery();
 if (result > 0)
 resultBox.SetValue("Record inserted successfully.");
 catch (Exception ex)
 resultBox.SetValue("Exception occured" + ex.Message);

Now your code is ready. Just test it whether it is working fine or not. To test this one save the project and close the editor. Now goto infopath form and click on preview option or click F5. Now test it. If it is not working fine then open the code editor and put a debug points and press F5 and find out where mistake was happened.  Lets hope every thing is working fine.

Build the project and get .dll file:

Now we need to collect the .dll file. To copy the dll open once the code editor and click on the root node in the solution explorer. in the properties pane the path where the project was saved will appear. Copy that path and paste in the windows explorer. From there got BIN –>Release copy the .dll file. and paste in any other folder from where you want to deploy your solution package.

Publish  .xsn form with as administrator approved:

Its time to approve our form with administrator privilege.  Why administrator privilege? Any reason? Yes! Because we are deploy this one as a farm solution. So administrator only can do. Thats why we are publishing with administrator approved.  To do this click on file menu in infopath designer and click on farm options and select the following values and click on ok.

Programming : C# (because i given code in c#).

Compatability : Webbrowser form

Security and trust : Full trust.

Now select the publish option in the file menu select sharepoint server. Now one window will come there you enter the site collection to where your form should deploy. Click next –> Next –> Give the location where you want to store your published form. Next –>Next. The screens will appear like this.

publishstep1 publishstep2 publishstep3

Now your form was published. You have published form and .dll file.

Create Feature to deploy into sharepoint server:

you have to take care at this step.  Now i am showing to create feature manually. We can also do with visual studio. But Manual deployment will give you the good practice in writing scripts for deployment.

Now create a folder any where and in that folder create a 14 hive structure for features as below.

Your_folder_Name\14\Template\Features\Your_Folder_Name (here feature name need not be the same. But if you give same name it is safe side).

Paste the published xsn file and .dll file in the last folder.

In the last folder create two xml files with names element.xml , feature.xml. Elements.xml should contain following code.

<?xml version="1.0" encoding="utf-8" ?>
 <Elements xmlns="">
<Module Name="XSN" Url="FormServerTemplates" RootWebOnly="TRUE">
 <File Url="<span style="color: #ff6600;">myxsnname.xsn"</span> Name="<span style="color: #ff6600;">myxsnname.xsn</span>" Type="GhostableInLibrary" />

feature.xml should contain following code.

<?xml version="1.0" encoding="utf-8" ?>
<Feature xmlns=""
 Id="<span style="color: #ff6600;">68B4013A-DD8D-48DB-ADA2-D6561A8E7E54</span>"
 Description="This feature deploys the browser enabled Expenses Workflow InfoPath Form."
 ReceiverAssembly="Microsoft.Office.InfoPath.Server, Version=, Culture=neutral, PublicKeyToken=71e9bce111e9429c" >
 <ActivationDependency FeatureId="C88C4FF1-DBF5-4649-AD9F-C6C426EBCBF5"/>
 <ElementManifest Location="element.xml"/>
 <ElementFile Location="myxsnname.xsn"/>
 <ElementFile Location="dllname.dll"/>

Here .dll name will generate by the code editor it self. so just copy that name and paste it here. Make sure all the valueswere give correctly or not. I marked in red color where you want to take care about it.

Now come back to root folder. Now you have to create two batch files. One is to create the .wsp file and another one is to deploy into sharepoint server. Lets name the two files as Createwsp.bat InfopathInstall.bat.


echo Running WSP Builder
"C:\WSPBuilder\Buildx86\Buildx86\WSPBuilder.exe" -wspname NWInfopath_Approved.wsp -Buildcas false -solutionId 336BF7D6-E848-4ABD-98B1-EA96B7779DEC

Every time you are using this change the solution id to new GUID.


SET STSADM="C:\Program Files\Common Files\Microsoft Shared\web server extensions\14\BIN\STSADM"

ECHO ======================================

ECHO Retract Solution
%STSADM% -o retractsolution -n NWInfopath_Approved.wsp -immediate
ECHO ======
%STSADM% -o execadmsvcjobs
ECHO Remove Solution
%STSADM% -o deletesolution -n NWInfopath_Approved.wsp -override
ECHO ======
%STSADM% -o execadmsvcjobs
ECHO Adding Solution
%STSADM% -o addsolution -f NWInfopath_Approved.wsp
ECHO ======
%STSADM% -o execadmsvcjobs
ECHO Deploying Solution
%STSADM% -o deploysolution -n NWInfopath_Approved.wsp -immediate -allowgacdeployment -force
ECHO ======
%STSADM% -o execadmsvcjobs


ECHO Installation Completed

first run the createwsp.bat file. You can see the wsp created in your folder. Now run the infopathinstall.bat now the solution will deploy into sharpeoint sever.

Activating  feature in  site collection :

Now goto your site collection and see in the site collection features. under the site collection features you can see your feature name. Now activate it.

Now it was activated. We have to use this as a content type in the document library.

If you know how to add content types to a document library its fine. Otherwise I will show how to use this infopath form to use as a content type for a document library in my next post.

Happy coding.

Make automatic Logout when user is inactive for “X “minutes

1. We can do session management in sharepoint applications or sites. When ever we prepare Public facing websites we have to enable this session management. For example banking applications are the good examples for the session management applications. If we are inactive for 10 mins (more or less), it will automatically signed out after performing any actions.
2. This session management can do for the users who are created through forms based authentication. By default if you login through windows authentication, the session expiration time is 10hrs.
3. First you have to enable the site with Forms based authentication functionality. If you don’t know how to do it, follow my previous post which is documented nicely.
4. After you done with the above step, just need to enable the session with the powershell script.

$sts = Get-SPSecurityTokenServiceConfig 
$sts.UseSessionCookies = $true 
$sts.FormsTokenLifetime = (New-Timespan –Minutes 10)
$sts.LogonTokenCacheExpirationWindow = (New-Timespan –Minutes 10)

In above script make sure that you should provide a space between “New-TimeSpan” and “-Minutes 10” terms. Other wise it should throw an error as object not found.
5. Now login with forms based authentication user and check. For testing purpose it is better to give time as 1 or 2mins. If it works fine for you then increase the time and execute the script again.

Good luck.

Creating custom master page in visual studio and deploy it to the sharepoint site

To achieve this task, we have to perform following tasks.
1. Open the sharepoint designer and open any site. Goto master pages section in the designer and take a copy of existing master page and paste into the same gallery. Do some customization. After customization my site is appearing as below.

2. Now open the visual studio and create a New project–> Empty Sharepoint project (select the .net framework 3.5) and give the project name. Give the url in the coming screen into which you want to deploy your master page.

3. Now right click on the solution in the visual studio, Add–> New Item–>Module.

4. Rename the Sample.txt into Sample.master. Open the Sample.master page and remove the existing content. Now paste the content form the master page you already customized earlier. Open the Elements.xml file and enter the following code.

<?xml version="1.0" encoding="utf-8"?>
<Elements xmlns="">
  <Module Name="CustomMaster" Url="_catalogs/masterpage">
    <File Path="CustomMaster\Sample.Master" Url="CustomMaster/Sample.Master" Type="GhostableInLibrary" IgnoreIfAlreadyExists="TRUE" />

Now deploy the solution.

Now the solution was deployed into your site. We have to enable the necessary features and map our master page to our site. For this follow the below steps.
1. Goto the site in which you deployed your solution and goto Site Settings and activate the following features at site collection level(Site Settings –> Site Collection Administration –>Site collection features ) and site level (Site Settings –> Site Actions –> Manage Site features) respectively.
a. SharePoint Server Publishing Infrastructure
b. SharePoint Server Publishing

2. After activating come back to the site settings page and goto Look and Feel section –> Master page. Now select our required master page from the drop down and click on ok.

In the above image I just only applied our master page to the site. If you want to use the same master page to System pages also, the select our master page in the below section also and click ok.

3. Now goto home page and check whether our master page applied or not. After applying the changes my final page looks like this.

4. upto now every thing is fine. But some times while opening the popups like adding a new item, we came across a situation like our custom menu may appear int the popup like below.

If you found like this, don’t worry we have a solution.
Goto visual studio solution once and open our Sample.master page and search for the area what coming in the popup. In my case, my custom menu is appearing in the popup. I went to that custom menu area in the master page and applied the class s4-notdlg.

<div class="navigationarea s4-notdlg">

Now deploy the solution again and refresh the page and open the popup once and see the magic.

Hope this post is helpful to you.