Quick Launch and Top Navigation link programmatically – SharePoint Add In

We can add or remove Quick Launch and Top Navigation link programmatically using SharePoint JavaScript Object Model (JSOM), in this below sample I have added both links for this I have used web.get_navigation().get_topNavigationBar() and web.get_navigation().get_quickLaunch(). You can find the full source code download link in this page,

Source code download link

174https://code.msdn.microsoft.com/Quick-Launch-and-Top-0dbcba8b

get_topNavigationBar

Solution compatibility
This sample is tested with SharePoint Online
This sample also compatible with SharePoint 2013 and SharePoint 2016

To create new project
Open visual studio 2015
On the file menu select New -> Project (Ctrl + Shift + N)
In the New Project window select or search “App for SharePoint”
In the “New App for SharePoint” wizard choose options based on your preferences

Add new “Client Web Part (Host Web)” and select “Create a new app web page for the client web part content”, Edit newly created aspx page which is located in the Pages folder.

Code Flow
I have added four buttons for add and remove both Quick Launch and Top Navigation links, buttons call respective function for do operation. in the page load I got the web object and utilized in button events

After Add or Remove links we have refresh the page for see the changes, in below i have shared both HTML and JavaScript. you can also download complete project.

'use strict';

var context;
var web;
context = SP.ClientContext.get_current();
var hostweburl;
var appweburl;
var appContextSite;

// This code runs when the DOM is ready and creates a context object which is needed to use the SharePoint object model
$(document).ready(function () {
getUrl();
});

// This function get the URL informations
function getUrl() {
hostweburl = getQueryStringParameter("SPHostUrl");
appweburl = getQueryStringParameter("SPAppWebUrl");
hostweburl = decodeURIComponent(hostweburl);
appweburl = decodeURIComponent(appweburl).toString().replace("#", "");
var scriptbase = hostweburl + "/_layouts/15/";
$.getScript(scriptbase + "SP.RequestExecutor.js", execOperation);
}

// This function get list data from SharePoint
function execOperation() {
var factory = new SP.ProxyWebRequestExecutorFactory(appweburl);
context.set_webRequestExecutorFactory(factory);
appContextSite = new SP.AppContextSite(context, hostweburl);
web = appContextSite.get_web();
context.load(web);
context.executeQueryAsync(onGetWebSuccess, onFail);
}

// This function is executed if the above call is successful
function onGetWebSuccess() {
console.log('Hello ' + web.get_title());
}

// This function is executed if the above call fails
function onFail(sender, args) {
console.log('Failed. Error:' + args.get_message());
}

//for adding new link to Quick Launch
function AddQuickLaunchLink() {
var ql = web.get_navigation().get_quickLaunch();
var nnci = new SP.NavigationNodeCreationInformation();
nnci.set_title('My Custom Link');
nnci.set_url('/_layouts/settings.aspx');
nnci.set_asLastNode(true);
ql.add(nnci);
context.load(ql);
context.executeQueryAsync(
function () {
$('#lblmessage').append("QuickLaunch link added successfully...");
}, onFail);
}

//adding new link to Top Navigation
function AddTopNavicationLink() {
var TopNav = web.get_navigation().get_topNavigationBar();
var nnci = new SP.NavigationNodeCreationInformation();
nnci.set_title('My Custom Link');
nnci.set_url('/_layouts/settings.aspx');
nnci.set_asLastNode(true);
TopNav.add(nnci);
context.load(TopNav);
context.executeQueryAsync(
function () {
$('#lblmessage').append("Top Navigation link added successfully...");
console.log("TopNav Added");
}, onFail);
}

//Removing new link to Quick Launch
function RemoreQuickLaunchLink() {
var ql = web.get_navigation().get_quickLaunch();
context.load(ql);
context.executeQueryAsync(
function () {
var e = ql.getEnumerator();
var notFound = true;
while (notFound && e.moveNext()) {
var node = e.get_current();
if (node.get_title() === "My Custom Link") {
node.deleteObject();
notFound = false;
}
}
context.executeQueryAsync(
function () {
$('#lblmessage').append("QuickLaunch link removed successfully...");
console.log("QuickLaunch link removed");
},
onFail);

},
onFail);
}

