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>
Advertisement

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

How to Create and Export Self-Signed Certificate

To create Self-Signed Certificate using IIS follow below steps.

Navigate to IIS

Select Server Certificate

Click on “Create Self-Signed Certificate” link

Enter the details as shown below.

Click on OK.

Do IISRESET

Now Certificate will be available in Server Certificates.

You can check by editing any existing binding

Save Certificate :

Double click on the Certificate in IIS.

Click on Details tab and click on Copy to File.

Now Certificate Export Wizard will available.

Click Next

Click Next Give Certificate Name.

Click Next

Click Finish

It will display message “The export was successful.”

Export Certificate in Personal Exchange Format (.pfx)

Navigate to IIS

Select the Certificate which you want to export.

Click on Export

Give Certificate Export Location and Certificate Name

Enter Password and Confirm Password.

Click on OK.

It will Export Certificate in PFX format.

 

SharePoint APP – Hide Show Ribbon Row and Site Logo using CSS and jQuery

To Hide Show SharePoint Ribbon and Site Logo follow below steps.

Default SharePoint APP Page

CSS to hide SharePoint Suite Bar, Ribbon and Site Logo (DeltaSiteLogo)


<style type="text/css">
/*Start - Hide SharePoint Suite Bar*/
#suiteBar {
display: none;
}
/*End- Hide SharePoint Suite Bar*/

/*Start - Hide SharePoint Ribbon*/
#s4-ribbonrow {
display: none;
}
/*End - Hide SharePoint Ribbon*/

/*Start - Hide SharePoint Logo*/
#DeltaSiteLogo {
display: none;
}
/*End - Hide SharePoint Logo*/
</style>

Result :

Once we hide Site Logo it keeps space of Div

I added JavaScript to completely remove it.


<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function () {
$("#siteIcon").remove();
});
</script>

Result :

 

To hide Breadcrumb and Title we can use below script


/*Start - Breadcrumb and Title*/
#s4-titlerow {
display: none !important;
}
/*End - Breadcrumb and Title*/

Or to remove it we can use below script


<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function () {
$("#s4-titlerow").remove();
});
</script>

Result:

SharePoint Hosted APP

Step by Step guide to develop and host SharePoint Hosted APP

Open Visual Studio

File -> New Project -> SharePoint Add-In

Select SharePoint Site Where you want to Host SharePoint APP
Select SharePoint Hosted in hosting location

Select “SharePoint 2016”

Click Finish

SharePoint APP Project is created as shown in an Image .

This Add-in inserts data into “Student” list. Lets look HTML of Page which is in  Default.aspx page.


<%-- The following 4 lines are ASP.NET directives needed when using SharePoint components --%>

<%@ Page Inherits="Microsoft.SharePoint.WebPartPages.WebPartPage, Microsoft.SharePoint, Version=15.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" MasterPageFile="~masterurl/default.master" Language="C#" %>

<%@ Register TagPrefix="Utilities" Namespace="Microsoft.SharePoint.Utilities" Assembly="Microsoft.SharePoint, Version=15.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
<%@ Register TagPrefix="WebPartPages" Namespace="Microsoft.SharePoint.WebPartPages" Assembly="Microsoft.SharePoint, Version=15.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
<%@ Register TagPrefix="SharePoint" Namespace="Microsoft.SharePoint.WebControls" Assembly="Microsoft.SharePoint, Version=15.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>

<%-- The markup and script in the following Content element will be placed in the <head> of the page --%>
<asp:Content ContentPlaceHolderID="PlaceHolderAdditionalPageHead" runat="server">
<script type="text/javascript" src="../Scripts/jquery-1.9.1.min.js"></script>
<SharePoint:ScriptLink name="sp.js" runat="server" OnDemand="true" LoadAfterUI="true" Localizable="false" />
<meta name="WebPartPageExpansion" content="full" />

<!-- Add your CSS styles to the following file -->
<link rel="Stylesheet" type="text/css" href="../Content/App.css" />
<link rel="Stylesheet" type="text/css" href="../Content/bootstrap.min.css" />

<!-- Add your JavaScript to the following file -->
<script type="text/javascript" src="../Scripts/App.js"></script>
<script type="text/javascript" src="../Scripts/Student.js"></script>
</asp:Content>

<%-- The markup in the following Content element will be placed in the TitleArea of the page --%>
<asp:Content ContentPlaceHolderID="PlaceHolderPageTitleInTitleArea" runat="server">
SharePoint Hosted APP - Student Info
</asp:Content>

<%-- The markup and script in the following Content element will be placed in the <body> of the page --%>
<asp:Content ContentPlaceHolderID="PlaceHolderMain" runat="server">

