How To Create A Hub Site in SharePoint Online

To Create Hub Site in SharePoint Online follow below steps

Crete SharePoint Site

I have created SharePoint Site URL: https://nrsharepoint.sharepoint.com/sites/Contoso

Now Open SharePoint Online Management Shell and run below commands


Connect-SPOService -Url "https://nrsharepoint-admin.sharepoint.com"    

Make Sure you need to pass admin site url in my case it is “nrsharepoint-admin” while connecting using SPOService

It will ask your Credentials for the site.

Once you are able to login add below powershell commnad to register your given site as Hub Site.


Register-SPOHubSite -Site "https://nrsharepoint.sharepoint.com/sites/Contoso"   

Once you run above command it will ask you Principals[0]: parameter value do not pass anything for that value.

After Successfully execution of commnad it will Convert or Connect Existing Site to Hub Site

Update Application Pool Password using PowerShell Script

By using below script we can update Passwod of Specific User for all his assigned Application Pool

PowerShell Script:


Import-Module WebAdministration
$applicationPools = Get-ChildItem IIS:\AppPools | where { $_.processModel.userName -eq "SPServer\administrator" }
 
foreach($pool in $applicationPools)
{
    $pool.processModel.userName = "SPServer\administrator"
    $pool.processModel.password = "sp#123@admin"
    $pool.processModel.identityType = 3
    $pool | Set-Item
}
 
Write-Host "Password Sucessfully Updated." -ForegroundColor Magenta 
Write-Host "" 

log4net With SharePoint 2016

Log4net library is a tool to help the programmer output log statements to a variety of output targets.

You may use below steps to configure Log4Net in SharePoint 2016 On Premise.

For this demonstration I have used my SharePoint Site: http://sps2012:1111/Pages/default.aspx

First Create SharePoint Solution

Next select Deploy as Farm Solution as we need to Deploy Log4Net DLL on our SharePoint Server GAC.

Here I am going to create 2 separate projects. 1 For Logging Application and 2 for SharePoint Web Parts where we can create our web parts. We can modify Logging Project as per our requirement without making any kind of changes in Web Parts Project.

Next let’s install Log4Net using NuGet Package Manager

Select Project -> Right Click on Project – >Select Manage NuGet Packages

Search Or Browse for log4net by Apache Software Foundation

Click on Install

When you click on Install it will preview changes which is going to be added in project

Click on Ok and it will install log4Net in Project

After Installation we are able to see Log4Net reference in project

Next Step is to build solution

Once we build solution we are able to see log4net.dll in Debug folder of solution.

Now we need to use this DLL: log4net.dll in SharePoint Web Part Project. So that we can create web part and check Logging Functionality.

Create WebPart in SP.WebParts Projects.

I have added WebPart and also updated its information as shown in Image

Now we need to refer Log4Net.dll in project

Navigate to Project -> References -> Right Click on Add Reference

It will open window. Click on Browse and select log4Net.dll file. Make sure you select correct file which we have added in SP.Log4Net.Solution Project. You can also copy log4Net.dll from bin folder and keep it on your desired location where you can assign reference to project.

Once you click on Ok it will add reference in Web Parts Project.

For Demonstration purpose I am going to add button on Visual Web Part and on its click event going to add Log Information so that we can create log using log4Net.dll file.

I have added button into web part and added Log Information. Now we are able to deploy this solution on SharePoint.

Also we need to keep in mind that Log4Net.Dll is also needs to deploy with Visual Web Part so that SharePoint Server can refer it in application.

To add custom dll reference in SharePoint Select Package and Open it.

Navigate to Advance

Click on Add Existing Assembly (As we already have log4Net.dll)

And select log4Net.dll from your project or saved directory location

Click on OK and this will add log4Net.dll in project’s package which eventually deploys dll in GAC.

Save Project and deploy it

Till now we have added log4Net.dll into project and its reference for logging mechanism. But we also needs to configure require information for Log4Net.

We can configure Log4Net configuration in SharePoint Web Application Web.Config and global.asax File.

As you are aware that we are using our SharePoint Application: : http://sps2012:1111/Pages/default.aspx

Next Navigate to C:\inetpub\wwwroot\wss\VirtualDirectories\1111 where we are able to find global.asax and web.config file.

Add Following code in global.asax


<%@ Assembly Name="Microsoft.SharePoint"%><%@ Application Language="C#" Inherits="Microsoft.SharePoint.ApplicationRuntime.SPHttpApplication" %>
<%@ Assembly Name="log4net, Version=2.0.8.0, Culture=neutral, PublicKeyToken=669e0ddf0bb1aa2a" %>
<%@ Import Namespace="log4net" %>
<%@ Import Namespace="log4net.Config" %>
<%@ Import Namespace="System.IO" %>

<script language="C#" runat="server">
void Application_Start(object sender, EventArgs e)
    {      
		log4net.Config.XmlConfigurator.Configure(new FileInfo("C:\\inetpub\\wwwroot\\wss\\VirtualDirectories\\1111\\web.config"));     
    }
</script>


Note: If you are getting an error while adding log4net dll information in Global.asax then it may be due to dll is not added in GAC.
You may read my post regarding How to Add DLL in GAC and How to Get DLL Publickeytoken

Now let’s updateWeb.Config File

Open Web.config file

And add below section in “<configSections>”


<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" requirePermission="false" />

Also Add below configuration in “<configuration>” section


<log4net>
    <appender name="RollingFileAppender" type="log4net.Appender.RollingFileAppender">
      <file value="C:\Program Files\Common Files\microsoft shared\Web Server Extensions\16\LOGS\log4net\Logs\ApplicationLog" />
      <appendToFile value="true" />
      <rollingStyle value="Composite" />
      <datePattern value=".yyyyMMdd-HHmm" />
      <lockingModel type="log4net.Appender.FileAppender+MinimalLock" />
      <layout type="log4net.Layout.PatternLayout">
        <conversionPattern value="%date [%thread] %-5level %logger - %message%newline" />
      </layout>
    </appender>
    <root>
      <level value="ERROR" />
      <appender-ref ref="RollingFileAppender" />
      <appender-ref ref="SmtpAppender" />
    </root>
  </log4net>

Note that you can change or update this log4Net configuration as per your own requirement.I have added Configuration value so that I can create log on each minute with dynamic file name added HHMM value.

Now we are done with all configurations and it’s time to test functionality.I have created Page named “CustomLog.aspx” and added web part Custom Log on it.

Now when we click button Add Log Information it will create log with string “Log Detail Information” on our mentioned location. Make sure here location is file Creation location which we have mentioned in web.config file for log4net configuration.

Once you click button you can see log as below

Also note that I have configured log mechanism as per each minute so that we can create or see log on each and every minute as shown in below image

From above steps we learn how we can configure log4Net with SharePoint 2016.

SharePoint Custom Form Language Translation with Multilingual Site

You may use below steps to achieve language translation for custom form which is used in SharePoint multilingual site.

Create List named as: Translations


Above list contains information of translation for different language. I have used language pack Hindi for
Language Code: 1081 for SharePoint Site.

Columns detail for Translation list:
Title: Label code text. You can compare text by Title column to assign value +
TextToDisplay : English Language Text
TextToDisplay2: Hindi Or Other Language Text

Assign Language Translation Value to form control as shown in below code

<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <script type="text/javascript" src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
    <link rel="stylesheet" href="https://static2.sharepointonline.com/files/fabric/office-ui-fabric-js/1.4.0/css/fabric.min.css">
    <link rel="stylesheet" href="https://static2.sharepointonline.com/files/fabric/office-ui-fabric-js/1.4.0/css/fabric.components.min.css">
    <script type="text/javascript" src="https://static2.sharepointonline.com/files/fabric/office-ui-fabric-js/1.4.0/js/fabric.min.js"></script>
    <title>Responsive Test</title>
</head>

