Tuesday 16 October 2012

SharePoint 2010: Long Polling Technique Using JQuery and Wcf Rest Services Example

In the world of web 2.0 we need to make our application (in our case SharePoint) more collaborative, interactive and responsive.



In the world of web 2.0 we need to make our application (in our case SharePoint) more collaborative, interactive and responsive. That’s why I created a nice example that uses the Long Polling pattern to get us the real-time web applications experience like Gmail or Facebook has.
In our example we'll create a simple Like button that updates our custom list number filed and increases it every time we click our button. Below we'll create a label div that shows in real-time the number of likes. (At the end of my post you can download the sample project)

Here are the steps:

1) Create an empty SharePoint project.
2) Add our SharePoint a wcf service.
We have two choices, to create a mapped folder to ISAPI folder in hive 14 and add svc service or you can use my preferred way and just download CKS development extension for VS 2010 that takes care the annoying part of adding the wcf files for us.
After you downloaded the CKS extension you need to add to our SharePoint project wcf service(CKSDev), call it WCFLikeService
2012-10-09-LongPolling-01.png
As described in MSDN you have three configuration choices:
2012-10-09-LongPolling-02.png
We’ll choose REST Service and change the factory in our svc file to MultipleBaseAddressWebServiceHostFactory
2012-10-09-LongPolling-03.png
In our IWCFLikeService.cs file add the following lines:

1[OperationContract]
2       [WebInvoke(Method = "GET", ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Bare, UriTemplate = "/getLikes")]
3       string GetLikes();
4 
5       [OperationContract]
6       [WebInvoke(Method = "POST", ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Bare, UriTemplate = "/addLikes")]
7       bool AddLikes();

In our WCFLikeService.svc.cs file add the following lines:

01public string GetLikes()
02      {
03          SPList list = SPContext.Current.Web.Lists.TryGetList("likeList");
04          if (list == null)
05              return string.Empty;
06          SPListItem item = list.Items[0];
07          return item["likes"].ToString();
08      }
09 
10      public bool AddLikes()
11      {
12          try
13          {
14              SPWeb web = SPContext.Current.Web;
15              web.AllowUnsafeUpdates = true;
16              SPList list = web.Lists.TryGetList("likeList");
17              if (list == null)
18                  return false;
19              SPListItem item = list.Items[0];
20              int likeNum = int.Parse(item["likes"].ToString());
21              likeNum++;
22              item["likes"] = likeNum;
23              item.Update();
24              web.AllowUnsafeUpdates = false;
25              return true;
26          }
27          catch
28          {
29              return false;
30          }
31      }

3) Add script folder to a mapped Layouts folder and add jquey js and create a new js file called likeHelper
2012-10-09-LongPolling-04.png
4) Create a LikeWebPart
Register the two js files.

01protected override void OnInit(EventArgs e)
02       {
03           ClientScriptManager csm = Page.ClientScript;
04           if (!csm.IsClientScriptIncludeRegistered("jQuery-min"))
05           {
06               // register the extenal javascript file.
07               csm.RegisterClientScriptInclude(this.GetType(),
08 "jQuery-min", "/_layouts/SharePointProject/Scripts/jquery-1.7.2.min.js");
09           }
10 
11           if (!csm.IsClientScriptIncludeRegistered("likejs"))
12           {
13               // register the extenal javascript file.
14               csm.RegisterClientScriptInclude(this.GetType(), "likejs",
15 "/_layouts/SharePointProject/Scripts/likeHelper.js");
16           }
17       }

In on render method add div with ‘likeBtn’ id and another div with ‘like’ id

01protected override void Render(HtmlTextWriter writer)
02        {
03             
04            writer.Write("<div id=\"likeBtn\" style=\"width: 50px; hight: 20px;
05background-color: blue; color: white; margin-top: 5px; font-size: 12px; font-family:
06arial;\">LIKE</div>");
07            writer.Write("<br/>");
08            writer.Write("<div id='like' style='font-size:40px'></div>");
09       
10            
11        }

5) In our likeHelper.js we will add 3 main functions.
  1. document ready function

  2. 01var likeLabel;
    02$(document).ready(function () {
    03    likeLabel = $("#like");
    04     
    05    var likeBtn = $("#likeBtn");
    06    $(likeBtn).click(function () {
    07 
    08        updateLike();
    09    });
    10    waitForMsg(); /* Start the inital request */
    11});

  3. updateLike function that will update our number field in our list using wcf service and jquery POST request

  4. 1function updateLike() {
    2    
    3$.post("http://sp2010/_vti_bin/
    4SharePointProject/WCFLikeService.svc/addLikes");
    5 
    6}

  5. waitForMsg function that will use the Long Polling technique

  6. 01function waitForMsg() {
    02 
    03    (function poll() {
    04        $.ajax({ url: "http://sp2010/_vti_bin/
    05SharePointProject/WCFLikeService.svc/getLikes", success: function (data) {
    06            //Update like
    07            $(likeLabel).html(data);
    08 
    09        }, dataType: "json", complete: poll, timeout: 30000
    10        });
    11    })();
    12}

*Don’t forget to change the service host url.
*Create a custom list in your web called “likeList” and add a number field called “likes”.
Congratulations, you finished2012-10-09-LongPolling-05.png.
Every time you click on the like button you will see the number of likes increased.
2012-10-09-LongPolling-06.png





No comments:

Post a Comment