Thursday, October 7, 2010

Building a ‘real’ Windows Phone Twitter app Part 7 – Optimizing ProgressBar and First time app start up

 

ProgressBar

If you’ve been doing any Windows Phone development you may have run into Jeff Wilcox’s excellent blog: http://www.jeff.wilcox.name/blog/

He’s got on post in particular about the per issues with the built in ProgressBar: http://www.jeff.wilcox.name/2010/08/performanceprogressbar/

I’ll leave it as an exercise to follow this post as it’s quite simple. Roughly the steps are:

  1. Add a new file called “RelativeAnimatingContentControl.cs” and add the code provided in the blog.  I created this at the root of the project.
  2. Add a reference to the top of App.xaml.cs to reference the file and namespace from step 1.
  3. Add the style to the App.xaml.cs file as provided in Jeff’s blog post
  4. Add the style to all the “ProgressBar” elements whereever it’s used in the xaml files.  My code uses it in DetailPage.xsml, MainPage.xaml, TweetPage.xaml and TwitterAuthPage.xaml.  The progress bar code should look something like this:

<ProgressBar x:Name="ProgressBar" VerticalAlignment="Top" IsIndeterminate="False" Visibility="Collapsed" Style="{StaticResource PerformanceProgressBar}"/>

First Time App Start Up

Currently when our code launches MainPage.xaml is loaded the code behind will check if there is stored credentials.  If none are found it will load the TwitterAuthPage.xaml to show the user they need to authorize their Twitter account.  If you hit the back button you’ll be taken back to the MainPage.xaml file if you hit back button again the app will exit.

That seems ok right?  According to app submission policy, launching the app followed by the back key must exit the app and it will fail validation (I hit this one already).  There is a good solution however to this problem.

