How to format SharePoint Date to DD-MM-YYYY Format using Moment.js

It’s easy to format SharePoint Date in JavaScript Date Format e.g. mm/dd/yyyy OR dd/mm/yyyy

Use below code to format Date

Add Moment.js Reference

  <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.1/moment.js"></script>

Apply Date Format as per shown code


    //Get SharePoint Date Column Value 
    var itemBirthDate = items[i].BirthDate;   
    //Convert SharePoint Date to Javascript Date 
    var dateObj = new Date(itemBirthDate);
    //Convet JavaScript Date Object to Moment JS
    var momentObj = moment(dateObj);
    //Apply Moment.Js Formatter to your desire date format
    var formattedDate = momentObj.format('DD-MM-YYYY');   
    $("#divContent").append("Username : " + itemTitle + "  BirthDate :  " + formattedDate +" <br/>  ");      

Sample Code to retrieve item and Date Format

function GetData() {

	var listName = "Controls";
	var siteurl = _spPageContextInfo.webAbsoluteUrl;
	var condition = "$select=Title,BirthDate";

	getListItems(listName, siteurl, condition, function (data) {

		var items = data.d.results;

		for (var i = 0; i < items.length; i++) {
			var itemTitle = items[i].Title;
			//Get SharePoint Date Column Value 
			var itemBirthDate = items[i].BirthDate;
			//Convert SharePoint Date to Javascript Date 
			var dateObj = new Date(itemBirthDate);
			//Convet JavaScript Date Object to Moment JS
			var momentObj = moment(dateObj);
			//Apply Moment.Js Formatter to your desire date format
			var formattedDate = momentObj.format('DD-MM-YYYY');
			$("#divContent").append("Username : " + itemTitle + "  BirthDate :  " + formattedDate + " <br/>  ");
		}
	}, function (data) {
		alert("Ooops, an error occured. Please try again");
	});
}

function getListItems(listName, siteurl, condition, success, failure) {
	$.ajax({
		url: siteurl + "/_api/web/lists/getbytitle('" + listName + "')/items?" + condition,
		method: "GET",
		async: false,
		headers: {
			"Accept": "application/json; odata=verbose"
		},
		success: function (data) {
			success(data);
		},
		error: function (data) {
			failure(data);
		}
	});
}
Advertisement

SharePoint Provider Hosted APP How to create Navigation Link using HTML href Attribute

By using  HTML <a> href attribute we can set navigation link or href with SharePoint Provider Hosted APP.

To use <a> href Attribute tag as Navigation Link use below code.

We can extract QueryString and append it with new page’s url. Script to get Query String and other URL Related Information is as below:

 <script type="text/javascript">
 /*Get Server Name and Port Website Port Number e.g. http://localhost:1193*/
 var ServerandPort = window.location.host;
 /*Get Actual Page URL. e.g./ViewEmployees.aspx */
 var PageURL = window.location.pathname;
 /*Get Url's Query string e.g. ?SPHostUrl=http%3A%2F%2Fsqlserver%3A3333 ......*/
 var QueryString = window.location.search;
 </script>

To use <a> tag as navigation link:

 <a href="AddEmployee.aspx" onclick="location.href=this.href+QueryString;return false;">Add Employee</a>

CRUD Operation SharePoint Provider Hosted App

In my last post I have created SharePoint Provider Hosted APP . You may refer it from here.

In this post I will give more idea regarding CRUD Operation with SharePoint Provider Hosted APP.

I have added bootstrap style and html to improve default look and feel of APP.

Here asset folder contains required CSS and jQuery Files.

To perform CRUD Operation, I have added 2 more forms. AddEmployee.aspx and ViewEmployee.aspx.

To add new Form, Right Click on Pages -> Add -> New Item

It will Open Add New Item Wizard

Select Web Form and click on ADD. This will create AddEmployee.aspx form.Repeat same procedure to create ViewEmployee.aspx page.

Now App contains below pages. After applying jQuery and CSS it looks like as shown in below images.

Default Page

AddEmployee.aspx

ViewEmployees.aspx

To perform CRUD Operation, Create One list named “Employee” on Developer Site.

My Site and List Detail are as below

Site : http://sqlserver:3333/Lists/Employee/AllItems.aspx

List Name: Employee

When User Submit AddEmployee.aspx page it will add an item into Employee List.

Code for Submit Button Event or INSERT list item is as below


