Using the Twitter API

As part of my alerting project, I wanted to implement a Twitter push. I first googled on Bing and got this post. I made a quick implementation of my IAlert Interface like so:

public void Send()
{

    HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(_twitterUri);
    request.Credentials = new NetworkCredential(_twitterUserId, _twitterPassword);
    request.Timeout = 5000;
    request.Method = "POST";
    request.ContentType = "application/x-www-form-urlencoded";
    using (Stream requestStream = request.GetRequestStream())
    {
        using (StreamWriter streamWriter = new StreamWriter(requestStream))
        {
            streamWriter.Write(_message);
        }
    }
    WebResponse response = request.GetResponse();
}

However, I get a 401

image

it looks like it is an old implementation of the Twitter API.  I then went to this page and it looks like I can’t do basic HTTP authentication with Twitter – I have to use OAuth.  Twitter’s help page recommended using the C# Twitterizer library.  I went ahead and and installed it from NuGet

 

image

I then re-wrote the send method to use the Twitterizer:

public void Send()
{
    OAuthTokens tokens = new OAuthTokens();
    tokens.ConsumerKey = _consumerKey;
    tokens.ConsumerSecret = _consumerSecret;
    tokens.AccessToken = _accessToken;
    tokens.AccessTokenSecret = _accessTokenSecret;

    TwitterResponse<TwitterStatus> tweetResponse = TwitterStatus.Update(tokens, _message);
}

 

Alas, when I re-ran my unit tests

image

Ugh – I guess I need to add a reference to my test project.  Sure enough, that did the trick:

image

Now I am getting this message back from Twitter

image

I then when to my account settings for the app on Twitter and changed it from Read only to full control:

image

Hit save, regenerated the keys, and still got the same message

I then stumbled onto this.  I then restarted, changed the text of my integration test and voila (that’s French for “Whoop-de-do")

image

One Response to Using the Twitter API

  1. Kaylene says:

    Spot on with this write-up, I actually think this
    website needs a lot more attention. I’ll probably be back again to see more, thanks for the advice!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: