Posts Tagged ‘MVC’

In a previous post, we looked at how to consume a live streaming API from Twitter.  That was great and all, but you’re not going to become the next Twitter by consuming content — you need to have your own live streaming API.  In this post we’ll look at how to create a basic streaming API that others can open a streaming connection to and get real-time updates.

So, what groundbreaking web service will we be exposing to the masses?  We’ll be streaming the web server’s current datetime!  Ingenious, I know!  Hopefully, you’ll be able to adapt this to a slightly more engaging experience.

To start, let’s just take an ASP.NET MVC project and code the default controller action.  We clear all the headers of the response and add the “application/json” header.  Since we won’t be returning a view in the traditional sense of ASP.NET MVC, we don’t have to create an actual view.  We’ll just pause the thread for 1 second and then return the current timestamp for as long as the service is running.

On the consumer side, we’ll just refactor the code we had in the previous post to connect to the URL of the project we just created.  I’m running in on the local development machine so your port will likely be different.

You’ll notice we added some exception handling logic in case we lose our connection to our streaming API.  In this case, we’ll just keep trying to re-connect to the stream.  I’ll show you a sample of this in the last part of the post.

Once we have all the bits in place, we run the ASP.NET MVC application first so it is ready to start handling requests.  Then, we create multiple instances of our consumer console application to simulate multiple clients connecting to the streaming API.  You’ll end up seeing something like this:

To simulate what would happen on the consumer side if there was a broken connection or other exception on the server side, I killed the local development server for a few seconds and then restarted it.  Below you can see that we recovered after a few exception handling loops.

Of course, this post was just intended to provide a possible option for implementing a streaming API with ASP.NET MVC.  For a more realistic scenario you would likely have a queue listener around our Thread.Sleep() code.  As messages are picked up from the queue, you could stream it out and immediately start listening for the next message on the queue.

In a follow-up post, I will demo this same concept using Node.js.

Hope this helps.

I’ve always been a fan of how Twitter organized their API.  Particulary, I enjoyed being able to change the format of the response by just changing the extension of the URL from JSON to XML.  A typical Twitter API call looks like this:

http://api.twitter.com/version/statuses/public_timeline.format

So while this public timeline call will return XML:
http://api.twitter.com/1/statuses/public_timeline.xml

This one would return JSON:
http://api.twitter.com/1/statuses/public_timeline.json

The proper REST way to do this is by changing the headers in your request to ask for a particular file format.  Indeed, an implementation utilizing request headers has already been written.  However, I prefer Twitter’s implementation which coincidentally seems to be a feature of the Scala / Lift framework.  To accomplish this with ASP.NET MVC, we are going to build an attribute that checks the incoming request and then attempts to render the resulting model in the selected format.

First, some words of caution.  I don’t think this method will scale if your API / web application takes off.  Although it is a great example of the DRY (don’t repeat yourself), code-once software development practice, it does somewhat tightly couple your API to your front end.  Twitter faced a similar situation when their API was hosted on the same domain as the web application.  Eventually, Twitter moved the API to api.twitter.com.  This practice allows the API to evolve independently of the front-end of your application.  With that warning in mind, let’s dive into the code.

They way we’ll implement this functionaly is to develop a custom action attribute which will check for a “format” parameter on each request to decide whether to return the model as a JSON, XML or the default view that the controller will return. This is slightly different from Twitter’s implementation but it simplifies some of the routing issues we would have with ASP.NET MVC.  Using an API-driven development approach, I’ll start with an existing controller and add a (non-existent).  This gives me an idea of how it would work.

I could add some additional parameters at this point to restrict which formats to accept, but we’ll leave that out for now (KISS – Keep It Simple Stupid!).  Next we’ll just generate the class using the smart tag in Visual Studio which will create the stub for it.  We want this action filter to execute before the response is returned to the client but after the data model has been populated.  This implies we’ll be overriding the OnActionExecuted method:

At this point, everything should build.  Our next step is to create two custom ActionResult subclasses which will return either Xml or Json representations of the model you pass in.

ASP.NET MVC includes a JsonResult which we’ll use for the JSON format.  Although there is no XML equivalent, the MVCContrib library does have an XmlResult class.  You can download the bits here to provide the XmlResult class (along with some other very useful features).  Add the assembly as a reference to your project.

Now we have the two ActionResult’s we need to implement the solution.  Below is a screenshot of the finished method.  Essentially, we’re looking into the filter context to find the file extension.  Depending on if it’s json or xml, we use a different action result serialization technique.

Notice that we need to set the JsonRequestBehavior in order for this to work.  There are several security vulnerabilities which you should explore before defaulting this behavior at such a broad level. Phil Haack details some of the issues with JSON Hijacking here.

That’s all there is to it.  Hope this helps!

Solution Setup

For this project, I went with my tried and true solution structure:

/root
   /lib
   /src
   /tools

I copied the System.Web.Mvc assembly to the lib folder and updated the reference accordingly.  I always recommend this approach especially when dealing with pre-release libraries.  The New Project dialog adds a reference to the default installation directory for the ASP.NET MVC version you choose.  This is usually “C:\Program Files\Microsoft ASP.NET\ASP.NET MVC 3\Assemblies”.  The problem with this is that your web host probably doesn’t install pre-release software.  By including it as a local library and setting “Copy Local” to true you can ensure that the required version is copied to the output directory.  It also helps when you add to version control and want to update the library to the latest release candidate.
copy local true

I also did the same for the LinqToTwitter and DotNetOpenAuth libraries.

