Author: Ravichandran K

Weather Add-In for SharePoint

SharePoint weather Add-In can be added on the SharePoint home page (dashboard),  this add-in automatically fetch geolocation from the browser. And based on the location it will retrieve the Temperature, humidity and wind speed etc… you can see the step by step instructions to develop this SharePoint Add-In. Also, the complete project source code is available for download,

Souce Code Download link,

https://code.msdn.microsoft.com/Weather-Add-In-for-9635e488

Weather AddIn

Create new Project in the Visual Studio using “App for SharePoint” template, here I’m using visual studio 2015 version. In the new project wizard select SharePoint-Hosted and rest you can select based on your requirements. The provider-hosted application can also be selected.

I have used the Local-weather GitHub project to implement this Add-In, In the project, you can find the script in the ASPX file.

Add new “Client Web Part (Host Web)” and select “Create a new app web page for the client web part content” (If you want this add-in in the Home page then we have to use new ASPX file instead of default one because it uses SharePoint master page), Edit newly created an ASPX page which is located in the Pages folder and replace with HTML which you find in my project.

        $(document).ready(function () {
            // get location from user's IP address
            $.getJSON('https://ipinfo.io', function (info) {
                var locString = info.loc.split(', ');
                var latitude = parseFloat(locString[0]);
                var longitude = parseFloat(locString[1]);
                $('#location').html('Location: ' + info.city + ', ' + info.region + ', ' + info.country)

                // get weather using OpenWeatherMap API
                $.getJSON('https://cors.5apps.com/?uri=http://api.openweathermap.org/data/2.5/weather?lat=' + latitude + '&lon=' + longitude + '&units=metric&APPID=c3e00c8860695fd6096fe32896042eda', function (data) {
                    var windSpeedkmh = Math.round(data.wind.speed * 3.6);
                    var Celsius = Math.round(data.main.temp)
                    var iconId = data.weather[0].icon;
                    var weatherURL = "http://openweathermap.org/img/w/" +
                            iconId + ".png";

                    var iconImg = "<img src='" + weatherURL + "'>";
                    $('#sky-image').html(iconImg);
                    $('#weather-id').html('Skies: ' + data.weather[0].description);

                    $('#temperature').html(Celsius);
                    $('#toFahrenheit').click(function () {
                        $('#temperature').html(Math.round((9 / 5) * Celsius + 32));
                        $('#wind-speed').html(Math.round(windSpeedkmh * 0.621) + ' mph')
                    })
                    $('#toCelsius').click(function () {
                        $('#temperature').html(Celsius);
                        $('#wind-speed').html(windSpeedkmh + ' km/hr')
                    })

                    $('#wind-speed').html(windSpeedkmh + ' km/h');
                    $('#humidity').html('Humidity: ' + data.main.humidity + ' %');

                })
            })
        })
<div class="row">
<div class="col-6">
<div id="sky-image"></div>
<div id="location"></div>
<div id="weather-id"></div>
<div>Temperature: <span id="temperature"></span>&deg<a href="#" id="toCelsius">C</a> | &deg<a href="#" id="toFahrenheit">F</a></div>
<div>Wind speed: <span id="wind-speed"></span></div>
<div id="humidity"></div>
</div>
</div>

Please feel free to let me know if you have any queries in the comment section, I’m happy to help you!!

Souce Code Download link

https://code.msdn.microsoft.com/Weather-Add-In-for-9635e488

3D Tag cloud links from SharePoint List

3D Tag cloud Add-In can be used on the SharePoint home page to show important links with cool animation, links are retrieved from the Sharepoint list. so users can easily update or add links. In the below, you can see the step by step instructions to develop this SharePoint Add-In. Also, the complete project source code is available for download,

Souce Code Download link

https://code.msdn.microsoft.com/3D-Tag-cloud-links-from-b5fe9220

3D cloud Tag

Create new Project in the Visual Studio using “App for SharePoint” template, here I’m using visual studio 2015 version. In the new project wizard select SharePoint-Hosted and rest you can select based on your requirements. The provider-hosted application can also be selected.

I have used jquery.svg3dtagcloud.min.js to implement this add-in and link data retrieved from SharePoint Links list, So in the SharePoint select “Add a new app” option and filter link, you can find the app called “Links” select that app and you can name whatever you want, I have named as 3DTags, so we don’t have to change anything on this list just directly start to add links on that list.

Links App

Links List

Also, we have to configure the permission on the AppManifest to access the SharePoint list with edit permission.

Add new “Client Web Part (Host Web)” and select “Create a new app web page for the client web part content” (If you want this add-in in the Home page then we have to use new ASPX file instead of default one because it uses SharePoint master page), Edit newly created an ASPX page which is located in the Pages folder and replace with HTML which you find in my project. Add below JS code in the app.js file.


'use strict';

ExecuteOrDelayUntilScriptLoaded(initializePage, "sp.js");

