Sunday, May 02, 2010

Tweet Posting from Asp.net using OAuth - Twitterizer Tutorial

Twitter Tweet Posting from Asp.net Web Application using OAuth.

Main Steps
1) Create Twitter Application.
2) Post Tweet from Asp.net Website using Twitterizer Api

Now, lets understand each steps in more details, step by step.

Create Twitter Application
1) Open http://twitter.com/apps/new
2) Login to twitter and Fill the Application Information as follow.























 - Choose Image for your Twitter Application.
 - Fill in Twitter Application Name.
 - Description of Twitter Application
 - Fill in Application Website name, Organization























- Choose Application Type as "Browser" as we are developing asp.net website to post tweet.
- Callback Url is url where twitter would redirect after authentication.
    - Fill in rest of details as shown in figure and your Twitter Application is ready to use.























Now, lets begin the important part, how to post tweet.

Post Tweet from Asp.net Website using Twitterizer Api
1) Create Asp.net Application
2) Download Twitterizer
3) Add Reference of Twitterizer.dll files to newly created asp.net web application
4) Copy Consumer Key and Consumer Secret generated from Twitter Application.
5) Add Consumer Key and Consumer Secret to web.config file inside AppSettings

    <add key="consumerKey" value="XXXXXXXXXx"/>
    <add key="consumerSecret" value="XXXXXXXXXXXXXXXX"/>

6) In .aspx page arrange the controls as shown in figure.















7) Paste following code in "Authenticate User" Button Click event

protected void btnAuthenticate_Click(object sender, EventArgs e)
{
    // add these to web.config or your preferred location
    var consumerKey = ConfigurationManager.AppSettings["consumerKey"];
    var consumerSecret = ConfigurationManager.AppSettings["consumerSecret"];
    
    //If User is not valid user
    if (Request.QueryString["oauth_token"] == null)
    {
        //Step 1: Get Request Token
        OAuthTokenResponse RequestToken 
= OAuthUtility.GetRequestToken(consumerKey,                                                 consumerSecret);

        //Step 2: Redirect User to Requested Token
        Response.Redirect("http://twitter.com/oauth/authorize?oauth_token=" 
+ RequestToken.Token);
    }
    else
    {
        //For Valid User
        string Oauth_Token = Request.QueryString["oauth_token"].ToString();
        var accessToken = OAuthUtility.GetAccessToken(consumerKey,
                                              consumerSecret,
                                              Oauth_Token);

        lblMessage.Text = "<b>Hello " 
+ accessToken.ScreenName 
+ ", Welcome to Go4Sharepoint.com Twitter App<b>";

        lblMessage.Text += "<br/> Token: " + accessToken.Token;
        lblMessage.Text += "<br/> TokenSecret: " + accessToken.TokenSecret;
        lblMessage.Text += "<br/> UserId: " + accessToken.UserId;
    } 
}

8) Now run the application and try to click on "Authenticate User" button, it will redirect you to twitter website authenticate user and return back to your asp.net website.


















Click on Authenticate User button.













Press on Allow button after you enter your twitter login account details




















9) Create OAuthToken Object and Post Tweet.
protected void btnPostTweet_Click(object sender, EventArgs e)
{
    // add these to web.config or your preferred location
    var consumerKey = ConfigurationManager.AppSettings["consumerKey"];
    var consumerSecret = ConfigurationManager.AppSettings["consumerSecret"];
    
    OAuthTokens accessToken = new OAuthTokens();
    accessToken.AccessToken = "xxxxxxxxxxxxxxxxxxxxxxxxxxxx";
    accessToken.AccessTokenSecret = "xxxxxxxxxxxxxxxxxxxx";
    accessToken.ConsumerKey = consumerKey;
    accessToken.ConsumerSecret = consumerSecret;

    TwitterStatus TweetStatus = new TwitterStatus(accessToken);
    TweetStatus.Update(txtTweet.Text + " - http://www.Go4Sharepoint.com");                        
}

10) Type in your Message and Press "Shout on Twitter" button