In App.xaml.cs add an event handler for navigating in the constructor (note I’ve taken the comments out of the code to make it easier to read.

public App()
{
    UnhandledException += Application_UnhandledException;

    if (System.Diagnostics.Debugger.IsAttached)
    {
        Application.Current.Host.Settings.EnableFrameRateCounter = true;
    }

    InitializeComponent();

    InitializePhoneApplication();

    RootFrame.Navigating += RootFrame_Navigating;
}

 

Under the “Properties” folder is the WMAppManifext.xml file we’re going to have it ask for a new xaml file when the app launches.  However we won’t be creating a file for this.  Change the “NavigationPage” attribute of the “DefaultTask node to:

<DefaultTask  Name ="_default" NavigationPage="Views/HomePage.xaml"/>

Now we need to add the event handler.  This handler will check to see if the “HomePage.xaml” file is ever called. If it’s called, we’ll then check if credentials have been stored, if they have load our MainPage.xaml otherwise load the TwitterAuthPage.xaml file:

private void RootFrame_Navigating(object sender, NavigatingCancelEventArgs e)
{
    // Only care about HomePage
    if (e.Uri.ToString().Contains("/HomePage.xaml") != true)
        return;

    e.Cancel = true;

    // check if credentials are stored
    var credentialsFound = false;
    var twitterSettings = Helper.LoadSetting<TwitterAccess>(Constants.TwitterAccess);
    if ((twitterSettings != null &&
        !String.IsNullOrEmpty(twitterSettings.AccessToken) &&
        !String.IsNullOrEmpty(twitterSettings.AccessTokenSecret)))
    {
        credentialsFound = true;
    }

    RootFrame.Dispatcher.BeginInvoke(delegate
    {
        RootFrame.Navigate(credentialsFound
                                ? new Uri("/Views/MainPage.xaml", UriKind.Relative)
                                : new Uri("/Views/TwitterAuthPage.xaml", UriKind.Relative));
    });
}

 

We now have to make a minor change to TwitterAuthPage.xaml.cs in the “RequestAccessTokenCompleted”.  We use to just go back, but since this page can now be the first page, if we successfully get the token and there is no back history load the MainPage.xaml” file:

 

private void RequestAccessTokenCompleted(RestRequest request, RestResponse response, object userstate)
{
    var twitteruser = new TwitterAccess
        {
            AccessToken = GetQueryParameter(response.Content, "oauth_token"),
            AccessTokenSecret = GetQueryParameter(response.Content, "oauth_token_secret"),
            UserId = GetQueryParameter(response.Content, "user_id"),
            ScreenName = GetQueryParameter(response.Content, "screen_name")
        };

    if (String.IsNullOrEmpty(twitteruser.AccessToken) || String.IsNullOrEmpty(twitteruser.AccessTokenSecret))
    {
        Dispatcher.BeginInvoke(() => MessageBox.Show(response.Content));
        return;
    }

    Helper.SaveSetting(Constants.TwitterAccess, twitteruser);

    Dispatcher.BeginInvoke(() =>
        {
            if (NavigationService.CanGoBack)
            {
                NavigationService.GoBack();
            }
            else
            {
                NavigationService.Navigate(new Uri("/Views/MainPage.xaml", UriKind.Relative));
            }
        });
}

 

Now we can remove the check in MainPage.xaml.cs that we used to see if credentials were entered.  The new MainPage_Loaded method looks like this:

private void MainPage_Loaded(object sender, RoutedEventArgs e)
{
    if (!App.ViewModel.IsDataLoaded)
    {
        App.ViewModel.LoadData();
    }
}

That’s it, if you launch the app for the first time, the Twitter authorization page will show and hitting back will now exit the app.  Launching after credentials have been stored will bring up the MainPage.xaml as it did before.

The source code is available at http://twitt.codeplex.com/

Sam

45 comments:

  1. Hey Sam,

    I just purchased your Feed Reader App yesterday. When I try to sign in to Google Reader I get the following error message: The remote server returned an error: NotFound.

    Can you please help me, I really want to use your app!

    Best Regards!
    Jan

    ReplyDelete
  2. Hi Jan,
    Absolutely I'd like to help! Can you email me at wpfeedreader@gmail.com and we can figure out what's up. If you have time as well would you mind trying to create a new google reader account at http://wwwgoogle.com/reader then trying that account on Feed Reader, that will help us determine if it's something specific to your account or not?

    thanks,
    Sam

    ReplyDelete
  3. Hey Sam,

    Extremely detailed and well written.Great work !

    I stumbled upon your blog while doing some research about windows 7 phone application development. I am currently a graduate student at State University of New York,Binghamton. I am working on my master's termination project which involves developing a social networking app.

    Is it possible for you to tell me any helpful material or a book which I can use for win 7 phone development. Since I am a newbie on this platform it is little hard to follow the logic behind the code and I am not going to just replicate the code.

    Please do reply
    Regards,
    Ameya

    ReplyDelete
  4. Hi Ameya,
    A great place to start is the Microsoft Phone site: http://create.msdn.com they've got a ton of info and step by step guides on building apps.
    Another place to get great links is the reddit site: http://www.reddit.com/r/wp7dev/

    Best of luck and also follow #wp7dev tag on Twitter. Best of luck

    Sam

    ReplyDelete
  5. Thanks a lot sam ! I do have experience in C# development but totally new to phone platform. If it's okay I will keep in touch if I come across any major difficulty

    thanks a lot and again it was extremely helpful to read the posts about twitter app development.

    Regards,
    Ameya

    ReplyDelete
  6. You bet Ameya!
    I actually got a new job as a Program Manager on the Silverlight team at Microsoft at the beginning of the month, so if I can't answer any questions I'm sure I can forward them on.

    ReplyDelete
  7. That's great Sam. Thanks a lot. I also came down to Seattle for interview at Microsoft but didn't make it. Hopefully second time is the charm :-)

    Regards,
    Ameya

    ReplyDelete
  8. This comment has been removed by the author.

    ReplyDelete
  9. This comment has been removed by the author.

    ReplyDelete
  10. Hey Sam, I was just curious why in the Twitt source code you are calling MessageBox using Dispatcher.BeginInvoke, for example: Dispatcher.BeginInvoke(() => MessageBox.Show("error calling twitter")

    Is there a performance reason for this? Normally I just open the MessageBox without the Dispatcher.

    Just curious, thanks.

    ReplyDelete
  11. Hi Ryan,
    That's just to get back to the UI thread to show a messageBox. It will throw an expeption if you try to make some calls off of the UI thread, sot Dispatcher.BeginInvoke sends it back to that thread.

    Hope that's helpful.
    Sam

    ReplyDelete
  12. The twitter app demonstration is awesome.. I have a small doubt regarding Google login in my wp7 app can u please help out with it? The problem is that am able to login to Google account through my app... but am not receiving the User Id from Google..Is there anything particular that i will have to do to receive the user id?

    ReplyDelete
  13. hi i know this is a older blog but i reference to it here and there and maybe its because im building for windows phone 8 but the sample data wont take also while follow you complete tutorial i get "twitter error:NotFound" when running on the phone any help would appreciated thanks.

    ReplyDelete
  14. Any manner to spare back the Previewbuffer as a stream or any method to apply channels straightforwardly to the a film bolster and recovery it as a Mp4? I have a little channel I apply to the snapshot cushion and works exceptionally pleasant yet I need to have the capacity to spare the outcome as a film.mobile app development // mobile app developers // iPhone app maker

    ReplyDelete
  15. Nutra Trials defines personal characteristics of different health products including skincare, weight loss, muscle and male enhancement. The study presented here is briefly described for reader convenience and to deliver them assurance with health standards. The best possible answers are given here regarding the selection of an ideal supplement or cream or serum that possibly remains to be safe for health and do not cause any side effects.

    ReplyDelete
  16. HealRun is a health news blog we provide the latest news about health, Drugs and latest Diseases and conditions. We update our users with health tips and health products reviews. If you want to know any information about health or health product (Side Effects & Benefits) Feel Free To ask HealRun Support Team.

    ReplyDelete
  17. We are here to give you a complete review on the Parallel Profit project by Steve Clayton and Aidan Booth. If you are someone from the field you would already be familiar with these two names, for those of who are new. Parallel Profits Price

    ReplyDelete
  18. Supplements For Fitness Sleeping pills tend to make you clumsy and confused, and this can be dangerous and cause you to hurt yourself when falling. This is especially dangerous for older people who may be more likely to fall and break a bone.

    ReplyDelete
  19. Boost Keto : It wasn't in the cards that I would give up weight loss for the benefits of weight loss. I read in a magazine this weight loss will become more urgent that year. What I have to talk about is not dealing with weight loss, however rather the strategy and philosophy behind weight loss.

    Visit Us : https://supplementsbook.org/boost-keto/

    ReplyDelete
  20. Keto 180 Shark Tank : When you burn 350 calories but intake 450 over a high-carbohydrate pasta dish, you're adding additional calories to your body than you otherwise would have. So over time the body can burn the fat or discard the fat so long as the small meals keep coming back. Carbohydrates serve crucial functions in the human body.

    http://180keto.net/

    ReplyDelete
  21. Legends Keto Here are a portion of the full-body practices you have to begin utilizing: Standard deadlifts, Romanian deadlifts, Barbell back squats, Barbell front squats, Dumbbell thrusts, Dumbbell step ups, Dips, Pull-ups, Chin-ups, Renegade free weight columns, Dumbbell lines, One arm grabs, Two-arm iron weight swings (my undisputed top choice).

    https://t.im/c5s4

    ReplyDelete
  22. Brother printer offers you exclusive features like network support option, Wi-Fi setup printing and many more. But like other electronic devices, you may face some problems while using Brother Printer. If you get any issue while using Brother Printer, call Brother Printer support Number and get the reliable solution without any kind of delay. Brother Printer Customer Service Number will provide you support for all the issues. We are offering you 24*7 support, you can give us a call any time you get into an issue.

    ReplyDelete
  23. Healthy GNC - In usa is a wide variety of health,wellness and Male health performance products.which has include protein,male health performance and weight Loss management supplements.This product is really made to help improve your health, whether you are at the beginning of your fitness. Healthy GNC,gnc,weightloss, bodybuilding, vitamins,energy,fitness,strength, healthfulness,stamina, Wellness.
    For more info - http://www.healthygnc.com/


    ReplyDelete
  24. AlkaTone Keto is the weight loss supplement which fulfills all the desires of an obese person at a very cheap and reasonable price. It works on the basis of ketosis which is the fastest way to reduce weight. Kindly Visit on http://www.choosetolose.net/alkatone-keto-shark-tank-new-weight-loss-supplement-review/

    ReplyDelete
  25. Keto Ignite Diet is one of the best dietary supplements that is dedicated to shed pounds and drive instant weight loss reduction naturally. It is a dual action appetite suppressant that works on the ketosis process and controls the carbohydrate conversion to fat structure and drives energy and strength level.

    ReplyDelete
  26. Keto Viante is a natural supplement that is utilized to uncover a new option for lowering fat and cholesterol degree in the body. This supplement is all-natural made compounds as well as related to whole lots of ingredients that are 100% natural. It is primarily used for natural weight management and able to give a possible solution for your need and also desires. Kindly Visit On Keto Viante

    ReplyDelete
  27. Keto Buzz is an advanced ketogenic weight loss formula composed of all herbal ingredients that helps to shed off the stored fat safely. All the ingredients are effective for fat loss. The most powerful ingredients of this supplement are magnesium, sodium, calcium, and BHB aka beta Hydroxybutyrate. All these ingredients combine in such a way that they offer quick weight loss procedure. All the ingredients use in the supplement is clinically prove and recommend by the scientists and doctor for weight loss. Kindly Visit On Keto Buzz

    ReplyDelete
  28. Keto Buzz is an advanced ketogenic weight loss formula composed of all herbal ingredients that helps to shed off the stored fat safely. All the ingredients are effective for fat loss. The most powerful ingredients of this supplement are magnesium, sodium, calcium, and BHB aka beta Hydroxybutyrate. All these ingredients combine in such a way that they offer quick weight loss procedure. All the ingredients use in the supplement is clinically prove and recommend by the scientists and doctor for weight loss. Kindly Visit On Keto Buzz

    ReplyDelete
  29. Constantly CBD Oil seems like the Natural and Pure herbal Oil, which ensures to give quick relief from a headache and nervousness. This outstanding product is not only employed for treating anxiety-related problems; instead, it might also be utilized for treating multiple disease and ailments. Individuals can use this supplement without bothering about unwanted effects. A lot of men and women seem to doubt marijuana and Constantly CBD Oil, but both are entirely distinct. Visit On http://www.healthenrich.org/constantly-cbd-oil-pure-hemp-to-decrease-anxiety-chronic-pain/

    ReplyDelete
  30. Welcome to my own where that you can appreciate that how girl Escorts administrations delivering by way of me and my exclusive administrations at above Escorts all affordable bills at 24 hours. Presently a days, individuals are dwelling unpleasant and boisterous lifestyles.


    Chandigarh call girls
    jaipur escorts


    ReplyDelete
  31. Velofel South Africa is the trusted Health & Wellness supplement Online Website. Its All Information and real evaluations, rate regarding Wellness, Fitness, Diet.

    ReplyDelete
  32. I blog quite often and I seriously thank you for your information. The article has truly peaked my interest. I am going to take a note of your site and keep checking for new details about once a week. I subscribed KBC Game Show to your RSS feed too.

    ReplyDelete
  33. Supreme Vigor is the person Supreme Vigor Testosterone Male Enhancement root which gives you higher testosterone levels. This quantity is especially organized for the men who are protection the problems in their sexual life and it helps in finding the difficulty of erectile dysfunction in uninjured way. It helps you to fulfill thirstier in the bed and eliminates the job of premature exclamation. This Supreme Vigor Testosterone Product is clinically tested and contains exclusive unhazardous and innate ingredients which helpfulness you to enjoy your sex life. Visit On http://www.theapexme.com/supreme-vigor-testosterone-booster-male-enhancement-capsules/

    ReplyDelete
  34. Supreme Vigor is the person Supreme Vigor Testosterone Male Enhancement root which gives you higher testosterone levels. This quantity is especially organized for the men who are protection the problems in their sexual life and it helps in finding the difficulty of erectile dysfunction in uninjured way. It helps you to fulfill thirstier in the bed and eliminates the job of premature exclamation. This Supreme Vigor Testosterone Product is clinically tested and contains exclusive unhazardous and innate ingredients which helpfulness you to enjoy your sex life. Visit On http://www.theapexme.com/supreme-vigor-testosterone-booster-male-enhancement-capsules/

    ReplyDelete
  35. Ultra fast keto boost is an advanced version of regular fat burners to promote weight loss. It uses the power of keto diet to help people in getting rid of unwanted fat, without doing anything extra.Ultra Fast Keto Boost is the dynamic and revolutionary weight loss enhancement for all men and women alike. VISIT ON http://www.choosetolose.net/ultra-fast-keto-boost-advanced-weight-loss-with-metabolic-ketosis-support/

    ReplyDelete
  36. Next time I read a blog, Hopefully it doesn't fail me just as much as this one. I mean, I know it was my choice to read, however I actually believed you would have something useful to say. All I hear is a bunch of complaining about something that you could fix if you were not too busy seeking attention.

    KBC Head Office Contact Number Mumbai
    KBC Lottery Winner 2020
    KBC
    KBC Registration for 2020
    Contact Us Today

    ReplyDelete
  37. An impressive share! I have just forwarded this onto a coworker who had been conducting a little research on this. Roku com link is one of the most popular activation link for Roku devices that allows you to stream the various video contents on your device.

    ReplyDelete
  38. We will tell you about the simple troubleshooting tips to fix the WiFi not showing up error and let your computer connect hp deskjet 3755 printer to wifi setup.when still many HP deskjet printers need WiFi setup to begin printing.

    ReplyDelete
  39. Everyone knows With online TV's sports offerings appear seems to be growing FuboTV, it does include major networks. it provides a wide range of interrelate channels to meet different viewing needs. the main one being its inimitable Unlimited Cloud Storage DVR. Still, when it comes to value for money and sports coverage, So it's hard to forget about FuboTV's plans. fubo.tv/Connect

    ReplyDelete
  40. Nice content and thanks for sharing such an informative and interesting blog, really nice required information. The things I never imagined and I would request, write more blogs and blog posts like that for us. Thank you once again.

    Name correction in Birth Certificate

    Name change in education certificate

    Surname change after marriage

    Name change in punjab

    Name change affidavit

    Name change after adoption

    Name change gazette

    ReplyDelete