//removing new link to Top Navigation
function RemoveTopNavicationLink() {
var tn = web.get_navigation().get_topNavigationBar();
context.load(tn);
context.executeQueryAsync(
function () {
var e = tn.getEnumerator();
var notFound = true;
while (notFound && e.moveNext()) {
var node = e.get_current();
if (node.get_title() === "My Custom Link") {
node.deleteObject();
notFound = false;
}
}
context.executeQueryAsync(
function () {
$('#lblmessage').append("Top Navigation link removed successfully...");
console.log("TopNav link removed");
},
onFail);

},
onFail);
}



//This function split the url and trim the App and Host web URLs
function getQueryStringParameter(paramToRetrieve) {
var params =
document.URL.split("?")[1].split("&");
for (var i = 0; i < params.length; i = i + 1) {
var singleParam = params[i].split("=");
if (singleParam[0] == paramToRetrieve)
return singleParam[1];
}
}
<%@ Page Language="C#" Inherits="Microsoft.SharePoint.WebPartPages.WebPartPage, 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" %>
<%@ 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" %>

<WebPartPages:AllowFraming ID="AllowFraming" runat="server" />

<html>
<head>
<title></title>
<script type="text/javascript" src="../Scripts/jquery-1.9.1.min.js"></script>
 <script type="text/javascript" src="/_layouts/1033/init.js"></script>
<script type="text/javascript" src="/_layouts/15/MicrosoftAjax.js"></script>
 <script type="text/javascript" src="/_layouts/15/sp.runtime.js"></script>
<script type="text/javascript" src="/_layouts/15/sp.js"></script>
 <script type="text/javascript" src="../Scripts/App.js"></script>
	<link href="../Content/bootstrap.min.css" rel="stylesheet" />
<script type="text/javascript">
 // Set the style of the client web part page to be consistent with the host web.
 (function () {
 'use strict';

 var hostUrl = '';
 if (document.URL.indexOf('?') != -1) {
 var params = document.URL.split('?')[1].split('&');
 for (var i = 0; i < params.length; i++) {
 var p = decodeURIComponent(params[i]);
 if (/^SPHostUrl=/i.test(p)) {
 hostUrl = p.split('=')[1];
 document.write('	<link rel="stylesheet" href="' + hostUrl + '/_layouts/15/defaultcss.ashx" />');
 break;
 }
 }
 }
 if (hostUrl == '') {
 document.write('	<link rel="stylesheet" href="/_layouts/15/1033/styles/themable/corev15.css" />');
 }
 })();
 </script>
</head>
<body>
<style>
input {
margin: 10px;
}
</style>
<div style="width: 450px">
<input type="button" id="btnQLAdd" onclick="AddQuickLaunchLink()" value="Add Link to QuickLaunch" />
<input type="button" id="btnQLRemove" onclick="RemoreQuickLaunchLink()" value="Remove Link from QuickLaunch" />
<input type="button" id="btnTopAdd" onclick="AddTopNavicationLink()" value="Add Top Navication Link" />
<input type="button" id="btnTopRemove" onclick="RemoveTopNavicationLink()" value="Remove Top Navication Link" />
</div>
<p id="lblmessage" style="color: green"></p>

</body>
</html>

Please let me know if you have any queries regarding this sample in comments

Souce Code Download link

174https://code.msdn.microsoft.com/Quick-Launch-and-Top-0dbcba8b

 

SharePoint List to JQuery Chart SharePoint Add In

JQuery Chart is easy to implement as a SharePoint Add In, in this sample I have retrieved SharePoint list data and formed it as JSON data and then JSON data object is passed into JQuey chart as input parameter. we can implement various type of chart using JQuery chart for as example bar, circle, line, doughnut, etc,… Here I’m going to explain detail about this SharePoint Add-In implementation.

You can download complete source code from the below URL

174https://code.msdn.microsoft.com/SharePoint-List-to-JQuery-90bfd45f

JQuery Chart SharePoint List

To create new project

Open visual studio 2015

On the file menu select New -> Project (Ctrl + Shift + N)

In the New Project window select or search “App for SharePoint”

In the “New App for SharePoint” wizard choose options based on your preferences

To add new resource file (.js or .css or Images) into project

Select a folder from solution explorer based on your file type (Images or Scripts or Content for CSS)

Right click and select “Open Folder in File Explorer” option

