Contact Login Register
h M

How to Setup Twitter Integration

How to Setup Twitter Integration

Author: Chad Nash/Monday, September 23, 2013/Categories: Uncategorized

Rate this article:
No rating

How to Setup Twitter Integration

Registered users can also download Linq2Twitter sample. Please register an account to get a copy.

In this article:

  • AuthenticationAccount Information
  • Friends and Followers
  • Get Statuses and Retweets
  • Update Status
  • How to Retweet
  • References


Twitter is a micro-blogging service that allows people to post messages. The maximum length of each message is 140 characters. Twitter enables social networking by allowing people to follow and communicate with each other. Over time, this has proven to be a powerful communications medium because of its real-time nature.

Whenever news breaks around the world, people are tweeting that news as it happens. This article will talk about how to integrate twitter API into ASP.NET application. There are few libraries introduced in twitter developer website for using in .NET application

All may have its own pros & cons. This article will focused on LinqToTwitter library which as its name shown completely based on linQ. You can download the source code or dll’s from codeplex. Then you should add references to your web applications.

How to Start

First thing you should consider for creating any twitter application is you have to register the application and get Consumer key and Consumer secret:

These keys should be kept on safe place.  Web.config is good place to put these keys and it is easy to access them through all places in ASP.NET application.


Twitter has recently changed its authentication from basic to OAuth authentication. OAuth is a security protocol that allows applications to act on your behalf without requiring you to give out your password to every application. This definition is a generalization and simplification of what OAuth truly is.

There is an increasing need for Web applications to communicate with each other. In the Twitter space, there are literally hundreds of 3rd party applications that access Twitter on your behalf to provide functionality. Examples include posting photos, scheduling tweets, and full-featured clients.

Many of these applications fill holes in Twitter's offerings and deliver value, contributing to their popularity. Without OAuth, each of these applications would need to collect your username and password to interact with Twitter on your behalf and therein lays the problem.

Sharing secrets (credentials) with a 3rd party application requires putting trust in that application to act responsibly. This is a risky proposition because eventually some unscrupulous application will misuse your secrets for their own gain or engage in malicious behavior. Therefore, you need to minimize who you share your secrets with.

Adding to the unfortunate circumstances of finding yourself in a position where an application has misused secrets, the first line of defense is to change passwords. The problem with changing passwords is that the same password has been given to multiple other applications.

Therefore, after changing your Twitter password, you also need to change passwords for every other application. Giving out secrets to every application is fraught with risk and complication.

OAuth is a way to enable the scenario of working with 3rd party applications, without giving out your secrets. Essentially, a 3rd party application that wants to access your Twitter account, using OAuth, will perform a redirection to an authorization page on Twitter, you will then tell Twitter to give them permission, and the application will be able to perform actions on your behalf.

This whole sequence of events occurs without needing to share a password with the 3rd party site. Instead, Twitter has shared a token to your account that the 3rd party application uses. If later, you find that you can't trust the 3rd party application, go to Twitter and cancel their access and Twitter will no longer allow that specific application to access your account.

Because access is controlled through Twitter, you don't have to do anything special for other applications because they still have access to your account. No one has your Twitter password and you don't have to encounter the pain of visiting every site.

OAuth is really the way forward in building applications that work with Twitter. By implementing OAuth, you can instill a degree of trust in your application because visitors know that you're taking a responsible approach, rather than asking them to unnecessarily share secrets.

I encourage you to use OAuth in all of your application development endeavors, which is fully supported by LINQ to Twitter. Anyway let’s do some coding; this code will do the authentication: 
private WebAuthorizer auth;

protected void Page_Load(object sender, EventArgs e)
IOAuthCredentials credentials = new SessionStateCredentials();

if (credentials.ConsumerKey == null || credentials.ConsumerSecret == null)
credentials.ConsumerKey = ConfigurationManager.AppSettings["twitterConsumerKey"];
credentials.ConsumerSecret = ConfigurationManager.AppSettings["twitterConsumerSecret"];

auth = new WebAuthorizer
Credentials = credentials,
PerformRedirect = authUrl => Response.Redirect(authUrl)

if (!Page.IsPostBack)