<div>
<p id="message" style="display:none">
<!-- The following content will be replaced with the user name when you run the app - see App.js -->
initializing...
</p>
</div>

<div class="container">
<h2>Add Student Information</h2>
<form>
<div class="form-group">
<label for="email">Name:</label>
<input type="name" class="form-control" id="name" placeholder="Enter Name">
</div>
<div class="form-group">
<label for="contactnumber">Contact Number:</label>
<input type="contactnumber" class="form-control" id="contactnumber" placeholder="Enter Contact Number">
</div>
<div class="form-group">
<label for="email">Email:</label>
<input type="email" class="form-control" id="email" placeholder="Enter Email">
</div>
<div class="form-group">
<label for="BirthDate">BirthDate:</label>
<input type="BirthDate" class="form-control" id="BirthDate" placeholder="Enter Contact Number">
</div>
<div class="form-group">
<label for="BirthDate">Gender:</label>
<input type="radio" name="gender" value="Male" />Male
<input type="radio" name="gender" value="Female" />Female
</div>
<input type="button" class="btn btn-default" value="Submit" id="btnCreate" />
</form>
</div>

</asp:Content>

JavaScript File for CRUD Operation of Student List named “Student.js”.


$(document).ready(function () {

$("#btnCreate").on('click', function () {
AddListItem();
});

//Add New Item In List and Return Result
function AddListItem() {

var listName = "Students";
var name = $('#name').val();
var number = $('#contactnumber').val();
var email = $('#email').val();
var dob = new Date().toISOString();
var gender = $('input[name="gender"]:checked').val();
var itemType = GetItemTypeForListName(listName);

var item = {
"__metadata": { "type": itemType },
'Name': name, 'ContactNumber': number, 'Email': email, 'Gender': gender, 'DOB': dob
};

jQuery.ajax({
url: _spPageContextInfo.siteAbsoluteUrl + "/_api/web/lists/getbytitle('" + listName + "')/items",
type: "POST",
data: JSON.stringify(item),
headers: {
"accept": "application/json;odata=verbose",
"content-type": "application/json;odata=verbose",
"X-RequestDigest": $("#__REQUESTDIGEST").val()
},
success: function (d) {
alert("Student Information Added Successfuly.");
},
error: function () { alert("An Error Occured while adding Student Information"); }
});

return false;
}

// Get List Item Type metadata
function GetItemTypeForListName(name) {
return "SP.Data." + name.charAt(0).toUpperCase() + name.split(" ").join("").slice(1) + "ListItem";
}
});

Please note that I have used bootstrap CSS file to enhance look and feel.

In Student.js file AddListItem() method is used  to create Item using REST service

After completion of Code deploy Add-In. It will appear in Site Contents and you can access it

While Adding record below error will raise

It indicates that user doesn’t have rights to insert item in website’s list.Which means we need to add access permission for user so that he can add item in list.

To give access to use click on AppManifest.xml. Go to Permissions Tab. Add Write rights as shown in Image.

Now Deploy Add-In.
While Accessing Add-In it will now ask for permission which user needs to allow to use Add-in.

Trust APP and perform Insert Operation.

Now it will add an item into list and also gives success method message.

Data in SharePoint List

 

 

ASP.Net JavaScript Print Div Content

To Print Div Content using JavaScript use below code

HTML Page

HTML Page Code


<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Print.aspx.cs" Inherits="Print" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">