private void SaveEmployee()
{
try
{
var spContext = SharePointContextProvider.Current.GetSharePointContext(Context);

using (var context = spContext.CreateUserClientContextForSPHost())
{
Web web = context.Web;

List list = web.Lists.GetByTitle("Employee");

ListItemCreationInformation itemCreateInfo = new ListItemCreationInformation();

Microsoft.SharePoint.Client.ListItem newItem = list.AddItem(itemCreateInfo);
newItem["Name"] = txtEmployeeName.Text.ToString();
newItem["Designation"] = txtDesignation.Text.ToString();
newItem["Department"] = ddlDepatment.SelectedItem.Text.ToString();
newItem["Address"] = txtAddress.Text.ToString();
newItem["ContactNo"] = txtContactNo.Text.ToString();
newItem["Email"] = txtEmail.Text.ToString();
DateTime dob = DateTime.Parse(txtDOB.Text.ToString());
newItem["DOB"] = dob;

newItem.Update();

context.ExecuteQuery();

lblMessage.Text = "Employee Information Added Sucessfully.";
lblMessage.ForeColor = System.Drawing.Color.Green;
lblMessage.Font.Bold = true;

}
}
catch (Exception ex)
{
lblMessage.Text = ex.ToString();
}
}

Once Item is added into List it will appear on View Employee Page.

Code to display Employees on ViewEmployee Page


private void BindEmployee()
{
var spContext = SharePointContextProvider.Current.GetSharePointContext(Context);

using (var context = spContext.CreateUserClientContextForSPHost())
{
Web web = context.Web;

List list = web.Lists.GetByTitle("Employee");

CamlQuery caml = new CamlQuery();
Microsoft.SharePoint.Client.ListItemCollection items = list.GetItems(caml);

context.Load<List>(list);
context.Load<Microsoft.SharePoint.Client.ListItemCollection>(items);

context.ExecuteQuery();

DataTable table = new DataTable();
table.Columns.Add("Id");
table.Columns.Add("Name");
table.Columns.Add("Designation");
table.Columns.Add("Department");
table.Columns.Add("Address");
table.Columns.Add("ContactNo");
table.Columns.Add("Email");
table.Columns.Add("DOB");

foreach (Microsoft.SharePoint.Client.ListItem item in items)
{
DateTime now = Convert.ToDateTime(item["DOB"].ToString());

string date = now.ToLocalTime().ToShortDateString();

table.Rows.Add(item["ID"], item["Name"], item["Designation"], item["Department"], item["Address"], item["ContactNo"], item["Email"], date);

}

rptContractType.DataSource = table;
rptContractType.DataBind();

}

}

I have added few items in list and it will available as below.

To Edit an Item user can click on Edit button and update record. Code for Update Button and UPDATE list item is as below.


private void UpdateEmployee()
{
try
{
var spContext = SharePointContextProvider.Current.GetSharePointContext(Context);

string strEmpID = Request.QueryString["empID"].ToString();

using (var context = spContext.CreateUserClientContextForSPHost())
{
Web web = context.Web;

List oList = web.Lists.GetByTitle("Employee");

Microsoft.SharePoint.Client.ListItem oListItem = oList.GetItemById(strEmpID);

context.Load(oListItem);
context.ExecuteQuery();

oListItem["Title"] = "1";
oListItem["Name"] = txtEmployeeName.Text.ToString();
oListItem["Designation"] = txtDesignation.Text.ToString();
oListItem["Department"] = ddlDepatment.SelectedItem.Text.ToString();
oListItem["Address"] = txtAddress.Text.ToString();
oListItem["ContactNo"] = txtContactNo.Text.ToString();
oListItem["Email"] = txtEmail.Text.ToString();
DateTime dob = DateTime.Parse(txtDOB.Text.ToString());
oListItem["DOB"] = dob;

oListItem.Update();

context.ExecuteQuery();

lblMessage.Text = "Employee Information Updated Sucessfully.";
lblMessage.ForeColor = System.Drawing.Color.Green;
lblMessage.Font.Bold = true;

}

}
catch (Exception ex)
{
lblMessage.Text = "An Error occured while updating Employee Information." + ex.ToString();
throw ex;
}
}

To Delete record user can click on Delete button, it will ask him for Delete confirmation. If user confirms then item will be deleted.

Delete Confirmation :

Code to Delete event or DELETE list item is as below.


private void DeleteEmployee(int id)
{
try
{
var spContext = SharePointContextProvider.Current.GetSharePointContext(Context);

using (var context = spContext.CreateUserClientContextForSPHost())
{

Web web = context.Web;

List oList = web.Lists.GetByTitle("Employee");

Microsoft.SharePoint.Client.ListItem oListItem = oList.GetItemById(id);

oListItem.DeleteObject();

context.ExecuteQuery();

}
}
catch (Exception ex)
{
lblMessage.Text = ex.ToString();
}
}

How to create SharePoint Provider Hosted APP/Add-ins

In this post we are going to create SharePoint Provider Hosted Add-in.

Provider Hosted Apps are simply a SharePoint app where the code in your app runs in a space you provide. I am going to use ASP.Net Web Forms application as APP.