<body>
    <script type="text/javascript">
        $(document).ready(function () {
            LaunchResponsivePage();
            if (_spPageContextInfo.currentLanguage == 1033) {
                alert("User Selected Language :English == Language Code" + _spPageContextInfo.currentLanguage);
            } else {
                alert("User Selected Language : Hindi == Language Code" + _spPageContextInfo.currentLanguage);
            }
            /********************************GEt Value from Translation List and Set Value to Controls Code Start ****************************************/
            var listName = "Translations";
            var url = _spPageContextInfo.webAbsoluteUrl;
            var condition = "$select=Title,TextToDisplay,TextToDisplay2'";
            getListItems(listName, url, condition, function (data) {
                var items = data.d.results;
                for (var i = 0; i < items.length; i++) {
                        
                    	if (_spPageContextInfo.currentLanguage == 1033) 
						{						
							if (items[i].Title == "Name")	{ $('#lname').html(items[i].TextToDisplay);}
							if (items[i].Title == "City")	{ $('#lcity').html(items[i].TextToDisplay);}			 
							if (items[i].Title == "Choose a programming language")	{ $('#lchooseprogram').html(items[i].TextToDisplay);}			 
							if (items[i].Title == "Send me promotional emails from Microsoft")	{ $('#lpromotional').html(items[i].TextToDisplay);}			 
							if (items[i].Title == "Male")	{ $('#lmale').html(items[i].TextToDisplay);}			 
							if (items[i].Title == "Female")	{ $('#lfemale').html(items[i].TextToDisplay);}			 
						}
						else 
						{					
							if (items[i].Title == "Name")	{ $('#lname').html(items[i].TextToDisplay2);}
							if (items[i].Title == "City")	{ $('#lcity').html(items[i].TextToDisplay2);}			 
							if (items[i].Title == "Choose a programming language")	{ $('#lchooseprogram').html(items[i].TextToDisplay2);}			 
							if (items[i].Title == "Send me promotional emails from Microsoft")	{ $('#lpromotional').html(items[i].TextToDisplay2);}			 
							if (items[i].Title == "Male")	{ $('#lmale').html(items[i].TextToDisplay2);}			 
							if (items[i].Title == "Female")	{ $('#lfemale').html(items[i].TextToDisplay2);}			 
						}			

                }
            }, function (data) {
                alert("Ooops, an error occured. Please try again");
            });
            /********************************GEt Value from Translation List and Set Value to Controls Code End ****************************************/
        });
    </script>
    <div id="ResponsiveTestDiv">
        <div class="ms-Grid">
            <div class="ms-Grid-row">
                <div class="ms-Grid-col ms-u-sm12">
                    <div class="ms-fontSize-xl"> SharePoint Language Translation Form </div>
                </div>
            </div>
            <div class="ms-Grid-row">
                <div class="ms-Grid-col ms-u-sm12">
                    <div class="ms-TextField">
                        <label id="lname" class="ms-Label is-required">Name</label>
                        <input id="txtName" class="ms-TextField-field is-required" type="text" value="" placeholder=""> </div>
                </div>
            </div>
            <div class="ms-Grid-row">
                <div class="ms-Grid-col ms-u-sm12">
                    <div class="ms-TextField">
                        <label id="lcity" class="ms-Label">City</label>
                        <input id="txtCity" class="ms-TextField-field" type="text" value="" placeholder=""> </div>
                </div>
            </div>
            <div class="ms-Grid-row">
                <div class="ms-Grid-col ms-u-sm12">
                    <div class="ms-Dropdown" tabindex="0">
                        <label class="ms-Label" id="lchooseprogram">Choose a programming language</label>
                        <i class="ms-Dropdown-caretDown ms-Icon ms-Icon--ChevronDown"></i>
                        <select id="dropdownProg" class="ms-Dropdown-select">
                            <option>Choose a programming language</option>
                            <option>Javascript</option>
                            <option>C#</option>
                            <option>F#</option>
                            <option>Python</option>
                            <option>Other</option>
                        </select>
                    </div>
                </div>
            </div>
            <div class="ms-ChoiceFieldGroup" id="choicefieldgroup" role="radiogroup">
                <div class="ms-ChoiceFieldGroup-title">
                    <label class="ms-Label is-required" id="lgender">Gender</label>
                </div>
                <ul class="ms-ChoiceFieldGroup-list">
                    <li class="ms-RadioButton">
                        <input tabindex="-1" type="radio" class="ms-RadioButton-input">
                        <label role="radio" class="ms-RadioButton-field" tabindex="0" aria-checked="false" name="choicefieldgroup">
                            <span class="ms-Label">Option 1</span>
                        </label>
                    </li>
                    <li class="ms-RadioButton">
                        <input tabindex="-1" type="radio" class="ms-RadioButton-input">
                        <label role="radio" class="ms-RadioButton-field" tabindex="0" aria-checked="false" name="choicefieldgroup">
                            <span class="ms-Label">Option 2</span>
                        </label>
                    </li>
                </ul>
            </div>
            <div class="ms-CheckBox">
                <input tabindex="-1" type="checkbox" class="ms-CheckBox-input">
                <label role="checkbox" class="ms-CheckBox-field" tabindex="0" name="checkboxa">
                    <span class="ms-Label" id="lpromotional">Send me promotional emails from Microsoft</span>
                </label>
            </div>
            <div class="ms-Grid-row">
                <div class="ms-Grid-col ms-u-sm6">
                    <button type="button" id="buttonSave" class="ms-Button ms-Button--primary">
                        <span class="ms-Button-label">Save</span>
                    </button>
                    <button id="buttonCancel" type="button" class="ms-Button">
                        <span class="ms-Button-label">Cancel</span>
                    </button>
                </div>
            </div>
        </div>
    </div>
