Using ASP.NET MVC 2 to Query Twitter's Public API - FIFA 2010

Posted by: Malcolm Sheridan , on 7/8/2010, in Category ASP.NET MVC
Views: 42541
Abstract: The following article demonstrates how to use ASP.NET to query Twitter's public API.
If you've been living under a rock for the last few years, you might not have heard of Twitter, but for the rest of us, it is a great communication tool. I have made countless friends with it including the authors of DotNetCurry! Thankfully Twitter has a public Application Programming Interface (API) which you can use and incorporate into your site, if you'd like to add Twitter feeds to it. This article demonstrates how to do it using ASP.NET MVC. 
To see this in action, I'm going to create a small ASP.NET MVC 2 website. If you haven't got Microsoft Visual Studio 2010, you can download the Express edition here
 
To begin with, let's take a look at the Twitter's API. The documentation is here, but for a brief overview, here's what you can do:
 
 
I'm going to be using the search API to search Twitter. Search returns tweets in two formats, json and atom. I'll be using the atom format for my code. Let's get started!
 
The tweet returned from Twitter will be in atom format, but I don't want to mess with that! I want a POCO object to play with, so I've created a class called TwitterViewData to store the tweets. Here's the class:
 
 
C#
 
public class TwitterViewData
{
      public string AuthorName { get; set; }
       public string AuthorUri { get; set; }
       public string Content { get; set; }
       public string Updated { get; set; }
       public string Link { get; set; }
}
 
VB.NET (10.0)
 
Public Class TwitterViewData
      Public Property AuthorName() As String
         Public Property AuthorUri() As String
         Public Property Content() As String
         Public Property Updated() As String
         Public Property Link() As String
End Class
 
 
That being done I'm next going to tackle the view. I need to make a web request to search for tweets. Thankfully making a web request in ASP.NET is simple. Once the data is returned, I'll use a LINQ query to transform the data to my TwitterViewData class and pass that to the view. Here's the action code below:
C#
 
public ActionResult Index()
{
      var request = WebRequest.Create("http://search.twitter.com/search.atom?q=worldcup&rpp=5") as HttpWebRequest;
       var twitterViewData = new List<TwitterViewData>();
 
       if (request != null)
       {
            using (var response = request.GetResponse() as HttpWebResponse)
              {
                    using (var reader = new StreamReader(response.GetResponseStream()))
                   {
                        var document = XDocument.Parse(reader.ReadToEnd());
                        XNamespace xmlns = "http://www.w3.org/2005/Atom";
 
                        twitterViewData = (from entry in document.Descendants(xmlns + "entry")
                                    select new TwitterViewData
                                    {
                                        Content = entry.Element(xmlns + "content").Value,
                                        Updated = entry.Element(xmlns + "updated").Value,
                                        AuthorName = entry.Element(xmlns + "author").Element(xmlns + "name").Value,
                                        AuthorUri = entry.Element(xmlns + "author").Element(xmlns + "uri").Value,
                                        Link = (from o in entry.Descendants(xmlns + "link")
                                                where o.Attribute("rel").Value == "image"
                                                select new { Val = o.Attribute("href").Value }).First().Val
                                    }).ToList();
                    }
                }
            }
      return View(twitterViewData);
}
 
 
VB.NET
 
Public Function Index() As ActionResult
      Dim request = TryCast(WebRequest.Create("http://search.twitter.com/search.atom?q=worldcup&rpp=5"), HttpWebRequest)
         Dim twitterViewData = New List(Of TwitterViewData)()
 
         If request IsNot Nothing Then
               Using response = TryCast(request.GetResponse(), HttpWebResponse)
                              Using reader = New StreamReader(response.GetResponseStream())
                                    Dim document = XDocument.Parse(reader.ReadToEnd())
                                    Dim xmlns As XNamespace = "http://www.w3.org/2005/Atom"
 
                                    twitterViewData = (
                                        From entry In document.Descendants(xmlns + "entry")
                                        Select New TwitterViewData With {.Content = entry.Element(xmlns + "content").Value, .Updated = entry.Element(xmlns + "updated").Value, .AuthorName = entry.Element(xmlns + "author").Element(xmlns + "name").Value, .AuthorUri = entry.Element(xmlns + "author").Element(xmlns + "uri").Value, .Link = (
                                                From o In entry.Descendants(xmlns + "link")
                                                Where o.Attribute("rel").Value = "image"
                                                Select New With {Key .Val = o.Attribute("href").Value}).First().Val}).ToList()
                              End Using
               End Using
         End If
      Return View(twitterViewData)
