Pages

Saturday, December 31, 2011

Twitter mash-up with JavaScript + LinqToTwitter + WCF


Writing a simple web mash-up has never been easier than it is today.

Most popular sites, including Twitter, have an API provided for querying user data.  The creators of the LinqToTwitter project have written a LINQ query provider that will turn your LINQ expressions into Twitter API calls and deserialize the results into the various Twitter specific entities (Tweet, User, etc). This is essentially what any LINQ provider will do; Expression goes in, translation of the expression to the desired type (SQL, REST call, etc), data comes back as .NET objects--hiding the details of the underlying platform/language from the developer.



This tutorial will show you how to create a simple custom twitter client in 15 lines of C# using LinqToTwitter and WCF without having to do any JSON parsing on the front-end.  The JavaScript objects we need will be automatically generated by WCF.

We'll also make sure the application displays correctly on a Windows Phone.


WCF

Here's the entirety of our WCF service.


   1:  namespace Uppercutt
   2:  {
   3:      [ServiceContract(Namespace = "")]
   4:      public class UpperCut
   5:      {
   6:          [OperationContract]
   7:          public List<AtomEntry> GetTweets(string currentURL)
   8:          {
   9:              var interests = currentURL.Replace("?","").Split('&');
  10:   
  11:              if (interests.Count() == 1) return null;
  12:   
  13:              var twitterCtx = new TwitterContext();
  14:              var tweets = new List<AtomEntry>() ;
  15:   
  16:              foreach (var interest in interests)
  17:              {
  18:                 var twit = twitterCtx.Search
  19:                     .Where(x => x.Hashtag == interest 
  20:                          && x.Type == SearchType.Search)
  21:                     .FirstOrDefault()
  22:                     .Entries;
  23:   
  24:                 tweets = tweets.Union(twit).ToList();
  25:              }
  26:   
  27:              tweets.Shuffle();
  28:   
  29:              return tweets;
  30:          }
  31:      }
  32:  }

And that's it.  The "currentURL" parameter is just the querystring that has all of the hashtags you wish to see (Ex : http://localhost:7472/follow.htm?csharp&microsoft)

The query for retrieving the list of matching hashtags is very simple.  Query the "Search" TwitterQueryable which provides information from the twitter social graph and then retrieve all of the entries for that hashtag.

In my posted example, I actually took the LinqToTwitter project down from Codeplex and added it to my solution.  I recommend you use NuGet to add the LinqToTwitter library to your project, but it's up to you.  I would've definitely used NuGet to pull the assembly if I weren't creating this example.


If you look at lines 21 through 23, you can see that I have to evaluate the IQueryable for each search to actually get the entries, which means I have to hit the service multiple times.  This is most likely a restriction of the Twitter API.  I'm fairly sure there isn't a way to do it but if anyone can figure it out, post in a comment.

JavaScript


You can find your automatically generated JavaScript proxies by navigating to the service URL and adding /js to the end of your service.  You can include the JavaScript file with a snippet like this

/// <reference path="http://localhost:7472/UpperCut.svc/js"/>

You can enable intellisense for the service by bringing this file down locally and adding the following to the top of the JavaScript file you're working in (I'm using the Microsoft Content Delivery network for both jQuery and Microsoft Ajax)

/// <reference path="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.6.4.js"/>
/// <reference path="http://ajax.aspnetcdn.com/ajax/4.0/1/MicrosoftAjax.js"/>
/// <reference path="http://localhost:7472/UpperCut.svc/js"/>


After we initialize our JavaScript proxy object, you can easily call the service operation we've defined.



The parameter for our service is the first argument (in this case it'll be the query string for the current page) and the second and third parameters are JavaScript callbacks that have a single parameter containing the result of the service call (In this case we get back an array of tweets).  After we've got our callback wired up, there's nothing left to do but to use jQuery to dump the results to a div element.

Phone Viewport sizing


We can make sure we size our page's viewport for windows phone by adding the following snippet in our HTML document in the head tag

<meta name="Viewport" content="width=320; user-scaleable=no; initial-scale=3.0" />

This will give it a nice display size and won't let the user accidentally zoom in and out since we've specified that there should be no scaling.

Conclusion


This post was made to show how a powerful library like LinqToTwitter and a powerful framework like WCF can work together to write an application in a short amount of time. Another reason I wrote this tutorial is because there aren't many complete examples of WCF JavaScript proxy generation.

The code in the example is very terse and you'd be smart to write integration tests that actually consume the Twitter API.  Also, you probably don't want to put all of your code in the service method body.

Source code + Solution can be downloaded here (MIT license)