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.
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.
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:
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="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.
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:
TwitterInfo.TwitterInfoStatus status =
if (status == TwitterInfo.TwitterInfoStatus.ExceededMaxLength)
ltlInfo.Text = "You have exceeded the twitter max length of 140 characters";
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.
AuthorizeAndLoadInfo method is called whenever a new
TwitterInfo object is created.
public void AuthorizeAndLoadInfo()
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"];
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;
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", "");
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>();
Regex UrlMatcher = new Regex(@"([\d\w-.]+?\.(a[cdefgilmnoqrstuwz]|b
MatchCollection Matches = UrlMatcher.Matches(Text);
foreach (Match m in Matches)
string url = m.Value;
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