Friday, 12 May 2017

5 Steps to achieve Lazy Loading in SharePoint

Hello SharePointers!  
Through this blog, I will walk you through a JS library implemented by me which helps us to load SharePoint list items on demand with no trouble. All you need to do is include LazyLoading.JS file in your java script code and call its methods.
Without any delay, I will go straight to the implementation.
Problem Statement
Load 10 ( it may vary as per requirement ) list items from a SharePoint list initially and then on vertical scroll down load another 10 and so on until there are not items left in the SharePoint list.
Solution
1.        Include LazyLoading.JS in your code
2.        Initialize LazyLoading objects
3.        Call LazyLoading.Functions.loadItems() method
4.        Define onLazyLoadSuccess() and onLazyLoadFail() methods
5.        Pagination Logic
1.Include LazyLoading.JS in your code
You can download the LazyLoading.JS from my GitHubrepository. Include the JS file:
<script src="../LazyLoading.js"></script>
2.Initialize LazyLoading Objects
Initialize subsequent objects which are self-describing:
   //Initialization
LazyLoading.ListName = "MyList";
LazyLoading.PageIndex = 1;
LazyLoading.PageSize = 30;
LazyLoading.ResultCounter = 0;
LazyLoading.SiteUrl = _spPageContextInfo.siteAbsoluteUrl;
LazyLoading.ViewPortHeight = $(window).height();
LazyLoading.Context = SP.ClientContext.get_current();
LazyLoading.Web = LazyLoading.Context.get_web();
LazyLoading.List = LazyLoading.Context.get_web().get_lists().getByTitle(LazyLoading.ListName);

Initialize CAML Query as well by applying filter and page size. 
LazyLoading.CamlQuery = new SP.CamlQuery();
LazyLoading.CamlQuery.set_viewXml("<View><ViewFields><FieldRef Name='Title'/><FieldRef Name='Details'/></ViewFields>"+"<RowLimit>"+LazyLoading.PageSize+"</RowLimit></View>");


3.Call loadItems() methood
Make a call to loadItems()

//Loads Initial bunch of items with specified page size
LazyLoading.Functions.loadItems();
This method will load the list items with depending upon the PageSize and PageIndex value specified in step 2.                                                
4.Define onLazyLoadSuccess() and OnLazyLoadFail() methods
onLazyLoadSuccess( ) and onLazyLoadFail( ) are the callback function for loadItems( ) method. So, we need to generate the html and bind the values returned by loadItems( ).
// This function returns list items w.r.t. specified page value
function onLazyLoadSuccess() {
 
LazyLoading.ListEnumerator = LazyLoading.SpItems.getEnumerator();
while(LazyLoading.ListEnumerator.moveNext()) {
generateDynamicHTMLCode();
}
if( LazyLoading.ResultCounter < LazyLoading.PageSize)
{
$("#loadingImg").hide();
}
LazyLoading.Functions.managePagerControl();
}
//Error callback
function onLazyLoadFail(error) {
console.log(error);
}
//Generates dynamic HTML for each List Item
function generateDynamicHTMLCode()
{
var htmlCode = "";
LazyLoading.Item = LazyLoading.ListEnumerator.get_current();
LazyLoading.ResultCounter++;
//ID
var itemId = LazyLoading.Item.get_item('ID');
//Title
var titleValue = LazyLoading.Item.get_item('Title');
//Details
var detailsValue = LazyLoading.Item.get_item('Details');
//Generate HTML
htmlCode = htmlCode + "<div>";
htmlCode = htmlCode +"<p>"+titleValue+"</p>";
htmlCode = htmlCode +"<p>"+detailsValue+"</p>";
htmlCode = htmlCode + "</div>";
$('#ItemsGrid').append(htmlCode);
}
5.Pagination logic
To load the next bunch of data, we need call getNextPage( ) function which loads the data with updated Page Index value.
$("#s4-workspace").scroll(function() {
       getNextPage();
});
//Gets next bunch of data    
function getNextPage()
{
if($("#loadingImg").offset().top < LazyLoading.ViewPortHeight)
{
 LazyLoading.PageIndex = LazyLoading.PageIndex + 1;
if (LazyLoading.NextPagingInfo) {
LazyLoading.Position = new SP.ListItemCollectionPosition();
LazyLoading.Position.set_pagingInfo(LazyLoading.NextPagingInfo);
}
else {
LazyLoading.Position = null;
}
if(LazyLoading.Position != null)
{
LazyLoading.Functions.loadItems();
}
else
{
$("#loadingImg").hide();
}
}
}


This is how we ca use LazyLoading.JS to accomplish loading of list items on demand. You can find the source code here.
Happy learning ! 😎