</body>
<script>
    function LaunchResponsivePage() {
        MakeResponsive();
        InitializeComponents();
        AddEventHandlers();
    }
    // READ operation  
    // listName: The name of the list you want to get items from  
    // siteurl: The url of the site that the list is in.  
    // success: The function to execute if the call is sucesfull  
    // failure: The function to execute if the call fails  
    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);
            }
        });
    }
    function MakeResponsive() {
        $("#s4-ribbonrow").hide(); //hide the ribbon row
        $("#s4-workspace").children().hide(); //hide all elements in workspace
        var div = $("#ResponsiveTestDiv"); //move the div to make it visible
        $("#s4-workspace").append(div); //add the div after s4-workspace
    }

    function InitializeComponents() {
        var TextFieldElements = document.querySelectorAll(".ms-TextField");
        for (var i = 0; i < TextFieldElements.length; i++) {
            new fabric['TextField'](TextFieldElements[i]);
        }
        var ChoiceFieldGroupElements = document.querySelectorAll(".ms-ChoiceFieldGroup");
        for (var i = 0; i < ChoiceFieldGroupElements.length; i++) {
            new fabric['ChoiceFieldGroup'](ChoiceFieldGroupElements[i]);
        }
        var CheckBoxElements = document.querySelectorAll(".ms-CheckBox");
        for (var i = 0; i < CheckBoxElements.length; i++) {
            new fabric['CheckBox'](CheckBoxElements[i]);
        }
        var DropdownHTMLElements = document.querySelectorAll('.ms-Dropdown');
        for (var i = 0; i < DropdownHTMLElements.length; ++i) {
            var Dropdown = new fabric['Dropdown'](DropdownHTMLElements[i]);
        }
    }

    function AddEventHandlers() {
        $("#buttonSave").click(function () {
            var output = "Hello " + $("#txtName").val();
            alert(output);
            return false;
        });
        $("#buttonCancel").click(function () {
            alert("Cancelled");
            return false
        });
    }
</script>

</html>

Once we implement above code to form it will appear as below for Hindi and English language site.

Form in Hindi Language Site

Form in English Language Site

SharePoint Get GUID Of List and Columns

While developing SharePoint solution code we require GUID of List and Columns Id.We can easily get this using below format

Custom List:

Note that this list has 2 columns
1.Title
2.Target
To view GUID for this list Navigate to list settings.

Once we Navigate to List settings we are able to see below URL. Copy Full URL from browser

https://onsps.sharepoint.com/_layouts/15/listedit.aspx?List=%7B2CB2E87A-04CD-445A-9201-4F41FD8EF9A1%7D 

Replace the following characters as follows:
%7B to {
%2D to –
%7D to }

Once you replace above encoded character then list GUID will available which is {2CB2E87A-04CD-445A-9201-4F41FD8EF9A1}

To View all Columns and files inside this list change or append URL as below

https://onsps.sharepoint.com/_vti_bin/owssvr.dll?Cmd=ExportList&List=2CB2E87A-04CD-445A-9201-4F41FD8EF9A1

When we type above url it will open or download xml file which file has all information regarding list and its columns with GUID.

Here SourceID indicates GUID for List and ID indicates Column ID.

SharePoint 2010 List View Search as you type in Textbox

Title: SharePoint Content Query Search
We can search from existing list using textbox search using jQuery and List view.
Follow below steps to search in list using Textbox.
1.Add Textbox using Content Editor Web Part on Page.
2.Create List View which you want to appear on Page.

Once above things available on Page use below JavaScript Code which is responsible to search from list view using textbox.


<script language="javascript" type="text/javascript">

$(document).ready(function() {

    // SharePoint List View Table 
    var list = $("table.ms-listviewtable");
    // Table row of the items in list.
    var listItems = $("table.ms-listviewtable tr:not(.ms-viewheadertr)");
    // Our filter input.
    var input = $("input#filterInput");

    input.keyup(function() // On key presses
        {
            listItems.each(function() // for each items in list
                {
                    var text = $(this).text().toLowerCase(); 
                    console.log(text);
                    if (text.indexOf(input.val()) != -1) 
                    {
                        $(this).show(); 
                    } else {
                        $(this).hide(); 
                    }
                });
        });


});
</script>

After adding script, we are able to search from textbox’s key press event or as you type in textbox.

For this example, I have used Color List for demonstration and I am filtering list using color name.

Active Directory Setup For SharePoint Development Environment

To configure Active Directory Domain Service on Windows Server follow below steps:

Navigate to Server Manager

Click On Add roles and features.

It will start Add Roles and Features Wizard.

Click on Next

Select Installation Type as shown in Image

Click on Next

Select Option as shown in Image

Click on Next

Select Active Directory Domain Service

When you click on it, it will prompt you to add features for Active Directory Domain Service

Click on Add Features

Now Active Directory Domain Service is checked or selected.

Click on Next

On Features Tab Click on Next

On AD DS tab click on Next

On Confirm Installation selection section click on Install.

Next step will show us Installation Progress

Once the installation succeeds click on Close

After Successful installation, you can see in Dashboard Notification Message to promote this server for a domain controller.

Click on it.

It will Start “Active Directory Domain Service Configuration Wizard”

Click on Add New Forest. Enter Root Domain name

Clock on Next

Enter Password and Confirm Password

Click on Next

It will show DNS Options

Click on Next

Additional Options will check Domain Name

Click on Next

Select Path

Click on Next

Review Option.Review Entered information

Click on Next

Check Prerequisites.Click On Install.It will start installation process.

Once installation is complete restart server.

 

 

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.