Home > C#

Twitter API Friends Timeline and LINQ to XML

15. April 2009

So here is some code to grab the friends timeline utilizing LINQ to XML.  There are two parts to this. 1) a function to make the request to their API and bring back the response and 2) use LINQ to XML to read the friends timeline.

You'll notice in my code I add the querystring item "count" because it's open to bring back the items you want. Without "count" it brings back the 20 items.

1) Code to make the request and return a string (which is the XML) brought back

public string GetFriendsTimeline(int count)
{
        WebRequest req = WebRequest.Create(string.Format("http://twitter.com/statuses/friends_timeline.xml?count={0}", count));
        NetworkCredential creds = new NetworkCredential(_username, _password);

        req.Credentials = creds;
        req.Method = "GET";
        WebResponse resp = (WebResponse)req.GetResponse();

        Stream respStream = resp.GetResponseStream();
        StreamReader reader = new StreamReader(respStream);

        string respString = reader.ReadToEnd();

        reader.Close();
        respStream.Close();
        resp.Close();

        return respString;
}

_username and _password are private variables stored in the class that holds this function so replace the variable with your credentials if need be during testing

2) The function that utilizez LINQ to XML to easily roll through the XML string in the Friends Timline

private void GetRecentTweets()
{

        timelineString = objTwitter.GetFriendsTimeline(10);

        XDocument xDoc = XDocument.Parse(timelineString);

        var resultTweets = from tweets in xDoc.Descendants("status")
                          select new
                          {
                              ID = tweets.Element("id").Value,
                              Text = tweets.Element("text").Value,
                              Source = tweets.Element("source").Value,
                              UserID = tweets.Element("user").Element("id").Value,
                              UserName = tweets.Element("user").Element("name").Value,
                              UserScreenName = tweets.Element("user").Element("screen_name").Value,
                              UserImageUrl = tweets.Element("user").Element("profile_image_url").Value,
                              CreatedDate = tweets.Element("created_at").Value,
                          };

 //...the rest of your code here for

}

remember the function in step one is located in a class so a simple copy and paste of this code will not work in your program.  However, the two functions combined will deciding how you want them to be laid out in your program.  Happy programming.

Digg It!DZone It!StumbleUponTechnoratiRedditDel.icio.usNewsVineFurlBlinkList

C# ,

blog comments powered by Disqus