if (string.IsNullOrWhiteSpace(credentials.ConsumerKey) ||
// The user needs to set up the web.config file to include Twitter consumer key and secret.
lblInfo.Text = "Please set up Consumekey and ConsumerSecret in your web.config";
else if (auth.IsAuthorized)
screenNameLabel.Text = "Logged in as " + auth.ScreenName;
lblInfo.Text = "";
else {

lblInfo.Text = "You are not authorized from twitter.";


protected void authorizeTwitterButton_Click(object sender, EventArgs e)

The WebAuthorizer class is the class will do the OAuth authentication for you, when user click on authorize button the browser will be redirected to a page like this:

So the page will redirect to twitter site and user will pass his username/password to twitter website, not the application. After successful authentication the page will be redirect to application callback URL and IOAuthCredentials property of WebAuthorizer class is loaded now.

Now the user is authenticated and can use his/her twitter account through the application features. There are few points should be considered, the credential will hold OAuthToken and AccessToken from twitter, these values can be hold in a Session and set in SessionStateCredentials class so user doesn’t need to login again and again when navigating through different pages of application, they can also save in database and in this way user will login into the website just once.

Account Information

Account class hold information related to twitter account, this contains numbers of Friends ( following account ) , Followers, Updates and favorites. So to get these information a linQ query should be written from this class:

twitterCtx = new TwitterContext(auth);
var accountTotals =
(from acct in twitterCtx.Account
where acct.Type == AccountType.Totals
select acct.Totals)

lblFriends.Text = accountTotals.Friends.ToString();
lblFollowers.Text = accountTotals.Followers.ToString();
lblupdates.Text = accountTotals.Updates.ToString();
lblFavourites.Text = accountTotals.Favorites.ToString();

From a coding experience perspective, the TwitterContext type is analogous to DataContext (LINQ to SQL) or ObjectContext (LINQ to Entities). TwitterContext instance, twitterCtx uses to access IQueryable<T> tweet categories.

Each tweet category has a Type property for the type of tweets wants to get back. For example, Status tweets can be made for Public, Friend, or User timelines. Each tweet category has a type enum to helps figure out what is available.

Just like other LINQ providers, IQueryable<T>returns from the query. You can see how to materialize the query by invoking the ToList operator. Just like other LINQ providers, LINQ to Twitter does deferred execution, so operators such as ToList and ToArray or statements such as for and foreach loops will cause the query to execute and make the actual call to Twitter.

Friends and Followers

Now to get details on these data, some other queries should be used from other classes. User class is used to get details about friends and followers:
twitterCtx = new TwitterContext(auth);

var friends =
from tweet in twitterCtx.User
where tweet.Type == UserType.Friends &&
tweet.ID == auth.UserId
select tweet;

gvFriends.DataSource = friends;

var followers =
from tweet in twitterCtx.User
where tweet.Type == UserType.Followers &&
tweet.ID == auth.UserId
select tweet;

gvFollowers.DataSource = followers;

This class contains other information related to user like Categories, Lookup and Search. This can be used the same way as Friends and followers.

Get Statuses and Retweets

To get statuses from your friends Status class can be queries, it contains different type of filters which can be included in Where clause. As an example this block of code will return statuses by friends:

twitterCtx = new TwitterContext(auth);
var tweets =
from tweet in twitterCtx.Status
where tweet.Type == StatusType.Friends
select tweet;

StatusType is an enum which can be used to get retweets by me, or retweets by specific user and also retweets by/to me/user. Nice and easy.

Update Status

Updating status is very easy and one line of the code:

twitterCtx.UpdateStatus(“New status”);

There are many overloads for this method, for example it gets inReplyToStatusId , Latitude, Longitude, placeId

How to Retweet

Again this part is very easy, only StatusID of tweet is needed:

twitterCtx = new TwitterContext(auth);

var retweet = twitterCtx.Retweet(txtStatusId.Text);

lblInfo.Text = "User: " + retweet.Retweet.RetweetingUser.Name +
" - Tweet: " + retweet.Retweet.Text +
" - Tweet ID: " + retweet.Retweet.ID

Retweet method returns a Status object which holds information related to the tweet.


Registered users can also download Linq2Twitter sample. Please register an account to get a copy.


Number of views (8917)/Comments (-)

blog comments powered by Disqus

Enter your email below AND grab your spot in our big giveaway!

The winner will receive the entire Data Springs Collection 7.0 - Designed to get your website up and running like a DNN superhero (spandex not included).

united luxury shop
konulu porno
deneme bonusu maltcasino bahis siteleri
sex video free download in mobile hot sexy naked indian girls download free xxx video
antalya escort
atasehir eskort antalya escort bahcelievler escort alanya escort atasehir escort
porno izle
gaziantep escort gaziantep escort
escort pendik
izmir escort kayseri escort gaziantep rus escort
vdcasino casino metropol casinomaxi
beylikdüzü escort