tags:

views:

1295

answers:

4

Hello,

I'm trying to update a user's Twitter status from my C# application.

I searched the web and found several possibilities, but I'm a bit confused by the recent (?) change in Twitter's authentication process. I also found what seems to be a relevant StackOverflow post, but it simply does not answer my question because it's ultra-specific regading a code snippet that does not work.

I'm attempting to reach the REST API and not the Search API, which means I should live up to the stricter OAuth authentication.

I looked at two solutions. The Twitterizer Framework worked fine, but it's an external DLL and I would rather use source code. Just as an example, the code using it is very clear and looks like so:

Twitter twitter = new Twitter("username", "password");
twitter.Status.Update("Hello World!");

I also examined Yedda's Twitter library, but this one failed on what I believe to be the authentication process, when trying basically the same code as above (Yedda expects the username and password in the status update itself but everything else is supposed to be the same).

Since I could not find a clear cut answer on the web, I'm bringing it to StackOverflow.

What's the simplest way to get a Twitter status update working in a C# application, without external DLL dependency?

Thanks

+10  A: 

If you like the Twitterizer Framework but just don't like not having the source, why not download the source? (Or browse it if you just want to see what it's doing...)

Jon Skeet
Well, I guess a dumb question deserves a simple answer... Somehow I missed the fact their sources were available. Thanks :)
Roee Adler
+7  A: 

I'm not a fan of re-inventing the wheel, especially when it comes to products that already exist that provide 100% of the sought functionality. I actually have the source code for Twitterizer running side by side my ASP.NET MVC application just so that I could make any necessary changes...

If you really don't want the DLL reference to exist, here is an example on how to code the updates in C#. Check this out from dreamincode.

/*
 * A function to post an update to Twitter programmatically
 * Author: Danny Battison
 * Contact: [email protected]
 */

/// <summary>
/// Post an update to a Twitter acount
/// </summary>
/// <param name="username">The username of the account</param>
/// <param name="password">The password of the account</param>
/// <param name="tweet">The status to post</param>
public static void PostTweet(string username, string password, string tweet)
{
    try {
     // encode the username/password
     string user = Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(username + ":" + password));
     // determine what we want to upload as a status
     byte[] bytes = System.Text.Encoding.ASCII.GetBytes("status=" + tweet);
     // connect with the update page
     HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://twitter.com/statuses/update.xml");
     // set the method to POST
     request.Method="POST";
     request.ServicePoint.Expect100Continue = false; // thanks to argodev for this recent change!
     // set the authorisation levels
     request.Headers.Add("Authorization", "Basic " + user);
     request.ContentType="application/x-www-form-urlencoded";
     // set the length of the content
     request.ContentLength = bytes.Length;

     // set up the stream
     Stream reqStream = request.GetRequestStream();
     // write to the stream
     reqStream.Write(bytes, 0, bytes.Length);
     // close the stream
     reqStream.Close();
    } catch (Exception ex) {/* DO NOTHING */}
}
RSolberg
It's amazing that there are development frameworks for Twitter out there when just 10 lines of C# is sufficient to do this!+1
NathanE
@NathanE: There are lots of things which are only about 10 lines of code, but which are good to have in a library. It stops you from making silly mistakes like forgetting `using` statements for streams, and swallowing exceptions, for example...
Jon Skeet
@NathanE: I still hold true to my recommendation which Jon echoed as well that use the Library's where possible and create the library if you need one...
RSolberg
Hi, I like this code very much and tried it out, however in case the username/password are incorrect it fails gracefully and I can't tell if the operation failed (no exception is thrown, I've put code in the catch clause). Any suggestions?
Roee Adler
I'll try to look in a couple hours. I provided the link for where the code came from. I'd look there to see if someone else has had the same issue in the comments area.
RSolberg
I'm also using this. Please note though that Twitter supports UTF8 character encoding, so the following is more appropriate: byte[] bytes = System.Text.Encoding.UTF8.GetBytes("status=" + tweet);
Junto
+2  A: 

Another Twitter library I have used sucessfully is TweetSharp, which provides a fluent API.

The source code is available at Google code. Why don't you want to use a dll? That is by far the easiest way to include a library in a project.

Adam Lassek
+1  A: 

The simplest way to post stuff to twitter is to use basic authentication , which isn't very strong.

    static void PostTweet(string username, string password, string tweet)
    {
         // Create a webclient with the twitter account credentials, which will be used to set the HTTP header for basic authentication
         WebClient client = new WebClient { Credentials = new NetworkCredential { UserName = username, Password = password } };

         // Don't wait to receive a 100 Continue HTTP response from the server before sending out the message body
         ServicePointManager.Expect100Continue = false;

         // Construct the message body
         byte[] messageBody = Encoding.ASCII.GetBytes("status=" + tweet);

         // Send the HTTP headers and message body (a.k.a. Post the data)
         client.UploadData("http://twitter.com/statuses/update.xml", messageBody);
    }
Darwyn