function initializePage()
{
var context = SP.ClientContext.get_current();

// 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 () {
getlinks();
});
var linkItems;
// This function prepares, loads, and then executes a SharePoint query to get the current users information
function getlinks() {
var website = context.get_site().get_rootWeb();
var linklist = website.get_lists().getByTitle("3DTags");
var camlQuery = new SP.CamlQuery();
linkItems = linklist.getItems(camlQuery);
context.load(linkItems);
context.executeQueryAsync(onGetLinkSuccess, onGetLinkFail);
}

// This function is executed if the above call is successful
// It replaces the contents of the 'message' element with the user name
function onGetLinkSuccess() {
var entries = [];
var linkEnumerator = linkItems.getEnumerator();
while (linkEnumerator.moveNext()) {
var oListItem = linkEnumerator.get_current();
entries.push({ label: oListItem.get_item('URL').get_description(), url: oListItem.get_item('URL').get_url(), target: '_top' })
}
var settings = {
entries: entries,
width: 480,
height: 480,
//width: '100%',
//height: '100%',
radius: '65%',
radiusMin: 75,
bgDraw: true,
bgColor: '#fff',
opacityOver: 1.00,
opacityOut: 0.05,
opacitySpeed: 6,
fov: 800,
speed: 2,
fontFamily: 'Oswald, Arial, sans-serif',
fontSize: '15px',
fontColor: '#111',
fontWeight: 'normal',
fontStyle: 'normal',
fontStretch: 'normal',
fontToUpperCase: true
};
$('#holder').svg3DTagCloud(settings);
}

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

Please feel free to let me know if you have any queries in the comment section, I’m happy to help you!!

Souce Code Download link

174https://code.msdn.microsoft.com/3D-Tag-cloud-links-from-b5fe9220

Text to speech Add-In for SharePoint

Text to speech add-in can be used to speak text contents of the textarea in the SharePoint dashboard. Below you can see step by step instructions to develop this SharePoint Add-In. Also, the complete project source code is available for download,

Souce Code Download link

174https://code.msdn.microsoft.com/Text-to-speech-Add-In-for-af5abf7f

SharePoint Text to Speak

Create new Project in the Visual Studio using “App for SharePoint” template, here I’m using visual studio 2015 version. In the new project wizard select SharePoint-Hosted and rest you can select based on your requirements. The provider-hosted application can also be selected.

I have used articulate.js to implement this add-in, you can find this JavaScript file in the project which is modified by me for fix some issues and some changes, and this JS file implemented using SpeechSynthesis, The SpeechSynthesis interface of the Web Speech API is the controller interface for the speech service;

 

Add new “Client Web Part (Host Web)” and select “Create a new app web page for the client web part content” (If you want this add-in in the Home page then we have to use new ASPX file instead of default one because it uses SharePoint master page), Edit newly created an ASPX page which is located in the Pages folder. Add below JS code and HTML.

</div>
<div>

<%@ 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/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/articulate.js"></script>
<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>
<textarea id="texttospeck" style="height:200px;width:500px"></textarea>

<input type="button" id="btnSpeak" onclick="javascript: $('#texttospeck').articulate('speak');" value="Speak" />
<input type="button" id="btnPause" onclick="javascript: $('#texttospeck').articulate('pause');" value="Pause" />
<input type="button" id="btnResume" onclick="javascript: $('#texttospeck').articulate('resume');" value="Resume" />
<input type="button" id="btnStop" onclick="javascript: $('#texttospeck').articulate('stop');" value="Stop" />
</body>
</html>

</div>
<div>

Please feel free to let me know if you have any queries in the comment section, I’m happy to help you!!

Souce Code Download link

174https://code.msdn.microsoft.com/Text-to-speech-Add-In-for-af5abf7f

Creating Custom link in Site Setting and Site Action menu using JSOM

Here we are going to see how to add custom Site Action and Site Settings links in SharePoint Online, same code can be used for SharePoint 2013 and 2016. It’s very useful to provide our custom application navigation link in site action and custom application setting link Under site setting. This application provides easy user interaction.

cover 01

I have used custom page layout for developing this application and I used JSOM. If you are not familiar creating custom page layout, Check my previous post SharePoint custom page layout  .

In general, we have to use user custom action object to create link in site settings or site action menu. In that we have to pass the location and the group ID as a parameter, in the below table we can find out the all locations and group IDs for other possibilities.

list if group IDs

Sequence parameter will define top or bottom of the another link; Ex, 100 Sequence will place our link in the next to 99 Sequence link
Removing our custom link is very simple, we just have to loop all the custom links and filter the link based on link title, then we can remove the link object.

Adding custom link in site settings


var collUserCustomAction = web.get_userCustomActions();

var userCA = collUserCustomAction.add();
userCA.set_location('Microsoft.SharePoint.SiteSettings');
userCA.set_group("SiteAdministration");
userCA.set_sequence(100);
userCA.set_title('Custom SS Link');
userCA.set_url('http://www.google.com');
userCA.update();