Monday, 2 May 2016

Node JS with SharePoint


What is Node JS and why?

Node JS is a java script based web development platform, where we can develop and host Web applications and Web Services. 

Let’s assume a scenario where we need to access SharePoint resources (list/library data) on mobile app or some other web application. The first thing comes to our mind is a web service.  Now we have two options to implement a web service:
1. WCF RESTful Service in C# and
2. NODE JS Web API.
The reasons to choose Node JS web service over WCF service are:
1. Open source
2. Lightning Fast Speed
3. JavaScript based
4. Comparatively faster than WCF
5. Easy to Unit Test

Prerequisites

  1. Node JS – Download and Install latest version of Node JS from here. 
  2.  Custom packages from GitHub – Download and install node packages as and when required. The cmdlets to install packages are explained in “Install Node packages” section. 
  3.  Visual studio/any other IDE

Supports only Basic or NTLM Authentication of SharePoint

To communicate with SharePoint, we are going to use a node package HTTPNTLM. It supports only NTLM authentication mode of SharePoint. If your SharePoint site supports claims based authentication, we may achieve it using a node package called request. ButI amnot going to explain it here.

Install Node Packages

Node packages can be installed using node console which will be available after installation of Node JS. Below are the packages that we need to install.

httpntlm

httpntlm package is used to communicate with SharePoint REST APIs. We just need to pass the credentials
$ npm install httpntlm --save

express

Express is a Node JS’s web application framework that provides a robust set of features for mobile and web applications
$ npm install express –save

cors

cors package allows a Web API to accept cross domain requests.
$ npm install cors –save

xml2js

Used to convert xml data into JSON format
$ npm install xml2js –save

deasync

Used to make synchronous calls to java script functions
$ npm install deasync –save

What is Express App

Express is a most popular web application framework in Node JS just like MVC in .NET.  If you are using Visual Studio, download a project template for Node JS form here. Create a new project of type ‘Basic Node.Js Express 4 Application’.



Replace the code in app.js with below code snippet.
If you are not using Visual Studio, create a JS file namedapp.js and put the below code snippet:

“use strict”
var express =require('express');
var app =express();
varroutes =require('./Routes')(app); //to be added in next step
app.listen(4444); // app.listen(<Port no>)

module.exports = app;

Routes

Routes are the application endpoints which redirects to specific web service depending upon the Request type (GET/POST) and URI.  Create a folder named Routes and add a file named index.js. Put below code: 

“use strict”
module.exports= function(app) {
varservices= require ('../Services');
varcors = require ('cors');
app.use(cors());
  //Services Routes 
app.get('/_api/getAllEmployees',cors(),Services.getAllItems);    
// app.post ('/_api/addEmployee',cors(),Services.addItem);  
}
Observe the above code snippet and find the routes.
Routes: '/_api/getAllEmployees' and /_api/addEmployee

Services

Now it’s time to access SharePoint resources using REST API. Let’s expand the above codeadd definition for Services.getAllItems. Add a new folder named Services and add a JS file named index.js and put below code in it:


“use strict”
var httpntlm = require('httpntlm');
var parseString = require('xml2js').parseString;
var deasync = require('deasync');
var siteURL = "http://<SiteCollectionName>", domainName = "<domain name>";
 
//1.Get All Employee Service 
exports.getAllItems = function (req, res) {
var httpResponse = { "statusCode": 500, result: undefined };
var url = siteURL + "/_api/web/lists/getByTitle('<ListName>')/items";
var headers = { "Accept": "application/json;odata=verbose", 
                "content-type": "application/json;odata=verbose;"
         };
httpntlm.get({
                url: url,
                contentType: 'application/json;odata=verbose',
                username: '<MyUsername>',
                password: '<MyPassword>',
                domain: '<DomainName>',
                workstation: '',
                headers:headers},
         function success(error, response) {
                 httpResponse.result = JSON.parse(response.body);                     
                 res.send(httpResponse);
            })//End of get
};//End of getAllItems
I am not writing the Code for post method here, that will allow you to get some hands-on experience on node JS.  :)

Run The Web API

You can run the web api using a cmdlet node as
$ node app.js
To test if it’s functioning or not, put the URL in browser and check the response:

 
http://<ServerName>:4444/_api/getAllEmployees

Summary

Node JS is a web hosting platform for Web sites and Web Services. Follow the steps as mentioned in this post and access the required SharePoint resources.
Any questions, comments and suggestions are most welcome! Have a great day ahead!

5 Steps to achieve Lazy Loading in SharePoint

Hello SharePointers!   Through this blog, I will walk you through a JS library implemented by me which helps us to load SharePoint list it...