How to retrieve tweets via C#

Posted by Andrea on 2009-03-26 17:41
Twitter is a free social messaging utility for staying connected in real-time.
Retrieving tweets is really easy, thanks to the RESTful architecture exposed by Twitter's API, you can write your own Web User Control in a few lines:

   1:  <%@ Control Language="C#" AutoEventWireup="true" %>
   2:   
   3:  <%@ OutputCache Shared="true" Duration="60" VaryByParam="*" %>
   4:  <%@ Import namespace="System" %>
   5:  <%@ Import namespace="System.Text.RegularExpressions" %>
   6:  <%@ Import namespace="System.Web.UI.WebControls" %>
   7:  <%@ Import namespace="System.Xml" %>
   8:   
   9:  <script runat="server" >
  10:      // Fields
  11:      public string UserName { get; set; }
  12:      
  13:      // Methods
  14:      protected void Page_Load(object sender, EventArgs e)
  15:      {
  16:          XmlDocument xdc = new XmlDocument();
  17:          xdc.Load(string.Format("http://twitter.com/statuses/user_timeline/{0}.xml", UserName));
  18:   
  19:          foreach (XmlNode ndo in xdc["statuses"])
  20:          {
  21:              DateTime dtm = ParseDateString(ndo["created_at"].InnerText);
  22:   
  23:              if (ndo["in_reply_to_user_id"].InnerText.Trim().Length == 0)
  24:                  phl1.Controls.Add(new Literal() { 
  25:                  Text = string.Format("<span>[{0}]</span> {1} " + 
  26:                      "<span style=\"font-style:italic;\">via {2}</span> <br />", 
  27:                      dtm.ToString("yyyy-MM-dd HH:mm"), ndo["text"].InnerText, ndo["source"].InnerText) });
  28:          }
  29:      }
  30:      
  31:      /// <dev>Thanks to http://code.google.com/p/twitterizer</dev>
  32:      DateTime ParseDateString(string DateString)
  33:      {
  34:          Match match = new Regex("(?<DayName>[^ ]+) (?<MonthName>[^ ]+) (?<Day>[^ ]{1,2}) " + 
  35:              "(?<Hour>[0-9]{1,2}):(?<Minute>[0-9]{1,2}):(?<Second>[0-9]{1,2}) " + 
  36:              "(?<TimeZone>[+-][0-9]{4}) (?<Year>[0-9]{4})").Match(DateString);
  37:          return DateTime.Parse(string.Format("{0} {1} {2} {3}:{4}:{5}", 
  38:              new object[] { match.Groups["MonthName"].Value, match.Groups["Day"].Value, 
  39:                  match.Groups["Year"].Value, match.Groups["Hour"].Value, 
  40:                  match.Groups["Minute"].Value, match.Groups["Second"].Value }));
  41:      }
  42:  </script>
  43:  <asp:PlaceHolder ID="phl1" runat="server" />

You can take a look to the output in the about section of my website, please note:
  • Caching should be enabled to avoid Twitter be queried each time your page loads.
  • The profile I use is public, for private profiles, this won't work.