A Simple Twitter Client Tutorial in C# with OAUTH using TweetSharp



 

I've been playing around with Twitter recently so I thought I'd put together a little tutorial on how to write a really simple Twitter client using C# and the TweetSharp library.

Before we start here's what you'll need:

  1. Visual Studio 2010 - Express C# Edition (we're building a Console App after all)
  2. TweetSharp Library (I've used TweetSharp v1.0.0.0)

 

Step 1 - Register Your Application With Twitter

Go to Twitter and Login, then head over to:

 

  • http://dev.twitter.com/apps
  • Click on the Register a new app button
  • Fill out the form.
    • You need the ApplicationType to be Client
    • and Default Access Type: should be Read & Writer we do want to be able to Tweet afterall

 

 

Fill in the Captcha form and submit.

 

You'll now be shown the settings page. Jot down all the important information:

  • API Key
  • Consumer Key
  • Consumer Secret

 

Step 2 - Unzip the TweetSharp

Specifically I unzipped the TweetSharp-Binaries.zip\TweetSharp-Binaries\dotNET 3.5 SP1\NET Framework 3.5 to my lib folder.

 

Step 3 - Add References

Then in visual studio add references to Hammock , Newtonsoft.Json , TweetSharp , TweetSharp.Twitter and just check you can compile everything ok.

It might be worth noting I changed my Console App to compile under .Net 3.5 instead of .Net 4.0 for no particular reason apart from I thought it might be applicable to slightly more people. This can simply be done by doing right click on SimpleTwitterClient.Console in my case, clicking on Properties and then changing the Target Framework dropdown to .Net 3.5 save the changes say yes to the dialog that pops up and check we can compile. I also remove the broken reference to the CSharp assembly.

 

Step 4 - Write some code

So firstly we need to put the ConsumeKey and the ConsumerKeySecret into the App.config in appSettings

Now put the following code in:

 

using System.Configuration;
using TweetSharp;
using TweetSharp.Twitter.Service;

namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{

TwitterClientInfo twitterClientInfo = new TwitterClientInfo();
twitterClientInfo.ConsumerKey = ConsumerKey; //Read ConsumerKey out of the app.config
twitterClientInfo.ConsumerSecret = ConsumerSecret; //Read the ConsumerSecret out the app.config

TwitterService twitterService = new TwitterService(twitterClientInfo);
}



#region ConsumerKey & ConsumerSecret
private static string ConsumerSecret
{
get { return ConfigurationManager.AppSettings["ConsumerSecret"]; }
}

private static string ConsumerKey
{
get { return ConfigurationManager.AppSettings["ConsumerKey"]; }
}
#endregion
}
}

Step 5 - Putting in the Code to prompt you with the "Allow" page

At this point we need the Token and TokenSecret which come from the user Authorising our little Application to Tweet on their behalf.

 

//Now we need the Token and TokenSecret

//Firstly we need the RequestToken and the AuthorisationUrl
OAuthToken requestToken = twitterService.GetRequestToken();
string authUrl = twitterService.GetAuthorizationUrl(requestToken);

//authUrl is just a URL we can open IE and paste it in if we want
Console.WriteLine("Please Allow This App to send Tweets on your behalf");
Process.Start(authUrl); //Launches a browser that'll go to the AuthUrl.

That last bit will ultimately open a browser window so that you can allow your Twitter App to Tweet for you.

 

With a bit of extra code you'll have something like this (note the properties are not shown for brevity).

 

static void Main(string[] args)
{

TwitterClientInfo twitterClientInfo = new TwitterClientInfo();
twitterClientInfo.ConsumerKey = ConsumerKey; //Read ConsumerKey out of the app.config
twitterClientInfo.ConsumerSecret = ConsumerSecret; //Read the ConsumerSecret out the app.config

TwitterService twitterService = new TwitterService(twitterClientInfo);

//Now we need the Token and TokenSecret

//Firstly we need the RequestToken and the AuthorisationUrl
OAuthToken requestToken = twitterService.GetRequestToken();
string authUrl = twitterService.GetAuthorizationUrl(requestToken);

//authUrl is just a URL we can open IE and paste it in if we want
Console.WriteLine("Please Allow This App to send Tweets on your behalf");
Process.Start(authUrl); //Launches a browser that'll go to the AuthUrl.

//Allow the App
Console.WriteLine("Enter the PIN from the Browser:");
string pin = Console.ReadLine();

OAuthToken accessToken = twitterService.GetAccessToken(requestToken, pin);

string token = accessToken.Token; //Attach the Debugger and put a break point here
string tokenSecret = accessToken.TokenSecret; //And another Breakpoint here

Console.WriteLine("Write Down The AccessToken: " + token);
Console.WriteLine("Write Down the AccessTokenSecret: " + tokenSecret);



Console.ReadLine();
}