Steps to create Provider Hosted APP:

  1. Create Developer Site Collection
  2. Create and Export Certificate
  3. Set up trusted security token
    1. Create Issuer ID
    2. Create Client ID
  4. Create SharePoint Provider Hosted APP
  5. CRUD Operation Using SharePoint Provide Hosted APP

Create Developer Site Collection

Navigate to SharePoint Central Administration and Create a Site collection with template Developer Site.

Once site is created, it will appear as per below image:

Create and Export Certificate

Now Next step is to establish trust. A trust is necessary due to the fact that the provider-hosted app is hosted outside SharePoint in a separate web application.

Primary requirement to establish Trust is having a Certificate. I have already created separate post regarding create and export process of Certificate you may check here.

Set up trusted security token

To establish Trust, first thing, we need to do is to get ISSUER ID.

Create GUID using Visual Studio which needs to be added in PowerShell Script.

GUID: e9fe114f-3406-400d-bd22-50f077a8f17f

Note that GUID must be in Lowercase.

Create Folder on location: “C:\output” which is going to store output file of PowerShell Scrip

Create Issuer ID

Open SharePoint Management Shell and Run Issuer ID Script

PowerShell Script for Issuer ID:


Add-PSSnapin "Microsoft.SharePoint.PowerShell"

$issuerID = "e9fe114f-3406-400d-bd22-50f077a8f17f"

$targetSiteUrl = "http://sqlserver:3333"

$targetSite = Get-SPSite $targetSiteUrl

$realm = Get-SPAuthenticationRealm -ServiceContext $targetSite

$registeredIssuerName = $issuerID + '@' + $realm

$publicCertificatePath = "C:\Certificate\NileshSPDemoCertificate.cer"

$publicCertificate = Get-PfxCertificate $publicCertificatePath

Write-Host "Create Security token issuer"

$secureTokenIssuer = New-SPTrustedSecurityTokenIssuer -Name $issuerID -RegisteredIssuerName $registeredIssuerName -Certificate $publicCertificate -IsTrustBroker

$secureTokenIssuer | select *

$secureTokenIssuer | select * | Out-File -FilePath "c:\output\SecureTokenIssuer.txt"

#Turn off the HTTPS requirement for OAuth during development

$serviceConfig = Get-SPSecurityTokenServiceConfig

$serviceConfig.AllowOAuthOverHttp = $true

$serviceConfig.Update()

Write-Host "All done..."

Create Client ID

Now Next Step is to Create Client ID by mapping into APP Principal

PowerShell Script for Client ID: fee415ed-6977-4c3c-b5d0-a06682719fb7


Add-PSSnapin "Microsoft.SharePoint.PowerShell"

# set intialization values for new app principal

$appDisplayName = "EMployeeManagement"

$clientID = "fee415ed-6977-4c3c-b5d0-a06682719fb7"

$targetSiteUrl = "http://sqlserver:3333"

$targetSite = Get-SPSite $targetSiteUrl

$realm = Get-SPAuthenticationRealm -ServiceContext $targetSite

$fullAppPrincipalIdentifier = $clientID + '@' + $realm

Write-Host "Registering new app principal"

$registeredAppPrincipal = Register-SPAppPrincipal -NameIdentifier $fullAppPrincipalIdentifier -Site $targetSite.RootWeb -DisplayName $AppDisplayName

$registeredAppPrincipal | select * | Format-List

$registeredAppPrincipal | select * | Format-List | Out-File -FilePath "c:\output\ClientID.txt"

Write-Host "Registration Completed"

#Get-SpAppPrincipal -?

Remember or note down Client ID as we need to enter in Application Configuration.

Once Issuer ID and Cline ID Created and configured to use Certificate next step is to create Provider Hosted APP.

Create SharePoint Provider Hosted APP

Open Visual Sudio and create a project of type SharePoint Add-in

Click OK

Select Developer Site and Select Provider-Hosted Add-in Type

Click Next

Select Target Version I am using SharePoint 2016. You may choose as per your environment.

Click Next

Select Project Type : Asp.Net Web Forms Application. Click Next.

Here you need to select Certificate which was exported and having PFX key.

Make sure that you enter correct password for certificate and Issuer Id (GUID which was generated and associated with certificate.). Click Finish.

It will create SharePoint Hosted APP as shown above image.

I have added single line in Default Page

AppManifest.xml file of APP is as below.

With AppManifest.xml We can change App Icon and Start Page.

I have changed APP Icon. Make Sure that Icon size is  96 x 96 pixels.

Click on AppManifest.xml and Navigate to View Code

You may find below code in AppManifest.xml

AppManifest.xml contains user rights permission on app to be run or executed. Also it contains client id.

To add user permission  navigate to AppManifest.xml ==>Permissions Tab. Give appropriate rights as per requirement .

Add Client ID in RemoteWebApplication tag.

Complete AppManifest.xml will look below image.

Code For AppManifest.xml:

<?xml version="1.0" encoding="utf-8" ?>
<!--Created:cb85b80c-f585-40ff-8bfc-12ff4d0e34a9-->
<App xmlns="http://schemas.microsoft.com/sharepoint/2012/app/manifest"
 Name="EmployeeManagementAPP"
 ProductID="{47f6010d-e511-42d7-8210-49ca99f1bfd7}"
 Version="1.0.0.0"
 SharePointMinVersion="16.0.0.0"
>
 <Properties>
 <Title>EmployeeManagementAPP</Title>
 <StartPage>~remoteAppUrl/Pages/Default.aspx?{StandardTokens}</StartPage>
 </Properties>

 <AppPrincipal>
 <RemoteWebApplication ClientId="fee415ed-6977-4c3c-b5d0-a06682719fb7" />
 </AppPrincipal>
 <AppPermissionRequests>
 <AppPermissionRequest Scope="http://sharepoint/content/sitecollection/web" Right="FullControl" />
 <AppPermissionRequest Scope="http://sharepoint/taxonomy" Right="Write" />
 <AppPermissionRequest Scope="http://sharepoint/content/sitecollection" Right="FullControl" />
 </AppPermissionRequests>
</App>

Now Navigate to EmployeeManagementAPPWeb’s Web.config file section

Add below code in appSettings section


<appSettings>
<add key="webpages:Version" value="3.0.0.0" />
<add key="webpages:Enabled" value="false" />
<add key="ClientValidationEnabled" value="true" />
<add key="UnobtrusiveJavaScriptEnabled" value="true" />
<add key="ClientId" value="fee415ed-6977-4c3c-b5d0-a06682719fb7" />
<add key="ClientSigningCertificatePath" value="C:\Certificate\Export\NileshSPDemoCertificateExported.pfx" />
<add key="ClientSigningCertificatePassword" value="admin@123" />
<add key="IssuerId" value="e9fe114f-3406-400d-bd22-50f077a8f17f" />
</appSettings>

Also add location section


<location path="FederationMetadata">
<system.web>
<authorization>
<allow users="*" />
</authorization>
</system.web>
</location>

Web.config File Location Section

Web.Config File


<?xml version="1.0" encoding="utf-8"?>
<!--
For more information on how to configure your ASP.NET application, please visit
http://go.microsoft.com/fwlink/?LinkId=169433
-->
<configuration>
<location path="FederationMetadata">
<system.web>
<authorization>
<allow users="*" />
</authorization>
</system.web>
</location>
<system.web>
<compilation debug="true" targetFramework="4.5"/>
<httpRuntime targetFramework="4.5"/>
<authorization>
<deny users="?" />
</authorization>
</system.web>
<system.codedom>
<compilers>
<compiler language="c#;cs;csharp" extension=".cs"
type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
warningLevel="4" compilerOptions="/langversion:6 /nowarn:1659;1699;1701"/>
<compiler language="vb;vbs;visualbasic;vbscript" extension=".vb"
type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.VBCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
warningLevel="4" compilerOptions="/langversion:14 /nowarn:41008 /define:_MYTYPE=\&quot;Web\&quot; /optionInfer+"/>
</compilers>
</system.codedom>
<appSettings>
<add key="webpages:Version" value="3.0.0.0" />
<add key="webpages:Enabled" value="false" />
<add key="ClientValidationEnabled" value="true" />
<add key="UnobtrusiveJavaScriptEnabled" value="true" />
<add key="ClientId" value="fee415ed-6977-4c3c-b5d0-a06682719fb7" />
<add key="ClientSigningCertificatePath" value="C:\Certificate\Export\NileshSPDemoCertificateExported.pfx" />
<add key="ClientSigningCertificatePassword" value="admin@123" />
<add key="IssuerId" value="e9fe114f-3406-400d-bd22-50f077a8f17f" />
</appSettings>
<system.serviceModel>
<bindings>
<basicHttpBinding>
<!--Used by SharePoint Add-in-->
<binding name="secureBinding">
<security mode="Transport" />
</binding>
</basicHttpBinding>
</bindings>
<protocolMapping>
<add binding="basicHttpBinding" scheme="https" bindingConfiguration="secureBinding" />
</protocolMapping>
</system.serviceModel>
</configuration>

Now Navigate to EmployeeManagementAPPWeb’s Project’s Property -> Web Section

Click On Create Virtual Directory button

It will create Virtual Directory.

Navigate to EmployeeManagementAPPWeb’s Property

Set properties as shown in above image.

Now everything looks great and we are able to deploy application.

Click on Start it will deploy application.

After app deployment you will see below App Permission Page

Click on Trust It and it will open an APP as show below

CRUD Operation Using SharePoint Provide Hosted APP