Question

I have this piece of code:

    var settings = WebConfigurationManager.AppSettings;
    var consumerKey = settings["Twitter.ConsumerKey"];
    var consumerSecret = settings["Twitter.ConsumerSecret"];
    var authToken = settings["Twitter.OAuthToken"];
    var authVerifier = settings["Twitter.OAuthVerifier"];

    //var accessToken = GetAccessToken(
    //    consumerKey, consumerSecret, authToken, string.Empty);

    var tokens = new OAuthTokens()
    {
        AccessToken = authToken,
        AccessTokenSecret = authVerifier,
        ConsumerKey = consumerKey,
        ConsumerSecret = consumerSecret
    };

    TwitterStatus.Update(tokens, txtComment.Text);

All I need it to to is update my twitter status. Unfortunately it is not working. It only worked once when I initially logged in to twitter to grant the application access. I then stored the authToken and authVerifier so I can reuse them for future updates.

Any idea what is wrong?

UPDATE: I just changed the code to :

        TwitterResponse<TwitterStatus> tweetResponse = TwitterStatus.Update(tokens, txtComment.Text);
    if (tweetResponse.Result == RequestResult.Success)
        lblMessage.Text = "Twitter status successfully posted.";
    else
        lblMessage.Text = string.Format("Twitter status update failed with Error: '{0}'",
            tweetResponse.ErrorMessage);

and I get an error message: "Invalid / expired token".

Was it helpful?

Solution

You are storing the wrong values. The authToken and verifier values need to be quickly exchanged for an access token using OAuthUtility.GetAccessToken(...). The access token that is returned from that method is what should be stored and supplied to Twitterizer.

-Ricky
The Twitterizer Author

OTHER TIPS

I wanted to be able to make a simple status update from C#/.NET, but didn't want to embed a big library.

So I wrote a small OAuth.Manager class that does this stuff.

It's described here:
OAuth with Verification in .NET

Sample code to update status:

var oauth = new OAuth.Manager(); 
oauth["consumer_key"] = CONSUMER_KEY; 
oauth["consumer_secret"] = CONSUMER_SECRET; 
oauth["token"] = your_stored_access_token; 
oauth["token_secret"] = your_stored_access_secret; 
var url = "http://api.twitter.com/1/statuses/update.xml?status=Hello+World";
var authzHeader = oauth.GenerateAuthzHeader(url, "POST"); 

var request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "POST";
request.Headers.Add("Authorization", authzHeader);
using (var response = (HttpWebResponse)request.GetResponse())
{
    if (response.StatusCode != HttpStatusCode.OK)
        MessageBox.Show("There's been a problem trying to tweet:" +
                        Environment.NewLine +
                        response.StatusDescription +
                        Environment.NewLine +
                        Environment.NewLine +
                        "You will have to tweet manually." +
                        Environment.NewLine);
}

For the first time through, you need to get an access token and secret. This is done in a multi-step process, starting with this code:

var oauth = new OAuth.Manager();
oauth["consumer_key"] = MY_APP_SPECIFIC_KEY;
oauth["consumer_secret"] = MY_APP_SPECIFIC_SECRET;
oauth.AcquireRequestToken("https://api.twitter.com/oauth/request_token", "POST"); 

Step 2 is to tell the user** to visit https://api.twitter.com/oauth/authorize?oauth_token=XXXX where xxxx is replaced with the actual token received, accessible in this case by oauth["token"]. Step 3 is to tell the user to grab (ctrl-c) the PIN from the webpage and paste it into your app, where you use the pin to get another type of token.

A better way is to automate that web UI sequence by using a Windows Form with an embedded WebBrowser control. When you set the Url property of that control to the appropriate value, it will show that webpage for you, inside the main form of your own app. You can also automate the part where you retrieve the PIN. This reduces context switches for your user and makes things simpler to understand.

Anyway, with the pin you do, step 4:

oauth.AcquireAccessToken("https://api.twitter.com/oauth/access_token",
    "POST",
    pin); 

...which sends out another HTTP REST request, and when it returns you will have an accesss token and secret, available in oauth["token"] and oauth["token_secret"].

This authorization stuff with the web UI needs to happen only once; after you get the access token and secret once, you can store them and re-use them. They never expire, says Twitter.

You can then proceed to sending the status update...

var url = "http://api.twitter.com/1/statuses/update.xml?status=Hello+World";
var authzHeader = oauth.GenerateAuthzHeader(url, "POST"); 
...

...as above.

I know I am late to the game, but I created an end-to-end video tutorial showing exactly how to do this: I create an application on dev.twitter.com, install twitterizer using nuget, write the code to handle the oauth and finally write the code to use the access tokens received from twitter to make a tweet.

Video: http://www.youtube.com/watch?v=TGEA1sgMMqU

Tutorial: http://www.markhagan.me/Samples/Grant-Access-And-Tweet-As-Twitter-User-ASPNet

Code (in case you don't wan to leave this page):

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

using Twitterizer;

namespace PostFansTwitter
{
    public partial class twconnect : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            var oauth_consumer_key = "YOUR_CONSUMER_KEY_HERE";
            var oauth_consumer_secret = "YOUR_CONSUMER_SECRET_KEY_HERE";

            if (Request["oauth_token"] == null)
            {
                OAuthTokenResponse reqToken = OAuthUtility.GetRequestToken(
                    oauth_consumer_key,
                    oauth_consumer_secret,
                    Request.Url.AbsoluteUri);

                Response.Redirect(string.Format("http://twitter.com/oauth/authorize?oauth_token={0}",
                    reqToken.Token));
            }
            else
            {
                string requestToken = Request["oauth_token"].ToString();
                string pin = Request["oauth_verifier"].ToString();

                var tokens = OAuthUtility.GetAccessToken(
                    oauth_consumer_key,
                    oauth_consumer_secret,
                    requestToken,
                    pin);

                OAuthTokens accesstoken = new OAuthTokens()
                {
                    AccessToken = tokens.Token,
                    AccessTokenSecret = tokens.TokenSecret,
                    ConsumerKey = oauth_consumer_key,
                    ConsumerSecret = oauth_consumer_secret
                };

                TwitterResponse<TwitterStatus> response = TwitterStatus.Update(
                    accesstoken,
                    "Testing!! It works (hopefully).");

                if (response.Result == RequestResult.Success)
                {
                    Response.Write("we did it!");
                }
                else
                {
                    Response.Write("it's all bad.");
                }
            }
        }
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top