.Net Console App Access Token

Dec 3, 2010 at 10:32 PM

How can i create and use access token (oauth) to use in my console app with LinqToTwitter. I am using released v2.0.17 Bet.

Coordinator
Dec 4, 2010 at 3:42 AM
Edited Dec 4, 2010 at 6:41 PM

Hi,

Look at the Program.cs file in the LinqToTwitterDemo project.  Main starts with a Public query demo that doesn't require authentication, but the following part of the code has an OAuth demo.  It uses PinAuthorizer, which is appropriate for console or any desktop application.  The demo loads initial credentials from the configuration file which starts the initial authorization process.  If this is the first time a user uses your application, this would be appropriate.  However, it's not necessary (as you probably already know) if the user uses your application subsequent times.  You want to just load credentials for that user, bypassing the OAuth authentication process and proceeding with normal queries as the application needs.  Fortunately, Twitter will always return the same OAuth Token and Access Token for each user.  Here are a few tips to help manage those subsequent operations without needing to authorize your application again:

1. Save user credentials for the user after the first Twitter OAuth authentication.  There are two ways to do this:

  • Read PinAuthorizer.Credentials properties: ConsumerKey, ConsumerSecret, OAuthToken, and AccessToken.  Really, all you need is the OAuthToken and AccessToken because the ConsumerKey and ConsumerSecret belong to your application, not the user.
  • Use the PinAuthorizer.Credentials.ToString() to get a comma-separated list of credential properties.

2. On subsequent application operations, load PinAuthorizer.Credentials properties with values that you saved for that user.  You would probably store these in a database and retrieve them when the user logs into your application.  Alternatively, you can use the PinAuthorizer.Credentials.Load method, which accepts a comma-separated string to load into the Credentials class properties for you.  If you've saved the values from ToString(), the same string will work with Load.  Once the credentials are set, assign the PinAuthorizer that holds the credentials to TwitterContext and then perform queries as normal.

If you, or anyone else, has suggestions on how to make this easier, let me know.  This was my first approach and I wanted to start off simple and wait for feedback on the direction that users would like for me to go with this.

Joe

Dec 6, 2010 at 6:15 PM

Hi,

It works very well. I ll really appreciate it. i have few questions more.

For every use i have to get aToken and oToken and retrieve data ?

what's different in Twitter user and handle (@handle), like below

http://twitter.com/JoeMayo

https://twitter.com/#!/JoeMayo

@JoeMayo

I am also checking streaming demo. how can i get streamingUserName and streamingPassword ?

I am really looking forward LinqToTwitter documentation and final release.

 

Regards,

Shahid

 

Coordinator
Dec 7, 2010 at 4:54 AM

Good to hear you got it working.  Here are some answers to your questions.

The basic requirement is that the TwitterContext have an IOAuthAuthorizer derived type with a populated Credentials property.  The answer to your question has more to do with application statefullness than anything else.  For example, desktop applications are stateful, so you would instantiate a PinAuthorizer that would be held in memory and reused for all operations.  However, in a Web application, you must instantiate and initialize all your objects on every request.  In ASP.NET objects such as Request, Response, and so on are created behind the scenes and it feels like the application has state, but it really doesn't because ASP.NET instantiates and populates all of it's intrinsic objects too.  The current LINQ to Twitter OAuth implementation makes the loading of the IOAuthAuthorizer explicit, so that when you instantiate a WebAuthorizer, you must also populate it's properties.  Feedback is welcome if you or others have ideas on how to do it better.

Those URLs are unique to Twitter's Web page and have a meaning specific to that application.  They aren't applicable to the Twitter API, which means that LINQ to Twitter would have no reason to use them.  The current base URL for the Twitter API is http://api.twitter.com/1/ (or https)  Twitter is using the user's ScreenName to navigate to pages and as an address within Twitter.  Whenever you see the @UserName, you can use UserName as the ScreenName when using LINQ to Twitter.

In the streaming APIs that use basic authentication, streamingUserName and streamingPassword are the user's user name and password they use to log into Twitter.

Joe

Jan 25, 2013 at 4:11 AM
JoeMayo wrote:

Hi,

