image

Twitter continues to gain in popularity, in part because it offers a rich and easy to use query API.

Just for fun I made an ASP.NET Web Forms User Control to Display some recent Tweets on a web page.

The tweets are displayed in a ListView as follows.

Code Snippet
  1. <%@ Control Language=”C#” AutoEventWireup=”true” CodeBehind=”MyTweets.ascx.cs” Inherits=”NETOOP.Controls.MyTweets” %>
  2. <%@ OutputCache Duration=”3600″ VaryByParam=”None” %>
  3.     <asp:ListView ID=”MyTweetsListView” runat=”server”>
  4.         <LayoutTemplate>
  5.             <table class=”gridview”>
  6.                 <th>My Tweets</th>
  7.                 <tbody>
  8.                     <asp:PlaceHolder ID=”itemPlaceholder” runat=”server” />
  9.                 </tbody>
  10.             </table>
  11.         </LayoutTemplate>
  12.         <ItemTemplate>
  13.             <tr>
  14.                 <td><a href=’<%#Eval(“Url”)%>‘><%#Eval(“Title”) %></a></td>
  15.             </tr>
  16.         </ItemTemplate>
  17.     </asp:ListView>

Note the use of the OutputCache directive so the Twitter API doesn’t need to get called for very single request of any page that contains this control.

Since Microsoft’s .NET is so XML savvy and LINQ to XML is so powerful the C# code to fetch the tweets and bind to the ListView is pretty straight forward.

Code Snippet
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Web;
  5. using System.Web.UI;
  6. using System.Web.UI.WebControls;
  7. using System.Xml.Linq;
  8.  
  9. namespace NETOOP.Controls
  10. {
  11.     public partial class MyTweets : System.Web.UI.UserControl
  12.     {
  13.         protected void Page_Load(object sender, EventArgs e)
  14.         {
  15.             XNamespace slashNamespace = “http://purl.org/rss/1.0/modules/slash/”;
  16.  
  17.             XDocument rssFeed = XDocument.Load(“http://www.twitter.com/statuses/user_timeline/misfitgeek.rss” + “?count=5″);
  18.  
  19.             var posts = from item in rssFeed.Descendants(“item”)
  20.                         select new
  21.                         {
  22.                             Title = item.Element(“title”).Value,
  23.                             Url = item.Element(“link”).Value,
  24.                         };
  25.  
  26.             MyTweetsListView.DataSource = posts;
  27.             MyTweetsListView.DataBind();
  28.         }
  29.     }
  30. }

 

Notice that he URL in the XDocument.Load specifies “misfitgeek.rss” to pull my personal tweets (which you can include on your web site if you like). You could change the portion of the URL to reflect your own Twitter name.

Technorati Tags: ,,