Sudhindra Kovalam's Blog

My Geeky Blog

A Windows Phone Twitter Application : Part 2 of 2

with 33 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

33 Responses

Subscribe to comments with RSS.

  1. The Importance of Search Engine Visibility…

    I found your entry interesting thus I’ve added a Trackback to it on my weblog :)…

    Website Design Tips

    September 6, 2010 at 12:37 am

  2. Hey thanks for the Twitter Application. I just downloaded it.

    Diana Rupert

    September 6, 2010 at 12:07 pm

  3. 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 7, 2010 at 6:02 pm

  4. Hello, I’m trying to download the application source code, but, unfortunately, the link appears to be broken… Can you verify, please???

    Luiz Alberto

    September 8, 2010 at 12:47 am

    • Updating the link! Kindly Check back in a couple of minutes

      sudheerkovalam

      September 8, 2010 at 12:52 am

  5. I do not typically comment on blogs such as this but on this instance and in keeping using the comments above I would carry this chance to say how much I enjoyed your post. Truly educational and well composed – many thanks for sharing it with us!

    Best Strollers

    September 12, 2010 at 11:29 am

  6. Hi thanks for the app. I’m receiving a “Installation of the application failed. Run time error has ocurred. Fix the capabalities on WMAppManifest.xml” Can you please help? I’m new to WP7 and Silverlight and would like to get started…

    Juan

    September 13, 2010 at 7:09 pm

    • Was just wondering, are you on the public beta of the tools?
      Will update the code snippet for the RTM SDK (which releases this Thursday)

      sudheerkovalam

      September 14, 2010 at 3:38 am

  7. Hello,

    Our Managing Editor, Lyndsey Clevesy, recently enjoyed reading a post on your blog and wants to invite you to join DZone’s Most Valuable Blogger program. 

    The MVB program allows DZone’s editors to occasionally feature entries from your blog on our site under your DZone user profile. It has provided a great way for many of our participants to drive extra traffic and visibility to their blogs.

    Please contact karyl@dzone.com for more information about joining the program!

    Best,
    Karyl Gomoll

    Karyl Gomoll

    September 15, 2010 at 9:25 pm

  8. Fabulous post! Loved reading your great post, I always can tag it

    Benito III

    September 25, 2010 at 4:52 am

  9. Fantastic blog! I actually love how it is easy on my eyes as well as the information are well written. I am wondering how I can be notified whenever a new post has been made. I have subscribed to your rss feed which should do the trick! Have a nice day!

    Cathleen Roehrman

    September 27, 2010 at 2:00 am

  10. Hi, Thanks for sharing such a useful information. I have a requirement to upload the photos to twitter using WP7 app. Is it possible? If yes, How can i do that? Can u please help me?

    SanthoshA

    October 8, 2010 at 10:30 am

    • well for taking pics and selecting the same , you can look the camera capture and photo chooser task. (I have written a post on that too )
      As far as uploading to twitter is concerned, u can check it on twitter’s developer documentation as to how does it allow posting images 🙂

      sudheerkovalam

      October 8, 2010 at 10:37 am

      • Thanks for ur reply. I am pretty new to the twitter API and OAuth authentication. If u free, can u post the sample code on that(Uploading pictures to Twitter through WP7 app)?

        I found this info on Twitter developer documentation.
        ====
        The image update methods require multipart form data. They do not accept a URL to an image nor do they accept the raw image bytes. They instead require the data to be delivered in the form of a file upload filed as defined in RFC1867(http://www.faqs.org/rfcs/rfc1867.html).
        ====
        I am unable to proceed from here…

        SanthoshA

        October 8, 2010 at 12:12 pm

    • Hello SantonashA,

      Did you finally get that work? I want to upload an image to twitter from my WP7 app and I’m stuck!

      aZubi (@anderZubi)

      October 12, 2011 at 10:36 am

  11. Any chance someone could/has written this same thing in VB? I’m having issues translating it, but admit I’m learning oAuth as I go.

    Terry

    December 14, 2010 at 4:46 am

    • I really cannot help you on the VB front. But i can ask a friend of mine to try it
      and will host the code.
      Now I am not promising it! but will try for sure!

      sudheerkovalam

      December 14, 2010 at 5:32 am

      • That would rock if you do! Thanks either way.

        Terry

        December 14, 2010 at 5:48 pm

  12. I\

    Benetz

    January 31, 2011 at 12:01 am

  13. I have an issue with your application. Actually I cannot post nothing on twetter. It does not show any exception. What could I do?

    Kevlar23

    February 7, 2011 at 10:59 pm

    • Same issue with me too…..i cannot post any thing to twitter

      ajin

      February 21, 2011 at 4:51 am

  14. I used this code in my app and it worked good for me until few days ago.
    I believe it is related to the modified login page as result of changes in twitter permission levels.
    See
    http://blog.twitter.com/2011/05/mission-permission.html
    and
    https://dev.twitter.com/pages/application-permission-model

    Am I the only one facing this problem?
    Thanks,
    Amir

    Amir

    May 22, 2011 at 3:41 pm

  15. Nice post. Really helpful. I downloaded the code and tried running it. The OAuth authentication and authorization process completed successfully. But there was a problem with the callback while fetching the users timeline. I think this was because of the change in URI at Twitter end and also because Twitter changed its policy to allow only OAuth or XAuth clients.
    I refactored the code from your original post to supply credentials while fetching the users timeline. Here is the modified code.

    private void GetUserTimeLine(string userName)
    {
    //WebClient wcTwitterTimeline = new WebClient();
    //wcTwitterTimeline.DownloadStringCompleted += new DownloadStringCompletedEventHandler(wcTwitterTimeline_DownloadStringCompleted);
    //wcTwitterTimeline.DownloadStringAsync(new System.Uri(“http://api.twitter.com/1/statuses/user_timeline.xml?screen_name=” + userName));

    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,
    Authority = “https://api.twitter.com”,
    HasElevatedPermissions = true,
    Credentials = credentials,
    Method = WebMethod.Get
    };

    // Create a Rest Request and fire it
    var restRequest = new RestRequest
    {
    Path = “/1/statuses/home_timeline.xml”
    };

    restClient.BeginRequest(restRequest, new RestCallback(GetUserTimeLineRequestCallback));
    }

    And the callback function is

    private void GetUserTimeLineRequestCallback(RestRequest request, Hammock.RestResponse response, object obj)
    {
    XElement Tweets = XElement.Parse(response.Content);

    Dispatcher.BeginInvoke(() =>
    {
    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
    };

    listboxMyTimeline.Visibility = Visibility.Visible;
    txtBoxNewTweet.Visibility = Visibility.Visible;
    btnPostTweet.Visibility = Visibility.Visible;
    });
    }

    Nilesh Gule

    January 2, 2012 at 2:27 am

  16. when i run the sample app on my unlocked nokia lumia 710 device, it always give me error message “KeyNotFoundException”.

    However It does run fine in the emulator. It just the real device is giving me the error.

    do you know what caused this error… please help

    elvin

    February 25, 2012 at 4:00 pm

  17. nevermind… just found out the cause for the KeyNotFoundException error….. its actually my device clock is 12hrs in advance… that caused it…

    elvin

    March 1, 2012 at 10:31 am

  18. Hello, thanks for this amazing tutorial! I hava a question… I write my user and password and I get back the PIN, but I can not find where to write down the PIN to confirm the authentication. Thanks!

    Rodrigo Guerrero

    March 30, 2012 at 10:54 pm

    • Hi, can u elaborate that a bit?
      This blog was written some time ago when the twitter auth mechanism was different.
      and hence many people cannot get it to work without changing the code.

      sudheerkovalam

      April 1, 2012 at 2:15 am

      • Hi, thanks for your reply!

        I wasn’t able to connect, so I changed the CallbackUri in TwitterSettings.cs and set it to CallbackUri = “oob”; that made the trick, but now when I get the screen with the PIN, nothing else happens.

        I guess I have to modify something in the objAuthorizeBrowserControl_Navigating method in order to get the condition and execute instructions inside the if statement.

        I will take a look at it today. Thanks!

        Rodrigo Guerrero

        April 2, 2012 at 2:39 pm

  19. I’m also getting “KeyNotFoundException”. Checked my ddevice clock but it seems fine. Any idea what the problem could be?

    ftone

    June 18, 2012 at 12:21 pm

  20. I run the sample app in my device and i get “KeyNotFoundException”.
    What seems to be the problem?

    wel

    June 28, 2012 at 4:46 am

  21. Hey the above source code link is broken, saying “Service not available”. Can you fix it?

    Manikandan S

    March 5, 2014 at 9:16 am


Leave a reply to sudheerkovalam Cancel reply