Look at the Program.cs file in the LinqToTwitterDemo project.  Main starts with a Public query demo that doesn't require authentication, but the following part of the code has an OAuth demo.  It uses PinAuthorizer, which is appropriate for console or any desktop application.  The demo loads initial credentials from the configuration file which starts the initial authorization process.  If this is the first time a user uses your application, this would be appropriate.  However, it's not necessary (as you probably already know) if the user uses your application subsequent times.  You want to just load credentials for that user, bypassing the OAuth authentication process and proceeding with normal queries as the application needs.  Fortunately, Twitter will always return the same OAuth Token and Access Token for each user.  Here are a few tips to help manage those subsequent operations without needing to authorize your application again:

1. Save user credentials for the user after the first Twitter OAuth authentication.  There are two ways to do this:

  • Read PinAuthorizer.Credentials properties: ConsumerKey, ConsumerSecret, OAuthToken, and AccessToken.  Really, all you need is the OAuthToken and AccessToken because the ConsumerKey and ConsumerSecret belong to your application, not the user.
  • Use the PinAuthorizer.Credentials.ToString() to get a comma-separated list of credential properties.

2. On subsequent application operations, load PinAuthorizer.Credentials properties with values that you saved for that user.  You would probably store these in a database and retrieve them when the user logs into your application.  Alternatively, you can use the PinAuthorizer.Credentials.Load method, which accepts a comma-separated string to load into the Credentials class properties for you.  If you've saved the values from ToString(), the same string will work with Load.  Once the credentials are set, assign the PinAuthorizer that holds the credentials to TwitterContext and then perform queries as normal.

If you, or anyone else, has suggestions on how to make this easier, let me know.  This was my first approach and I wanted to start off simple and wait for feedback on the direction that users would like for me to go with this.

Joe

Hi, Joe.

thanks for answer how to save PinAuthorizer, but when I loaded it when reopen my app(WP7) with PinAuthorizer.Credentials.Load method , and then try to post a twitter ,with my code:

      pa = new PinAuthorizer()
            {
                Credentials = new InMemoryCredentials
                {
                    ConsumerKey = AppConfigHelper.GetConfigValue("twitterConsumerKey"),
                    ConsumerSecret = AppConfigHelper.GetConfigValue("twitterConsumerSecret"),
                },
                UseCompression = true,
            };
            pa.Credentials.Load(content);//content =PinAuthorizer.Credentials.ToString() when first authenticated.

      ITwitterAuthorizer auth = pa ;

            var twitterCtx = new TwitterContext(auth);
            twitterCtx.UpdateStatus(phoneTextBox1.Text);

it throw an exception:The remote server returned an error: NotFound.

 

I want to why. 

 

THX. 

Coordinator
Jan 25, 2013 at 6:00 AM

Hi,

Sometimes the NotFound isn't the true error.  It might mean that you're trying to tweet the same test message more than one time - because duplicates aren't allowed. Watching the HTTP traffic with Fiddler or looking around at other fields in the exception message might provide more info. Stepping through code will indicate which line the problem occurs at and Fiddler will confirm the exact query that's causing the problem. The Fiddler response provides the message specifically from Twitter.

Another thing I noticed is that you're loading Credentials after assigning them to PinAuthorizer. There's a sequencing glitch where you should either load credentials while constructing the authorizer or instantiate credentials and load before assigning to the authorizer's Credentials property.

@JoeMayo

Jan 25, 2013 at 6:23 AM

Thanks for reply with a wonderful sln. I found you another answer in http://linqtotwitter.codeplex.com/discussions/389539.

Thx again.

 

Jan 27, 2013 at 9:40 AM
JoeMayo wrote:

Hi,

Sometimes the NotFound isn't the true error.  It might mean that you're trying to tweet the same test message more than one time - because duplicates aren't allowed. Watching the HTTP traffic with Fiddler or looking around at other fields in the exception message might provide more info. Stepping through code will indicate which line the problem occurs at and Fiddler will confirm the exact query that's causing the problem. The Fiddler response provides the message specifically from Twitter.

Another thing I noticed is that you're loading Credentials after assigning them to PinAuthorizer. There's a sequencing glitch where you should either load credentials while constructing the authorizer or instantiate credentials and load before assigning to the authorizer's Credentials property.

@JoeMayo

Hi, I coma again.

