Learning the Basics of using the Twitter API in ASP.NET Web Pages with Razor syntax

This tutorial will demonstrate how to use the Twitter API in WebMatrix using Razor. If you do not understand the basic concepts of WebMatrix you should go to http://www.microsoft.com/web/webmatrix for discussion and additional tutorials. You can also download WebMatrix from this site.

Getting Started

These steps will create the initial web site. At this point there is no code specific to WebMatrix or Twitter.

1. Create a new site using “Site From Template”->”Empty Site” setting the Site Name to “Twitter API Tutorial”.

2. Now we’ll add the default cshtml page. Click on the “Files” icon near the lower left corner of the window. Then click the “Create a new file” link. This will give you a choice of what type of file to add – we’re going to add a CSHTML file named “default.cshtml”.

3. Add some text to the default body and title elements for a quick test. The file should look something like:

<!DOCTYPE html>
<html lang="en">
   <head>
      <meta charset="utf-8" />
      <title>Twitter API Tutorial</title>
   </head>
   <body>
      Twitter API Tutorial
   </body>
</html>

Click on the “Run” button in the toolbar; your browser should launch displaying the text that you entered.

Creating a TwitterAPI Search Helper

Now we’ll create a helper that will access the Twitter API using the search function.. There isn’t a lot of code and it could go in the default.cshtml file but by creating a helper file we see how to make calls to helpers. The Twitter API is accessed through http calls. We’ll use the “search” function as it is straight-forward and does not require the use of authentication. Use of authentication through OAuth is beyond the scope of this tutorial; you’ll want to go to the Twitter documentation at http://dev.twitter.com/doc for details on using it. The search URI is http://search.twitter.com/search.atom?q=value. It can be accessed using whatever web function you want. We’ll use WebClient – you could also just load it as an xml stream.

1. Create a new folder in the project called “App_Code” and create a new cshtml file in it called “MyCustomHelpers.cshtml”.

2. Delete the default html content and add an empty Razor functions block:

@functions{

}

3. Put this using statement at the top of the file:

@using System.Xml.Linq;

This will allow us to parse the Xml string that is returned from Twitter.

4. Now add this function to the functions block:

public static string TwitterSearch(string value)
{

   string xml;

   // The WebClient class is located in the System.Net namespace; it provides 
   // methods for sending data to and from uri resources. In this case we’ll
   // download the uri content as a string.

   WebClient web = new WebClient();

   xml = web.DownloadString(String.Format("http://search.twitter.com/search.atom?q={0}", "deviantART")); 

   return xml;
}

This is the actual helper function that will be called from the html; it can now be called from the body element of the default page (default.cshtml):

<body>

@MyCustomHelpers.TwitterSearch("deviantArt");

</body>

This will just display the Twitter feed as a string – not very exciting. We’ll add some code that will allow us to modify the display of the entries.

Add a class that will represent the items in the Twitter feed

Now we’ll create a class that will allow us to parse the Twitter feed items and manipulate their elements. This will let us right code that is neater and easier to maintain.

1. Create a new C# class file in the App_Code folder by right-clicking on the App_Code folder, then clicking on “New File”, select “Class (C#)”. Name the file “TwitterClasses” Change the default ClassName to “TwitterEntry”. All of the code in this step will be added to this class in this file.

2. Each entry in the Twitter feed has elements for an id, the date and time published, a couple of link, title, content, date and time updated, geodata, possible metadata and source info, and author name and uri. We’ll add properties for some of these elements to the class. Properties are generally placed right after the class declaration before any constructors or other methods:

public class TwitterEntry
{

   public string Id { get; set; }
   public DateTime Published { get; set; }
   public string Title { get; set; }
   public string Content { get; set; }
   public DateTime Updated { get; set; }
   public string Source { get; set; }
   public string AuthorName { get; set; }
   public string AuthorURI { get; set; }

}

3. Also add a constructor to the class to initialize these properties:

