Exception or Error with Windows Phone 7 Emulator [SOLVED]

If some of you have encountered having issues with Windows Phone 7 Emulator saying that

“An instance is already running” or “Different user access control is called”

First thing a developer will surely check if there was really an instance running in the system and will check the task manager if there are any XDE.exe that are running.

And then, you find out that there are no instances that are running and the Windows phone 7 emulator will not just RUN even if you try to run Visual Studio 2010 as an ADMINISTRATOR .

The error message is quite tricky at first because I myself was a victim. I had to uninstall Visual Studio 2010, WP7 SDK, and other related libraries that might cause the Emulator not to run properly.

Again, the minimum requirements is 2 GB RAM so if you ever had a lower 2 GB RAM that will be an issue for you having these kind of error message. But for me, it was different because I have an 8 GB RAM. Memory is not the problem for me.

I tried searching for some answers for this but I didn’t find any solutions that worked for me.

The most common solution for you to make your emulator work is these

  • Run Visual Studio 2010 as an Administrator
  • Make sure that there are no instances of XDE.exe running
  • Make sure that you have a DirectX 10 installed
  • Re-install Windows Phone 7 SDK and Visual Studio 2010
  • Make sure that there are no running instances of VM by using your command prompt and typing “sc query vmm”
One nasty user experience from the Installer also led me to confusion. Because if you try to run the Windows Phone 7 SDK and tried to download and reinstall the SDK, the Uninstall option is not there, you only have Customize or Repair. So I ended up trying to download the .ISO of Windows Phone 7 SDK and tried again but just have the same thing. So I was trying to uninstall everything and restarting, and I am already thinking to just reformat my laptop because I think my Windows Phone 7 registry was messed up.  It got also worst because my initial problem was just that the Windows Phone 7 emulator just loads up and ended up closing right away. After doing all these things, the next thing I saw is that the WP7 Emulator is not in the drop down list in Visual Studio 2010, so whenever I try to deploy an application to the emulator it just says error instance, or command paramter error.
Sure, some of you might say that I must use a CCleaner or any register cleaner. Frankly speaking, I did that and nothing happened.I had several issues with the Windows Phone 7 emulator after I installed the Bitdefender anti virus, before the emulator was just working perfectly fine. So my hypothesis is that maybe my anti-virus is blocking some port/firewall that’s why the Emulator won’t launch. So I tried uninstalling it again, restoring my OS to the previous version and hoping that it will work again. Still, no luck.

So, I came to my BIOS and checked if other than these experiments and the problem still occured, maybe there is a virtualization that is being used in my CPU that’s why my emulator is not running. I checked that intel in my laptop supports the virtualization and it was turned enabled.
This was the first time I had a laptop with the “virtualization” feature, so I really had no idea about it that would cause my emulator not to work.
Therefore, if you tried to run your emulator and it doesn’t work. I suggest to check if your laptop supports virtualization and check if its enabled or disabled. If it’s enabled try to disable it. I hope this helps for the developers out there who would encounter the same problem that I did.

Multitasking in Windows Phone 7 (Agents, Reminders, Alarms)

Multitasking is a major part in Windows Phone 7 Mango, in the previous talk we’ve discussed a part of it the “Fast Application Switching”, if we think about it FAS is really a simulation of multi tasking since in reality deactivated apps do not keep running in the background whether they get tombstoned or frozen in memory. Multitasking is the ability to do more than one things at a time, which means, working can be done in the background while something else is running in the foreground.

In mango, multitasking needs the ability to start and experience in the foreground and continue to work in the background, or conversely to start something in the background and continue in the foreground. Now in the Windows Phone OS obviously does multi tasking internally such as syncing emails in the background or handling phone calls and so on. The point is multitasking has not been available to us third party developers and the reason for that is the key requirement on maintaining a balance between the phone’s user experience and system health which includes battery consumption, network efficiency and internal services CPU and memory performance.

Opening the Operating System to third party multitasking without restrictions could potentially have disaster consequences on that balance as it would make system health dependence on the individual applications that are installed on the phone. So to preserve the system health while still allowing tons of scenarios that background processing would enable the Windows Phone team has come up with an infrastructure that we can use to do such as background processing in our applications.

