Saturday, December 5, 2009

Updating your Twitter Status from C#

Today I needed a way to update my Twitter Status via C#, and for that I found this library: Yedda Twitter C# Library.

After I added a reference to the Yedda.Twitter.dll, I tried working with the following code:

namespace TestingAPIs
{
    using Yedda;

    class Program
    {
        static void Main(string[] args)
        {
            var t = new Twitter();
            t.Update(
                "myUsername",                          // Username
                "myPassword",                          // Password
                "From Visual Studio",                  // New Status
                Yedda.Twitter.OutputFormatType.JSON);  // Output Type
        }
    }
}

Simple eh?

Well, much to my amazement, that threw an exception -_- ...obviously, it wouldn't as much fun if it worked on the first try eh!

So, after some googling, I found some posts that detailed the problem:

This error is seemingly because Twitter servers have started rejecting Expect HTTP header with value "100-Continue".


So anyways, to fix this problem we need to modify a method from the Twitter.cs file of the Yedda library.

Open up the file and find the following method: ExecutePostCommand

At the start of the method, add the following line of code:

System.Net.ServicePointManager.Expect100Continue = false;

That will fix the above problem.

Here is the complete modified method:

protected string ExecutePostCommand(string url, string userName, string password, string data) {
 System.Net.ServicePointManager.Expect100Continue = false;
 WebRequest request = WebRequest.Create(url);
 if (!string.IsNullOrEmpty(userName) && !string.IsNullOrEmpty(password)) {
  request.Credentials = new NetworkCredential(userName, password);
  request.ContentType = "application/x-www-form-urlencoded";
  request.Method = "POST";

  if (!string.IsNullOrEmpty(TwitterClient)) {
   request.Headers.Add("X-Twitter-Client", TwitterClient);
  }

  if (!string.IsNullOrEmpty(TwitterClientVersion)) {
   request.Headers.Add("X-Twitter-Version", TwitterClientVersion);
  }

  if (!string.IsNullOrEmpty(TwitterClientUrl)) {
   request.Headers.Add("X-Twitter-URL", TwitterClientUrl);
  }


  if (!string.IsNullOrEmpty(Source)) {
   data += "&source=" + HttpUtility.UrlEncode(Source);
  }

  byte[] bytes = Encoding.UTF8.GetBytes(data);

  request.ContentLength = bytes.Length;
  using (Stream requestStream = request.GetRequestStream()) {
   requestStream.Write(bytes, 0, bytes.Length);

   using (WebResponse response = request.GetResponse()) {
    using (StreamReader reader = new StreamReader(response.GetResponseStream())) {
     return reader.ReadToEnd();
    }
   }
  }
 }

 return null;
}