public TwitterEntry(string id, string published, string title, string content, string updated, string source, string authorName, string authorURI)
{

   Id = id;

   Published = DateTime.Parse(published);

   Title = title;

   Content = content;

   Updated = DateTime.Parse(updated);

   Source = source;

   AuthorName = authorName;

   AuthorURI = authorURI;

}

4. Add the “IComparable” interface to the class and implement the CompareTo() method; this will allow us to sort the feeds (in this case we’ll sort by author name). The class statement should look like:

public class TwitterEntry : IComparable<TwitterEntry>

and the CompareTo() method:

public int CompareTo(TwitterEntry other)
{

   return AuthorName.CompareTo(other.AuthorName);

}

Update the TwitterSearch Helper Function

Now we’ll update the TwitterSearch(string value) helper function in the MyCustomHelpers.cshtml file to return a sorted List of TwitterEntries rather than the xml. The modified function will look like:

public static List<TwitterEntry> TwitterSearch(string value)
{

   // create the empty TwitterEntry List
   List<TwitterEntry> twitterEntries = new List<TwitterEntry>();

   // Get the Twitter feed
   // The WebClient class is located in the System.Net namespace; it 
   // provides methods for sending data to and from uri resources.
   WebClient web = new WebClient();

   string xml = web.DownloadString(String.Format("http://search.twitter.com/search.atom?q={0}", value));

   // Declare the namespaces that we'll need to select the different
   // elements using LINQ..
   XNamespace ns = "http://www.w3.org/2005/Atom";
   XNamespace nsTwitter = "http://api.twitter.com/";

   // Select the entry elements
   var entries = from elem in XDocument.Parse(xml).Descendants(ns+"entry")
   select elem;

   // Create an instance of TwitterEntry for each entry eleent and add it to the list
   foreach (var entry in entries)
   {
      TwitterEntry twitterEntry = new TwitterEntry(entry.Element(ns+"id").Value, entry.Element(ns+"published").Value,
      entry.Element(ns+"title").Value, 
      entry.Element(ns+"content").Value, 
      entry.Element(ns+"updated").Value, entry.Element(nsTwitter+"source").Value,
      entry.Element(ns+"author").Element(ns+"name").Value,
      entry.Element(ns+"author").Element(ns+"uri").Value);
      twitterEntries.Add(twitterEntry);
   }

   // Sort the list
   twitterEntries.Sort();

   // Return the list
   return twitterEntries;
}

Update the default.cshtml file to call the Helper

Finally we’ll update the html code in default.cshtml file to call the helper (MyCustomHelpers.TwitterSearch()), iterate through the resulting list, and display part of each entry. We’ll use Razor code to access the properties in the Twitter item (such as “@entry.Title”) and add anchor links for the author uri. The default.cshtml file should now look like:

@using System.Xml.Linq;
<!DOCTYPE html>
<html lang="en">
   <head>
      <meta charset="utf-8" />
      <title>Twitter API Tutorial</title>
   </head>
   <body>
      @{
      // Get the TwitterEntry list and iterate through it
         foreach (TwitterEntry entry in Helpers.TwitterSearch("deviantART"))
         {
            // Dress up the Title
            <font face="Times New Roman" size="+1" color="#ff0000">
               <b>@entry.Title</b>
            </font>
            <p></p>
   
         // Add the authors uri to their name
            <a href=@entry.AuthorURI>
               @entry.AuthorName;
            </a>
   
         // include the TTwitter content
            @entry.Content

            <hr/>
         }
      }
   </body>
</html>

Additional Resources

Download WebMatrix http://www.microsoft.com/web/webmatrix

Learn more http://www.microsoft.com/web/category/learn

More tutorials http://www.asp.net/webmatrix

Twitter http://twitter.com/mswebplatform

Dev Twitter http://dev.twitter.com/doc

 

For any questions or comments about this tutorial please contact the Aeshen team at http://www.twitter.com/aeshen

You can discuss this article using the adjacent Facebook talkback.

For technical questions please visit our discussion forums, where we have a vibrant community of developers like you, as well as Microsoft engineers who are ready to answer your questions!