Follow me on Twitter at Twitter.com/wbm
FYI, I'm blogging most of my stuff over at More Wally now.
You might want to add my rss feed to your reader at:http://morewally.com/cs/blogs/wallym/rss.aspx
Calling the Twitter API in C# - Wallace B. McClure

Wallace B. McClure

All About Wally McClure - The musings of Wallym on Web, HTML5, Mobile, Xamarin.iOS, Xamarin.Android, and Windows Azure.

News

Visual Studio Magazine Column Personal Blog

.NET

Book Authors

Business

Family

Friends

Georgia Tech Bloggers

Personal

Archives

Calling the Twitter API in C#

I've been working on this application to send out tweets at a particular time.  One thing thing I want to do is be able to look at the logged in user's timeline.  I've been playing with the ASP.NET 4.0 AJAX Previews, so I thought I would marry the two.  As a result, I wrote the WCF code below in C#.  Note that the password is hidden, so the code won't work until you add that in.  Basically, I make a request to get the friends timeline.  This gives me the most recent 20 posts by default. I store the result in an XmlDocument.  I need to get that data out as a complex object of type UserStatusSvc as I am returning an array of that type.  I used Linq to Xml for that.

          [OperationContract]
        public UserStatusSvc[] GetUserTimeLine(string username)
        {
            string url = "http://twitter.com/statuses/friends_timeline.xml";
            //string user = Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(username + ":" + password));
            HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
            request.Method = "POST"; // <--- you probably need to change this to a GET after a twitter change a couple of months ago.
            request.Credentials = new NetworkCredential(username, password);
            WebResponse response = request.GetResponse();
            StreamReader reader = new StreamReader(response.GetResponseStream());
            string responseString = reader.ReadToEnd();
            reader.Close();
            XmlDocument xmld = new XmlDocument();
            xmld.LoadXml(responseString);
            XDocument document = XDocument.Parse(responseString);

            var query = from e in document.Root.Descendants()
                        where e.Element("user") != null
                        select new UserStatusSvc
                        {
                            UserName = e.Element("user").Element("screen_name").Value,
                            ProfileImage = e.Element("user").Element("profile_image_url").Value,
                            Status = HttpUtility.HtmlDecode(e.Element("text").Value),
                            StatusDate = e.Value.ParseDateTime().ToString()
                        };

            var users = (from u in query
                         where u.Status != ""
                         select u).ToList();

            return (users.ToArray());
        }

Here's the definition of my UserStatusSvc object.

    [DataContract]
    public class UserStatusSvc
    {
        [DataMember]
        public string UserName { get; set; }
        [DataMember]
        public string ProfileImage { get; set; }
        [DataMember]
        public string Status { get; set; }
        [DataMember]
        public string StatusDate { get; set; }
    }

    public static class StringExtensions
    {
        public static DateTime ParseDateTime(this string date)
        {
            string dayOfWeek = date.Substring(0, 3).Trim();
            string month = date.Substring(4, 3).Trim();
            string dayInMonth = date.Substring(8, 2).Trim();
            string time = date.Substring(11, 9).Trim();
            string offset = date.Substring(20, 5).Trim();
            string year = date.Substring(25, 5).Trim();
            string dateTime = string.Format("{0}-{1}-{2} {3}", dayInMonth, month, year, time);
            DateTime ret = DateTime.Parse(dateTime);
            return ret;
        }
    }

Thanks to Tim Heuer for some code he posted on his blog to get me started.  I have primarily stolen his code and reposted it here.  :-)

Original Url: http://morewally.com/cs/blogs/wallym/archive/2009/03/17/calling-the-twitter-api-in-c.aspx

PS. I modified this code example to remove the hokey CheckForNull(...).  It was stupid and not necessary.  I didn't realize I had left it in until I got hassled for it.  The line 'where Element("user") != null' resolved my problem.

Comments

webbes said:

After another look.. you could also better use the DownloadString method of the WebClient class:

msdn.microsoft.com/.../fhd1f0sw(VS.80).aspx

Cheers,

Wes

# March 19, 2009 10:07 AM

webbes said:

I had a look for you at the twitter date format and indeed it isn't that wierd. To parse the date you could simply use this:

<code>

string twitterDate = "Sat Jan 24 22:14:29 +0000 2009";

DateTime parsedDateTime = DateTime.ParseExact(twitterDate, "ddd MMM dd HH:mm:ss zzz yyyy", CultureInfo.InvariantCulture);

</code>

Cheers,

Wes

P.S. You could glue my three reactions into on comment or not post them at all. Maybe it's good to just change the code sample.

# March 19, 2009 10:31 AM

Howdy said:

What did you mean while saying "marry the two"?

# March 20, 2009 1:17 PM

harushard said:

got problem..~

{"The remote server returned an error: (400) Bad Request."}

i do ur code in windows form.. ithink same also..

what's the problem..?

read about rate limiting, but didnt know what to add to avoid this.. HELPP

# June 2, 2009 11:46 AM

Wallym said:

if you are getting an error, you probably need to change to using a GET instead of a POST. I think Twitter changed this a couple of weeks after I posted this.

# June 2, 2009 2:39 PM

Peter Benson said:

How about the license to use the API for commerical purpose?

# January 21, 2010 2:36 AM