em, I found some demo code in ConsoleAccountDemo :

     void VerifyAccountCredentials(TwitterContext twitterCtx)
        {
            var accounts =
                from acct in twitterCtx.Account
                where acct.Type == AccountType.VerifyCredentials
                select acct;

            try
            {
                Account account = accounts.SingleOrDefault();
                User user = account.User;
                Status tweet = user.Status ?? new Status();

                Console.WriteLine(
                    "User ID: {0}\nScreen Name: {1}\nTweet: {2}\n Tweet ID: {3}",
                     user.Identifier.ID,
                     user.Identifier.ScreenName,
                     tweet.Text, 
                     tweet.StatusID);

                Console.WriteLine("Account credentials are verified.");
            }
            catch (WebException wex)
            {
                Console.WriteLine(
                    "Twitter did not recognize the credentials. Response from Twitter: " 
                    + wex.Message);
            }
        }

But when I new an instace of PinAuthorizer in LinqToTwitter WP v2.0.28.0, to use these code to get my twitter account Name (the screenName )

                            var accounts = from acct in ctx.Account
                                           where acct.Type == AccountType.VerifyCredentials
                                           select acct;
                            Account account = accounts.SingleOrDefault();
                            User user = account.User;
                            ((TwitterAccount)App.AcconutsVM.CurrentOpratance).TwitterAuthorizer = pinAuth;

it threw an exception ,said the

account is NULL,I think some differences between in WP version and PC version?
Wait for answers.Thanks again.
Coordinator
Jan 27, 2013 at 6:47 PM

All the console demos have been upgraded to work with Twitter API v1.1, which is LINQ to Twitter v2.1.0.1 and above. The old API v1.0 is deprecated and no longer supported by Twitter - they will turn it off in March. l It would be better to upgrade to the current version, v2.1.0.3, which is available on this site or via NuGet.

@JoeMayo

Jan 28, 2013 at 3:46 AM

Thanks again, I get latest version from NuGet. It help me a lot.Thanks again.

 

FYI.

Jan 28, 2013 at 3:46 PM
JoeMayo wrote:

All the console demos have been upgraded to work with Twitter API v1.1, which is LINQ to Twitter v2.1.0.1 and above. The old API v1.0 is deprecated and no longer supported by Twitter - they will turn it off in March. l It would be better to upgrade to the current version, v2.1.0.3, which is available on this site or via NuGet.

@JoeMayo

Em, I researched some source code in WP version of LinqToTwitter, I found that this version only support One Twitter Account saved in device in IsolatedStorageCredentials.cs ,I saw you saved token and sreenname in a txt file named "Linq2TwitterCredentials.txt", I think it is a good method, but maybe we should support muti-account in one device?

That is a simple idea, I am not experienced in coding, but I learned a lot from the LinqToTwitter, Thanks a lot for making so great tool for developers.

Jan 28, 2013 at 3:52 PM
zgwjms wrote:
JoeMayo wrote:

All the console demos have been upgraded to work with Twitter API v1.1, which is LINQ to Twitter v2.1.0.1 and above. The old API v1.0 is deprecated and no longer supported by Twitter - they will turn it off in March. l It would be better to upgrade to the current version, v2.1.0.3, which is available on this site or via NuGet.

@JoeMayo

Em, I researched some source code in WP version of LinqToTwitter, I found that this version only support One Twitter Account saved in device in IsolatedStorageCredentials.cs ,I saw you saved token and sreenname in a txt file named "Linq2TwitterCredentials.txt", I think it is a good method, but maybe we should support muti-account in one device?I found you set a method to custom save by developer, but will be there a better method in the LinqToTwitter?

That is a simple idea, I am not experienced in coding, but I learned a lot from the LinqToTwitter, Thanks a lot for making so great tool for developers.

 

Coordinator
Jan 28, 2013 at 3:56 PM

There are many different technologies and ways that people want to store credentials. Recognizing this, I created the IOAuthCredentials interface, which is the type of the Credentials property of a class that implements ITwitterAuthorizer. Therefore, anyone can create a class that implements IOAuthCredentials and provide an implementation that works for them. There are several examples in the LINQ to Twitter source code that will give you ideas on how to implement your own type that implements IOAuthCredentials.

@JoeMayo

Jan 29, 2013 at 2:49 AM

Hi,

you are right, I am working to storage muti-account in local device. I will research IOAuthCredentials more. THX.