This infrastructure is comprised of a set of new operating system services, background agents which are transient services in our applications that can run when invoked by the system.

We’ll be examining agents in the next posts I will publish.

Enhance resource management system that monitors and maintain system health, so in our applications when we need to perform some work in the background we use AGENTS. Mango introduces several different agents that corresponds to our specific needs.

 

When working with Agents there are two aspects to consider:

1. Code that runs in the foreground

2. Code that runs in the background

 

Let’s look at the API that mango exposes as that will give as a overall picture of how the agents work.

On the foreground side, the top level abstraction that we use is the ScheduleAction class, this represents something that can run even if the application that scheduled something is no longer running.

There are two categories of ScheduleActiosn

1. ScheduleNotifications – includes reminders and alarms

2. ScheduleTask – also known as generic agents allow us our own custom code in the background at regular system controls

The difference between the two types of ScheduleTask, PeriodicTask and ResourceIntesiveTask is how often and how long the agent is run by the system.

We use the ScheduledActionService Class to schedule actions and tasks in the background and to retrieve update and remove currently scheduled actions.

Now aside from the foreground API, the code that needs to run in the background is contained within an Agent, if you want to develop your generic agent you need to use a class derived from ScheduledTaskAgent which will run in the background process, Scheduledtaskagent derives from Backgroundagent which we see as it is the base class for all of our agents.  In the foreground application we use the schedule task to schedule an agent, as a result our custom code will run in regular intervals regardless whether the foreground application that scheduled the task is running or closed.

In the next posts, I will show you how does Schedule Notification works.

Building Games for the Windows Phone 7 Platform

Day 2 of my Windows Phone 7 series. It has been a very busy month for me, but here it goes. In this post you will learn how to develop your own 2D game using XNA and deploy it on Windows Phone 7/Xbox 360/Windows Game. This post will be straight forward tutorial just like other XNA tutorials that you could see.  This tutorial assumes that the readers have a basic C#/.Net understanding. I hope that it will help you to understand the basics of the framework and that it will motivate you to go further in. Just an overview of XNA, XNA framework is a .NET Game development of Microsoft that you use to develop in Xbox 360, Windows and now with Windows Phone 7. XNA Framework lets you focus on your game not on the platform because of its easy-to-use API’s. It is a powerful .NET API to help you handle graphics, sounds, videos, inputs networking and storage. The rest of the information about XNA can be found here. When I was still on my college lower years, I sometimes ask myself how to start developing my first simple game? How to handle objects? How to change map? Thanks to XNA Community and free e-books and blogs, I get to learn how to code my own.