clientContext.executeQueryAsync(function () {
console.clear();
console.log("Site settings link added");
}, OnFailure);

Adding custom link in site action menu


var collUserCustomAction = web.get_userCustomActions();

var userCA = collUserCustomAction.add();
userCA.set_location('Microsoft.SharePoint.StandardMenu');
userCA.set_group("SiteActions");
userCA.set_sequence(100);
userCA.set_description('Menu item added via ECMAScript');
userCA.set_title('Custom SA Link');
userCA.set_url('http://www.google.com');
userCA.update();

clientContext.executeQueryAsync(function () {
console.clear();
console.log("Site action link added");
}, OnFailure);

Removing custom link based on the link title


function removeCustomAction(title) {
var collUserCustomAction = web.get_userCustomActions();
clientContext.load(collUserCustomAction);
clientContext.executeQueryAsync(function () {
var item = collUserCustomAction.getEnumerator();
while (item.moveNext()) {
var currAction = item.get_current();
if (currAction.get_title() === title) {
currAction.deleteObject();
clientContext.load(currAction);
clientContext.executeQueryAsync(function () {
console.clear();
console.log(currAction.get_title() + " link removed");
}, OnFailure);
break;
}
}
}, OnFailure);
}

Please feel free to let me know if you have any queries in the comment section, I’m happy to help you!!

Happy coding!!

Create custom page layout in SharePoint Online

This post will explain about creating new page layout for SharePoint Online, same logic is  applicable for SharePoint 2013 and 2016.

Custom page layout can be used in SharePoint publishing site or Publishing feature enabled sites. Custom page layout can be used in SharePoint default master page or our custom master page,

SharePoint page layout sections

check my previous post about how to create custom master page for SharePoint
Navigate to SharePoint design manager and click Edit Page Layout link then click Create a page layout, in the popup enter new layout name and select master page and select existing SharePoint default content type or create new content type based on your requirement, you can find the create new content type link on the same popup.

SharePoint new page layout popup
Once the page layout is  created, open SharePoint Designer 2013 and open site on that. On the left side of SharePoint Designer select layout and you can find newly created layout files, there will be two files in same name one is HTML and another one is ASPX extension.
Check out the newly created page layout (HTML extension) and right click and select Edit File in Advanced Mode option.

SharePoint designer layouts

Once page layout opened then find out ContentPlaceHolder ID of “PlaceHolderMain”, clear all div elements inside the place holder and paste your page layout HTML or prepare your HTML inside.
If you created custom master page using HTML template conversion logic, then you have to cut center content(layout content) from master page and paste in this page layout.
Navigate to site home page and edit the page and select page tab, in that tab open page layout drop down and select our new layout.

And now your new page layout is ready..!!

Please feel free to let me know if you have any queries in the comment section, I’m happy to help you!!

Happy coding!!

Create custom master page for SharePoint Online

This post will explain about creating new master page for SharePoint Online, same logic is applicable for SharePoint 2013 and 2016.

There are various ways we can create custom master page for SharePoint, here I’m going to convert bootstrap HTML template to SharePoint mater page, hope you know that the bootstrap templates can change design based on the screen size, so these templates design are called responsive design.


You can download any HTML template from web; you will can zipped file then extract all files,

HTML Template files
Navigate to SharePoint admin center https://<tenant name>-admin.sharepoint.com

In the site collection tab click new and select Private or Public site collection

New Site Collection ButtonFill all the required details and select Publishing Portal template under Publishing tab

Create new publishing site
Once the site collection is created, open the site in the browser and SharePoint Designer 2013.
Once site is opened in the SharePoint Designer 2013, navigate to All files  _catalogs  masterpage

Master Page Directry
And copy and paste all the downloaded html template files like image, css, script folders and HTML file etc,.
Go back to the browser and click the gear button which is located on top right of the SharePoint page and select Design Manager.

Design Manager Link
On the design manager click edit master pages and click “Convert an HTML file to a SharePoint master page”

SharePoint Disign Manager Master page
On the dialog popup select you pasted HTML page and click Insert

now open SharePoint designer 2013 and find the newly created master page, you can find two files, in that edit the HTML extension and remove the center content(layout section contents) and find below highlighted code and cut and paste into the layout section.

layout section
Then publish the newly added master page in Design Manager or SharePoint design manager

Publishing Master Page
After publishing, go to the site settings and click master pages link under look on feel, select newly added master page in site master page drop down list and click OK to apply the new master page.

Select Master Page

And to finish it off  you will need to create a page layout and we are done!!

To create the page layout for the center content please click the below link and go ahead.

we have to create page layout for centre content which we removed from master page, check this URL for How to create SharePoint Page layout. 

Please feel free to let me know if you have any queries in the comments section,I’m happy to help you!!

Happy coding!!

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