Click here to Skip to main content
15,886,518 members
Articles / Web Development / ASP.NET

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

Rate me:
Please Sign up or sign in to vote.
4.81/5 (13 votes)
1 Oct 2010CPOL4 min read 109.1K   3.3K   38   32
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

XML
<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.

C#
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:

C#
//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.

C#
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.

C#
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.

C#
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.

C#
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)


Written By
Software Developer (Senior)
United States United States
I am a .Net developer with over 10 years experience.

Check out my latest project, True Novelist

Comments and Discussions

 
AnswerRe: Twitter post without bit.ly? Pin
Grunge Boy29-Dec-10 2:36
Grunge Boy29-Dec-10 2:36 
GeneralWhere can I get TwitterUserId Pin
AmerZafar18-Oct-10 23:14
AmerZafar18-Oct-10 23:14 
GeneralRe: Where can I get TwitterUserId Pin
Neil Meredith19-Oct-10 2:56
Neil Meredith19-Oct-10 2:56 
GeneralError when compiling Pin
Corobori13-Oct-10 5:37
Corobori13-Oct-10 5:37 
GeneralRe: Error when compiling Pin
Neil Meredith13-Oct-10 8:49
Neil Meredith13-Oct-10 8:49 
GeneralRe: Error when compiling Pin
ItalloSan30-Nov-10 7:14
ItalloSan30-Nov-10 7:14 
GeneralRe: Error when compiling Pin
Neil Meredith30-Nov-10 7:59
Neil Meredith30-Nov-10 7:59 
GeneralRe: Error when compiling Pin
ItalloSan30-Nov-10 9:47
ItalloSan30-Nov-10 9:47 
Thanks - worked a treat. This article has saved me a few hours - cheers

Stephen
GeneralNice Pin
giridhar 35-Oct-10 7:45
giridhar 35-Oct-10 7:45 
GeneralNice Aricle. Pin
Gaurav Dudeja India3-Oct-10 20:01
Gaurav Dudeja India3-Oct-10 20: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.