Now paste your files into the folder

Again in the solution explorer window at the top, click “Show All Files” icon

Now you can find the file without active icon, right click and select “Include in Project” Option

Solution compatibility

This sample is tested with SharePoint Online

This sample also compatible with SharePoint 2013 and SharePoint 2016

Code Flow

Fetching Host web URL and App web URL from query string

Host web content created using app web proxy

Retrieved list data from the host web

on the success event, list item collection converted as JSON data using JSON.parse

then the JSON data sent to chart js as parameter

//'use strict';

ExecuteOrDelayUntilScriptLoaded(initializePage, "sp.js");

function initializePage() {
var context = SP.ClientContext.get_current();
var user = context.get_web().get_currentUser();
var hostweburl;
var appweburl;
var appContextSite;
var list;
var listItems;
var web;


// This code runs when the DOM is ready and creates a context object which is needed to use the SharePoint object model
$(document).ready(function () {
getUrl();
});

// This function get the URL informations
function getUrl() {
hostweburl = getQueryStringParameter("SPHostUrl");
appweburl = getQueryStringParameter("SPAppWebUrl");
hostweburl = decodeURIComponent(hostweburl);
appweburl = decodeURIComponent(appweburl).toString().replace("#", "");
var scriptbase = hostweburl + "/_layouts/15/";
$.getScript(scriptbase + "SP.RequestExecutor.js", execOperation);
}

// This function get list data from SharePoint
function execOperation() {
var factory = new SP.ProxyWebRequestExecutorFactory(appweburl);
context.set_webRequestExecutorFactory(factory);
appContextSite = new SP.AppContextSite(context, hostweburl);
web = appContextSite.get_web();
context.load(web);
var camlQuery = new SP.CamlQuery();
list = web.get_lists().getByTitle("Post Reach");
listItems = list.getItems(camlQuery);
context.load(list);
context.load(listItems);
context.executeQueryAsync(onGetSPListSuccess, onGetSPListFail);
}


// This function is executed if the above call is successful
function onGetSPListSuccess() {
$("#DivSPGrid").empty();
var chartlabel = '';
var chartdata1 = '';
var chartdata2 = '';
var barChartData = '';
var listEnumerator = listItems.getEnumerator();
chartlabel = "{\"labels\":[";
chartdata1 = "],\"datasets\":[{" +
"\"fillColor\":\"rgba(220,220,220,0.5)\"," +
"\"strokeColor\":\"rgba(220,220,220,0.8)\"," +
"\"highlightFill\":\"rgba(220,220,220,0.75)\"," +
"\"highlightStroke\":\"rgba(220,220,220,1)\"," +
"\"data\":[";
chartdata2 = "]},{" +
"\"fillColor\":\"rgba(151,187,205,0.5)\"," +
"\"strokeColor\":\"rgba(151,187,205,0.8)\"," +
"\"highlightFill\":\"rgba(151,187,205,0.75)\"," +
"\"highlightStroke\":\"rgba(151,187,205,1)\"," +
"\"data\":[";
while (listEnumerator.moveNext()) {
var listItem = listEnumerator.get_current();
chartlabel += "\"" + listItem.get_item("Title") + "\",";
chartdata1 += listItem.get_item("Facebook") + ",";
chartdata2 += listItem.get_item("Twitter") + ",";
}
chartlabel = chartlabel.replace(/,\s*$/, "");
chartdata1 = chartdata1.replace(/,\s*$/, "");
chartdata2 = chartdata2.replace(/,\s*$/, "");
var str = chartlabel + chartdata1 + chartdata2 + ']}]}';
barChartData = JSON.parse(str);
var ctx = document.getElementById("chartCanvas").getContext("2d");
window.myBar = new Chart(ctx).Bar(barChartData, { responsive: true });
}

// This function is executed if the above call fails
function onGetSPListFail(sender, args) {
alert('Failed to get list data. Error:' + args.get_message());
}

//This function split the url and trim the App and Host web URLs
function getQueryStringParameter(paramToRetrieve) {
var params =
document.URL.split("?")[1].split("&");
for (var i = 0; i < params.length; i = i + 1) {
var singleParam = params[i].split("=");
if (singleParam[0] == paramToRetrieve)
return singleParam[1];
}
}
}
<%-- 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" />

 <!-- Add your JavaScript to the following file -->
 <script type="text/javascript" src="../Scripts/App.js"></script>