Razor Template

Before you start using Razor templates, I highly recommend you read Scott Guthrie’s overview on Razor layouts.   There’s a couple new files you need to be familiar with including  _ViewStart.cshtml and _Layout.cshtml.  Essentially, _ViewStart removes the need for you to explicitly set the layout for each view you add and specify any common view code you want to have execute before rendering the view.  _Layout is what you commonly know as your Site.Master page.

First Try – Twitter API

To wrap this post up, I want to just take a quick look at wiring up all the Twitter API authentication process. The first step to get OAuth working is to get a consumer key and secret from Twitter. It’s a quick and easy process. Just go to https://twitter.com/oauth_clients and select “Register a New Application”. Complete all the required fields and you’ll be presented with the key and secret. Make sure you select “Browser” as the Application Type. Don’t worry about the callback URL for now – just put http://google.com or something similar for now.

Next, add the required assemblies that you downloaded with Linq to Twitter to your project. These include LinqToTwitter.dll and DotNetOpenAuth.dll. An important step is to create a class that implements the IConsumerTokenManager interface in the DotNetOpenAuth library. This is the class that will manage all the access tokens and secrets for OAuth. For the sake of this quick POC, I’m using the InMemoryTokenManager included in the Using OAuth with ASP.NET MVC sample project. The only configuration change you have to make is to add a your consumer secret and key to the Web.config as illustrated below:

Linq to Twitter Configuration Settings

Linq to Twitter Configuration Settings

Take a look at that project to get a quick connection to the Twitter API going. I ran my project and was able to connect exactly as expected. Next time we’ll look at the wireframes for the application and getting more of the functionality of the site going.

Overview

Have you ever tweeted something that you would like your friends to retweet as soon as possible.  I’ve seen this with new product announcements, Twitter contests, building buzz and even when applying for a social media gig.  Usually the tweet includes something like “Pls RT!”  With this project, I thought I’d create a retweeting engine to announce to your friends that you have a status you’d like them to retweet.  This sounded like a great opportunity to deep dive into the Twitter API and OAuth within .NET application.  Hence a neat side project that may have some usefulness and will definitely get us exploring some important API’s.

Technology Stack

Twitter API

There are plenty of good .NET Twitter Libraries available with varying degrees of functionality.  I am a huge fan of Linq so I decided to give Linq to Twitter a spin since it has high API coverage and supports oAuth out of the box.

ASP.NET MVC R3

I’ve been using the ASP.NET MVC framework since it’s first community preview several years ago and have fallen in love. It has evolved in many ways since the first CTP and I’m looking forward to experiment with some of its newest features – particularly the Razor view engine.

OAuth

I believe the best way to get up to speed with an API is to jump right in and start working with it.  One of the components I’m most excited to explore is the OAuth implementation for the Twitter API.  With more and more services adopting the OAuth protocol, I think its safe to expect it to become the de-facto security layer for most social API’s available.

Other Tools

As to the other frameworks and tools involved in the project, you can expect to see the usual suspects. At this time I don’t think they’ll be a need for a database since most of the data will be coming from the Twitter API. The tools of the trade up to this point will include:

  • Visual Studio 2010 Ultimate
  • jQuery v1.4.4

I’m looking forward to sharing the experience step-by-step so don’t be surprised if I hit some speed bumps (or canyons) along the way. In the next part we’ll look at some preliminary solution setup and wiring some of the external libraries together. We’ll also mockup some screens and see what views and controllers it would be implying.

You may have noticed this blog has been awfully quiet in the past couple of months.  That’s because I’ve been working on a neat side project with a couple of other developers.  Today, we’d like to submit our project to the ASP.NET community to get some feedback. The site is called WorkGrabber.com.  You can check it out here:  http://workgrabber.com

What we’re trying to create with WorkGrabber is something like the eBay of local service contractors. In an nutshell, when you post a job, you’re bringing the entire project directly to contractors in detail. You can upload photos and videos as well as answer questions and interact with contractors while keeping your information private.  You can review bids from local contractors and accept the one that you like the most.  You can read more about the features of WorkGrabber on the WorkGrabber blog. In this post, I want to focus more on the technology we used to create it.

We started developing WorkGrabber during the earlier releases of ASP.NET MVC although we were pretty sure we weren’t going to release it until the first RTM. It gave us more time to beta test the site with friends and family before releasing it into the wild. Here’s a breakdown of some of the tools we used.

WorkGrabber is built on top of ASP.NET MVC 1.0. Not a whole lot changed in the past couple releases of MVC so upgrading was fairly simple. The data access code is developed mostly using LINQ to SQL with a SQL 2005 database. jQuery is used throughout the site to create some cool visual effects. For example, we used jQuery Tag Suggestion plugin to create this neat auto-suggest tagging feature for when you’re posting a job.

 tag samples

Throughout WorkGrabber, we use the jQuery Facebox plugin to create really cool modal windows.  The modal windows themselves are ViewUserControls which are rendered back to the client.  Here’s an example:

 facebox sample

The majority of images are hosted by ImageShack and the galleries use the jQuery lightBox plugin to create a really neat modal effect.  So much is built into this jQuery plugins that they really make client side development a blast.

 photo gallery

I plan to post more about the internals of WorkGrabber in later posts.  I’d love to hear some of your feedback.  If you have a project on your “honey-do” list that you keep putting off, try posting it on WorkGrabber to get some free local contractor bids.

Try posting a job and let me know what you think in the comments here.