Before we start developing with XNA here are some of the FAQ’s.

  1. What’s the difference between XNA 3.1 and XNA 4.0? Do I have to upgrade to XNA 4.0 for me to develop games for Windows Phone 7?
  • Yes, You have to upgrade from XNA 3.1 to XNA 4.0 in order to create games for Windows Phone 7, but if your target is just for Xbox 360/Windows then XNA 3.1 is fine, but IMO I would update it to 4.0 since later on, you could see how easy it is to deploy my existing game to other platforms with just few lines of code.
  1. I only have DirectX 9.1c? Is it okay?
  • As far as I know, the minimum requirement for debugging  games for WP7 is DirectX 10, but you are still able to develop games using DirectX 9.1c.
  1. I only have Visual Studio 2008, is there a difference between using Visual Studio 2010?
  • There’s of course a difference between using Visual Studio 2010 and Visual Studio 2008, for more information please check this site. Here. If you’re using Visual Studio 2008 and you have XNA 4.0 installed and WP7 SDK then there is no difference when developing in VS2008 or VS2010 as long as the SDK are updated with VS2008.

    Let’s start developing our very first 2D game.

    To start our project, we go to File -> New -> Project and this window will show up. On the left side of our installed templates you can see that XNA Game Studio 4.0 is there, choose it and you will see different kind of project templates that we could use for WP7, Windows and Xbox360. If you’re using XNA Game Studio 3.1 you won’t be able to see Windows Phone Game and Windows Phone Game Library.

    By default, your solution explorer should look like this.

    Properties:  This is generated for you by Visual Studio and it’ basically a general information about your assembly.

    References: This is where your libraries are called. Just like in your Turbo C class, “#include<stdio.h>”.

    Content References: This is your content pipeline, this is where you add your existing files like images,  sounds, etc.

    Game.ico: This is your game icon in Windows when executed.

    Game1.cs: This is your game engine or the main source code for our game.

    GameThumbnail.png: This is your game’s thumbnail image.

    Program.cs: Main entry for your application which initializes the game1.cs.

    I have mentioned about Content Pipeline, what’s Content Pipeline anyway?

    • Content Pipeline’s objective is to manage our game assets (graphics, sounds, 3D models, etc) from the importation up to the execution with less code.

    Now for the supported file formats, here’s the list:

    2D graphics: .bmp, .png, .jpg;

    3D models: .x, .fbx;

    Shaders: .fx;

    Audio: .mp3, .wav, .wma;

    5

    Video: .wmv;

    Font: TrueType;

    Any XML, text or binary files.

    Next, let’s try opening our game1.cs. If you have notice our game1.cs inherits the XNA game class. Your game1.cs will be your game engine, you could probably create your own game class but you would end up similar to the XNA game class. The game class is composed of five methods:

    Initialize:  The objective of this method is to initialize all the class members similar to a Winforms/WPF Application.

    Load Content: The objective of this method is to load all our game assets from the content pipeline to be used in our game.

    Unload Content: This method ensures that all of our assets that we loaded are disposed correctly and that our memory allocation are handled properly.

    Update:  Always called before the Draw method and is used to update our game engine. This method handles our logic (collision, user inputs, level update, etc.)

    Draw: This method is called in an infinite loop (game loop). It is used to draw the game assets that we used in our content pipeline into runtime.

    Our game1.cs by default have two fields initialized:

    GraphicsDeviceManager: This class provides us useful methods, properties, etc. that allows us to know the screen resolution, screen bounds, etc.

    SpriteBatch: This class provides us methods for 2D drawings. This is likely the class that communicates with our Graphics Processor Unit.

    Let’s first try adding our game assets to our solution. Right click on our content pipeline

    I’m going to import a simple texture in order for us to learn the basics of loading game assets and drawing it to our game runtime.

    Now in our game1.cs, let’s initialize a Texture2D class, this is will be the variable to handle the image that we are going to load.

    Texture2D spriteSheet;

    After declaring spriteSheet, we go to Load method (this is where we load the game assets as I’ve mentioned earlier).

    spriteSheet = Content.Load<Texture2D>(@”xna”);

    Content is a default Game class member representing our Content Project. In order for us to link our game assets to our project we need to access it through Content member. Using Content’s method “Load” it would be easy for the developer to easily load our supported file by specifying its type Load<DataType>, then after specifying its type we have to specify the asset location.

    We have successfully linked our game asset to our variable spriteSheet, now let’s try drawing it in our game. We go to draw method.

    protected override void Draw(GameTime gameTime)

    {

    GraphicsDevice.Clear(Color.CornflowerBlue);

    // TODO: Add your drawing code here

    base.Draw(gameTime);

    }

    The first line basically just clears out the entire screen and sets the background to Cornflowerblue color. The last line calls Draw method and should always be the last instruction of our Draw method.

    To draw simple 2D graphics, the only class we need to use is SpriteBatch (which is initialized by default).

    If we try to load our screen in Windows base the screen should look like this.

    If you are familiar with Cartesian plane, at first glance you would probably say you do and it’s easy to understand its definition and apply it on the screen. The problem is that, it is just similar to Cartesian plane but its Y value is not the same as the definition we know. If our Y axis goes up the value of Y will be negative not positive, and if our Y axis is going down then its Y value is positive.

    In our SpriteBatch class, we can start drawing by calling its function SpriteBatch.Draw(); We could overload this method in 7 different types of arguments to be passed.

    spriteBatch.Draw(Texture2D, Rectangle, Rectangle, Color);

    Where Texture2D (the texture to be passed), Rectangle (destination rectangle), Rectangle (source rectangle), Color (Color to be used).

    Considering our game asset that we load earlier, let’s try to put this code in our Draw method.

    spriteBatch.Begin();

    spriteBatch.Draw(spriteSheet, new Rectangle(50, 50, 100, 100), new Rectangle(0,0, 70, 48), Color.White);

    spriteBatch.End();

    As you notice, spriteBatch.Begin is called first and spriteBatch.End the last, this is a must everytime we are going to draw our game assets into our game. The begin method is simply like “GPU, these are the game assets you are going to draw and how you are going to draw them”. The end method tells that the GPU can start drawing the game assets that it must draw and how it should be drawn in the game.

    That’s the basic for drawing 2D game. Now let’s start developing our own ping pong game in Windows Phone 7.

    As I have said earlier, XNA lets you focus on the game not on the platform. So first we have to think what assets do we need in order to create a simple pong game?

    • Two rectangle bars
    • Ball
    • Background
    • Score display
    • Sounds

    In our content pipeline, I’m going to use my defined game assets. You can download the files here. After downloading the files you should find the following files:

    • spriteSheet.png: A sheet that contains two rectangles and a ball.
    • Background.png: An image that we will use as a background for the game.
    • Bounce.wav: A sound file when a ball bounces.
    • Supporters.wav: A sound file when a player scores.

    After adding them to our game assets, next thing we need to do is declare variables that will link the game assets to our variables so that we could manipulate them.

    // our pong entities

    Rectangle blueBar;

    Rectangle redBar;

    Rectangle ball; // since there’s no “circle” class in XNA, we’ll simulate it

    with a bounding rectangle box

    // our pong clone textures

    Texture2D grass;

    Texture2D spriteSheet;

    // our sound effects

    SoundEffect ballBounce;

    SoundEffect playerScored;

    Next, we go to our Initialize method and initialize the destination of our game assets.

    protected override void Initialize()

    {

    // initializing our entities

    blueBar = new Rectangle(

    32, // x coordinate of the upper left corner of our rectangle

    10

    GraphicsDevice.Viewport.Bounds.Height / 2 – 64, // y coordinate of the

    upper left corner

    32, // its width

    128); // and its height

    redBar = new Rectangle(

    GraphicsDevice.Viewport.Bounds.Width – 64, // x coordinate of the

    upper left corner of our rectangle

    GraphicsDevice.Viewport.Bounds.Height / 2 – 64, // y coordinate of the

    upper left corner

    32, // its width

    128); // and its height

    ball = new Rectangle(

    GraphicsDevice.Viewport.Bounds.Width / 2 – 16, // x coordinate of the

    upper left corner of our rectangle

    GraphicsDevice.Viewport.Bounds.Height / 2 – 16, // y coordinate of the

    upper left corner

    32, // its width

    32); // and its height

    base.Initialize();

    }

    Our bars are 32×128 pixels and must be placed to the left and right of the screen and perfectly place on the center of the corner. If we define a Rectangle it consists of four parameters: the x coordinate of the upper left corner, the y coordinate of the upper left corner, the width of the rectangle, and its height.

    Next, the common part where my audience gets shocked after seeing this line of code

    GraphicsDevice.Viewport.Bounds.Height / 2 – 64;

    Basically, this is just a simple formula on how we vertically center our bars. Notice that I used the GraphicsDevice class to determine the Bounds of the height which I mentioned earlier the use of GraphicsDevice. With this class it would be easy for us to determine the screen size.

    Next, let’s go load our game assets just like we did earlier before starting our pong game.

    protected override void LoadContent()

    {

    // Create a new SpriteBatch, which can be used to draw textures.

    spriteBatch = new SpriteBatch(GraphicsDevice);

    // load our textures from the Content Pipeline

    grass = Content.Load<Texture2D>(@”Textures/Grass”);

    spriteSheet = Content.Load<Texture2D>(@”Textures/Objects”);

    11

    // load our sound effects from the Content Pipeline

    ballBounce = Content.Load<SoundEffect>(@”Sounds/Bounce”);

    playerScored = Content.Load<SoundEffect>(@”Sounds/Supporters”);

    }

    Next, we will have to go to Draw method and start drawing these game assets. But before we go to our Draw method, we have one basic problem that we already have encountered in our real life if we have tried painting in our Arts class.

    It’s similarly called as the Painter’s problem. Normally, if you’re going to paint something and you already painted the subject the next problem you would encounter is how you would perfectly paint the background without touching the subject or accidentally painted the subject by the background’s colour. Graphics API is similar the way it draw game assets. Everything that is drawn will recover what’s already drawn if it overlaps. So you

    have to draw graphics according to their distance from the camera.

    Currently, according to handcraft

    “It is not completely true since there’s some hardware magic called the Z-buffer

    which sorts everything out even if you draw everything in a random order. But the Z-buffer has been

    designed for 3D purposes and when dealing with 2D graphics, we’re no more working with Z

    coordinate so we have to sort this ourselves.”

    XNA provides a method in order to sort 2D graphics via the SpriteSortMode argument of the Draw method but it is still cleaner to draw things in the right order (background first then subject).

    Let’s start drawing our background first.

    protected override void Draw(GameTime gameTime)

    {

    GraphicsDevice.Clear(Color.CornflowerBlue); // clear all the screen with a

    blue color

    // draw the grass background

    spriteBatch.Begin();

    spriteBatch.Draw(

    grass, // use the grass texture

    GraphicsDevice.Viewport.Bounds, // stretch the texture to the whole

    screen

    // GraphicsDevice.Viewport.Bounds is Rectangle corresponding to the

    actual viewport (meaning the entire screen no matter the resolution), only available

    as of XNA 4.0 CTP

    Color.White);

    spriteBatch.End();

    Similar to the code that we’ve put earlier it just simply draw the background, but notice that I used GraphicsDvice.Viewport.Bounds in order to stretch the texture to the whole screen. If you notice I used the bounds as my destination rectangle because remember that the whole screen is represented in Rectangle.

    If we try to run and debug this we should be able to display a screen similar to this

    [Picture]

    After drawing the background, let’s try adding the subjects (bars and rectangle). If you are familiar with Sprite Sheet then we are going to use the same technique. Sprite Sheet allows us to draw all our game assets in one file so that we would only load the file once in our Load method.

    Let’s define the three source rectangle for our game assets. Notice I said three source rectangles and you might be asking that our ball is not a rectangle it is a circle shape. The answer is that, the .NET framework does not provide a Circle class yet but you can probably write your own Circle class.

    // source rectangles of our graphics

    Rectangle blueSrcRect = new Rectangle( // blue bar src rectangle

    0, // upper left corner x-coordinate of the blue bar inside the

    spriteSheet

    0, // upper left corner y-coordinate

    32, // width

    128); // height

    Rectangle redSrcRect = new Rectangle( // red bar src rectangle

    32, // upper left corner x-coordinate of the red bar inside the

    spriteSheet

    0,

    13

    32,

    128);

    Rectangle ballSrcRect = new Rectangle( // ball src rectangle

    64, // upper left corner x-coordinate of the ball inside the spriteSheet

    0,

    32,

    32);

    After declaring the source location of our game assets in Sprite Sheet, let’s start drawing them. In our existing draw method, we add this code after drawing our background

    // draw the entities (bars and ball)

    spriteBatch.Begin(SpriteSortMode.Immediate, BlendState.AlphaBlend); //

    setup alpha blend to support transparency

    // draw the red bar

    spriteBatch.Draw(

    spriteSheet, // use the sprites texture

    redBar, // the rectangle where to draw the bar on the screen

    redSrcRect, // the source rectangle of the bar inside the sprite sheet

    Color.White);

    // draw the blue bar

    spriteBatch.Draw(

    spriteSheet,

    blueBar,

    blueSrcRect,

    Color.White);

    // draw the ball

    spriteBatch.Draw(

    spriteSheet,

    ball,

    ballSrcRect,

    Color.White);

    spriteBatch.End();

    Press F5 and you should be able to see a screen similar to this

    We’re done drawing our background and positioning our game assets. If you notice how easy it is to load and draw our game using XNA. Just a few lines of code and there you have it, we have how we want our game to look like. Let’s start coding our gameplay.

    The next thing you would probably ask is the common question that a student would ask “How would I move those images? Objects or whatever you call them?” with XNA, it’s also easy to handle inputs just like how we load our game assets. In our update method you would notice that there is a default content which is

    if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed) // if the

    Back gamepad button is pressed

    this.Exit(); // exit our game

    Now this GamePad class just allows us to determine the current state of the user input.  Since Windows Phone 7 is not using gamepad nor Keyboard state to play our pong game, we have to import a class in our .NET which is touch location.

