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.

Come Work, Learn & Play with the Campus Rockstars!

The Microsoft Academic Team, in partnership with the Microsoft Student Partners, will be throwing an exclusive Christmas Tech Party for MSPhil AcadTeam friends!

This year’s MSAcadPH Community event, entitled, <METAHYPE/> Embedding Students To The Next Web highlights learning sessions on HTML5, Internet Explorer 9 and CSS3.

Get the chance to learn new techie stuff, play Kinect games and bond with the Microsoft Student Partners in a night full of exciting games and interactive activities for all the participants.

So save the date and details:
December 15, 2011, 5:00 pm ‚Äď 8:30 pm
16th flr. 6750 Ayala Office Tower, Ayala Ave., Makati City

MetaHype

Here’s how to get a pass for this exclusive event:

1. Play at least 1 of the following IE9 games:

2. Send us a screenshot of your highest score by posting on our wall. Screenshots must include the complete IE9 browser as proof of using IE9. Deadline is on December 14, 2011, 6pm.

3. The highest scorers will receive an event pass and a special Microsoft item from MsPhil AcadTeam.

Limited slots only! So play now and post, post, post! Smile

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.

Navigating in Windows Phone 7 using Caliburn Micro

Everything must be shocking to new developers who haven’t used a framework and has been following the traditional way of developing applications in Windows Phone 7.

In this post, I will teach you how to code from Traditional way to Caliburn Micro way.

Assuming we have a MainPage.xaml which contains a button that just simply navigates us from MainPage to Page1.xaml.

The basic way to do this is by adding a click event on our button and then saying that

NavigationService.Navigate(new Uri(“/Page1.xaml”, UriKind.Relative));

in Caliburn Micro, since the PhoneApplication Class is abstracted away from us, we have no idea if its still the same. Our bootstrapper is inheriting from it and assuming we registered our ViewModel in our IoC Container, then we could probably say that,

public void GotoPageTwo() {
navigationService.UriFor<PivotPageViewModel>()
.WithParam(x => x.NumberOfTabs, 1)
.WithParam(y => y.PageName, “leo”)
.Navigate();
}

So what benefit did I get, not only was the code readable but it has a extension methods that can support lambda expressions which we cannot do in traditional way. We could have a longer line of code just to pass a parameter. And did I forgot to mention that you don’t need to do much Binding your your commands? I think I did not, but like I said, before you need to either brute force and just double click the button or create a property and bind a command into it.

In Caliburn Micro, I could just simply say

<Button x:Name=”GoToPageTwo” />

and behind the scenes, it automatically binds the command whether its a delegate or composite command it is supported.

 

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.

Creating your first Windows Phone 7 with Caliburn Micro

Caliburn Micro is a small, yet powerful framework designed for WPF, Silverlight and WP7. It implements a variety of UI patterns for solving real-world problems. Patterns that are highlighted include MVVM (Presentation Model), MVP and MVC.

It’s “Convention over configuration” helps you build rapid¬†application¬†development faster , clean code and easy to data bind.

More on this can be find in this website : http://caliburnmicro.codeplex.com/

In traditional programming, most of us will be doing the application stuff layer like tombstoning, navigation exception, startup URIs in the App.xaml.cs. but if you are used to using a Bootstrapper then you might be surprised let’s say Caliburn Micro that if you use this framework, the App.xaml.cs will now be just this

public partial class App : Application

    {

        public App()

        {

            InitializeComponent();

        }

    }

So, where did this 100 lines of code went from? Because even in App.xaml, we’re going to remove the default code that adds the 4 States of the Phone (Launching, Activated, Deactivated, Closing) and chance it to this

<Application.Resources>
<local:Bootstrapper x:Key=”bootstrapper” />
</Application.Resources>

Now, we create a new class in our project, and let’s call it the Bootstrapper. This Bootstrapper is from Caliburn Micro and this framework automatically binds your properties to your View AND you can easily bind Commands to your controls!

