Sudhindra Kovalam's Blog

My Geeky Blog

A Windows Phone 7 Twitter Application : Part 1 of 2 (Understanding oAuth)

with 58 comments

(Update : For trying out code posted on this blog post, Kindly use the official/ locked emulator . The unlocked emulator images have a known issue with HTTPS )

As Promised in the previous post(I Know it was very long ago), We will try to build a Twitter application. Building a twitter app is a very easy task, and this post intends to guide you Step by step in creating your first twitter application. This post will speak about getting the app authenticated/authorized using the oAuth Mechanism.
The target platform is Windows Phone 7  in  this post, but you can pretty much a build a twitter app on any other platform based on this tutorial
Step 1: Register Your Twitter app on dev.twitter.com
Twitter needs to know that You are writing an app which accesses/posts tweets on your behalf. You tell this to twitter by registering your app on twitter.
image
twitterAppRegistration
When Registering your app, ensure that You set the Application type to browser and specify a call-back URL. (Twitter has certain requirements on Call-back URLs, i.e. it will not accept non HTTP URLs ( You need to ask twitter specially for  that ). For Demo purposes, i have specified Google.com as my default call-back URL.You can specify your custom page hosted on your domain, if you want to
This is how your app settings on twitter would look like:
AppSettings
Make a note of the highlighted URLs and your consumer key and secret.( Wondering what these are? Continue Reading or Read about oauth here)
Now comes the fun part, As usual fire up Visual studio 2010. Do a File | New Project. Select a Windows Phone Application from Silverlight for Windows Phone Section.
Twitter exposes a RESTful Service to access a user’s tweets etc. Twitter as of now only allows oAuth and XAuth as the only authorization mechanism. Since we have to have to consume a REST service along with oAuth, we will be  using a REST Client helper, that abstracts a lot of the hard work for me. (Such as adding the necessary headers, Computing oAuth Parameters such as Signature, Nonce, Timestamp etc. etc.)
For this demo, we’d be using the Hammock REST client available for download here. (Ohh BTW, Hammock is a very good example as to how same source code can target multiple platforms and multiple .net versions. Curious , about knowing how ? Go straight to the site and download the source code and have a look for yourselves.)
Now Lets get our hands dirty with some code for our first Twitter Application on Windows Phone 7 Smile
First Using the consumer Key and consumer key secret that you got by registering your application on twitter’s site, you need to request for a request token and request token secret
Request Token and request token secret are temporary set of credentials that let you acquire oauth access Tokens. The access token and access token secret are needed to access a user’s tweets.
To do this, I will use some neatly written helper classes in the Hammock library.( Else I would be actually writing code to do a lot of ugly stuff)

 var oauth = new OAuthWorkflow
{
     ConsumerKey = TwitterSettings.consumerKey,
     ConsumerSecret = TwitterSettings.consumerKeySecret,
     SignatureMethod = OAuthSignatureMethod.HmacSha1,
     ParameterHandling = OAuthParameterHandling.HttpAuthorizationHeader,
     RequestTokenUrl = TwitterSettings.RequestTokenUri,
     Version = TwitterSettings.oAuthVersion,
     CallbackUrl = TwitterSettings.CallbackUri
};

var info = oauth.BuildRequestTokenInfo(WebMethod.Get);
var objOAuthWebQuery = new OAuthWebQuery(info);
objOAuthWebQuery.HasElevatedPermissions = true;
objOAuthWebQuery.SilverlightUserAgentHeader = "Hammock";
objOAuthWebQuery.SilverlightMethodHeader = "GET";

What this helper class does is, hide a lot of stuff from the end user that needs to be done to acquire the request token and secret. Using the oauth WebQuery object all i have to do is to instantiate  a Hammock Rest Client object to fire a request to twitter’s servers.

 var requestTokenQuery = oAuthHelper.GetRequestTokenQuery();
 requestTokenQuery.RequestAsync(TwitterSettings.RequestTokenUri, null);
 requestTokenQuery.QueryResponse += new EventHandler(requestTokenQuery_QueryResponse);
In the response received event, I parse the response sent across by twitter. This should have the request token and request token secret in the response body.
var parameters = HelperMethods.GetQueryParameters(e.Response);
OAuthTokenKey = parameters["oauth_token"];
tokenSecret = parameters["oauth_token_secret"];
var authorizeUrl = TwitterSettings.AuthorizeUri+ "?oauth_token=" + OAuthTokenKey;

Now using the request token and secret, we need to get our app authorized to read/write data from the end user’s twitter account. To do this, we need to open a web browser and redirect the end user to twitter’s sign-in/ authorize page. To do this, I will be using a Web browser control and redirecting it to the authorize URL I have created above.

Dispatcher.BeginInvoke(() =>
{
      this.objAuthorizeBrowserControl.Navigate(new Uri(authorizeUrl));
});
The XAML for the browser control would look something like this:







The User sees the twitter page, where s/he signs in to twitter. Here, s/he is asked to authorize our twitter app.
twiiter_HomeScreentwitter_startScreentwitter_signIntwitter_signIn_2tiwtter_authorize
After you have authorized the application to access your data on your behalf, twitter will send the oauth request token (you received in the previous step) and a verification pin. Using these tokens, you can now request for the access token and access token secret. ( Arrgh!!! another set of tokens….)
Using the Hammock helper class that we used to get request tokens, we can acquire Access tokens as follows:
 var AuthorizeResult = HelperMethods.GetQueryParameters(e.Uri.ToString());
var VerifyPin = AuthorizeResult["oauth_verifier"];
this.objAuthorizeBrowserControl.Visibility = Visibility.Collapsed;

//We now have the Verification pin
//Using the request token and verification pin to request for Access tokens

var AccessTokenQuery = oAuthHelper.GetAccessTokenQuery(
                                             OAuthTokenKey,     //The request Token
                                             tokenSecret,       //The request Token Secret
                                             VerifyPin         // Verification Pin
                                          );

AccessTokenQuery.QueryResponse += new EventHandler(AccessTokenQuery_QueryResponse);
AccessTokenQuery.RequestAsync(TwitterSettings.AccessTokenUri, null);
In response twitter sends us the access tokens, the userID and the user’s screen name. I am going to store ‘em all, (Can prove to be very handy.)
var parameters = HelperMethods.GetQueryParameters(e.Response);
 accessToken = parameters["oauth_token"];
accessTokenSecret = parameters["oauth_token_secret"];
userID = parameters["user_id"];
userScreenName = parameters["screen_name"];

HelperMethods.SetKeyValue("AccessToken", accessToken);
HelperMethods.SetKeyValue("AccessTokenSecret", accessTokenSecret);
Dispatcher.BeginInvoke(() =>
{
    MenuItemSignIn.IsEnabled = false;
    MenuItemSignOut.IsEnabled = true;
    TweetButton.IsEnabled = true;
});
Phew!!! Now we are authenticated. We can now use the tokens we have received till now and the app can now access the user’s data(such as tweets, timeline etc.)
About these ads

Written by sudheerkovalam

August 28, 2010 at 7:58 am

58 Responses

Subscribe to comments with RSS.

  1. I downloaded the unlocked emulator and still got the same exception KeyNotFound please help me out.I am facing this issue since long time

    Vimal

    November 30, 1999 at 12:00 am

  2. [...] A Windows Phone 7 Twitter Application : Part 1 of 2 (Understanding oAuth) « Sudhindra Kovalam&… [...]

    sss | Viddler

    August 28, 2010 at 4:52 pm

  3. [...] A Windows Phone 7 Twitter Application : Part 1 of 2 (Understanding oAuth) « Sudhindra Kovalam&… [...]

    Vanquish Trailer | Viddler

    August 28, 2010 at 4:53 pm

  4. [...] This post was mentioned on Twitter by Indrajit Chakrabarty, coelacanth, Ginny Caughey, Indrajit Chakrabarty, Larry King and others. Larry King said: A Windows Phone 7 Twitter Application : Part 1 of 2 (Understanding … http://bit.ly/cMZAmY #SL #RIA [...]

  5. [...] A Windows Phone 7 Twitter Application : Part 1 of 2 (Understanding oAuth) « Sudhindra Kovalam&… [...]

    ooo01 | Viddler

    August 29, 2010 at 12:48 am

  6. [...] A Windows Phone 7 Twitter Application : Part 1 of 2 (Understanding oAuth) « Sudhindra Kovalam&… [...]

  7. Do you have a code sample available to download?
    I’m confused on the step after the user sets credentials in browser, what event is used to trap the data sent back from twitter?

    thanks,
    Sam

    Sam Jarawan

    September 2, 2010 at 6:22 pm

    • Yes I do, In fact, i do intend to post the entire solution in the part 2 blog post.

      sudheerkovalam

      September 3, 2010 at 1:12 am

  8. [...] Part 1: Understanding oAuth [...]

    • Great article Sudheer!

      Looking forward to part two..

      -Don Burnett

      Expression Blend MVP 2010

      Don Burnett

      September 6, 2010 at 12:17 am

  9. I just reviewed the code that you have posted in the zip file.. There are several issues with the project that I had to correct right away…

    1) there is a deleted reference to MSCORLIB that causes an error related not to be able to load the system.object. The reference doesn’t even show up in the project. This cannot be easily fixed in VS2010, but can be fixed in Blend which will modify the project file if you load it into Blend for Windows Phone and re-add the reference there.

    2) there is a problem is with the WMAPPManifest.xml file found in the properties folder. If you replace it with the one that you’ll find in the generic project then project will load and compile..

    Don Burnett

    September 6, 2010 at 3:08 am

    • Hi Don,
      I do realize the issues you are seeing are due to intermediate TAP build of the SDK I am on,
      I apologize for the inconvenience. Will update the code snippet ASAP :)

      sudheerkovalam

      September 6, 2010 at 7:44 am

  10. [...] Post(s) in this series: Part 1: Understanding oAuth [...]

  11. It’s glad to see that sudheerkovalam have admitted his mistake and appreciable to solve Don’s problem. Well, I am completely indulge in Twitter based applications and enjoying the twitter as marketing account where my followers follow me and they can be followed automatically, it’s available at Google by “marketontwitr”.

    Cheers.

    twitter app

    September 8, 2010 at 8:12 am

  12. This site just created my week! I had been searching close to for information on this. I’m glad now that I ran across this webpage. Woohoo!

  13. Thank you very much my friend, you are very kind in sharing this useful information with? others…. he details were such a blessing, thanks.

    Marie Chelle

    September 14, 2010 at 8:43 pm

  14. Thanks for this post.

    I’m testing the code you posted – and altered the API keys as needed. When i click the sign-in I get a “KeyNotFoundException”.

    No login screen is ever presented.

    The exception occurs because the Parameters object is empty ( var parameters = HelperMethods.GetQueryParameters(e.Response);)

    I’m thinking that something else is going on… as I can’t see where the login screen should be displayed.

    Any advice?

    Thanks

    liam

    October 2, 2010 at 11:32 pm

    • I had the same exception. I corrected this error bij changing mine settings on dev.twitter.com. I get this exception when the application type is set on client.

      bas

      October 5, 2010 at 2:51 pm

      • Unfortunately… APP settings are already set to Browser. Thanks for the suggestion.

        liam

        October 5, 2010 at 4:00 pm

  15. OK…. so further testing.. and of course I figured out what is supposed to be happening. The first “request_token” call results in no content back from Twitter and the status of “NotFound”. I can’t see anything wroing with my ConsumerKey or ConsumerSecret… anyone know what might be happening? Thanks!

    -Liam

    liam

    October 4, 2010 at 3:47 am

    • Hi Liam, Sorry about the delayed reply.
      I am not able to reproduce your problem!

      sudheerkovalam

      October 4, 2010 at 3:46 pm

      • hi guys,

        i am also facing same problem as liam…………KeyNotFoundException…………..
        any one solved this problem

        pandhari

        October 7, 2010 at 4:41 pm

      • Hi Pandhari, thnx for downloading the code.

        I double checked,
        I put my consumer key and consumer key secret values in twittersettings.cs and everything works like a charm. what seems to be the problem.

        sudheerkovalam

        October 8, 2010 at 1:21 am

  16. hi,
    i got following exception when i click on sign in.

    {System.Net.WebException: The remote server returned an error: NotFound. —> System.Net.WebException: The remote server returned an error: NotFound.
    at System.Net.Browser.ClientHttpWebRequest.InternalEndGetResponse(IAsyncResult asyncResult)
    at System.Net.Browser.ClientHttpWebRequest.c__DisplayClass5.b__4(Object sendState)
    at System.Net.Browser.AsyncHelper.c__DisplayClass2.b__0(Object sendState)
    at System.Reflection.RuntimeMethodInfo.InternalInvoke(RuntimeMethodInfo rtmi, Object obj, BindingFlags invokeAttr, Binder binder, Object parameters, CultureInfo culture, Boolean isBinderDefault, Assembly caller, Boolean verifyAccess, StackCrawlMark& stackMark)
    at System.Reflection.RuntimeMethodInfo.InternalInvoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture, StackCrawlMark& stackMark)
    at System.Reflection.MethodBase.Invoke(Object obj, Object[] parameters)
    at System.Delegate.DynamicInvokeOne(Object[] args)
    at System.MulticastDelegate.DynamicInvokeImpl(Object[] args)
    at System.Delegate.DynamicInvoke(Object[] args)
    at System.Windows.Threading.Dispatcher.c__DisplayClass1.b__0()
    at System.Reflection.RuntimeMethodInfo.InternalInvoke(RuntimeMethodInfo rtmi, Object obj, BindingFlags invokeAttr, Binder binder, Object parameters, CultureInfo culture, Boolean isBinderDefault, Assembly caller, Boolean verifyAccess, StackCrawlMark& stackMark)
    at System.Reflection.RuntimeMethodInfo.InternalInvoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture, StackCrawlMark& stackMark)
    at System.Reflection.MethodBase.Invoke(Object obj, Object[] parameters)
    at System.Delegate.DynamicInvokeOne(Object[] args)
    at System.MulticastDelegate.DynamicInvokeImpl(Object[] args)
    at System.Delegate.DynamicInvoke(Object[] args)
    at System.Windows.Threading.DispatcherOperation.Invoke()
    at System.Windows.Threading.Dispatcher.Dispatch(DispatcherPriority priority)
    at System.Windows.Threading.Dispatcher.OnInvoke(Object context)
    at System.Windows.Hosting.CallbackCookie.Invoke(Object[] args)
    at System.Windows.Hosting.DelegateWrapper.InternalInvoke(Object[] args)
    at System.Windows.RuntimeHost.ManagedHost.InvokeDelegate(IntPtr pHandle, Int32 nParamCount, ScriptParam[] pParams, ScriptParam& pResult)

    at System.Net.Browser.AsyncHelper.BeginOnUI(SendOrPostCallback beginMethod, Object state)
    at System.Net.Browser.ClientHttpWebRequest.EndGetResponse(IAsyncResult asyncResult)
    at Hammock.Web.WebQuery.GetAsyncResponseCallback(IAsyncResult asyncResult)
    at System.Net.Browser.ClientHttpWebRequest.c__DisplayClassd.b__b(Object state2)
    at System.Threading.ThreadPool.WorkItem.doWork(Object o)
    at System.Threading.Timer.ring()
    }

    pandhari

    October 7, 2010 at 4:50 pm

  17. hi got solution .

    there is problem for unlock emulator to use https link because it requires the certificate .

    so try this application on offical emulator……………………huuuuuuuuuuuuuuuuuuuu

    pandhari

    October 8, 2010 at 6:51 am

    • ohh!! o u were using the unlocked emulator eh!!
      Your’s and liam’s comments had me worried about this demo app !

      sudheerkovalam

      October 8, 2010 at 7:54 am

    • Hii I hav downloaded the same code from sudheer kovalam blog and got the same exception “KeyNotFound”. I am using the Emulator which was downloaded from the official microsoft site.
      I am not able to find out diff between locked/unlocked emulators.
      Plz any one help me on this.

      Thanks in adv
      Kishor chandra

      kishor chandra

      April 25, 2011 at 7:32 am

  18. Brilliant detective work. I had no idea using the unlocked emulator would have any impact on this (I need some features of the unlocked emulator for my Apps… but I’ll switch back to try this out). Thanks again.

    liam

    October 8, 2010 at 8:43 am

  19. So yep…. that was it. THANKS!!! I am a happy dude. You guys are awesome.

    liam

    October 8, 2010 at 8:59 am

  20. And now of course I see the big message at the top of this post about using the locked emulator. Did I miss that before (that would be normal for me :-)

    liam

    October 8, 2010 at 9:02 am

  21. Thanks for the code!

    Tejji Zip Code

    tejji

    October 23, 2010 at 2:57 am

  22. I don’t even know how I ended up here, but I thought this post was interesting. Cheers!

    Matt Rogers

    November 1, 2010 at 3:24 pm

  23. Have you ever regarded as including a lot more videos for your weblog posts to maintain the readers a lot more entertained? I imply I just read via the entire write-up of yours and it was rather great but due to the fact I’m additional of a visual learner,I found that to be more useful. Just my my idea, Great luck

    glee music

    December 6, 2010 at 5:20 am

  24. Hi,

    So is this using a web browser control to carry out the auth? – if so is there a way to do this using a couple of text boxes and a button?

    Super

    December 9, 2010 at 5:28 pm

    • The Point of OAuth is that the application developer should not get access to end user’s username and password.
      This way, the developer can be transparent to the authentication process and the end user is comfortable using your app since, s/he is entering username/pwd on
      twitter’s page and not your app.
      So, the answer to your question is “NO”

      Ping me back if you have more comments :)

      sudheerkovalam

      December 10, 2010 at 3:10 am

      • Actually, that’s possible if you convince Twitter to let you use xAuth. Their developer site has instructions on how to contact them with your app’s information so they can review your request. Not sure how many apps pass this process

        Sriram Krishnan

        November 30, 1999 at 12:00 am

      • did i say, not possible? i am mistaken in that case.

        sudheerkovalam

        December 27, 2010 at 10:12 am

  25. Understood, thanks.

    I have just tried running this app but unfortunately the TwitterAccess var is always null – the store never seems contain the value:

    public static T LoadSetting(string fileName)
    {
    using (var store = IsolatedStorageFile.GetUserStoreForApplication())
    {
    if (!store.FileExists(fileName)) // TwitterAccess is always null

    Any thoughts?

    Super

    December 10, 2010 at 9:36 am

  26. Hi this really nice,

    But I have problem with CallbackURL, I used my server URL. and I found that it is not firing webBrowser1_ScriptNotify method from Java script. What I have to do. Please help me!!

    Naga Harish Movva

    December 29, 2010 at 7:19 pm

    • Have You set the Script Enabled property for your browser control ?

      sudheerkovalam

      December 30, 2010 at 3:15 am

  27. some really great info , Gladiola I detected this.

    Augustine Evaristo

    February 10, 2011 at 8:42 am

  28. nice blog nice info any good stuff thank you very much well done

    mobilefanatics

    April 21, 2011 at 8:44 am

  29. Hi sudheer…
    when i call a https enabled java webservice in asp.net its working fine and i am using servicepoint manager to jump over the certificate issue. But when i try to run the same code in wp7 i am not able to communicate the webservice and getting an error : REMOTE SERVER NOT FOUND. And also i am not able to add cookie to my httprequest header.

    Suresh

    June 2, 2011 at 11:05 am

    • Please post some code so that it could help eveyrone

      sudheerkovalam

      June 5, 2011 at 6:31 am

  30. unable to call a https webservice from wp7.Service point manager is not available. the same service works fine in asp.net.

    Suresh

    June 2, 2011 at 11:14 am

    • Can you post some code?

      sudheerkovalam

      June 5, 2011 at 6:31 am

  31. Hi I am Rachit. When i run the above app then we got login successfully but the signout and post tweet buttons are not going to visible. By using breakpoint i tested so many times but the controls never comes in those functions in which the code resides. So please tell me where is the problem.

    Thanks in advance
    Rachit

    Rachit Gaur

    July 26, 2011 at 11:11 am

  32. Do you know any payment gateway used in wp7 apps…
    Its urgent if anybody know then please tell me.

    thanks in advance
    Rachit

    Rachit Gaur

    July 26, 2011 at 11:24 am

  33. Extremely absorbing blog column.

    Norine Morey

    July 27, 2011 at 12:06 am

  34. Excellent article over again. I am looking forward for more updates=)

  35. wow.. this is what i am searching for.. nice post, i need something like this :D thanks.

    LM Kurt

    September 5, 2011 at 1:38 am

  36. Hi,

    Thanks for such a great article. I have used the details but i am not getting this done. I have intigrate code but when i run this project in phone, it shows blank black screen. The project is not showing any error. i have update the keys.

    What i am missing? DLL ? or someother issue? Please help me.

    David Jacob

    February 17, 2012 at 12:11 pm

  37. [...] A Windows Phone 7 Twitter Application : Part 1 of 2 (Understanding oAuth) « Sudhindra Kovalam's Blo… The target platform is Windows Phone 7 in this post, but you can pretty much a build a twitter app on any other platform based on this tutorial Step 1: Register Your Twitter app on dev.twitter.com As Promised in the previous post(I Know it was very long ago), We will try to build a Twitter application. [...]

  38. Hi there, my app worked fine in the past. Somewhere Twitter changed something and I got the same error as some people posted already. KeyNotFoundException. The issue with an unlocked emulator should not be the case, I am using only the official tools from MS (VS2010professional). I see that the result that is coming back from twitter is a zip inside the memory stream, but I cannot get the code to work. I am working on the latest SDK from MS (7.1.1) for windowsphone… Any ideas? Oh besides using the emulator I tried the code on a Nokia 800 and on a Samsung Omnia…

    chefdog

    June 18, 2012 at 6:55 pm

    • I’m having the exact same problem, can’t seem to figure it out…

      toby

      July 4, 2012 at 8:44 pm

  39. If you had a fix please let me know! This is the only thing I have left to do for my app but can’t get it to work getting the error stated above. It seems to be happening on this line:
    OAuthTokenKey = parameters["oauth_token"];
    When debugging the try catch catches the error on that line.

    toby

    July 4, 2012 at 9:00 pm


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

%d bloggers like this: