Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Twitter Made Easy - Post to Your Twitter Account with Two Lines of Code (and Avoid OAuth Headaches)

0.00/5 (No votes)
1 Oct 2010 1  
Twitter Made Easy - A simple library that hides the complexities of OAuth authentication

Introduction

As social media grows ever more popular, an increasing number of businesses want to integrate it in some way into their existing sites. There are open source libraries that make this task much easier, but getting the initial OAuth authentication setup and working can still be difficult.

To fix this problem, I've created a very simple library build on top of the TweetSharp library (give credit where it's due - the TweetSharp code does all the heavy lifting). With a few web.config settings and two lines of code, you can have Twitter access up and running and get on to more important things.

Sample Project

The sample project demonstrates how a tweet is posted, how the latest tweet is pulled from Twitter, and how the links in the tweet are automatically shortened to help keep under the 140 character limit.

ScreenHunter_07_Sep._30_22.20.jpg

Creating Your Twitter Account

Let's get started by creating a new twitter account.

Once you sign up for and confirm your account, look for the RSS feed icon in the bottom right hand corner of the page. Roll over that to get your Twitter User ID - save that, we'll need it later.

Creating Your Twitter Application

Next, click on the API link at the bottom of the twitter page, then on the 'Register An App' button so we can create a twitter application.

Go ahead and put whatever you want in for the application website and callback URL - we'll override those later in the code anyway.

Create the application.

create_twitter_application.jpg

Get the Keys

Your application is now ready to go - all we need are the keys to access it! You can get these in the application details section.

get_consumer_key.jpg

Bit.ly - It's the Extra Touches that Matter

Since Twitter only allows 140 characters, people often use URL shorteners like Bit.ly to post links. We can add a nice feature to our tweets by automatically finding URLs in the text, and then replacing them with a shortened link.

To do this, sign up for Bit.ly, then get an API key:

api_key.jpg

Using the Code - Quick Start

If you're ready to get started and not interested in the details of the implementation, this is all you need to do.

1. Add the web.config Keys

<appSettings>

   <add key="TwitterUserId" value="197242530"/>
   <add key="TwitterConsumerKey" value="q4qjKjes4VoaNvG6HwOg"/>
   <add key="TwitterConsumerSecretKey" 
	value="stm32bJz9uCgLmExNPtjJr5EDNWn4rTvDFFcR26xQM"/>

   <add key="BitlyLogin" value="codeprojectex"/>
   <add key="BitlyApiKey" value="R_69790474429577367ff0b47c83bb22f3"/>
    
</appSettings> 

2. Add the .dlls to your Project

You need to add the following .dlls to your bin folder. All of them are located in the sample project .zip file.

  1. Hammock.dll
  2. Newtonsoft.json.dll
  3. TweetSharp.dll
  4. TweetSharp.Twitter.dll
  5. SocialMedia.dll

3. Create a Tweet!

As promised, here are the two lines of code required to create a tweet. This will post your tweet, and will also replace www.cnn.com with a shortened bit.ly link.

TwitterInfo ti = new TwitterInfo(); 
ti.PostTweet("My tweet for www.cnn.com", true) 

With a few more lines of code, we can check the status that comes back and be sure they haven't exceeded the 140 character limit:

//Post the tweet, and automatically shrink urls if requested
TwitterInfo.TwitterInfoStatus status = 
		ti.PostTweet(tbxTweet.Text, chkMinimizeUrls.Checked);

//Warn if we're past the max length
if (status == TwitterInfo.TwitterInfoStatus.ExceededMaxLength)
{
    ltlInfo.Text = "You have exceeded the twitter max length of 140 characters";
}
else
{
    //Otherwise, get the last tweet and display it
    ltlInfo.Text = "You tweeted successfully!  Your tweet is: " + ti.GetLastTweet().Text;
} 

Using the Code - Library Details

The first time you browse to the twitter page, the code checks for a saved authentication cookie. If it is not there, you are redirected to twitter to logon, and the authentication token is then saved. For all subsequent visits to the page, the authentication token is loaded from the cookie so the user does not have to login every time.

The AuthorizeAndLoadInfo method is called whenever a new TwitterInfo object is created.