End Function
 
The code above is pretty self explanatory. I'm making a web request to the API via the following line of code:
 
var request = WebRequest.Create("http://search.twitter.com/search.atom?q=worldcup&rpp=5") as HttpWebRequest;
 
From there I parse the atom string into an XDocument type so it's super easy to query. 
 
var document = XDocument.Parse(reader.ReadToEnd());
 
Next I'm using LINQ to XML to query the data and return the query as a list of TwitterViewData types. That list is passed as the model to the view.
 
The view as always is quite simple. Here it is:
 
<% foreach (var item in Model)
       { %>
    <a href="<%: item.AuthorUri %>" target="_blank">
        <%: item.AuthorName %></a>
    <p>
        <%= item.Content %></p>
    <img src="<%: item.Link %>" alt="Twitter Logo" /><br />
    <br />
    <% } %>
 
If you run the application, you'll get the latest searches on the 2010 FIFA world cup from Twitter. This is a cool way of interacting with Twitter. In an upcoming article I'll show you how to do this without ASP.NET. The entire source code of this article can be downloaded over here

This article has been editorially reviewed by Suprotim Agarwal.

Absolutely Awesome Book on C# and .NET

C# and .NET have been around for a very long time, but their constant growth means there’s always more to learn.

We at DotNetCurry are very excited to announce the The Absolutely Awesome Book on C# and .NET. This is a 500 pages concise technical eBook available in PDF, ePub (iPad), and Mobi (Kindle).

Organized around concepts, this eBook aims to provide a concise, yet solid foundation in C# and .NET, covering C# 6.0, C# 7.0 and .NET Core, with chapters on .NET Standard and the upcoming C# 8.0 too. Use these concepts to deepen your existing knowledge of C# and .NET, to have a solid grasp of the latest in C# and .NET OR to crack your next .NET Interview.

Click here to Explore the Table of Contents or Download Sample Chapters!

What Others Are Reading!
Was this article worth reading? Share it with fellow developers too. Thanks!
Share on LinkedIn
Share on Google+

Author
Malcolm Sheridan is a Microsoft awarded MVP in ASP.NET, a Telerik Insider and a regular presenter at conferences and user groups throughout Australia and New Zealand. Being an ASP.NET guy, his focus is on web technologies and has been for the past 10 years. He loves working with ASP.NET MVC these days and also loves getting his hands dirty with jQuery and JavaScript. He also writes technical articles on ASP.NET for SitePoint and other various websites. Follow him on twitter @malcolmsheridan


Page copy protected against web site content infringement 	by Copyscape




Feedback - Leave us some adulation, criticism and everything in between!
Comment posted by David Evan on Thursday, August 19, 2010 4:36 PM
Thanks for this nice post.

Sadly, my opinion, based on the fact that we don't (yet) live in a Star Trek economy, is that hard coding named business object elements/transformations as from XML to entities is never the answer; when the API changes the client needs to pay for redevelopment instead of using dynamic, adjustable business rules that a less expensive resource can maintain.  XDocument, XElement and un-pre-typed (dynamic) DataSets deal with this by dynamic or specific inference of an XML file's schema. The MS Entity Framework is only good when you have an unchanging pattern or an unlimited IT budget, which is not in the nature of many dynamic, agile business applications/efforts today.  
Comment posted by noha on Monday, May 16, 2011 6:10 AM
gr8, but wheres the article without asp.net?
Comment posted by Max on Sunday, July 10, 2011 5:43 PM
Thank you. Very helpful!!

Categories

JOIN OUR COMMUNITY

POPULAR ARTICLES

C# .NET BOOK

C# Book for Building Concepts and Interviews

Tags

JQUERY COOKBOOK

jQuery CookBook