Lifecycle Constraints in Windows Phone 7

When working with the execution model in Mango there is some key constraints that you should take into account. If you’re familiar with the Phone 7 OS you may be aware of these points.

Deactivation -> Dormant -> Tombstoned -> Closed

When you’re application is deactivated, it immediately goes into Dormant mode it later maybe go into Tombstoned and even later it may get Closed.

So when handling the deactivated event it’s important that you save any states that should span application instances such as user settings, disk storage as well as transient dictionaries so that state can be later restored even if the application gets closed by the OS.

In the launching event handler you should perform as little work as possible as long running test can delay the application startup. Likewise, the activation handler executes the four execution startup, so any work perform in it should complete quickly otherwise you should upload it to a separate thread. Just like in WP7 all event handlers and navigation methods should complete within 10 seconds or else the OS will terminate the application. Likewise, codes that runs in deactivation or closing should only complete within 10 seconds. Running code on a separate thread does not help in these cases since these applications are being stopped anyway.

So, if large data writes are necessary it’s best to save data incrementally throughout application execution instead of saving them all in deactivation.

Launchers and choosers will deactivate app and this is a change from WP7

When a launcher or chooser is open by the user the application will go into dormant mode, this behavior is a departure in WP7 where the application actually continued to execute code although this behavior was undocumented. Similarly, when the phone lock screen is engaged the application also goes in Dormant mode.

Unless the application is allowed to run under lock screen. If that’s the case the application will continue running and will not be deactivated which makes sense. Now to allow for an application to continue to run when the lock screen is engaged you need to set the ApplicationIdleDetectionMode property of the PhoneApplicationService object to devalue disabled. You can also handle the obscured and unobscured events that are exposed by the root frame to minimize CPU and battery consumption while the application is locked.

Managing Application State in Windows Phone 7

Application state is not related to a particular page, we handle the life cycle events launching, deactivated, activated, and closing to perform state saving and restoring operations. These events are raised by the operating system. These are still the same and unchanged. Event handlers are stabbed out by default.

Going back to the Life Cycle Graph that I posted earlier. Remember that the deactivated event is raised before the application goes into Dormant state so this is our last chance to save application data to the phone application services state dictionary which will persist data across deactivation just like it’s Page State counterpart.

Now if and when the application gets reactivated like the user hits the back button, the activated event is raised early on before any page is constructed and so before any pages OnNavigatedTo is called. This is where we get to restore global application state before we handle any page level state.

It’s important to remember that the activated event will be raised on activation whether the application is returning from tombstone or dormant mode.

Here again, if the application was merely put to sleep in dormant mode it was never tombstoned no state restoration is necessary, since the application’s memory image is preserved. And we can test for that with

ApplicationEventArgs.IsApplicationInstancePreserve flag of Deactivated Args parameter that’s passed in to the activated event handler. As the name of property implies, a true value indicates that the application was frozen and preserve in memory and not tombstoned. Finally, in the closing event handler we can save our application’s persistent data if any to permanent storage before the application closes for good.

Page States C# code in Windows Phone 7

In this post we’re gonna look at Page states and the Mango Life Cycle.

Let’s create a new project and let’s select the default template for Windows Phone Project.

If you’re new to Windows Phone 7 SDK, this time you get the chance to select whether the Windows SDK will be 7.1 as Mango as suppose to 7.0.

Let’s create two pages for our demo app.

In our MainPage.xaml let’s try adding a HyperLink Button linking it to our page 1, so in our xaml.

Now on page 1 let’s create another hyperlink button where it will link us to page 2.

Now if we run our application and if we click the hyperlink button we will navigate forward to page 1.

This text box represent page state. Now as a user, we can input on the text box to fill up something.

Now in 7.0 what we happens is that even if the application gets deactivated by user pressing the Start/Search button or the phone is receiving an incoming call and returns back to the application is that the user’s input text should be saved and not load the default value which is an empty string. That is where we handle the application life cycle.

In Mango 7.5, if you try to press the search/start button and press the back button that process is now called the Fast App Resume. The reason is that by default, the debugger simulates dormancy (Dormant state) when the application gets deactivated and that is the reason the page state is restored even if you did not handle anything in your App.xaml

Note: As we know there are chances that in case the operating system runs low on resources that are dormant applications will get tombstoned in the later state.

The question now is, so how do we test what happens with our page state if that happens?

– A typical scenario is that we run a bunch of different applications and hope that the OS run out of resources but fortunately there is an easier way to do this.

Let’s try to simulate this by going to the Properties of our Project.

Right click -> Select Properties -> Debug tab

Now notice in our debug window is that there is a check box to check whether we want the application to run tombstoning upon deactivation or not.

Remember in my previous post that I mentioned that when an application is tombstoned, it automatically kills the threads and processes. So if we try to return back to our application it will create a new instance of the threads and processes and it takes MORE TIME. This scenario is what is happening in Windows Phone 7

Here is the code for us to implement saving page states in Mango it’s the same with 7.0…

In our Page1.xaml.cs

Again, remember that when the application is tombstoned it CREATES a new instance of the threads and processes, so everything is loaded by default.

In the code shown above, we created a boolean variable where it checks whether the application is a new instance or not.

Now where do we Save and Restore Page states? Remember the OnNavigatedFrom and OnNavigatedTo methods that you can override?

  1. OnNavigatedFrom is fired if the application has switched to another page or exits the current page. Let’s say going to Page 2.
  2. OnNavigatedTo is fired if the application is going back to the page, let’s say you press the start button and launches again the application.
  3. State[“”] dictionary is now what you use to save and restore page state.

In this post, you should now have an idea on how EASY it is to handle page states in Mango as opposed to 7.0.

Navigation Methods in Windows Phone

You might now be wondering if you have been following my post is that..

When do you save a page state?

Assumming our application has a page state that it needs to maintain let’s look at when to save and restore it. First let’s consider when to page state from the OnNavigatedFrom method the purpose of saving page state is to able to restore visual state should deactivation occurs, therefore we want to save page state whenever the page is either navigated away from or being deactivated.

If navigating back however, so if the user hits the back button page state should not be saved from user’s perspective, the implicit agreement is that by pressing the back button the user is leaving the current page and if the user returns to it he expects a fresh instance of the page. And that’s the way how the navigation system works. Pressing the back button either navigates back from the history of stack or exits the applications. In both cases, the current page will get removed from the stack and the page instance is destroyed. So the next time is navigatedTo a new instance is created. There are code we can detect whether the user is navigating back by taking the navigationMode property of the OnNavigatedFrom methods navigation events args parameter, the navigation mode enumeration indicates the direction of the current navigation operation. So if the value is back so we can skip saving page state, otherwise we should go ahead and save it since that means the user is navigating forward and there’s a chance that he will be returning to the page at a later stage.

We can use the state dictionary of the PhoneApplicationService class to persist page state to memory the dictionary will be persisted across deactivation even if the application is tombstoned at a later stage so that we can later retrieve it on reactivation.

When to restore a page state?

First we need to understand in which cases a new instance of a page is constructed when navigating to it. A page is instantiated when reach through forward navigation or the page is the application’s main page when the application is first launch. In the following graph, the yellow arrow indicates when an instance of a page is created so again, backward navigation does not result into a new instance of the page being constructed.

Now when navigating back to the page after the application is being deactivated the page may, or may not be a new instance depending whether the application is tombstoned or not. Most of the times the application will just be put in dormant state, so as we’ve seen this made the application preserve intact in memory. And so when the user returns to the page, the same instance is revived. If on the other hand, at some point later the application is later tombstoned then when the user returns a new instance of a page is created on activation since the application is reconstructed a new one. So page state needs to be restored when the page is a new instance and state was previously saved in the previous dictionary. That’s the only case when returning the page from tombstone mode.

In your applications you can define a simple flag to test whether a current page is a new instance or not, which helps in deciding whether page states should be restored. Know that if you have an existing applications that target Windows Phone 7 typically no change would be necessary when regards to page state, since returning from dormant state scenarios which is new in mango is handled in the same way as the returning back from another page scenario which already exist in Phone 7.

Follow me on my next post as I teach you how to implement this in Visual Studio.