Step 6 - Running the App to get the Token and TokenSecret

Now attach the debugger on the string token line. The app will run though showing you the Allow page page. Once you've allowed the App you'll be shown your PIN number.

 

Closing the browser page will return you to your little TwitterClient, which then does a Console.ReadLine() for the PIN once you've entered the PIN, you can then get the AccessToken which is the really critical bit.

 

Step over and Copy and paste both the accessToken.Token and the accessToken.TokenSecret into your App.config this obviously isn't a very elegant or secure way of getting or storing the Token. I'd encourage you to at a minimum encrypt the App.config, or maybe store them in a secure database.

Step 7 - Cleanup

 

Now your AccessToken and AccessTokenSecret should be in your App.config write some simple properties to Wrap them as before. Now add some code in to simply check whether the AccessToken or AccessTokenSecret are empty and only do the authentication if they are.

The final touch is the actual Tweet:

 

twitterService.AuthenticateWith(AccessToken, AccessTokenSecret);
twitterService.SendTweet("A Simple Tweet from a Simple Twitter Client");

 


 

In Full

 

using System;
using System.Configuration;
using System.Diagnostics;
using TweetSharp;
using TweetSharp.Model;
using TweetSharp.Twitter.Service;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {

            TwitterClientInfo twitterClientInfo = new TwitterClientInfo();
            twitterClientInfo.ConsumerKey = ConsumerKey; //Read ConsumerKey out of the app.config
            twitterClientInfo.ConsumerSecret = ConsumerSecret; //Read the ConsumerSecret out the app.config

            TwitterService twitterService = new TwitterService(twitterClientInfo);

            if (string.IsNullOrEmpty(AccessToken) || string.IsNullOrEmpty(AccessTokenSecret))
            {
                //Now we need the Token and TokenSecret

                //Firstly we need the RequestToken and the AuthorisationUrl
                OAuthToken requestToken = twitterService.GetRequestToken();
                string authUrl = twitterService.GetAuthorizationUrl(requestToken);

                //authUrl is just a URL we can open IE and paste it in if we want
                Console.WriteLine("Please Allow This App to send Tweets on your behalf");
                Process.Start(authUrl); //Launches a browser that'll go to the AuthUrl.

                //Allow the App
                Console.WriteLine("Enter the PIN from the Browser:");
                string pin = Console.ReadLine();

                OAuthToken accessToken = twitterService.GetAccessToken(requestToken, pin);

                string token = accessToken.Token; //Attach the Debugger and put a break point here
                string tokenSecret = accessToken.TokenSecret; //And another Breakpoint here

                Console.WriteLine("Write Down The AccessToken: " + token);
                Console.WriteLine("Write Down the AccessTokenSecret: " + tokenSecret);
            }

            twitterService.AuthenticateWith(AccessToken, AccessTokenSecret);
            twitterService.SendTweet("A Simple Tweet from a Simple Twitter Client");
            Console.WriteLine("Enter a Tweet");
            string tweetMessage;

             while (true)
             {
                 tweetMessage = Console.ReadLine();
                 if(tweetMessage.ToLower() == "exit")
                 {
                     break;
                 }
                 twitterService.SendTweet(tweetMessage);
             }
        }



        #region ConsumerKey & ConsumerSecret
        private static string ConsumerSecret
        {
            get { return ConfigurationManager.AppSettings["ConsumerSecret"]; }
        }

        private static string ConsumerKey
        {
            get { return ConfigurationManager.AppSettings["ConsumerKey"]; }
        }

        private static string AccessToken
        {
            get { return ConfigurationManager.AppSettings["AccessToken"]; }
        }
        private static string AccessTokenSecret
        {
            get { return ConfigurationManager.AppSettings["AccessTokenSecret"]; }
        }
        #endregion
    }
}

 


And that concludes our extremely simple Twitter client. Have fun.


blog comments powered by Disqus

Search

Disclaimer

The opinions expressed herein are my own personal opinions and do not represent my employer's view in anyway.

© Copyright 2014