Sudhindra Kovalam's Blog

My Geeky Blog

Posts Tagged ‘Twitter

A Windows Phone Twitter Application : Part 2 of 2

with 32 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 )

This is the second post in the series of posts explaining how you can build your own twitter application on Windows Phone 7

Post(s) in this series:

Part 1: Understanding oAuth

As explained in part one, the hard part of writing a twitter application is, to figure out/ understand the authentication/ authorization mechanism. Once You have done that, you can pretty much write an app for any service that has oauth as its authentication/authorization mechanism.

Now that we have obtained all the necessary authorization token(s), we can now access the protected resources on the user’s behalf.

How to Post a Tweet on a User’s behalf?

Using the access token and our app’s consumer secret , we need to make a POST request to twitter’s API to post a tweet from our app.

Using Hammock’s REST Library, You would do something like this :

if (txtBoxNewTweet.Text.Trim().Length == 0) { return; }
var credentials = new OAuthCredentials
{
      Type = OAuthType.ProtectedResource,
       SignatureMethod = OAuthSignatureMethod.HmacSha1,
       ParameterHandling = OAuthParameterHandling.HttpAuthorizationHeader,
       ConsumerKey = TwitterSettings.consumerKey,
       ConsumerSecret = TwitterSettings.consumerKeySecret,
       Token = this.accessToken,
       TokenSecret = this.accessTokenSecret,
       Version = "1.0"
};

var restClient = new RestClient
{
        Authority = TwitterSettings.StatusUpdateUrl,
        HasElevatedPermissions = true,
        Credentials = credentials,
        Method = WebMethod.Post
};

restClient.AddHeader("Content-Type", "application/x-www-form-urlencoded");

// Create a Rest Request and fire it
var restRequest = new RestRequest
{
       Path = "1/statuses/update.xml?status=" + txtBoxNewTweet.Text
};

var ByteData = Encoding.UTF8.GetBytes(txtBoxNewTweet.Text);
restRequest.AddPostContent(ByteData);
restClient.BeginRequest(restRequest, new RestCallback(PostTweetRequestCallback));

Now that you are able to make posts, you need a way to see the posts you have made on the user’s twitter account!

Well For looking at status updates, you don’t need authorization. You can directly give a call to the twitter api and you will get your status updates. ( This sample code is as demonstrated on Scott Gu’s blog )

 private void GetUserTimeLine()
        {
            WebClient wcTwitterTimeline = new WebClient();
            wcTwitterTimeline.DownloadStringCompleted += new DownloadStringCompletedEventHandler(wcTwitterTimeline_DownloadStringCompleted);
            wcTwitterTimeline.DownloadStringAsync(new System.Uri("http://api.twitter.com/1/statuses/public_timeline.xml?screen_name=" + userScreenName));
        }

        void wcTwitterTimeline_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
        {
            if (e.Error != null)
            { return; }
            XElement Tweets = XElement.Parse(e.Result);
            listboxMyTimeline.ItemsSource = from tweet in Tweets.Descendants("status")
                                            select new TwitterItem
                                            {
                                                UserName = tweet.Element("user").Element("screen_name").Value,
                                                Tweet = tweet.Element("text").Value,
                                                ImageSource = tweet.Element("user").Element("profile_image_url").Value
                                            };
            Dispatcher.BeginInvoke(() =>
            {
                listboxMyTimeline.Visibility = Visibility.Visible;
                txtBoxNewTweet.Visibility = Visibility.Visible;
                btnPostTweet.Visibility = Visibility.Visible;
            });
        }

With this, you are pretty much able to make a basic twitter app, that allows you to post tweets.

Using the Twitter api (Found here) You can create a full fledged twitter app.

As promised, I am uploading the source code for the app. You can download the source here.

(UPDATE : I have updated the code snippet, so that the app now runs on the public beta of the tools , Thanks Don for pointing this out )

Once again, Thanks for your support. With the final SDK Bits coming out this September 16th and with WP7 hitting the RTM status (Congratulations to the Windows Phone team @MSFT, Will be  queuing up the store when, it hits retail Smile), The next couple of weeks seem to be really really interesting.  Stay tuned for more exciting WP7 stuff

Written by sudheerkovalam

September 5, 2010 at 2:12 pm

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.)

Written by sudheerkovalam

August 28, 2010 at 7:58 am

Follow

Get every new post delivered to your Inbox.