public class Bootstrapper : PhoneBootstrapper
{
private PhoneContainer _container;
protected override void OnLaunch(object sender, Microsoft.Phone.Shell.LaunchingEventArgs e)
{
base.OnLaunch(sender, e);
}

protected override void Configure()
{
_container = new PhoneContainer(RootFrame);

_container.RegisterPhoneServices();

// _container.PerRequest<MainPageViewModel>();
AddCustomConventions();
}

static void AddCustomConventions()
{
ConventionManager.AddElementConvention<Pivot>(Pivot.ItemsSourceProperty, “SelectedItem”, “SelectionChanged”).ApplyBinding =
(viewModelType, path, property, element, convention) =>
{
if (ConventionManager
.GetElementConvention(typeof(ItemsControl))
.ApplyBinding(viewModelType, path, property, element, convention))
{
ConventionManager
.ConfigureSelectedItem(element, Pivot.SelectedItemProperty, viewModelType, path);
ConventionManager
.ApplyHeaderTemplate(element, Pivot.HeaderTemplateProperty, viewModelType);
return true;
}

return false;
};

ConventionManager.AddElementConvention<Panorama>(Panorama.ItemsSourceProperty, “SelectedItem”, “SelectionChanged”).ApplyBinding =
(viewModelType, path, property, element, convention) =>
{
if (ConventionManager
.GetElementConvention(typeof(ItemsControl))
.ApplyBinding(viewModelType, path, property, element, convention))
{
ConventionManager
.ConfigureSelectedItem(element, Panorama.SelectedItemProperty, viewModelType, path);
ConventionManager
.ApplyHeaderTemplate(element, Panorama.HeaderTemplateProperty, viewModelType);
return true;
}

return false;
};
}

protected override object GetInstance(Type service, string key)
{
return _container.GetInstance(service, key);
}

protected override IEnumerable<object> GetAllInstances(Type service)
{
return _container.GetAllInstances(service);
}

protected override void BuildUp(object instance)
{
_container.BuildUp(instance);
}
}

Now, the next question for you guys is, how will you now handle tombstoning your applications? If you notice that there this Bootstrapper must Inherit from the PhoneBootStrapper class, and what does it contain?

public class PhoneBootstrapper : Bootstrapper
{
private bool phoneApplicationInitialized;
private PhoneApplicationService phoneService;

public PhoneApplicationFrame RootFrame { get; private set; }

public PhoneBootstrapper()
: base(true)
{
}

protected override void PrepareApplication()
{
base.PrepareApplication();
this.phoneService = new PhoneApplicationService();
this.phoneService.add_Activated(new EventHandler<ActivatedEventArgs>(this.OnActivate));
this.phoneService.add_Deactivated(new EventHandler<DeactivatedEventArgs>(this.OnDeactivate));
this.phoneService.add_Launching(new EventHandler<LaunchingEventArgs>(this.OnLaunch));
this.phoneService.add_Closing(new EventHandler<ClosingEventArgs>(this.OnClose));
this.Application.ApplicationLifetimeObjects.Add((object) this.phoneService);
if (this.phoneApplicationInitialized)
return;
this.RootFrame = this.CreatePhoneApplicationFrame();
((Frame) this.RootFrame).add_Navigated(new NavigatedEventHandler(this.OnNavigated));
this.phoneApplicationInitialized = true;
}

private void OnNavigated(object sender, NavigationEventArgs e)
{
if (this.Application.RootVisual == this.RootFrame)
return;
this.Application.RootVisual = (UIElement) this.RootFrame;
}

protected virtual PhoneApplicationFrame CreatePhoneApplicationFrame()
{
return new PhoneApplicationFrame();
}

protected virtual void OnLaunch(object sender, LaunchingEventArgs e)
{
}

protected virtual void OnActivate(object sender, ActivatedEventArgs e)
{
}

protected virtual void OnDeactivate(object sender, DeactivatedEventArgs e)
{
}

protected virtual void OnClose(object sender, ClosingEventArgs e)
{
}
}

So the PhoneBootstrapper abstracted away the original App.xaml.cs and we now just inherit it. If we ever wanted to handle these states therefore, we could just say in our Bootstrapper to override these methods.

Next, what’s the best thing about this is it automatically binds your ViewModel to your Views without having to manually implement dependency injection. Basically, if you have a MainPageView.xaml, and you created a MainPageViewModel then the caliburn micro should automatically inject the ViewModel to the View or from the View to the ViewModel which is normally called as ViewModel First or View First approach.

Next, how do we then bind our ViewModel properties to our View controls? The traditional way would be saying {Binding Path=FirstName}. In caliburn micro you don’t do it that way. You just say <TextBlock x:Name=”FirstName”/> and it will automatically bind the property name FirstName from the ViewModel. All the traditional ways are being abstracted away from us making it simplier to code and develop applications in WPF, Silverlight or Windows Phone 7. This is why the Framework’s slogan is “Convention over configuration”, so you are still doing MVVM but those manually long codes is now handled behind the scenes. It’s just like saying you are a new developer and you don’t know where to start. Most of the people before preferred to code in Visual Basic because its easy to use and most of the common things that have to be code are already handled by the Visual Basic. Same goes with this framework, if you are new to MVVM and would like to develop an application but want to make sure you are following the MVVM Pattern, then this framework is for you.