<head>
<title>Javascript Print</title>
<!--BootStrap CSS Start-->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" type="text/css" />
<!--BootStrap CSS End-->
<!--JQuery Script Start-->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js" type="text/javascript"></script>
<!--JQuery Script End-->
<!--Bootstrap Script Start-->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" type="text/javascript"></script>
<!--Bootstrap Script End-->
<!--Print Div Script Start-->
<script type="text/javascript">
function PrintDiv() {
var disp_setting = "toolbar=yes,location=no,directories=yes,menubar=yes,";
disp_setting += "";
var content_vlue = document.getElementById("divContent").innerHTML;
var docprint = window.open("", "", disp_setting);
docprint.document.open();
docprint.document.write('<html><head><title>Print Page Name</title>');
docprint.document.write('</head><body onLoad="self.print()">');
docprint.document.write(content_vlue);
docprint.document.write('</body></html>');
docprint.document.close();
docprint.focus();
}
</script>
<!--Print Div Script End-->
</head>
<body>
<form id="form1" runat="server">
<div class="container" id="divContent">
<form class="form-inline">
<div class="form-group">
<h1>h1 Bootstrap heading (36px)</h1>
<h2>h2 Bootstrap heading (30px)</h2>
<h3>h3 Bootstrap heading (24px)</h3>
<h4>h4 Bootstrap heading (18px)</h4>
<h5>h5 Bootstrap heading (14px)</h5>
<h6>h6 Bootstrap heading (12px)</h6>
<table class="table">
<thead>
<tr>
<th>Firstname</th>
<th>Lastname</th>
<th>Email</th>
</tr>
</thead>
<tbody>
<tr>
<td>Default</td>
<td>Defaultson</td>
<td>def@somemail.com</td>
</tr>
<tr class="success">
<td>Success</td>
<td>Doe</td>
<td>john@example.com</td>
</tr>
<tr class="danger">
<td>Danger</td>
<td>Moe</td>
<td>mary@example.com</td>
</tr>
<tr class="info">
<td>Info</td>
<td>Dooley</td>
<td>july@example.com</td>
</tr>
<tr class="warning">
<td>Warning</td>
<td>Refs</td>
<td>bo@example.com</td>
</tr>
<tr class="active">
<td>Active</td>
<td>Activeson</td>
<td>act@example.com</td>
</tr>
</tbody>
</table>
</div>
</form>
</div>
<!--Print Button Start-->
<div class="form-group">
<label for="pwd">
<a href="#" class="btn btn-success btn-lg" onclick="PrintDiv()">
<span class="glyphicon glyphicon-print"></span>Print
</a>
</label>
</div>
<!--Print Button End-->
</form>
</body>
</html>

JavaScript function PrintDiv() will get content of divContent and will use its content to print.

Print Screen :

Scenario 1 : Simple Print Without Alignment

Scenario 2: Here I just Updated alignment of content and because of that print content comes in center of the page.

Print Output

 

 

 

ASP.Net Image Handler to retrieve Image from Database

While Creating and Saving Image in Database I was facing an issue of retrieving image from Database and then assign that  image into Gridview’s image control. To resolve this issue, I have implemented Image handler code.

I used below code to save image in database and then display it in Gridview using Http handler

Save Button Code (Save Image in Database)

 protected void btnSave_Click(object sender, EventArgs e)
    {
        try
        {
            
            Byte[] bytes = null;

            // Read the file and convert it to Byte Array
            string filePath = FileUpload1.PostedFile.FileName;
            string filename = Path.GetFileName(filePath);
            string ext = Path.GetExtension(filename);
            string contenttype = String.Empty;

            //Set the contenttype based on File Extension
            switch (ext)
            {                
                case ".jpg":
                    contenttype = "image/jpg";
                    break;
                case ".jpeg":
                    contenttype = "image/jpeg";
                    break;
                case ".png":
                    contenttype = "image/png";
                    break;
                case ".gif":
                    contenttype = "image/gif";
                    break;               
            }
            if (contenttype != String.Empty)
            {
                Stream fs = FileUpload1.PostedFile.InputStream;
                BinaryReader br = new BinaryReader(fs);
                bytes = br.ReadBytes((Int32)fs.Length);
            }
            else
            {
                lblMessage.ForeColor = System.Drawing.Color.Red;
                lblMessage.Text = "File format not recognised.Please Upload Valid File.";
            }

            //Database Connection 
            SqlConnection sqlserverconnection = new SqlConnection(strDBConnection);

            //SQL Database Connection Open
            sqlserverconnection.Open();

            string strQuery;

            strQuery = "sp_InsertEmployee";
			 
            SqlCommand command = new SqlCommand(strQuery, sqlserverconnection);

            command.CommandType = System.Data.CommandType.StoredProcedure;

            command.Parameters.AddWithValue("@EmployeeType", ddlEmployeeType.SelectedItem.Text.ToString());
            command.Parameters.AddWithValue("@FullName", txtFullName.Text.ToString());
            command.Parameters.AddWithValue("@Designation", txtDesignation.Text.ToString());
            command.Parameters.AddWithValue("@Department", ddlDepatment.SelectedItem.Value.ToString());
            command.Parameters.AddWithValue("@ContactNo", txtContactNo.Text.ToString());
            command.Parameters.AddWithValue("@Email", txtEmail.Text.ToString());
            string dob = String.Format("{0}", Request.Form["txtDOB"]);
            command.Parameters.AddWithValue("@DOB", dob);
            command.Parameters.AddWithValue("@Education", txtEducation.Text.ToString());
            command.Parameters.AddWithValue("@Address", txtAddress.Text.ToString());
            command.Parameters.AddWithValue("@ExpInYears", txtEXP.Text.ToString());
            command.Parameters.AddWithValue("@Username", txtUserName.Text.ToString());
            command.Parameters.AddWithValue("@Password", txtPassword.Text.ToString());
		    command.Parameters.AddWithValue("@Photo", bytes);

            command.ExecuteNonQuery();

            //SQL Connection Close
            sqlserverconnection.Close();

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

            ClearControl();

        }
        catch (Exception ex)
        {
            throw ex;
        }
    }

