Home >
Blog >
Simple Twitter feed for the web-site
Monday, October 24, 2011
Twitter has a very rich API, but there are situations when you
need to do a very simple thing: show last N twitter records
authored by a certain Twitter user. How would we do that as simply
as we can using .NET and LINQ?
// First create the request string. Put actual twitter account name instead of 'username'. You can also specify how
// many of the last records to retrieve
string TwitterRequest = "http://twitter.com/statuses/user_timeline.xml?screen_name=username&count=5";
// Download the data in string
WebClient wc = new WebClient();
string TwitterResponse = wc.DownloadString(TwitterRequest);
// Parse the string and put the data into XDocument
XDocument doc = new XDocument();
doc = XDocument.Parse(TwitterResponse);
// Make a LINQ query - here we just need to get the first record
var q = from tw in doc.Descendants("status")
select tw;
/// Get the text of the tweet
if (q.Count() > 0)
{
XElement xe = q.First();
string twitter_text = xe.Element("text").Value;
string twitter_date = xe.Element("created_at").Value
}
It's also worth mentioning that Twitter provides the 'date
created' field in a format, that is not appropriate for direct
conversion to DateTime data type. The date and time in a
format like this 'Mon Oct 24 22:52:51 +0000 2011' will require
certain string manipulation and splitting parts of the date/time
before plugging into DateTime.
Post a comment