Now, check your twitter account (Example here: http://twitter.com/aspnetmvp )

















Check out Live Demo of Tweet Posting from Asp.net

17 comments:

Unknown said...

how can i eliminate the allow deny screen
also if after one time authentication does tokens expires..?

DotNetGuts said...

It is not possible to avoid allow/deny screen, but you can avoid reauthenticating by storing authentication infomation in DB to access again.

Unknown said...

How do you get the lblMessage to show up? When i create a label and then authenticate it does not work. Do you have to have the btnpostMessage_Click method under the Page_Load method?

Unknown said...

Is there any possibility to release the hidden codes available in the Twitterizer dll.

Unknown said...

i am getting a 401 error

Unknown said...

Hi, I'm trying to follow your step by step. But the method "GetAccessToken(consumerKey, consumerSecret, oauthToken);" seems different now. Another parameter is asked "verifier". So we need to get a pin number, and this is my problem, I don't have any idea about how to get this pin. Do you have an advice about?

Mithun said...

i am also getting a 401 error

Anonymous said...

hii,

i implemented same code in my asp .net web page but after authentication screen its not redirecting to my web page .its redirecting to my callback url page..
how to solve plz help

Rakesh said...

Please provide latest code. Your live demo works but code shown here is old and doesn't work.

Anonymous said...

After I click allow , a pin code is generated, how do I get red of this?

Help said...

I'm trying to follow your step by step. But the method "GetAccessToken(consumerKey, consumerSecret, oauthToken);"

tell me

Anonymous said...

you have same stupid problem in your solution as i do in mine..

when the user is authenticated and your app gets the token back from the Service provider, you can store it in a db.. so that you can sign the request by this access token next time and avoid giving allow / deny screen again..

but how would you know a given user has visited your site earlier in order to get his/ her access token back from your db?
if your answer is cookie.. dumb, not a wise idea to rely on for storing that information...

i cant see a single person talking about it and everyone is just doing a lame half legged dance for oauth..

dumb ass people

DotNetGuts said...

@vsaxena Thank you for pointing out that you are the only smart people in this world ;)

The solution for this blog post is a starting point to start custom programming. I hv provided a generalize solution to smart people like you, but unfortunately even after that it is hard for you to figure out a custom solution on your own :)

This blog post is way old and lot of things have changed, its my mistake that i haven't got chance to update, but i will do that shortly.

Ok now lets talk on your custom solution, Yes you can store token and other oauth information in DB,

If you want to store that user registration for your site, you can add a field call Registration Type to your UserInfo Table, wherein you can maintain detail about login from Twitter/FB/Linkedin or through your native registration process. If user is registered using Twitter and if you are unable to find oauth information in your UserInfo Table, that means user is login for first time with twitter, then you can redirect user to your custom registration, wherein you can take information for your site and that way user can login with those credential, but if user choose to login using twitter he has go through oauth procedure.

If you want to do auto-login when user visit next time, then cookie is the answer. Now it is upto you how wisely you store the cookies info.

I hope you may see some light at end of tunnel.

Anonymous said...

@dotnetguts, thanks for your post, i appreciate.. i guess the choice is going to be to find a way to query Service Provider for the token of logged on user using my consumer key..
lets see gotta work on this tonight..

Dragon said...

how to get oauth_token which is pass in query string .

carats5 said...

in btnPostTweet_Click()
Where is the accessToken.AccessToken = "xxxxxxxxxxxxxxxxxxxxxxxxxxxx";
accessToken.AccessTokenSecret = "xxxxxxxxxxxxxxxxxxxx";
come from?

TARUN said...

Iam getting the following errors
Error 1:No overload for method 'GetRequestToken' takes 2 arguments
Error 2: No overload for method 'GetAccessToken' takes 3 arguments..
I added the references..
plz help me...
thanks in advance


Most Recent Post

Subscribe Blog via Email

Enter your email address:



Disclaimers:We have tried hard to provide accurate information, as a user, you agree that you bear sole responsibility for your own decisions to use any programs, documents, source code, tips, articles or any other information provided on this Blog.
Page copy protected against web site content infringement by Copyscape