The Twitter Search API made easy with Linq to XML
My pal Lieven and I are preparing some cool demos to show at the Belgian TechDays SharePoint Preconference next week. Our goal is to build up a nice story that shows the various ways how to use SharePoint 2007 in combination with .NET 3.5. For some those demos we're going to make use of one of today's hypes: Twitter! This evening I tried to query Twitter data using Linq and I discovered there are lots of samples available on the net; there's even a complete Linq to Twitter provider on CodePlex. Too bad the Linq to Twitter provider is focused on the tweets for a specific Twitter user and I wanted to make use of Twitter's Search API. It turned out to be very, very easy (thanks to Robert Horvick's code snippets). Just dump the code at the bottom of this post in your .NET 3.5 project, and you can query the Twitter Search API using 'sharepoint' as the query like this:
foreach (U2U.Demos.TwitterSearch.Tweet t
in U2U.Demos.TwitterSearch.Query("sharepoint"))
{
MessageBox.Show(t.Title);
}
Here's the code for the TwitterSearch class:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;
namespace U2U.Demos
{
public class TwitterSearch
{
private const string urlTemplate = "http://search.twitter.com/search.atom?q={0}";
private static XNamespace atomNS = "http://www.w3.org/2005/Atom";
public static List<Tweet> Query(string query)
{
XDocument xDoc = XDocument.Load(string.Format(urlTemplate, query));
var tweets =
(from tweet in xDoc.Descendants(atomNS + "entry")
select new Tweet
{
Title = (string)tweet.Element(atomNS + "title"),
Published =
DateTime.Parse((string)tweet.Element(atomNS + "published")),
Id = (string)tweet.Element(atomNS + "id"),
Link = tweet.Elements(atomNS + "link")
.Where(link => (string)link.Attribute("rel") == "alternate")
.Select(link => (string)link.Attribute("href"))
.First(),
Author = (from author in tweet.Descendants(atomNS + "author")
select new Author
{
Name = (string)author.Element(atomNS + "name"),
Uri = (string)author.Element(atomNS + "uri"),
}).First(),
});
return tweets.ToList<Tweet>();
}
public class Tweet
{
public string Id { get; set; }
public DateTime Published { get; set; }
public string Link { get; set; }
public string Title { get; set; }
public Author Author { get; set; }
}
public class Author
{
public string Name { get; set; }
public string Uri { get; set; }
}
}
}