<script type="text/javascript" src="../Scripts/Chart.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">
SPListItemCollection to JQuery Chart SharePoint Add In
</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 style="width: 50%">
<canvas id="chartCanvas" height="300" width="450"></canvas>
</div>
</asp:Content>

You can download complete source code from the below URL

174https://code.msdn.microsoft.com/SharePoint-List-to-JQuery-90bfd45f

Hope you find this article helpful, check out my other articles too.
Like my Facebook page to get future articles notification
Let me know your Queries and feedback in comments

Export SharePoint List to Excel, Word, JSON, XML, SQL, CSV, TXT or PDF

Using JQuery we can export SharePoint list to Excel, Word, JSON, XML, SQL, CSV, TXT or PDF. Here I’m going to explain step by step explanation to implement this same in your environment. This will work for SharePoint 2013, 2016 and SharePoint online.

You can download complete source code from the below URL

zip_iconhttps://code.msdn.microsoft.com/Export-SharePoint-List-to-a802fd93

2016-02-17_23-46-38

Create “App for SharePoint” project in visual studio, in the new project creation wizard is select options based on your requirement. After project created rename your SharePoint App page, which is located under Pages folder, here I renamed as JQueryExport.aspx

Double click AppManifest.xml file and select SharePoint list view permission, because here we are just going read data from a SharePoint list, I’ve selected “Documents” list. List name and column name are hard coded  in the App.js file,


'use strict';

ExecuteOrDelayUntilScriptLoaded(initializePage, "sp.js");

function initializePage() {
var context = SP.ClientContext.get_current();
var user = context.get_web().get_currentUser();
var hostweburl;
var appweburl;
var appContextSite;
var list;
var listItems;
var web;
// This code runs when the DOM is ready and creates a context object which is needed to use the SharePoint object model
$(document).ready(function () {
getUrl();
});

// This function get the URL informations
function getUrl() {
hostweburl = getQueryStringParameter("SPHostUrl");
appweburl = getQueryStringParameter("SPAppWebUrl");
hostweburl = decodeURIComponent(hostweburl);
appweburl = decodeURIComponent(appweburl).toString().replace("#","");
var scriptbase = hostweburl + "/_layouts/15/";
$.getScript(scriptbase + "SP.RequestExecutor.js", execOperation);
}

// This function get list data from SharePoint
function execOperation() {
var factory = new SP.ProxyWebRequestExecutorFactory(appweburl);
context.set_webRequestExecutorFactory(factory);
appContextSite = new SP.AppContextSite(context, hostweburl);
web = appContextSite.get_web();
context.load(web);
var camlQuery = new SP.CamlQuery();
list = web.get_lists().getByTitle("Documents");
listItems = list.getItems(camlQuery);
context.load(list);
context.load(listItems);
context.executeQueryAsync(onGetSPListSuccess, onGetSPListFail);
}
// This function is executed if the above call is successful
function onGetSPListSuccess() {
$("#DivSPGrid").empty();
var listInfo = '';
var listEnumerator = listItems.getEnumerator();
listInfo += "
<table id='SPTable' class='display'>
<thead>
<tr>" +
"
<th>Id</th>
" +
"
<th>Title</th>
" +
"
<th>Colour</th>
" +
"
<th>Modified By</th>
" +
"
<th>Modified date</th>
" +
"</tr>
</thead>
<tbody>";
while (listEnumerator.moveNext()) {
var listItem = listEnumerator.get_current();
listInfo += '
<tr>
<td>' + listItem.get_item('ID') + '</td>
'
+ '
<td>' + listItem.get_item('FileLeafRef') + '</td>
'
+ '
<td>' + listItem.get_item('Colour') + '</td>
'
+ '
<td>' + listItem.get_item('Editor').get_lookupValue() + '</td>
'
+ '
<td>' + listItem.get_item('Modified').format('dd MMM yyyy, hh:ss') + '</td>
'
+ '</tr>
';
}
listInfo += '</tbody>
</table>
';
$("#DivSPGrid").html(listInfo);
$('#SPTable').dataTable();
}

// This function is executed if the above call fails
function onGetSPListFail(sender, args) {
alert('Failed to get list data. Error:' + args.get_message());
}

//This function split the url and trim the App and Host web URLs
function getQueryStringParameter(paramToRetrieve) {
var params =
document.URL.split("?")[1].split("&");
for (var i = 0; i < params.length; i = i + 1) {
var singleParam = params[i].split("=");
if (singleParam[0] == paramToRetrieve)
return singleParam[1];
}
}
}
<pre><!-- End --></pre>

