Twitter Feed Reader

Mar 19

I have done this many times over, and for once I plan on publishing the code so I can reuse it.  This is a Twitter Feed Reader, you pass it the user_status RSS url, with the number of updates you want. This should work flawlessly, but if it doesn’t… I’m sorry. If you need any help implementing this, just let me know. I’m always around to help.

public class TwitterStatus {
    public string Status { get; set; }
    public string Url { get; set; }
    public DateTime Date { get; set; }
    public static TwitterStatus[] GetTwitter(string url, int length) {
        XDocument xRoot = XDocument.Load(url);

        var items = (from item in xRoot.Descendants("item")
                     select new TwitterStatus() {
                         Status = LinkifyStatusUpdate(item.Element("title").Value),
                         Date = DateTime.Parse(item.Element("pubDate").Value),
                         Url = item.Element("link").Value
                     }).Take(length).ToArray();
        return items;
    }
    private static string LinkifyStatusUpdate(string status) {
        string ret = status.Substring(status.IndexOf(": ") + 2);
        ret = Regex.Replace(ret, @"(http[s]?:\/\/[^\s]+)", "<a href=\"$1\">$1</a>");
        ret = Regex.Replace(ret, @"(#[^\W]+)", "<a href=\"http://www.twitter.com/search?q=$1/\">$1</a>");
        ret = Regex.Replace(ret, @"@([^\W]+)", "<a href=\"http://www.twitter.com/$1/\">@$1</a>");
        return ret;
    }
}

Leave a Reply