A Developer’s Roadmap to Windows Phone 7 Launch Timing
    28

    August marks the six-month anniversary of the public unveiling of our next-generation mobile phone, Windows Phone 7. Six months is an interesting bit of time; it can fly by, or it can feel like it’s dragging on forever.  The gating factor tends to be how much fun you are having.  For us on the Windows Phone team, it feels like just yesterday that we first introduced Windows Phone 7 to the world. Now, just a blink of the eye and phones will be on shelves.

     

    All of the work of the last six months is certainly paying off, as just about every conversation we have with developers focuses on their strategy for generating more business with Windows Phone 7.  It’s amazing to see so many inspired developers looking to create experiences for Windows Phone 7. In fact, to date there have been north of 300,000 downloads of the Windows Phone Developer Tools.

     

    These first six months have affirmed that a rich application platform based on the well understood Silverlight and XNA technologies, combined with great free tools based on Visual Studio 2010 and Expression Blend is the right approach for enabling developers and designers of all skill levels who are looking to capitalize on the opportunities presented by Windows Phone 7. Throughout the process, the developer community has continued to astound us with their creative ideas.  Their use of the unique Windows Phone 7 features - like our design system, Live tiles, and location and notifications services - demonstrate that the experiences a developer can build on Windows Phone 7 match their imaginations.

     

    While our developer community has been busy stretching the capabilities of the application platform and developer tools, we have been working very closely with some amazing application and game developers to ensure that Windows Phone 7 customers have the applications they expect, across a wide swath of the categories they value. Here’s a just small sample of the variety of companies with whom we have been working:

    Adenclassifieds, Allociné (including sister brands: Screenrush, Filmstarts, Sensacine), APPA Mundi Ltd, Artificial Life, Inc., ebay, Inc., Esurance Insurance Services, Inc, Flixster, Intelligent Touch Solutions Ltd., Jobsite UK (Worldwide), Limited, Kelley Blue Book Co., Inc., Le Figaro group, My Interactive Limited, Open Table, Inc., Pageonce, Inc., Panoramic Software, Inc., photobucket inc., REALTOR.COM® Real Estate Search  (Move, Inc.), Red Badger Consulting Limited, rising systems networks GmbH, Seesmic, Sequence Collective Ltd, TBS Field Mobility Solutions, The Associated Press, Touchnote, Trip Mate, Inc., Tx3 Solutions, vente-privée.com, Viadeo S.A

     

    Of course, it’s not just the big names in development who are going to bring great titles to Windows Phone 7 customers.  There are many multiples more of lesser known developers who are looking to be in the Windows Phone Marketplace.  Large or small, all developers will have equal opportunity to capitalize on the first mover advantage of having their apps or games ready at launch.  In order to do that, there are a few things developers will need to do:

    1. Register at the marketplace today
    2. Finish you application or game using the Beta tools
    3. Download the final Windows Phone Developer Tools when they are released on September 16th
    4. Recompile your app or game using the final tools
    5. Have your XAP ready for ingestion into the marketplace in early October when it opens

    The final tools will likely have some minor breaking changes from the Beta tools, so developers may have to fix some bugs that arise.  The final tools will also include several highly requested Silverlight controls which will make it even easier for developers to deliver high quality Windows Phone 7 experiences.  Also in the September 16th final release, the panorama, pivot and Bing maps controls will all be available to drop into applications.

     

    The developer tools, controls and application platform are great, but we also recognize the need for smart training.  Just last week we released a course called the Windows Phone 7 Jump Start, delivered by two of our MVPs, Andy Wigley and Rob Miles.  It includes 12 hours of classroom training and supporting exercises.  We have also recently updated the Windows Phone 7 Developer Training Kit.  We will be releasing many more hours of training in the coming weeks and months. For the XNA developers, the XNA Creator Club announced today a new set of educational materials.

     

    We’re also taking additional steps to make sure that the developer experience with Windows Phone Marketplace is even more friendly and intuitive. Ask any mobile developers about their biggest headaches and you are likely to hear about an opaque or non-existent app store ingestion process.  We’ve shown how we are making the process of building apps and games easier for developers, but that is only part of the journey. The next step is getting apps and games in front of customers.  The Windows Phone Marketplace continues our commitment to having a clear and open process for certifying apps and games.  To reinforce that, today we have posted an updated set of Windows Phone Marketplace policies.  Further, in the coming weeks we will be conducting a limited Beta test cycle of our app submission and certification process.  We’re also working on significant changes to our developer portal that reflects feedback from the community.  In those changes, you’ll see enhancements meant to simplify and streamline the path for developers to get the information they need.

     

    So what does this all mean?  We’ve demonstrated that you can build a phone that doesn’t just allow developers to build apps, but rather one that enhances apps with unique features like Live tiles and a design system not available anywhere else.  We’ve shown that a phone isn’t there to just run apps, but rather to understand the full context of what customers are trying to do; integrating functions like maps and search and saving the state of apps so that customers can move between them without losing content or negatively impacting battery life.  Lastly, we aren’t just building a marketplace to deliver apps and games, but rather testing and certifying every one for quality and performance - all the while maintaining a fully open and transparent process to support the developer and their Marketplace success. Our rich developer ecosystem is creating a variety of quality apps and games that take advantage of the phone’s unique features and design.

     

    How will you spend the next couple of weeks?  For the developers telling us how much fun they are having with our productive set of tools and APIs, launch day will be here before they know it.  Developers now know when they will receive the final Windows Phone Developer Tools (September 16th!) and when they should have their XAPs ready for Marketplace ingestion.  300,000 tools downloads means quite a bit of imagination is going to be pouring into the apps and games that customers see on Windows Phone 7 this holiday season.  The clock is ticking.  Will you be ready?

    Windows Phone 7 Jump Start Training
    5

    Today we are publishing the first in our training content led by our MVPs.  Rob Miles and Andy Wigley led an incredibly well received live training course about a month ago, focused on getting developers trained up on building amazing applications and games for Windows Phone 7.

    We recognize that providing as much technical content as we can for the full range of developers is what developers deserve. While we plan on having more live training sessions in the coming weeks and months, we are also committed to making that content available as quickly as possible to as many developers as possible. Since this round of content is based on Beta Windows Phone Developer Tools, we will not be localizing it.  For our non-English speaking developers, we will be providing localized training once we have released the final developer tools.

    Andy and Rob provide a good bit of humor along with their incredible depth of knowledge on the topic of building apps and games for Windows Phone 7. We think they have covered a fair amount ground, but if there are topics you feel we need to cover more in depth, don't hesitate to let us know.

    There are 12 sessions in total, each about :50 minutes in length. Think of this as a semester's worth of class time to help you in your quest to be an awesome Windows Phone 7 developer. It's self-paced, and both Rob and Andy are pretty approachable. Head on over to their blogs if you want to get more plugged into what they are doing.

    Here are the sessions, and a link to their course material.  UPDATED: Here's a link to the Zune subscription link.  Also a link to the iTunes subscription.

    Windows Phone 7 Jump Start (Session 1 of 12): Introduction 

    A quick tour of Windows Phone 7 and how you write programs for it. We take a look at the platform capabilities and the software development options. We also offer you a chance to win a prize that is almost certainly not a private jet.

    Windows Phone 7 Jump Start (Session 2 of 12): Building a Silverlight Application, Part 1

    Building an application from scratch. How you can take a simple idea for a program and build the user interface, followed by the program behaviors that sit behind it. We take a look at databinding on Windows Phone and how best to structure your application to make best use of it.

    Windows Phone 7 Jump Start (Session 3 of 12): Building a Silverlight Application, Part 2

    Making more complex applications. You also get an overview of how the built in controls work, and how to tailor the user input to match your requirements. We also take a look at page navigation within a multi-form Silverlight application on the phone and how to use the navigation inputs for best effect.

    Windows Phone 7 Jump Start (Session 4 of 12): Building Games for the Windows Phone 7 Platform

    Using Silverlight as a platform for game creation. We show how to get a draw/update behavior into your Silverlight games and give you a fully worked game to chew on. We also illustrate how a Silverlight game can leverage the XNA libraries to add sound effects to a game.

    Windows Phone 7 Jump Start (Session 5 of 12): Building XNA Games for the Windows Phone 7 Platform, Part 1

    Getting Started with  XNA on Windows Phone. We talk about what makes the Windows Phone such a good platform for XNA development and how you create XNA games for it. We take a look at how games can manage the orientation of a phone and give you some tips on getting the best performance. Then we move on to take a look at the accelerometer input and how to make games that use this.

    Windows Phone 7 Jump Start (Session 6 of 12): Building XNA Games for the Windows Phone 7 Platform, Part 2

    Using the Windows Phone platform features in your XNA games. We continue with our look at Windows Phone features that make the platform so interesting to game developers. We cover the use of the touch screen, sound creation and finally give you some coverage of how to access the Zune media content in the device. Then we round off with a little look at how you can get text input from users by means of the Guide support in XNA.

    Windows Phone 7 Jump Start (Session 7 of 12): Advanced Application Development, Part 1

    Application Lifecycle. A look at the execution model on the phone, and how to create solutions that give a great user experience in the face of phone calls, termination and even total shutdown of the device itself. We show how to respond to messages to make your application give the appearance of being "always on" and the data persistence facilities that you will need to make this work.

    Windows Phone 7 Jump Start (Session 8 of 12): Advanced Application Development, Part 2

    Launchers and Choosers plus Using Isolated Storage. In this session we take a look at "Launchers and Choosers", how your application can use the built in phone behaviors to place calls, take pictures and select contacts, making it part of how the phone works. We also show how your application can store data in its own isolated storage on the phone device.

    Windows Phone 7 Jump Start (Session 9 of 12): Advanced Application Development, Part 3

    Storing Data and Using the Network. In this session we look at the connectedness of Windows Phone and how you can make this work for you. We demonstrate connected applications and how the notification service is used to allow external systems to give your application a wake-up call. 

    Windows Phone 7 Jump Start (Session 10 of 12): Marketing Your Windows Phone 7 Application

    Using Windows Marketplace. In this session we explain how to join the Marketplace and get your applications out there. We take a look at how your solutions are packaged and deployed and how you go about registering a device for development and then using that with Visual Studio 2010 to test your applications.

    Windows Phone 7 Jump Start (Session 11 of 12): Working with Media

    Using XNA in 3D and with Media. In this session we take a quick look at how the Windows Phone works as an excellent platform for 3D games in XNA. We also explore how an XNA game can make use of the media stored in the phone, including photographs taken by the user and media loaded onto it from Zune.

    Windows Phone 7 Jump Start (Session 12 of 12): Final Silverlight Topics and Wrap-Up

    Taking Silverlight to the max. We start with a look at the Application bar, a crucial component in Windows Phone applications. We then move on to the Expression Blend tool, and how to create compelling user experiences with it. Finally we round off the session by showing how easy it is to use the map services in your phone and demonstrate some of the really cool navigation tools that are coming.

    Here are the bios for our fearless session leaders.

    Rob Miles

    Rob Miles is a lecturer and Microsoft MVP based at Hull University in the UK. He teaches Programming, Software Engineering, Embedded Development and students. He has been working with XNA since before it was released and has been a big fan of Windows Phone 7 ever since he found out he could run his XNA and Silverlight programs on it. He writes a regular blog on programming and other forms of wit at www.robmiles.com and can be found on twitter with the unsurprising name of RobMiles.

    Andy Wigley 

    Andy Wigley is a device application development MVP and co-founder of UK-based mobile consultancy firm, Appa Mundi. He is the co-author of a number of Microsoft Press books, including the Mobile Development Handbook and the .NET Compact Framework Core Reference and is a regular speaker at major conferences such as Tech Ed. He lives in the mountains of Snowdonia, North Wales where a strong mobile phone signal is a total luxury which has helped him to hone his skills developing offline mobile apps. You can read his blog, and those of his Appamundi colleagues at http://mobileworld.appamundi.com/blogs.    

     

    Xbox LIVE Games for Windows Phone 7 Unleashed at Gamescom
    1

    I've been lucky enough this week to find myself in Köln Germany at Gamescom 2010. It's also a pretty exciting day as we announced a number of Xbox LIVE games that will launch with Windows Phone 7 this holiday season. You'll find several familiar names in our first wave of titles from companies like Gameloft, Konami, Namco, Popcap and THQ. Microsoft Game Studios is also publishing several titles for Windows Phone 7 and partnering with many independent studios like Press Start to bring innovative indie content to Windows Phone 7. This is really cool to me, because it shows another step forward Microsoft is taking with the small and independent developer community.

    One particular game that we announced that's interesting to me is CarneyVale: Showtime. It's because its story is intertwined with so many significant milestones through XNA Game Studios' history and really shows the growth from a great idea from a few folks to having a game available as a launch title for a platform. If you're unfamiliar with the game, CarneyVale: Showtime is an acrobatic puzzle game where players are asked to complete various circus stunts. CarneyVale was developed by Team GAMBIT, a small indie studio in Singapore backed by MIT (yep, that one!).

    CarneyVale first showed up on my radar when it was submitted for an entry in our second annual Dream.Build.Play contest circa 2008. As a member of the judging team that year, I was simply blown away at how polished the game was and how fun it was to play. Using XNA Game Studio, Team GAMBIT was able to build the game in four months and the game ended up winning the Grand Prize and $40,000. CarneyVale went on to accumulate other accolades such as the PAX 10 award and being chosen as a finalist in the Independent Games Festival. The game was included as part of our launch of Xbox LIVE Community games (now called Xbox LIVE Indie Games), which allows indies to publish their games on Xbox LIVE. In March of this year Team GAMBIT announced that they plan to bring CarneyVale: Showtime to the PC thanks to a distribution contract with Games for Windows – LIVE. They are taking full advantage of the portability that XNA Game Studio provides.

    For the Windows Phone 7 port of CarneyVale: Showtime, Team GAMBIT partnered with Microsoft Game Studios to integrate Xbox LIVE services available on the platform. In order for us to succeed, we want all types of content on Windows Phone 7, including games that are innovative and introduce concepts that are new to players. CarneyVale: Showtime is just that type of game.

    Because the game was already written in XNA Game Studio, the developers were able to bring their game across the Xbox 360 platform to Windows Phone 7 quickly. Instead of spending a lot of time re-coding the game, they were able to really focus on the differences between the platforms such as user input and screen resolution, while having the core game experience easily translate.

    CarneyVale: Showtime is just one example of a game that's built by indies who were able to utilize XNA Game Studio to bring their game to Xbox 360 and Windows Phone 7. Another great example of this is also included in our launch wave lineup; Rocket Riot from Codeglue, a game that's currently available on Xbox LIVE Arcade. We're looking to everyone, bigger studios, indie studios, or just a single person with a bright idea to create games for Windows Phone 7.

    If there's one piece of information that can really get you started it's that all the titles used the same toolset that's available to you today at http://developers.windowsphone.com. If you're part of an indie group like Team GAMBIT, or a developer with a bright idea you can get everything you need from the site above. If you're just starting out with game development, we're here to help along the way at the same site you download the tools, or at our XNA Game Studio site at http://creators.xna.com.

    I hope you get started today and will be looking forward to playing your next game on Windows Phone 7!

    Windows Phone 7 Design Resources – UI Guide and Design Templates
    13

    With the Windows Phone Developer Tools in Beta and Windows Phone 7 in Technical Preview, now is the time for you to build Windows Phone 7 apps in earnest. We have refreshed our developer documentation to help you build those apps, and we have two, new design-focused documents to help you make them look beautiful.

    First up, the UI Design and Interaction Guide for Windows Phone 7 v2.0 has been updated from the ground up for beta. With additional information and a new layout we hope you will find more readable, this guide provides detailed information about UI elements and controls, UI system behaviors, and the interaction model for the touch interface based on the design system internally named Metro. Designers and developers should read this guide to learn about the dos and don’ts of UI implementations for their Windows Phone apps. We've made it easier to find specific guidance by putting it in bold in the right-hand column of each page.

    Also available are the Design Templates for Windows Phone 7. These are a collection of 28 layered Photoshop template files and the Segoe WP font family that can be used to create pixel-perfect application layouts, to help guide UI development, or to pitch an idea. These design templates showcase many controls that are a part of the Windows Phone Developer Tools Beta. They also include examples of controls that are a part of Windows Phone, but are not available as a part of the Windows Phone Developer Tools.

    Let us know what you think. If you have suggestions or feedback about these design resources, please email us at wp7des@microsoft.com and help spread the word – if you find these resources helpful, please tweet about them.

    Understanding the Windows Phone Application Execution Model, Tombstoning, Launcher and more… – Part 3.
    10

    In the first two Understanding the Windows Phone Application Execution Model, Tombstoning, Launcher and Choosers, and… Few More Things on the Way posts (part 1, and part 2) you learned about the different application lifecycle events – Launching, Deactivated, Closing, and Activated, and how they differ from one another. Based on that knowledge and this code, we’ll move forward.

    Saving the transient state and navigating to the right page

    As you will recall, the second page of our simple application includes two textboxes, one for allowing the user to enter a phone number that will be used to save new contact information, and a second textbox for allowing the user to enter an SMS message to be sent. This will become useful when we start playing with Launchers and Choosers in the context of tombstoning applications.

    Let’s start by defining the problem. The easiest way is simply to run a small experiment:

    1. From Visual Studio, start your application.
    2. Navigate to the second page and enter some text in either or both textboxes.
    3. Press the Windows button; this will deactivate your application (see part 2 of this series).
    4. Press Back (once) to return to your application. This will result in a black screen on your emulator.
    5. Press F5, or use any other method to restart the Visual Studio debugging session to reactivate your application. (Again, if you are missing some context, please read part 2 of this series)
    6. At this stage, your application should be running and you should see the second page of the application. However, both textboxes are empty… the text that you entered before you deactivated your application is no longer there. It is gone!

    image

    From this little experiment you have learned that data entered into your application is not automatically saved when your application deactivates (remember, your application gets terminated). And since reactivating an application really means starting a new instance of the application with some tombstoned information, the page that you land on – in our case page 2, the DetailsPage, is a brand new instance of that page. This indicates that by default all the controls have no data, unless you load data into them.

    The most important thing to remember about tombstoned applications is the simple fact that the user may NOT return to your application, and therefore your application may not be reactivated. If you anticipate this happening, you need to save to disk any data that you wish to restore at a later time. It is completely up to you and your responsibility as a developer to handle the saving and retrieving of data in your application

    We identified two sets of data types that we want to store (copied from MSDN):

    • Persistent data - Data that is shared by all instances of an application. Persistent data is saved and loaded from isolated storage. Application settings are an example of persistent data that should be preserved between application executions.
    • Transient data –Data that describes the state of a single instance of an application. Transient data is stored in the State dictionary provided by the PhoneApplicationService class. A tombstoned application restores its transient state when it is activated.

    We will address the persistent data and working with isolated storage in a future post. For now, let’s focus on managing the transient data and using the State dictionary.

    One of the new classes in the SDK is PhoneApplicationService. The PhoneApplicationService class provides access to various conditions of the application’s lifetime. This includes management of the application’s idle behavior and management of the application’s state when it becomes active or inactive. This class plays a major role in the tombstoning game, since it exposes the Launching, Deactivate, Activated, and Closing events that have the corresponding methods (which you already saw) in the App.xaml.cs file. This class also includes a read-only State property of type IDictionary<string, object>. The importance of this dictionary is that it is persisted on your application’s behalf by the Windows Phone operating system when your application gets tombstoned. When the application reactivates, the objects that placed in the dictionary are returned. You don’t need to save these transient objects to disk as long as you expect your application to return from the tombstoned state. Therefore, if you intend to use the State dictionary, make sure you save only transient data in it– information that you don’t mind losing and that is local to the current application instance. In our example, we’ll save the phone number and SMS text message.

    Please note that the objects you store in this dictionary have to be serializable, or else you will get an exception during the deactivating event about the inability of the operating system to sterilize or desterilize your object.

    MSDN best practices recommend that you store transient page data in the State dictionary during the OnNavigatedFrom event, and load data during the NavigatedTo event.

    I’ve update the application to save the phone number and the SMS message in the Store dictionary, and load it each time the page get navigated to. If a “completely” new instance (indicated by the “Lunching” event) of the application is started, the State dictionary is empty.

       1: protected override void OnNavigatedFrom(System.Windows.Navigation.NavigationEventArgs e)
       2: {
       3:   Util.Trace("***** in DetailsPage: OnNavigatedFrom ( " + DateTime.Now.Ticks + " *****)");
       4:  
       5:   //try to locate the phone number from previous save and simply override it
       6:   if (true == PhoneApplicationService.Current.State.ContainsKey(PhoneNumberKey))
       7:   {
       8:     //clear prev value
       9:     PhoneApplicationService.Current.State.Remove(PhoneNumberKey);
      10:   }
      11:   PhoneApplicationService.Current.State.Add(PhoneNumberKey, this.PhoneNumberTxt.Text);
      12:  
      13:   //try to locate the SMS Messagefrom previous save and simply override it
      14:   if (true == PhoneApplicationService.Current.State.ContainsKey(SmsMessageKey))
      15:   {
      16:     //clear prev value
      17:     PhoneApplicationService.Current.State.Remove(SmsMessageKey);
      18:   }
      19:   PhoneApplicationService.Current.State.Add(SmsMessageKey, this.MessageTxt.Text);
      20: }
      21:  
      22: // Step 2
      23: protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
      24: {
      25:   Util.Trace("***** in DetailsPage: OnNavigatedFrom ( " + DateTime.Now.Ticks + " *****)");
      26:  
      27:   //try to locate the phone number from previous run
      28:   if (true == PhoneApplicationService.Current.State.ContainsKey(PhoneNumberKey))
      29:   {
      30:     string s = PhoneApplicationService.Current.State[PhoneNumberKey] as string;
      31:     if (!String.IsNullOrEmpty(s))
      32:     {
      33:       Util.Trace("***** in DetailsPage: OnNavigatedTo: Found phone number ( " + 
      34:                                                     DateTime.Now.Ticks + " *****)");
      35:  
      36:       this.PhoneNumberTxt.Text = s;
      37:     }
      38:   }
      39:  
      40:   // Step 2
      41:   //try to locate the phone SMS MSG from previous run
      42:   if (true == PhoneApplicationService.Current.State.ContainsKey(SmsMessageKey))
      43:   {
      44:     Util.Trace("***** in DetailsPage: OnNavigatedTo: Found Sms Msg ( " + DateTime.Now.Ticks + " *****)");
      45:  
      46:     string s = PhoneApplicationService.Current.State[SmsMessageKey] as string;
      47:     if (!String.IsNullOrEmpty(s))
      48:     {
      49:       this.MessageTxt.Text = s;
      50:     }
      51:   }
      52: }

    Note that with the following changes, the information in page 2 is stored between page navigation. That is when you press the Back button in page 2, the application navigates back to page 1. If you click the “Navigate to next page” from page 1, your application navigates to page 2. The OnNavigateTo (on page 2) event is raised, and with the above code the control will be loaded with data. This is important because if you take a closer look at the trace in the Output windows in Visual Studio you will find that the each time you navigate to page 2, its constructor is executed. This indicates that each time you press the Back button from page 2, that page is destroyed, and therefore each time you navigate back from page 1 to page 2, the page is recreated. To observe this behavior for yourself, simply navigate back and forth between the two pages, and note that the page 2 CTOR is called each time you navigate from page 1 to page 2. If you comment out the OnNavigatedFrom method in your application, and navigate between the two pages, you will see that the information on the second page is not saved.

    imageNow tombstone the application to see for yourself that the phone number and SMS message are being stored, not just between page navigations, but also after leaving the application and returning to it. Simply navigate to page 2, enter a phone number and some text, and press the Windows button to tombstone the application. You should see the deactivated trace and then the application terminated. Press the Back button and don’t forget to press F5 in Visual Studio to restart the debugging session. Your application will return from its tombstoned state and you will see the launching event, and then the DetailsPage (page 2) constructor. Next you will see the OnNavigatedTo trace and, if everything works, you will see the "Found phone number" and "Found Sms Msg" lines in the trace (and in the emulator), as shown in the next image.
    image

    All this is nice, and I hope it explains the way things work with tombstoning Windows Phone applications. But, now it is time to step up our game and show some cool things in action.

    First, I’ve added a helper Logger class that logs all the traces and displays them in the MainPage (first page) textbox. The goal of the Logger is to prove to you without a doubt that your application gets terminated and that the State dictionary really works. The logger will also allow you to run your application from the emulator, not in debug mode, and still get some information back through the traces shown in the log textbox.

    Logger class

    The Logger class includes a very simple (and most probably not that thread-safe) implementation of a Singleton. The main reason this class is a singleton is to show that even a singleton class is removed from memory when your application is terminated, as well as the order of events and the loading of data between the different events. This class has a string member, which is the log, and a DateTime member that saves the creation time of the Logger object. With the Logger class you can add new lines to the log, and get the entire log. This is good for debugging, which is exactly what the Logger is for. Each time you use the Util Class to add a trace, you also add it to the Logger.

    Usually a singleton implementation doesn’t have a public constructor. However, you are going to save this class in the State dictionary, which means that the Logger class must be serializable and therefore must have a public default (empty) constructor. Otherwise you will get an exception when trying to deactivate or activate your application.

    To “view” the log, I’ve added the OnNavigatedTo method to the MainPage.xaml.cl and loaded text in the log to the logTextBox control on the main page. Therefore each time you navigate to the main page of the application you will see the log file printed. Doing this enables you to view the trace in your application without the need to debug your application in VS (and thanks to Jaime Rodriguez for the tip). Let’s try it.

    1. First you need to deploy you application to the emulator. You can do this by right clicking on your project in the Visual Studio Solution Explorer panel, or from the Build menu. Simply click Deploy.
    2. In the emulator, navigate to the applications list by clicking on the white arrow on the top right corner of the phone.
    3. You should see the applications list, which is rather short. From the applications list pick your application. If you are using the code from this post, the application name is LWP.AppLifeCycle
    4. The application launches, and you see the trace in the MainPage textbox. You may want to change the phone setting (by clicking the wrench button) to set the zoom level of the emulator to 100%. The text in the log textbox is small to be able to show as much log history as possible without scrolling.
    5. In the log textbox you should see the trace from creating the application and the constructor of the main page.
    6. Click the Next Page button.
    7. On the second page, enter a phone number or some text to the SMS textbox.
    8. Then deactivate your application simply by clicking the Windows button. In the emulator, you should see the Start screen.
    9. Click the Back button to return to your application. This will reactivate your application and restore your application to the last page you viewed, that is the second page, and, if all goes well, you should also see the information you entered in step 7.
    10. On the second page, click the Back button to return to the first page. Take a look at the trace found in the log textbox. You should see something that looks the following image:

    imageThe interesting segment of this trace is the information between the dashed lines, and the following code snippet for which the Application Activated method is responsible.

     

       1: if (true == PhoneApplicationService.Current.State.ContainsKey(LoggerKey))
       2: {
       3:     Logger logger = (PhoneApplicationService.Current.State[LoggerKey] as Logger);
       4:     long timeDef = Logger.Instance.CreationTime.Ticks - logger.CreationTime.Ticks;
       5:     Util.Trace("-------------------------------------\n--> Time difference between Loggers = " 
       6:                 + timeDef
       7:                 + "\n" + logger.GetLog() 
       8:                 + "\n-------------------------------------");
       9:     }

     

    In this code, you can see that we are looking for the Logger object in the State dictionary. The object was put into the State dictionary in the deactivated event. Assuming the logger object is found, we are creating a temporary object called logger (note this is not the actual logger object that we are using in the current application). Next we compare the creation time of the Logger from the State to the singleton Logger instance of the “new” application that we just activated. As you can see in the trace, there is a difference in time; the logger from the State dictionary that we saved when we last deactivated the application is older than the new logger. From the code you can see that we can’t really initiate the older logger; its creation time and log are restored and printed to the textbox. So everything between the dashed lines is actually the previous run of the application up to the deactivated event.

    The first line after the dashed line is shows the constructor of the second page, as expected, and it shows the “new” application that got reactivated and returned to the second page, from which we had deactivated the application.

    To summarize

    Now you have seen all four events in action: Launching, Deactivated, Activated, and Closing. I hope you understand that when your application is not running, it is terminated, and any data you didn’t saved is gone. Then when you are return to the application, with either an Activated event or a Launching event, you get a NEW instance of the application (our little singleton experience proved that).

    The State dictionary can save transient data between Deactivated and Activated events and will turn out to be a very useful tool in the next post where we’ll talk about choosers and launchers.

Page 1 of 7 (35 items) 12345...Last