Navigate Up
Sign In
Supporters of Developer
Web

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

Item is currently unrated. Press SHIFT+ENTER to rate this item.1 star selected. Press SHIFT+ENTER to submit. Press TAB to increase rating. Press SHIFT+ESCAPE to leave rating submit mode.2 stars selected. Press SHIFT+ENTER to submit. Press TAB to increase rating. Press SHIFT+TAB to decrease rating. Press SHIFT+ESCAPE to leave rating submit mode.3 stars selected. Press SHIFT+ENTER to submit. Press TAB to increase rating. Press SHIFT+TAB to decrease rating. Press SHIFT+ESCAPE to leave rating submit mode.4 stars selected. Press SHIFT+ENTER to submit. Press TAB to increase rating. Press SHIFT+TAB to decrease rating. Press SHIFT+ESCAPE to leave rating submit mode.5 stars selected. Press SHIFT+ENTER to submit. Press SHIFT+TAB to decrease rating. Press SHIFT+ESCAPE to leave rating submit mode.

You may also be interested in: O'Reilly - SharePoint 2010 at Work

 

Editor's note: Contributor Alex Choroshin is a Sharepoint Team Leader at Bank Leumi. Follow him @choroshin

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:


[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();
              web.AllowUnsafeUpdates = false; 
              return true;
          }
          catch
          {
              return false;
          }
      }

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.


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");
           }
       }

In 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>");
      
           
        }

5) In our likeHelper.js we will add 3 main functions.

  1. document ready function

  2. var likeLabel;
    $(document).ready(function () {
        likeLabel = $("#like");
        
        var likeBtn = $("#likeBtn");
        $(likeBtn).click(function () {
    
            updateLike();
        });
        waitForMsg(); /* Start the inital request */
    });
    

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

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

  5. waitForMsg function that will use the Long Polling technique

  6. function waitForMsg() {
    
        (function poll() {
            $.ajax({ url: "http://sp2010/_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”.

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

Download the solution project.

That's all folks2012-10-09-LongPolling-05.png

Categories: C#; Javascript and jQuery; CSS; Web Part; dev; WCF; MOSS; WSS; 2010

Comments

Colin

Long Polling?

How is this long polling? It looks like just normal polling

Posted 14-Nov-2013 by Colin
manio

math

The supposition fortes especially designed providing clamor would be to fulfill the do my math homework finest criteria about educative providing. No cloth if you would homogeneous comment or composition fabric whiff turbine or it could be need definite rescue near your commonly college or university composition or dissertation, we've been extremely jocund to contemplates you aid feature!

Posted 09-Dec-2013 by manio
zyzkenny

Designer Handbags Replica

Many people may find this surprising, but the safest and most secure way to Designer Replica Handbags shop online is by credit card. This may sound counterintuitive, but there are Hermes Handbags several reasons why this is the case. Firstly, if a site turns out to be a Designer Handbags Replica scam, you can file a complaint with your credit card company and receive a full refund. Credit card is the only form of payment that Replica Handbags gives you this guarantee.

Posted 19-Mar-2014 by zyzkenny

Notify me of comments to this article

E-mail:
   

Add Comment

Title:

 
Comment:
Email:

   


Name:

 
Url: