Click here to Skip to main content
13,290,595 members (66,454 online)
Click here to Skip to main content
Add your own
alternative version

Tagged as


38 bookmarked
Posted 30 Sep 2010

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


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.


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.


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 - It's the Extra Touches that Matter

Since Twitter only allows 140 characters, people often use URL shorteners like 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, then get an API key:


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


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


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

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 with a shortened link.

TwitterInfo ti = new TwitterInfo(); 
ti.PostTweet("My tweet for", 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";
    //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"];
                //Otherwise, authorize the user and save the info to a cookie

                string AuthUrl = GetOAuthUrl();
                string OauthToken = 
                string OauthVerifier = 
                if (OauthToken == null)
                    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;

        } Details

The 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 = "" + 
		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,, and

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

public List<String> GetUrls(string Text)
            List<String> Urls = new List<String>();
            Regex UrlMatcher = new Regex(@"([\d\w-.]+?\.(a[cdefgilmnoqrstuwz]|b
            MatchCollection Matches = UrlMatcher.Matches(Text);
            foreach (Match m in Matches)
                string url = m.Value;  

            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

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.


  • 1st October, 2010: Initial post


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 over 10 years experience.

Check out my latest project, True Novelist

You may also be interested in...

Comments and Discussions

Questionupdates in 2015 ? Pin
kiquenet.com7-Aug-15 11:27
memberkiquenet.com7-Aug-15 11:27 
QuestionSSL is required Pin
Anubhav6892-Apr-14 20:43
memberAnubhav6892-Apr-14 20:43 
QuestionRemote server returned an error (401) Unauthorized Pin
Anas Ahmed Siddiqui26-May-13 22:41
memberAnas Ahmed Siddiqui26-May-13 22:41 
AnswerRe: Remote server returned an error (401) Unauthorized Pin
Jignesh K Patel26-Feb-14 20:43
memberJignesh K Patel26-Feb-14 20:43 
GeneralMy vote of 5 Pin
Nithish Ravindran11-Apr-13 1:41
memberNithish Ravindran11-Apr-13 1:41 
Questionsocial media .dll problem Pin
singh jaya25-Mar-13 2:04
membersingh jaya25-Mar-13 2:04 
QuestionNot posting to twitter Pin
singh jaya22-Mar-13 1:41
membersingh jaya22-Mar-13 1:41 
Questionpost on twitter Pin
singh jaya21-Mar-13 1:40
membersingh jaya21-Mar-13 1:40 
QuestionPost a image on twitter Pin
vishal katoch18-Aug-12 18:41
membervishal katoch18-Aug-12 18:41 
Questionhi.. need dll for silverlight Pin
Yasodha.eng12-Jul-12 2:25
memberYasodha.eng12-Jul-12 2:25 
AnswerRe: hi.. need dll for silverlight Pin
vishal katoch18-Aug-12 18:43
membervishal katoch18-Aug-12 18:43 
QuestionAdd an image Pin
Z@clarco28-May-12 3:19
memberZ@clarco28-May-12 3:19 
Questionerror when compiling your code Pin
satishmachineni23-Jan-12 23:47
membersatishmachineni23-Jan-12 23:47 
Questionhow to get rss value of twitter id which is alrady created Pin
satishmachineni22-Jan-12 18:37
membersatishmachineni22-Jan-12 18:37 
AnswerRe: how to get rss value of twitter id which is alrady created Pin
pgelinas23-Jan-12 9:34
memberpgelinas23-Jan-12 9:34 
Generaltwiiter info couldnot be found Pin
satishmachineni20-Jan-12 1:20
membersatishmachineni20-Jan-12 1:20 
QuestionVersion in vb Pin
zhongweiii28-Dec-11 23:13
memberzhongweiii28-Dec-11 23:13 
QuestionGreat Article... Pin
goodfela2224-Oct-11 11:19
membergoodfela2224-Oct-11 11:19 
QuestionHow to delete twitter post... Pin
Member 825372821-Sep-11 17:10
memberMember 825372821-Sep-11 17:10 
QuestionTwits Pin
TLadole2-Feb-11 22:27
memberTLadole2-Feb-11 22:27 
AnswerRe: Twits Pin
Member 449497222-Apr-11 6:36
memberMember 449497222-Apr-11 6:36 
QuestionTwitter post without Pin
Grunge Boy29-Dec-10 2:16
memberGrunge Boy29-Dec-10 2:16 
AnswerRe: Twitter post without Pin
Grunge Boy29-Dec-10 3:36
memberGrunge Boy29-Dec-10 3:36 
GeneralWhere can I get TwitterUserId Pin
amer chaudry19-Oct-10 0:14
memberamer chaudry19-Oct-10 0:14 
GeneralRe: Where can I get TwitterUserId Pin
Neil Meredith19-Oct-10 3:56
memberNeil Meredith19-Oct-10 3:56 
GeneralError when compiling Pin
Corobori13-Oct-10 6:37
memberCorobori13-Oct-10 6:37 
GeneralRe: Error when compiling Pin
Neil Meredith13-Oct-10 9:49
memberNeil Meredith13-Oct-10 9:49 
GeneralRe: Error when compiling Pin
stephenda30-Nov-10 8:14
memberstephenda30-Nov-10 8:14 
GeneralRe: Error when compiling Pin
Neil Meredith30-Nov-10 8:59
memberNeil Meredith30-Nov-10 8:59 
GeneralRe: Error when compiling Pin
stephenda30-Nov-10 10:47
memberstephenda30-Nov-10 10:47 
GeneralNice Pin
giridhar 35-Oct-10 8:45
membergiridhar 35-Oct-10 8:45 
GeneralNice Aricle. Pin
Gaurav Dudeja India3-Oct-10 21:01
memberGaurav Dudeja India3-Oct-10 21:01 

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

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

Permalink | Advertise | Privacy | Terms of Use | Mobile
Web01 | 2.8.171207.1 | Last Updated 1 Oct 2010
Article Copyright 2010 by Neil Meredith
Everything else Copyright © CodeProject, 1999-2017
Layout: fixed | fluid