SharePoint 2010: Long Polling technique using JQuery and WCF rest services example

June 15, 2012

Hi guys,

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 field and increases it every time we click our button. below we create a label div that shows in real-time the number of likes. (in 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 download the CKS extension you need to add to our SharePoint project a WCF service(CKSDev),call it WCFLikeService

image

As described in MSDN you have three configuration choices:

image

We’ll choose REST Service and change the factory in our svc file to MultipleBaseAddressWebServiceHostFactory

image

in our IWCFLikeService.cs file add the following lines:

[ServiceContract]

   public interface IWCFLikeService

   {

 

       [OperationContract]

       [WebInvoke(Method = "GET", ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Bare, UriTemplate = "/getLikes")]

       string GetLikes();

 

       [OperationContract]

       [WebInvoke(Method = "POST", ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Bare, UriTemplate = "/addLikes")]

       bool AddLikes();

   }

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

public string GetLikes()

       {

           SPList list = SPContext.Current.Web.Lists.TryGetList("likeList");

           if (list == null)

               return string.Empty;

           SPListItem item = list.Items[0];

           return item["likes"].ToString();

       }

 

       public bool AddLikes()

       {

           try

           {

               SPWeb web = SPContext.Current.Web;

               web.AllowUnsafeUpdates = true;

               SPList list = web.Lists.TryGetList("likeList");

               if (list == null)

                   return false;

               SPListItem item = list.Items[0];

               int likeNum = int.Parse(item["likes"].ToString());

               likeNum++;

               item["likes"] = likeNum;

               item.Update();

               return true;

           }

           catch

           {

               return false;

           }

       }

2) add script folder to a mapped Layouts folder , add JQuery  and create a new js file called likeHelper

image

2) Create a LikeWebPart

Register the two js files.

protected override void OnInit(EventArgs e)

       {

           ClientScriptManager csm = Page.ClientScript;

           if (!csm.IsClientScriptIncludeRegistered("jQuery-min"))

           {

               // register the extenal javascript file.

               csm.RegisterClientScriptInclude(this.GetType(), "jQuery-min", "/_layouts/SharePointProject/Scripts/jquery-1.7.2.min.js");

           }

 

           if (!csm.IsClientScriptIncludeRegistered("likejs"))

           {

               // register the extenal javascript file.

               csm.RegisterClientScriptInclude(this.GetType(), "likejs", "/_layouts/SharePointProject/Scripts/likeHelper.js");

           }

       }

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

protected override void Render(HtmlTextWriter writer)

        {

            

            writer.Write("<div id=\"likeBtn\" style=\"width: 50px; hight: 20px; background-color: blue; color: white; margin-top: 5px; font-size: 12px; font-family: arial;\">LIKE</div>");

            writer.Write("<br/>");

            writer.Write("<div id='like' style='font-size:40px'></div>");

      

           

        }

3) in our likeHelper.js we will add 3 main functions.

a)document ready function

var likeLabel;

$(document).ready(function () {

    likeLabel = $("#like");

    

    var likeBtn = $("#likeBtn");

    $(likeBtn).click(function () {

 

        updateLike();

    });

    waitForMsg(); /* Start the inital request */

});


 
b) updateLike function that will update our number field in our list using WCF service and jquery POST request

function updateLike() {

   

    $.post("http://sharon-7-lap/sites/test/_vti_bin/SharePointProject/WCFLikeService.svc/addLikes");

 

}

c) waitForMsg function that will use the Long Polling technique

function waitForMsg() {

 

    (function poll() {

        $.ajax({ url: "http://sharon-7-lap/sites/test/_vti_bin/SharePointProject/WCFLikeService.svc/getLikes", success: function (data) {

            //Update like

            $(likeLabel).html(data);

 

        }, dataType: "json", complete: poll, timeout: 30000

        });

    })();

}

 

*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”.

Every time you click on the like button you will see the number of likes increased. 

image

 

Download the solution project.

that’s all folks Smile

Add comment
facebook linkedin twitter email

Leave a Reply

Your email address will not be published.

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

*

4 comments

  1. Tal WinterJuly 25, 2012 ב 22:42

    אין אין, תמיד היית תותח 🙂

    Reply
  2. KienNovember 6, 2012 ב 10:49

    How to passing parameter to WCF Service?

    Reply
  3. choroshinNovember 8, 2012 ב 10:15

    Hi Kien,
    Since it’s a wcf rest service, you need to pass the parameter in the url.
    Here’s a good reference:
    http://msdn.microsoft.com/en-us/magazine/dd315413.aspx

    Best,
    Alex.

    Reply
  4. ShaneMarch 8, 2018 ב 5:47

    For long poll to work though, wouldn’t the GetLikes service method need hold off on sending a response until something new happened? In which case the thread would probably need to be tied up in a loop that polls the database for an amount of time e.g. every second for 30 seconds max?
    Currently, GetLikes responds immediately?

    Reply