/ C#

Search Twitter from C# using LINQ to XML

In some applications, it could be cool to have a feature that enabled the user to quickly get a glimpse of what people are saying on Twitter about the user or their product, service, company etc.

For instance, a service like GetSatisfaction.com has a feature just like that. They call it Overheard, and this is what it looks like:

overheard

There’s nothing like Twitter to give you feedback. I think MediaTemple felt the effect of unhappy customers on Twitter when their servers broke down, and stayed there for more than two days!

Anyway. I wanted to search from C#, and get back a DataTable. Here’s how it’s done:

///

/// Searches Twitter for the specified query./// /// The query./// Returns the search results as a DataTablepublic DataTable Search(string query) { DataTable dt = new DataTable(); dt.Columns.Add("text"); dt.Columns.Add("html"); dt.Columns.Add("pubdate"); dt.Columns.Add("id"); dt.Columns.Add("link"); dt.Columns.Add("authorname"); dt.Columns.Add("authorlink"); XDocument tweetResults = XDocument.Load(String.Format(

"http://search.twitter.com/search.atom?q={0}", HttpUtility.UrlEncode(query)));

XNamespace atomNS = "http://www.w3.org/2005/Atom"; var q = from tweet in tweetResults.Descendants(atomNS + "entry") select new { Text = (string)tweet.Element(atomNS + "title"), Html = (string)tweet.Element(atomNS + "content"), DatePublished = DateTime.Parse((string)tweet.Element(atomNS + "published")), Id = (string)tweet.Element(atomNS + "id"), Link = (string)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 { Name = (string)author.Element(atomNS + "name"), Uri = (string)author.Element(atomNS + "uri"), }).First() }; foreach (var item in q) { dt.Rows.Add(item.Text, item.Html, item.DatePublished, item.Id, item.Link,

item.Author.Name, item.Author.Uri); } return dt; }