Click here to Skip to main content
Click here to Skip to main content

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

, 1 Oct 2010
Rate this:
Please Sign up or sign in to vote.
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, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

Neil Meredith
Software Developer (Senior)
United States United States
I am a .Net developer with 8 years of professional development experience. After 4 years in Florida, I made my way up to the frozen north and am currently living in Chicago.
 
For more development tips and tricks (focusing on game development with Unity), check out my blog at IPhoneTopApp.com.
 
Google Plus Profile
Follow on   Twitter

Comments and Discussions

 
QuestionSSL is required PinmemberAnubhav6892-Apr-14 19:43 
QuestionRemote server returned an error (401) Unauthorized PinmemberAnas Ahmed Siddiqui26-May-13 21:41 
AnswerRe: Remote server returned an error (401) Unauthorized PinmemberJignesh K Patel26-Feb-14 19:43 
GeneralMy vote of 5 PinmemberNithish Ravindran11-Apr-13 0:41 
Questionsocial media .dll problem Pinmembersingh jaya25-Mar-13 1:04 
QuestionNot posting to twitter Pinmembersingh jaya22-Mar-13 0:41 
Questionpost on twitter Pinmembersingh jaya21-Mar-13 0:40 
QuestionPost a image on twitter Pinmembervishal katoch18-Aug-12 17:41 
Questionhi.. need dll for silverlight PinmemberYasodha.eng12-Jul-12 1:25 
AnswerRe: hi.. need dll for silverlight Pinmembervishal katoch18-Aug-12 17:43 
QuestionAdd an image PinmemberZ@clarco28-May-12 2:19 
Questionerror when compiling your code Pinmembersatishmachineni23-Jan-12 22:47 
Questionhow to get rss value of twitter id which is alrady created Pinmembersatishmachineni22-Jan-12 17:37 
AnswerRe: how to get rss value of twitter id which is alrady created Pinmemberpgelinas23-Jan-12 8:34 
Generaltwiiter info couldnot be found [modified] Pinmembersatishmachineni20-Jan-12 0:20 
QuestionVersion in vb Pinmemberzhongweiii28-Dec-11 22:13 
QuestionGreat Article... Pinmembergoodfela2224-Oct-11 10:19 
QuestionHow to delete twitter post... PinmemberMember 825372821-Sep-11 16:10 
QuestionTwits PinmemberTLadole2-Feb-11 21:27 
AnswerRe: Twits PinmemberMember 449497222-Apr-11 5:36 
QuestionTwitter post without bit.ly? PinmemberGrunge Boy29-Dec-10 1:16 
AnswerRe: Twitter post without bit.ly? PinmemberGrunge Boy29-Dec-10 2:36 
GeneralWhere can I get TwitterUserId Pinmemberamer chaudry18-Oct-10 23:14 
GeneralRe: Where can I get TwitterUserId PinmemberNeil Meredith19-Oct-10 2:56 
GeneralError when compiling PinmemberCorobori13-Oct-10 5:37 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Mobile
Web03 | 2.8.140721.1 | Last Updated 1 Oct 2010
Article Copyright 2010 by Neil Meredith
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid