Sudhindra Kovalam's Blog

My Geeky Blog

Archive for August 2010

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

with 59 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
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.
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 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:
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.
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.)

Written by sudheerkovalam

August 28, 2010 at 7:58 am

Windows Phone 7 : Launcher and Choosers : Part 2

leave a comment »

Let us continue our exploration of Windows Phone 7 Launchers and Choosers.

I had described Windows Phone 7 launchers here.

Chooser is an API , that launched a  built in functionality for the user to accomplish some task and returns back the data that was chosen by the user to the app.

We had seen how we could do a new launcher as and where needed, But in case of Choosers, the game is a little different.

A Chooser starts a different application ( Your app gets tombstoned)  and after the intended action is complete, ( Your app is back from the grave mwahahah!! ) the results are returned to your application. So we will have to declare the Chooser objects at a global scope within the PhoneApplicationPage class and  instantiate  it  in the page’s ctor and do the necessary plumbing (By that, i mean handling the necessary events etc.)

As of now following choosers are exposed

1. CameraCaptureTask:

The Camera Capture Task starts the camera of the phone. Now, the user is  actually seeing the phone’s camera app, where s/he can click  photos. Once the Photo is taken , we can save this photo in the Phone’s Media library. For doing this, we need to add a reference to XNA.Framework assembly.

using Microsoft.Xna.Framework.Media;
public partial class page2 : PhoneApplicationPage
   CameraCaptureTask cameraCaptureTask;

   // Constructor
   public page2()
      // Initialize the CameraCaptureTask and assign the Completed handler in the page constructor.
      cameraCaptureTask = new CameraCaptureTask();
      cameraCaptureTask.Completed += new EventHandler<PhotoResult>(cameraCaptureTask_Completed);

   private void btnCamera_Click(object sender, RoutedEventArgs e)
   void objCameraCapture_Completed(object sender, PhotoResult e)
       if (e.TaskResult == TaskResult.OK)
          MediaLibrary library = new MediaLibrary();
          Random r = new Random(1234);
          Picture pic = library.SavePicture("SavedPicture_" + r.Next(11, 99).ToString() + ".jpg", e.ChosenPhoto);

Picture Capture Screen Accept or Retake the Pic

2. PhotoChooserTask:

As the Name suggests, the choosers shows you the WP7 picture library,from where you are allowed to pick a photo, in the completed event,
you receive a PhotoResult object that contains the Stream representation of the photo Chosen.
You Can do what you want to with the Photos’ File stream.
(Such as displaying it, uploading it to some service provider etc etc)

public partial class Page2 : PhoneApplicationPage
     PhotoChooserTask objPhotoChooser;
     public Page2()
            objPhotoChooser = new PhotoChooserTask();
            objPhotoChooser.Completed += new EventHandler<PhotoResult>(objPhotoChooser_Completed);
     private void btnChosePhoto_Click(object sender, RoutedEventArgs e)
        {            objPhotoChooser.Show();        }

     void objPhotoChooser_Completed(object sender, PhotoResult e)
            if (e.TaskResult == TaskResult.OK)
                MessageBox.Show("Photo Selected");


Media Library : Album ViewPhoto List shown in a pivot

3. SavePhoneNumberTask:

This Chooser, as  the name suggests, saves a phone number in the Phone’s contacts. This chooser does not return anything. The Completed event receives argument stating the status of the operation.

Note : You need to set the PhoneNumber property before you call the Choosers show() method. (Else your code might not work)

<pre>public partial class Page2 : PhoneApplicationPage
     SavePhoneNumberTask objSavePhoneNumber;
     public Page2()
            objSavePhoneNumber = new SavePhoneNumberTask();
            objSavePhoneNumber.Completed += new EventHandler<TaskEventArgs>(objSavePhoneNumber_Completed);
     private void btnSavePhoneNumber_Click(object sender, RoutedEventArgs e)
            objSavePhoneNumber.PhoneNumber = "123-345-4567";

     void objSavePhoneNumber_Completed(object sender, TaskEventArgs e)
            if (e.TaskResult == TaskResult.OK)
                MessageBox.Show("Phone Number Saved..");

Saving a phone number for a existing contact Phone Number Type

4. PhoneNumberChooserTask

PhoneNumberChooserTask Allows you to pick a phone number from your contacts. If the contact has multiple phone numbers, you get to pick one of the phone numbers ( Isn’t that quite handy)

public partial class Page2 : PhoneApplicationPage
     PhoneNumberChooserTask objPhoneNumberChooser;
     public Page2()
            objPhoneNumberChooser = new PhoneNumberChooserTask();
            objPhoneNumberChooser.Completed += new EventHandler<PhoneNumberResult>(objPhoneNumberChooser_Completed);
     private void btnChoosePhoneNumber_Click(object sender, RoutedEventArgs e)

     void objPhoneNumberChooser_Completed(object sender, PhoneNumberResult e)
            if (e.TaskResult == TaskResult.OK)
                MessageBox.Show("Selected :" + e.PhoneNumber);


5. SaveEmailAddressTask

As the name suggests, this choosers saves an email to the contact list.

6. EmailAddressChooserTask

As the name suggests, this choosers shows you the contact list from where , you can chose a  contact and your app will receive the chosen contact’s default email address. Again, if multiple email addresses are available, the user is presented a choice of picking up an email address. This is sent back to your app.

Source Code for the sample Launcher and Chooser Demo,( whose screenshots are visible above )

Once Again, thanks for your support by reading this post. Keep watching this space for more on windows Phone 7.

Next Post : Building your twitter client for Windows Phone 7 with oAuth 🙂

Written by sudheerkovalam

August 14, 2010 at 9:01 am

Windows Phone 7 : Launchers and Choosers

with 5 comments

Windows Phone 7 seems to have captured my attention a lot these days. So I am ( and will be ) blogging about Windows Phone 7 like crazy. I believe that it is Microsoft’s first step in the right direction (in the phone OS business). So coming back to Windows phone 7 Platform. We all, by now know that all applications in Windows Phone 7 runs in its own sandbox (execution and file storage, both). And since, we  are developing apps for windows Phone 7, we will certainly need access to common, phone related functionality, say like sending an email, SMS etc. Recently, in Community Tech Days Pune, in the Windows Phone 7 app development session by Mayur Tendulkar, a very cool app was demoed for Windows Mobile 6.x. This app would send “happy new year” or “happy holidays” message to all the contacts in your phone. The idea was pretty cool. So for designing this app, we would need access to the phone’s contact list and then, will have to use the phone’s SMS API to send out Text messages. It is a different ball game here on Windows Phone 7 platform. Windows Phone 7 doesn’t give you access to native functionality directly, so Microsoft has exposed certain common functionality that you would want to use in your apps in the form of Launchers and Choosers.

A Launcher is an API, that launches built in functionality for the user to accomplish some task and returns nothing back to the calling function in  your app. API to make calls, Send SMS or Emails etc are an example of such APIs

A Chooser on the other hand is an API , that launched a  built in functionality for the user to accomplish some task and returns back the data that was chosen by the user to the app. API for Choosing contacts, photos etc. come under this category.

Important Note : Your application de-activates (i.e. gets tombstoned), when you trigger a launcher or a chooser. (Not sure what tombstoned means, read more about Windows Phone app life cycle here ). How to use Launchers in your application : Launchers are available in Microsoft.Phone.Tasks Namespace. Make sure to add a using statement for this namespace.

As of now Following Launchers have been exposed to us (Not exactly …):

1. EmailComposeTask :

As the name suggests, The EmailComposeTask lets you compose emails and send ‘em. You will off course need to setup an email account before you can actually use the email compose functionality. The good news, if no email account has been setup, the shell will ask you to setup an account. ( I guess in the final RTW SDK, this might actually trigger email setup, if not done already)

EmailComposeTask emailComposeTask = new EmailComposeTask();
emailComposeTask.To = "";
emailComposeTask.Body = "Windows Phone Rocks!!!"
emailComposeTask.Cc = "";
emailComposeTask.Subject = "Windows Phone";

2. PhoneCallTask:

Again, quite evident by the name itself. Phone call task will let you make a phone call.

PhoneCallTask phoneCallTask = new PhoneCallTask();
phoneCallTask.PhoneNumber = "180018001800";
phoneCallTask.DisplayName = "Steve Jobs";

Quite a wrong person to call, I know 😉

3. SMSComposeTask :

Lets you compose an SMS

SmsComposeTask smsComposeTask = new SmsComposeTask();
smsComposeTask.To = "1800-180-1800";
smsComposeTask.Body = "Cool Phone!!";

4. SearchTask :

Lets you open the shell search engine

SearchTask searchTask = new SearchTask();
searchTask.SearchQuery = "Windows Phone 7";

5. MediaPlayerLauncher:

Will Trigger the Phone’s Media Player Application

MediaPlayerLauncher mediaPlayerLauncher = new MediaPlayerLauncher();
mediaPlayerLauncher.Media = new Uri("vs_logo2010_WMV9_640x360.wmv", UriKind.Relative);

6. WebBrowserTask:

The WebBrowserTask will let you trigger the phone’s IE mobile browser and redirect the user to the page specified.

WebBrowserTask webBrowserTask = new WebBrowserTask();
webBrowserTask.URL = "";;

I was not able to find much detail on these Launchers. Folks reading this block can contribute.:


From the Name of it seems, it will launch the phone’s Marketplace app and show details. Not used this one.

8. MarketplaceHubTask:

Launches the Marketplace Hub, i guess. I don’t think we will be able to test this on the locked emulator.

9. MarketplaceReviewTask

10. MarketplaceSearchTask

I will be posting the next post on using the Choosers and will also post the entire solution for your ready reference. Once again, thanks for your support and keep looking at this space for more Windows Phone 7 related posts.

Written by sudheerkovalam

August 6, 2010 at 3:02 am