public void AuthorizeAndLoadInfo()
        {
            //If the info is already saved to a cookie, load it up
            if (HttpContext.Current.Request.Cookies[CookieName] != null)
            {
                HttpCookie AuthCookie = HttpContext.Current.Request.Cookies[CookieName];
                RequestToken.Token = AuthCookie.Values["oauth_token"];
                RequestToken.TokenSecret = AuthCookie.Values["oauth_verifier"];
                AccessToken.Token = AuthCookie.Values["access_token"];
                AccessToken.TokenSecret = AuthCookie.Values["access_token_secret"];
            }
            else
            {
                //Otherwise, authorize the user and save the info to a cookie

                string AuthUrl = GetOAuthUrl();
                string OauthToken = 
		HttpContext.Current.Request.QueryString["oauth_token"];
                string OauthVerifier = 
		HttpContext.Current.Request.QueryString["oauth_verifier"];
                if (OauthToken == null)
                {
                    HttpContext.Current.Response.Redirect(AuthUrl);
                }
                else
                {
                    HttpCookie AuthCookie = new HttpCookie(CookieName);
                    AuthCookie.Expires = DateTime.Now.AddYears(100);

                    AccessToken = GetAccessToken(OauthToken, OauthVerifier);
                    AuthCookie["access_token"] = AccessToken.Token;
                    AuthCookie["access_token_secret"] = AccessToken.TokenSecret;
                    AuthCookie["oauth_token"] = OauthToken;
                    AuthCookie["oauth_verifier"] = OauthVerifier;

                    RequestToken.Token = OauthToken;
                    RequestToken.TokenSecret = OauthVerifier;

                    HttpContext.Current.Response.Cookies.Add(AuthCookie);
                }
            }
        } 

Bit.ly Details

The bit.ly code is fairly simple - just a direct web request that passes the username, API key, and URL you want to shorten. It then returns the shortened URL.

public string ShortenUrl(string LongUrl)
        {
            string result = "";
   
            string RequestUrl = "http://api.bit.ly/v3/shorten?login=" + 
		LoginName + "&apiKey=" + ApiKey + "&longUrl=" + 
		HttpUtility.UrlEncode(LongUrl) + "&format=txt";
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(RequestUrl);
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            StreamReader ResponseStream = new StreamReader(response.GetResponseStream());
            result = ResponseStream.ReadToEnd().Replace("\n", "");
            return result;
        } 

The trickiest part of the code is the part that parses out all of the URLs from the passed in string. The regular expression that handles that is a bit of a monster, but it recognizes URLs in multiple formats, such as http://www.cnn.com, www.cnn.com, and cnn.com.

I did not write the regular expression, but used one that was available on regexlib.com. Once the matches are found, I just loop through them and add them to a list of URLs, which will then be sent to Bit.ly to shorten.

public List<String> GetUrls(string Text)
        {
            List<String> Urls = new List<String>();
            //from regexlib.com
            Regex UrlMatcher = new Regex(@"([\d\w-.]+?\.(a[cdefgilmnoqrstuwz]|b
		[abdefghijmnorstvwyz]|c[acdfghiklmnoruvxyz]|d[ejkmnoz]|e
		[ceghrst]|f[ijkmnor]|g[abdefghilmnpqrstuwy]|h[kmnrtu]|i
		[delmnoqrst]|j[emop]|k[eghimnprwyz]|l[abcikrstuvy]|m
		[acdghklmnopqrstuvwxyz]|n[acefgilopruz]|om|p[aefghklmnrstwy]|
		qa|r[eouw]|s[abcdeghijklmnortuvyz]|t[cdfghjkmnoprtvwz]|
		u[augkmsyz]|v[aceginu]|w[fs]|y[etu]|z[amw]|aero|arpa|biz|
		com|coop|edu|info|int|gov|mil|museum|name|net|org|pro)
		(\b|\W(?<!&|=)(?!\.\s|\.{3}).*?))(\s|$)");
            MatchCollection Matches = UrlMatcher.Matches(Text);
            foreach (Match m in Matches)
            {
                string url = m.Value;  
                Urls.Add(url);
            }

            return Urls;
        } 

Advanced Usage

The library only includes a few basic methods to post a tweet, get all tweets, and get the last tweet.

To do more than that is very simple. If you access the Twitter property of the TwitterInfo object, it will return an authenticated endpoint to the TweetSharp fluent API. In other words, once you access that property, you can add other methods after it to get users, add tweets, etc.

In the example below, all statuses for the user id are returned as a list. For more details, you can look at the code intellisense to find the methods (they are fairly self explanatory) or go to the TweetSharp CodePlex site.

TwitterInfo ti = new TwitterInfo(); 
var UserTweets = ti.Twitter.Statuses().OnUserTimeline().For
	(ti.UserId).AsJson().Request().AsStatuses().ToList();  

Points of Interest

The library doesn't handle error conditions such as hitting the rate limit on webrequests, the twitter service being unavailable, etc. This is just a starting point, and it's up to you to handle those errors as needed.

History

  • 1st October, 2010: Initial post

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here