ViewEmployee Page is going to get all employee Detail and bind all information into Gridview.
Gridview contain Image tag which displays Employee Image.
GridView Image control Code:

<asp:Image ID="Image1" runat="server" ImageUrl='<%# "ImageHandler.ashx?id="+ Eval("EmployeeID") %>' Height="80px" Width="80px" />

Here ImageHandler.ashx is custom HTTP handler which is responsible to return employee Image as per EmployeeID
To add HTTP Handler right click project > Add New Item > Generic Handler > ImageHandler.ashx.
Code For ImageHandler.ashx

&lt;%@ WebHandler Language="C#" Class="ImageHandler" %&gt;

using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public class ImageHandler : IHttpHandler
{

    public void ProcessRequest(HttpContext ctx)
    {
        string id = ctx.Request.QueryString["id"];

        String strDBConnection = ConfigurationManager.AppSettings["DatabaseConnection"];

        SqlConnection sqlserverconnection = new SqlConnection(strDBConnection);
        SqlConnection con = new SqlConnection(strDBConnection);
        SqlCommand cmd = new SqlCommand("Select Photo From EmployeeMaster Where EmployeeID = @EmpID", con);
        cmd.CommandType = CommandType.Text;

        cmd.Parameters.AddWithValue("@EmpID", id);

        con.Open();
        byte[] pict = (byte[])cmd.ExecuteScalar();
        con.Close();

        ctx.Response.BinaryWrite(pict);
    }

    public bool IsReusable
    {
        get
        {
            return false;
        }
    }

}

 

 

SharePoint App Catalog

Several scenario developer or organization don’t want to publish their app on Office Store.

In this situation we can deploy our app to specific user or client or to use it in internal organization.

An app catalog site contains a special type of document library that is used to upload and store app package files. Along with storing the app package file, this document library also tracks various types of metadata for each app. Some of this metadata is required, whereas other metadata is optional.

You must have farm administrator permissions within an on-premises farm to create an app catalog site.

Steps to create App Catalog Site in SharePoint.

Navigate to Central Administration.

Click on Apps Link

It will redirect to the Apps Page.

Here you can see App Related Configuration.

Click on Manage App Catalog. It will redirect you the page where App Catalog Website needs to be created. Note that the app catalog site must be created as a top-level site within a new site collection

You must provide read access to End users if you want them to have the ability to discover apps and install them at site scope.

Once you provide all information App Catalog site is going to be created.

You will find that there is a document library with a title of Apps for SharePoint which is used to publish SharePoint apps. There is a second document library with a title of Apps for Office that is used to publish apps created for Office applications such as Word and Excel.

You publish a SharePoint app by uploading its app package to the Apps for SharePoint document library.

I found this useful information from site : https://www.microsoftpressstore.com/articles/article.aspx?p=2222447&seqNum=3

 

 

SharePoint APPS – Deployment Subscription Settings Service Configuration Issue

While deploying SharePoint APP I am getting an error
“The Subscription Settings service and corresponding application and proxy needs to be running in order to make changes to these settings.”

To resolve this issue App Management and a Subscription Settings Service Application and that needs to be created and started.

Why we need to create App Management Service?

Apps rely on the App Management and Microsoft SharePoint Foundation Subscription Settings service applications. These service applications use the multi-tenancy features to provide app permissions and create the sub domains for apps. Therefore, even if you are not hosting multiple tenants, you must still establish a name for the default tenant for your environment (any SharePoint site that is not associated with a tenant will be in the default tenant).

Powershell Script to configure Subscription Settings


Get-SPManagedAccount NRWEBS\nilesh
$appPool = New-SPServiceApplicationPool -Name SubscriptionServiceAppPool -Account $account
$serviceApp = New-SPSubscriptionSettingsServiceApplication -ApplicationPool $appPool -name “Subscription Settings Service Application” -DatabaseName “SP2013DEV-SubscriptionSettingsDB”
$serviceAppProxy = New-SPSubscriptionSettingsServiceApplicationProxy -ServiceApplication $serviceApp

Once Service is configured , Start services as shown in above image.

As both required service are started now we are able to deploy SharePoint APP.

But before that we also needs to Configure APP URLs.

To Configure APP URL

  • Go to Central Administration
  • Click on “Apps” in the left side navigation
  • Click “Configure App URLs”

  • Fill in the URL of the app domain that you configured.
  • Fill in an app prefix.

Once APP URL is configured we can deploy our APP without an error.