Sending Tweets with C#

 

If you ever want to send updates to Twitter from C# it fairly easy to do. Recently, we added the option to send a tweet when someone registers for our upcoming dotNed user group meeting. Below is the client code.

using System;

using System.Web;

using System.Net;

using System.IO;

 

namespace Dotned.UI.Framework

{

    public class TwitterClient

    {

        public string Username { get; set; }

        public string Password { get; set; }

        public Exception Error { get; set; }

        private string _twitterUpdateUrl = "http://twitter.com/statuses/update.json";

 

        public TwitterClient(string userName, string password)

        {

            this.Username = userName;

            this.Password = password;

        }

 

        public void SendMessage(string message)

        {

            try

            {

                HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(_twitterUpdateUrl);

                request.Credentials = new NetworkCredential(this.Username, this.Password);

 

                SetRequestParams(request);

 

                string post = string.Format("status={0}", HttpUtility.UrlEncode(message));

                

                using (Stream requestStream = request.GetRequestStream())

                {

                    using (StreamWriter writer = new StreamWriter(requestStream))

                    {

                        writer.Write(post);

                    }

                }

 

                WebResponse response = request.GetResponse();

                string content;

 

                using (Stream responseStream = response.GetResponseStream())

                {

                    using (StreamReader reader = new StreamReader(responseStream))

                    {

                        content = reader.ReadToEnd();

                    }

                }

            }

            catch (Exception ex)

            {

                Error = ex;

            }

        }

 

        private static void SetRequestParams(HttpWebRequest request)

        {

            System.Net.ServicePointManager.Expect100Continue = false;

            request.Timeout = 50000;

            request.Method = "POST";

            request.ContentType = "application/x-www-form-urlencoded"; 

        }

    }

}

It is important to notice that you need to set a static flag in the ServicePointManager. Otherwise, Twitter will reply with error 417 – Expectation Failed.  Here’s an example that shows how to use this class:

   1: TwitterClient client = new TwitterClient("__Sander", "[not telling you of course...]");

   2: client.SendMessage("Testing my twitter client code.");