Add CSS files into the ASPX


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

Add set of JS files as reference in your ASPX page


<!-- Add your JavaScript to the following file -->
 <!--our custom js file-->
 <script type="text/javascript" src="../Scripts/App.js"></script>

<script type="text/javascript" src="../Scripts/jquery-1.9.1.min.js"></script>
 <script type="text/javascript" src="../Scripts/bootstrap.min.js"></script>
 <!--For export PDF file-->
 <script type="text/javascript" src="../Scripts/jspdf/libs/base64.js"></script>
 <script type="text/javascript" src="../Scripts/jspdf/libs/sprintf.js"></script>
 <script type="text/javascript" src="../Scripts/jspdf/jspdf.js"></script>
 <!--For export PNG file-->
 <script type="text/javascript" src="../Scripts/html2canvas.js"></script>
 <!--For export all other formats-->
 <script type="text/javascript" src="../Scripts/tableExport.js"></script>
 <script type="text/javascript" src="../Scripts/jquery.base64.js"></script>
 <!--For HTML Table format-->
 <script type="text/javascript" src="../Scripts/jquery.dataTables.js"></script>

I have used bootstrap drop down for listing export options,

<div class="dropdown">
<button class="btn btn-warning btn-sm dropdown-toggle" data-toggle="dropdown"><i class="fa fa-bars"></i>Export Table Data</button>
<ul class="dropdown-menu " role="menu">
	<li><a href="#" onclick="$('#SPTable').tableExport({type:'json',escape:'false'});">
<img src="../Images/json.png" width='24px' />
JSON</a></li>
	<li><a href="#" onclick="$('#SPTable').tableExport({type:'json',escape:'false',ignoreColumn:'[0]'});">
<img src='../Images/json.png' width='24px' />
JSON (ignoreColumn)</a></li>
	<li><a href="#" onclick="$('#SPTable').tableExport({type:'json',escape:'true'});">
<img src='../Images/json.png' width='24px' />
JSON (with Escape)</a></li>
	<li class="divider"></li>
	<li><a href="#" onclick="$('#SPTable').tableExport({type:'xml',escape:'false'});">
<img src='../Images/xml.png' width='24px' />
XML</a></li>
	<li><a href="#" onclick="$('#SPTable').tableExport({type:'sql'});">
<img src='../Images/sql.png' width='24px' />
SQL</a></li>
	<li class="divider"></li>
	<li><a href="#" onclick="$('#SPTable').tableExport({type:'csv',escape:'false'});">
<img src='../Images/csv.png' width='24px' />
CSV</a></li>
	<li><a href="#" onclick="$('#SPTable').tableExport({type:'txt',escape:'false'});">
<img src='../Images/txt.png' width='24px' />
TXT</a></li>
	<li class="divider"></li>
	<li><a href="#" onclick="$('#SPTable').tableExport({type:'excel',escape:'false'});">
<img src='../Images/xls.png' width='24px' />
XLS</a></li>
	<li><a href="#" onclick="$('#SPTable').tableExport({type:'doc',escape:'false'});">
<img src='../Images/word.png' width='24px' />
Word</a></li>
	<li class="divider"></li>
	<li><a href="#" onclick="$('#SPTable').tableExport({type:'png',escape:'false'});">
<img src='../Images/png.png' width='24px' />
PNG</a></li>
	<li><a href="#" onclick="$('#SPTable').tableExport({type:'pdf',pdfFontSize:'7',escape:'false'});">
<img src='../Images/pdf.png' width='24px' />
PDF</a></li>
</ul>
</div>
<div id="DivSPGrid">
</div>
<script type="text/javascript">
 $(document).ready(function () {
 $('.dropdown-toggle').dropdown();
 });
 </script>

Let me know if you have any queries,

zip_iconhttps://code.msdn.microsoft.com/Export-SharePoint-List-to-a802fd93