J2i.Net

Nothing at all and Everything in general.

IE9 Rocks!

And now for some off topic comments!

I've been using IE9 Beta since it was released to public beta and I have to say it rocks! I've installed it on most of my machines and have to say that it looks clean and runs fast. The interface has as many buttons as needed and no more. And the things you can do with HTML 5 are awesome!

What Happened to the WP7 Icon Pack?

In case you were looking for the Windows Phone 7 Icon Pack and noticed all the links to it on the Microsoft Download site are dead, don't worry, getting the icons is easier than you might think. The Icon Pack is now part of Expressions Blend for Windows Phone. When you are working with the application bar and add items you can change the icon used using a drop down in Expressions Blend for Windows Phone. When you select an icon it is automatically added to your project. If you want to get to the icons to work with them yourself you can find them on your drive in C:\Program Files\Microsoft SDKs\Windows phone\v7.0\Icons.

Getting to System Information on Windows Phone 7

There's a requirement that Windows Phone 7 applications not use more than 90 MB of memory to run. One might wonder how to know how much memory that their program is consuming. You can find that information through the DeviceExtendedProperties class. Given the myrid of programs on Windows Mobile and Android devices that display the technical details of a device I know it is tempting to surface some of this information up to a user. But Microsofts guidance on using it is that the information shouldn't be surfaced. Nor should you try to parse or process this information on the device. Rather the information exposed through this API should be for diagnostic purposes. Note that using this API in your programs will cause the program to need the DeviceInformation permission.

The DeviceExtendedProperties class has two methods that are of interest. object GetString(string) and bool TryGetString(String, out object). For both methods the string argument is the name of the property to be retrieved. The first method will return the value of a property of throw an exception of that property cannot be read. The second method will return true and copy the value of a property to the out variable if the property can be read, otherwise it returns false.

Some of the properties may not have values or may be blank. Here are some of the properties that can be retrieved

PropertyDescription
DeviceManufacturer The name of the manufacturer for the device. This could be blank.
DeviceName The name of the device. This could be blank
DeviceUniqueId The unique hash for the device. This is immutable across firmware updates. It should not be used to identify the user since a device could change ownership.
DeviceTotalMemory The total amount of memory in the device. This value will actually be less than the actual amount of physical memory by some amount
ApplicationCurrentMemoryUsage The amount of memory that the application is presently using
ApplicationPeakMemoryUsage The maximum amount of memory that the program has use

To demonstrate the use of this class there's a link to download sample code at the top of this article. The code retrieves the values for a few of these properties and displays them.

        public void UpdateProperties()
        {
            object temp = null;
            ;
            DeviceManufacturer = (DeviceExtendedProperties.TryGetValue("DeviceManufacturer", out temp))
                                     ? (temp as string)
                                     : String.Empty;
            DeviceName = (DeviceExtendedProperties.TryGetValue("DeviceName", out temp) 
                                    ? (temp as string) : string.Empty);
            DeviceUniqueID = (DeviceExtendedProperties.TryGetValue("DeviceUniqueID", out temp)
                                    ? (temp as byte[])
                                    : new byte[0]);
            DeviceFirmwareVersion = (DeviceExtendedProperties.TryGetValue("DeviceFirmwareVersion", out temp)
                                    ? (temp as string)
                                    : String.Empty);
            DeviceHardwareVersion = (DeviceExtendedProperties.TryGetValue("DeviceHardwareVersion", out temp)
                                    ? (temp as string)
                                    : String.Empty);
            DeviceTotalMemory = (long)DeviceExtendedProperties.GetValue("DeviceTotalMemory");
            ApplicationCurrentMemoryUsage = (long) DeviceExtendedProperties.GetValue("ApplicationCurrentMemoryUsage");
            ApplicationPeakMemoryUsage = (long) DeviceExtendedProperties.GetValue("ApplicationPeakMemoryUsage");
        }

Screenshot of Running Program

What's New in the Windows Phone 7 RTM SDK?

The Windows Phone 7 SDK was released earlier today. There are a few things that have changed from the Beta to the RTM, a few of which caught my attention. If you want to see the change list you cah find it here.

  • There's a limit of 10 side-loaded applications that can be on a retail device
  • Changes have been made to the picture sharing API
  • Character support encoding has been limited to 4 encodings (utf-9, utf-16, utf-16LE, utf-16BE, ISO-8859-1)
  • XNA Framework strong name has changed
  • Manifest Validation is now turned on

The first item was of interest to me. I've got well over 10 side-loaded applications on my device (some of which or trivial "Hello World" type applications).

Windows Phone 7 : How did We Get Here

Windows Phone 7 Logo

At the time of this writing the initial RTM version of WP7 is done and the developers will have their hands on the RTM development tools in a few days. The Windows Phone 7 developer tools are still being discovered by developers on a regular basis and many of them with Windows Mobile experience have questions as to why their Windows Mobile expectations don’t carry forward to Windows Phone 7 that well and how Microsoft made the huge jump from Windows Mobile to Windows Phone 7. There’s a commonly repeated explanation that I often hear.

So the short version of the story goes like this:

One day Microsoft realized that in today’s competitive market Windows Mobile sucked so they made something completely unlike Windows Mobile and called it Windows Phone 7. The end.

If some one that had questions read that it would leave them having more questions than they started with. Unfortunately I’ve never seen any complete stories on how Microsoft made the huge leap from Windows Mobile to Windows Phone. So I’ve tried to assemble the story to the best of my ability. I've had to leave out a lot of details that I would much rather share. But for the sake of not making this entry any long than it is I've left them out.

Windows Embedded CE

Windows CE

Let’s go back 13 years to 1996. Microsoft made a trimmed down version of it’s Windows Desktop operating system intended for use on devices. It was named Windows CE. Windows CE (aka Windows Embedded CE) was designed to run on low power hardware, multiple CPU architectures, and to be highly customizable for various hardware designs. There have been a few products that have broken off from Windows Embedded CE including an automotive edition of Windows CE (found in products such as the Ford Sync), Windows Mobile, and PMC. PMC is one of the less known Windows CE derived products. I’ll talk about that in just a moment…

Windows XP Media Center Edition

The evolution of the Windows Desktop also ties into Windows Phone 7 history. In 2002 Microsoft released a version of Windows XP that made the computer act as a media hub. The Media Center application packaged with this version of Windows XP used huge fonts that could be clearly read from a distance and clearly readable on televisions which at the time had pixel resolutions that were much lower than computer displays.

Portable Media Center

Portable Media Center

A year later Microsoft announced PMC, or Portable Media Center. PMC was a Windows Embedded CE derived operating system for making media centric devices. It had an interface similar to what was used in Windows Media Center. A PMC device could play videos that were recorded on Media Center PCs (the computer would transcode video while syncing it). The operating system was supported until 2007 when Microsoft announced the end of the product. One of the most notable implementations of hardware that ran PMC was the Toshiba Gigabeat.

Zune and Zune HD

Zune Logo

Microsoft and Toshiba worked together and took the design of the Gigabeat S to create another media-centric device that was given the name Zune before its public release. The device featured a user interface that also used large easily readable fonts. Microsoft also created an online music store for the device that was branded as the Zune Marketplace. The Zune Marketplace could be accessed through the Zune Desktop software which sported an interface that had a style similar to that of the device. By the release of the fourth version of the desktop software the desktop interface was given a clean minimalistic look. The most recent version of the Zune hardware (named the Zune HD) was a total redesign of the device and has a four point multitouch screen, solid state storage, and an HD FM radio.

XNA

The Xbox 360 (the second version of Microsoft’s home video game console) was launched in 2005. In addition to playing video games the Xbox 360 could act as a Media Center Extender; it could play content from a Media Center PC that is on the same network. In late 2008 the Xbox 360 received a user interface that looked to be inspired by the same style used in the Zune and Media Center. With later updates to the Xbox Live service the Xbox could play videos that a user had purchased through the Zune marketplace.

During the first quarter of 2006 Microsoft released the first version of the XNA framework. The XNA framework was a .Net based SDK that allowed independent and hobby developers to write software for their Xbox 360. Developers could create XNA based applications for their home PCs for free (the development tools didn’t cost anything). However, to deploy their programs to the Xbox 360 registration and a subscription fee was required. For the price of 99 USD per year a developer could deploy his or her programs and make them available for sell through the Xbox Live Marketplace. Being a closed consumer oriented device the XNA framework does not expose the underlying native APIs of the Xbox 360. Version 3.0 of the software included the ability to use the 2D features of XNA on the original Zune. With version 3.1 support for the Zune HD was added along with a class to interact with the accelerometer and another to interact with 4-point multi-touch.

Silverlight

While Microsoft was working on Vista one of the technologies it created was called WPF. WPF used a retain mode graphics engine and supported declarative interfaces. A lighter weight version of WPF was also developed named WPF/E which stood for WPF Everywhere. WPF/E was designed to be light weight, supported on multiply operating systems, safe, and to give developers a tool with which to create common experiences across those operating systems. By it’s release WPF/E was given the name “Silverlight.” The initial versions of Silverlight were for making rich internet applications and experiences. Silverlight versions 1 and 2 ran within a browser. Silverlight 3 received new features that allowed iSilverlight based applications to run outside the browser as standalone applications. At the time of this writing Silverlight 4 is the most recent version, but for the sake of Windows Phone 7 as it stands now only up to version 3 should be considered. Up to version 3 Silverlight does not make the underlying native APIs available to the developer. The Silverlight runtime also doesn’t expose the physical file system. Instead it makes a logical file system available to Silverlight applications without indicating the location in which the logical file system is stored.

Windows Mobile

The one contributing technology of Windows Phone that I’ve not spoken on much is Windows Mobile. I mentioned earlier that Windows Mobile was derived from Windows Embedded CE. Like Windows CE, Windows Mobile was designed to be adaptable to different hardware designs. Unlike the desktop there’s no such a thing as a generic version of Windows Mobile. Every Windows Mobile build has been customized by an OEM for their hardware design. There was a great amount of hardware variation over which Windows Mobile could run. It could run with a number of different resolutions, different amounts of memory, different graphic capabilities, different computational capabilities, and different OEMs extended it in their own way to support features that were not originally supported in the operating system such as front facing cameras and accelerometer. But the customizable features of Windows Mobile also had some drawbacks. Since every build of Windows Mobile was customized new builds were never available directly from Microsoft. Instead Microsoft released updates to the OEM and the OEM and carriers would decide whether or not to make those updates available to the user. In most cases a user would never see more than one update for their device. Beyond that there were no supported upgrade paths for the device. If the user wanted a newer version of the OS a newer hardware purchase was needed. The variance in hardware designs also meant there would be a variance in user experiences. The challenges were also present for the developer too. A developer could choose between supporting a subset of available Windows Mobile devices or putting out extra effort to make their program compatible with the different variations. In the mean time two other major operating systems were providing much longer upgrade paths for their users (Google’s Android and Apple’s iOS) along with a centralized way for finding applications.

Windows Marketplace for Mobile

To address purchasing and selling applications Microsoft created the Windows Marketplace for Mobile. The Marketplace opened in October of 2009. Additionally every Windows Mobile 6.5 device sold included a boot-strapper to install the Marketplace client. For the operating system Microsoft had initially started to make an updated version of the Windows Mobile operating system but ultimately decided this wouldn’t do, they needed something entirely different. So the project was scrapped and they started from square one.

Bringing it All Together

Rather than reinvent the wheel Microsoft made two technologies the core technologies that developers would use to develop against their new mobile operating system; XNA and Silverlight. To address the variance in user experiences that could be found in Windows Mobile Microsoft also will ensure that hardware design falls within their guidelines. The guidelines include minimal requirements for memory, processor and graphics capability, defined supported resolutions, defines the buttons that will be available, and more. Microsoft will be releasing the OS updates directly to the user themselves. For managing the device’s media and applications form the desktop the phones will use the Zune desktop software. Like the Xbox the development tools for the Zune are free but require registration. Like the Xbox 360 the native underlying APIs are not exposed to third party developers. Certain authorized publishers are also granted access to the Xbox Live APIs so that Windows Phone Games can publish achievements.

Juxtaposed to the history of PMC, Zune, XNA, the Xbox, and Silverlight I have to say that Windows Phone 7 doesn’t look to be as much as a spontaneous leap from one design to another as much as a well thought out combination of proven technologies.

Removing items from the "Ready to Install List."

One of the reoccurring questions that comes up in the user's forums is how does one remove an item from the Ready to Install list in the Windows Marketplace for Mobile. The answer to this question is You do not. There is no functionality in the Windows Marketplace for Mobile to do this.

On one hand this makes sense. The Xbox 360 works the same way. On the Xbox 360 every item you've ever downloaded is added to a list. Should you ever want to redownload it you can either find it in the Xbox Live Marketplace again or you can go to the list of applications you've previously downloaded and grab it again. I like having this option, especially when my xbox only had 20 gigs; it was reassuring to know that if I cleared space on my harddrive that I wasn't loosing content.

On the Windows Marketplace for Mobile user's are not as welcoming of this permanent list as they are on the Xbox 360. Though it seems that most Xbox 360 owners that I've spoken to don't know the list exists and thus don't really evaluate it. From my own viewpoint though while the functionality is identical on both devices I must admit it would be nice to have an additional option to hide items from the Ready to Install List. Perhaps it is because the 3 inch screen on the Windows Mobile device doesn't have as much realestate as the 50 inch HDTV that the Xbox is connect to, perhaps it is easier for me to scroll down the list with my controller, keyboard, or remote than it is to scroll down the touch screen. I'm not sure. But what ever the reason may be I know that I would like the option of being able to hide the items.

It will be interesting to see how Windows Phone 7 handles this. The RTM tools will be released nine days from now. I'm keeping my fingers crossed that the RTM firmware will be available too. I guess I will know in 7 days.

Is my Program running in the Emulator or on a Real Device

There are times in which you would want to know whether or not your program is running in the Windows Phone emulator or on a real device. It's easy to determine on which your application is running with a single line of code. 

 

bool IsInEmulator = Microsoft.Devices.Environment.DeviceType == DeviceType.Emulator;

Running the Windows Phone Dev Tools in Emulation

I had previously written about running the Windows Phone Developer's Tools on Windows XP. Moving on to another unsupported setup I decided to try to run the development tools in an emulator. My conclusion: It's far from reliable.

I used VMWare on both a PC and a Mac. On the Mac I was able to get the emulator started before receiving a message about the computer's video adapter not meeting minimum requirements. The emulator did actually start, but it looked like crap. So I didn't bother to go any further to see how functional it was while looking like crap.

I tried a version of VMWare 7 on my Windows 7 machine. I wasn't able to so much as start the emulator. An update to VMWare that came some time later looked promising. When I checked the information on the emulated video card it looked to be compatible with the emulator. So I tried to start the emulator. Several times. Each time the result was that VMWare locked up and not even the task manager could kill it (the computer was still responsive but the emulated machine was pretty much dead). the only way to kill it was to disrupt power to the computer.

Peter Foot also installed the WPDT in an emulated environment. Hist results were much different. Before the update he wasn't able to run the emulator but after the update he was.

Having gone through that exercise and having not found success I'm not inclined to suggest a virtualized dev environment unless you have a physical device that you can use for registering.

Introduction to Windows Phone Programming: Part 2

Introduction to Windows Phone Programming: Part 2

This is part 2 of a multi-part article. For Part 1 see this.

I'm writing a rather lengthy piece on Windows Phone programming and rather than wait for the entire piece to be completed I've decided to start making the sections available in draft form. My intent is to cover XNA (2D and 3D) and Silverlight concepts. I'm planning to put the finished article on CodeProject.com along with the code samples before starting on another piece in which I document the making of an XNA 3D game. If you see anything in this draft that needs to be correct, further detailed, or improved feel free to let me know.

Adding Sound

The sounds that you would need to play in your game in general could be classified as background sounds (such as background music) or incidental sounds (such as sound affects from some event happening). Let's start of making a program that will play a sound using the simplest way available. Create a new XNA Windows Phone Game project. After the project is created right-click on the Content project and select "Add Existing." Navigate to a small PCM *.wav  file on your system and select it to be added to your project. If you don't have any PCM WAV files laying around I'd suggesd downloading a free audio editor such as Audacity and use it to convert a section of a music file to a sound. Once the file is added to your content project rename it to "MySound.wav". You can rename it by right-clicking on the file and selecting the "rename" option. Within the Update() method we are going to add code so that when the user presses and releases any area of the screen the sound will play. Create a new boolean field for the class called _screenPressed and a new field of type SoundEffect named mySoundEffect. Within the LoadContent() method populate mySoundEffect using Content.Load<SoundEffect>("MySound.wav");. Now if you run the program it will play your sound every time you touch the screen.

protected override void Update(GameTime gameTime)
{

    var touchState = TouchPanel.GetState();
    bool touchDetected = touchState.Count > 0;
    if ((!_screenPressed) && (touchDetected))
    {
        mySoundEffect.Play();
    }
    _screenPressed = touchDetected;

    base.Update(gameTime);
}

If you want to be able to do other things with the sound you will need to use the SoundEffectInstance class. A new SoundEffectInstance can be instantiated with a call to the CreateInstance() member of the SoundEffect class. Once you have a SoundEffectInstance you can do things such as pause the sound after begining play, changing the speed at which it plays, or loop the sound. Let's change the program so that it loops the sound as long as the screen is being touched. ADd a new SoundEffectInstance field named soundEffectLoop. In the LoadContent(); method right after mySoundEffect is populated use the CreateInstance() method to populate soundEffectLoop.

protected override void LoadContent()
{
    // Create a new SpriteBatch, which can be used to draw textures.
    spriteBatch = new SpriteBatch(GraphicsDevice);

    mySoundEffect = Content.Load<SoundEffect>("MySoundFile2");
    soundEffectLoop = mySoundEffect.CreateInstance();
}

protected override void Update(GameTime gameTime)
{
    // Allows the game to exit
    if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
        this.Exit();

    var touchState = TouchPanel.GetState();
    bool touchDetected = touchState.Count > 0;
    if ((!_screenPressed) && (touchDetected))
    {

       soundEffectLoop.Play();
    }
    else if ((_screenPressed)&&!(touchDetected))
    {
        soundEffectLoop.Stop();
    }
    _screenPressed = touchDetected;

    base.Update(gameTime);
}
        

Next Section

In the next section I will introduce XNA 3D rendering functionality

 

Introduction to Windows Phone Programming: Part 1

I'm writing a rather lengthy piece on Windows Phone programming and rather than wait for the entire piece to be completed I've decided to start making the sections available in draft form. My intent is to cover XNA (2D and 3D) and Silverlight concepts. I'm planning to put the finished article on CodeProject.com along with the code samples before starting on another piece in which I document the making of an XNA 3D game. If you see anything in this draft that needs to be correct, further detailed, or improved feel free to let me know.

Introduction

This article will get a .Net developer started with Windows Phone 7 development and introduce the basic application models and services available in WP7.

Prerequisites

My target audience for this article is a developer that is already comfortable with C# and uses a .Net development environment. To VB developers please note that at this time the VB language is not a supported language for creating Windows Phone 7 applications. C# is the only language that is available.

What you need at a Glance

If you were to create a new development environment today these are the things you would need.

  • Windows 7 Machine
  • DirectX 10 WDDM 1.1 Complian Video Card
  • Internet Connection

If you want to sell your applications or install or test them on real hardware you will also need the following:

  • Windows Marketplace for Mobile Registration (99 USD/year)
  • A Windows Phone 7 Device

Just an FYI, your ability to use the Windows Phone tools in an emulator will be rather limited.

Departure from Windows Mobile

One of the hardest things for new Windows Phone Developers to accept (Assuming that developer had experience with previous Windows Mobile operating systems) is that Windows Phone isn't Windows Mobile. While they are both operating systems that run on top of a CE kernel from an API perspective Windows Mobile and Windows Phone have very little in common. Windows Phone 7 has no compatibility with Windows Mobile applications.  Other than an optional restriction to only run signed code Windows Mobile doesn't actively restrict what an application can do.

Any applications that you had written for Windows Mobile would need to be rewritten to run on Windows Phone 7. If your code has proper separation of concerns then the amount of code you have to rewrite will be lower. But either way a different binary is needed.

If you have experience and expectations from developing for Windows Mobile now is the time to leave them behind. The APIs that you are familiar with from Windows Mobile are not present. Instead something entirely different is present. You also do not have access to teh entire system from within your code. Instead your code will run within a sandbox.   I don't want to get into all of the differences here. But understand that Windows Mobile and Windows Phone 7 have very few similarities.

Development Hardware and Software Requirement

To get started with Windows Phone 7 development you will need a computer running either Windows Vista SP 2 or later (any edition except starter edition will do) or a version of Windows 7. You'll need at least 2 gigabytes of RAM. If you plan on using the emulator (and chances are that you will unless you have a Windows Phone 7 device) the video display in your computer must support DirectX 10 and have a WDDM 1.1 complian driver. If your video display doesn't ahve adequate support then the emulator will fail to work properly on your machine.

Optionally the emulator will support a touch screen display for your desktop or laptop if you have one. Better yet if your computer has a multitouch capable display the emulator can take advantage of that too. Every now and then the question comes up on whether or not the emulator supports the multitouch tablets available from Wacom. These tablets translate your gestures into mouse messages such as a scroll message. They don't transmit the actual points at which the multi-touch interactions occur.

Phone Hardware Requirements

The hardware requirements for Windows Phone 7 are much higher than they were for Windows Mobile. Windows Mobile was designed to be able to run on a device with only a 200MHz processor, 32MB ram, and possibly no video accelerator or FPU. The standards for Windows Phone 7 are significantly higher. 

  • Capacitive 4 point Multitouch Screen
  • Accelerometer
  • GPS
  • 5-megapixel or better camera with flash
  • 256 MB RAM
  • 8 Gig Storage
  • DirectX 9 capable GPU
  • 1 GHz processor (Cortex/Scorpion)

These are the minimum hardware requirements. So a phone may exceed these requirements. Additionally all Windows Phones will have three buttons on the front of the device; a sart buttin, a back button, and a search button.

Windows Marketplace for Mobile Registration

If you want to deploy your programs to your own hardware or iyou want to distribute it you will need to be registered in the Marketplace. If you do not register you will still be able to create Windows Phone 7 programs. But these programs will only run within your emulator. (In other words all forms of deployment require Marketplace registration)

Once you are registered in the Marketplace you can register up to three devices as devices that you will use for development. At the time of this writing the exact procedure through which one goes to register a device isnot yet available to the general public (this area of the article will be updated when it is).

Device Registration tool.
Device Registration Tool.

Setup for your Development Environment

For Windows Phone 7 development you have the option of using either one of he full versions of Visual Studio 2010 or the Express version. If you plan on using one of the full versions install it first. After it is installed then proceed with installing the Windows Phone tools.

To install the Windows Phone Tools go to http://developer.windowsphone.com and selec the option to download the Windows Phone tools. The initial download is only three megs. This is just the installer bootstrap. It will examine your system to see what components are needed and then it will download and install those components.

Application Types Supported by Windows Phone 7

Windows Phone 7 supports two application types; Silverlight and XNA. Microsoft's Silverlight technology is available in some form or another on multiple operating system (Windows PC, Linux PC, Mac OS X, Symbian, Windows CE). The technology allows one to build user interfaces declaratively that scale to different resolutions, has built in support for smooth transitions and visual affects, media, and has strong support for web services. XNA is available on Windows Phone, Windows Desktop, and the Xbox 360. The XNA framework is designed with games in mind and has support for hardware accelerated 2-dimensional and 3-dimensional graphics, acces to the audio buffer, and has various resource management features built in.

The general guidance you'll here is that if you are making a game then make an XNA application. If you are making a business application then use Silverlight. But that is just general guidance and not a hard rule. One could make a game using Silverlight or making something fairly business oriented with XNA. You'll want to make your decision based on the type of interactions that you need to have with the user. The two application types have two entirely different ways of presenting a user interface to the user. If you use Silverlight then you get a palette of customizable controls including (but not limited to) the textbox, listbox, buttons, and so on. When designing your layout you can choose from concentrating just on control placement of existing controls, styling how those existing controls will look, and even creating your own controls. If you wanted to do the same thing in XNA you would be responsible for maintaining the placement of the controls in your own variables during runtime and you would also have to write the code to paint the controls to the screen in their proper places. If the user touches the screen you would need to calculate whether or not the touch overlaps with one of the controls (clearly Silverlight comes out to be the winner here). On the otherhand if you need to make an application where the display needs to be updated at a high frequency rate then XNA would be the preferred application type.

Creating a Simple XNA Application

We are going to create a simple XNA based application. Before you get too deep into creating the application let's do a test to ensure that your machine is capable of properly supporing the required functionality in the emulator. Start up Visual Studio 2010 and Create a new Windows Phone project.

 

From the "New Project" dialog select "XNA Game Studio 4.0" and then "Windows Phone Game."

Name the new project "Hello XNA" and select "OK." Once the project is completed press F5 to run it. If your computer doesn't meet the video requirements that I mentioned earlier then you'll receive an error during deployment stating  that the "display adapter does not meet the emulator requirements to run XNA Framework applications." If you get this error you'll either need to have real Windows Phone 7 hardware for testing your application, will need to update the display hardware and/or driver to meet requirements, or you will need to move the project to a different computer.

Incapable Driver Message

If you didn't get any errors congradulations, you'e got compatible hardware! You can stop the project from running and return back to the source code.

The Game Class

When you create an XNA game you will create a class that inherits from the Microsoft.Xna.Framework.Game and will override events on the class. These events will be called as a part of the execution loop that is built into this class.

Method Description
Draw(GameTime) Called to allow your game to render itself.
Update(GameTime) When this method is called you execute your games logic for what is changing within the game's virtual world.
LoadContent() This is where you would load the resources needed by your game.

 

A simplified view of the life cycle of an XNA application is as follows:

XNA Application Lifecycle
  1. Initialize -
  2. LoadContent -
  3. Update -
  4. Draw -
  5. Unload -

The Update and Draw methods will be called in a loop until your application is terminating.

For the first example I only want to get something on the screen. Open a paint editor and using your artistic skills (or in my case the lack thereof) to draw a plane. Draw it from the perspective that one might see if they were at a higher elevation than the plane looking down on it with the front of the plan pointing up. Keep the plan around 32x32 pixels and save it as a PNG file named "Plane.png".

Go back to Visual Studio. You'll see a Content project in your solution. Right-click on the project and select Add -> Existing Item. Navigate to your plane and add it. This will make the plane image available as a Texture2D object. Now that the plane image is available in the content resources we'll need to write the code that will use it.

Open the file for the Game1 class. You'll see that the class already has some members declared. In the section that is declaring fields you will see a declaration for spriteBatch and graphics. After these declare a Texture2D element named _planeTexture and a Vector2 element named _planePosition. The _planeTexture element will contain the plane that you just drew. The _planPosition element will hold the X, Y position of the plane. By default it will be (0, 0) and we will leave it as that for now.

There are a couple of things we will need to do in the methods that we were given. In the LoadContent method we will load the plane image and in the Draw method we will render the plane. Change the two methods so that they look like the following.

 protected override void LoadContent()
 {
     // Create a new SpriteBatch, which can be used to draw textures.
     spriteBatch = new SpriteBatch(GraphicsDevice);
     _planeTexture = Content.Load<Texture2D>("Plane");
 }
	
 protected override void Draw(GameTime gameTime)
 {
     GraphicsDevice.Clear(Color.CornflowerBlue);
     spriteBatch.Begin();
     spriteBatch.Draw(_planeTexture, _planePosition, Color.White);
     spriteBatch.End();
     base.Draw(gameTime);
 }

The purpose of Content.Load<T>() is intuitive. The calls on the sprite batch object are to prepare a queue up a set of graphic operations so that they can be passed to the graphic adapter at once. This is faster than making a call to the graphic adapter for each operation that is requested. If you run the program now you'll see the plan render.

Plane Rendering

The plane renders in the upper left hand corner of the emulator.

Getting Input

XNA supports input from a number of different devices; Xbox controllers, keyboards, mice, accelerometers, and touch screens. The classes for these input devices are available across the different implementations of XNA even if that actual device is not (in which case the class would always return no activity on that virtual device). The next change I'm making to the program is to read from an input device and move the plane.

Reading Touch Input

I know that Windows Phone 7 devices have 4-point multi-touch screens. But I am going to code as though it's a possibility that the target device doesn't. This is because I could potentially recompile this code for something else that doesn't have a touch screen (such as an xbox) or might decide to recompile it for a device that doesn't yet exists. To make sure the code properly adapts to all of the different implementations of XNA I will programmatically ask whether or not a certain input device exists before I attempt to use it. I only check for the presence of a touch screen device once. The static method TouchPanel.GetCapabilities() returns a TouchCapabilities object. I'm interested in the IsConnected member of this class. It contains the value true if there is an available touch screen. I store the result of this in _useTouch. I preferred _useTouch over _hasTouch because it is possible that a device is available but I don't want to use it.

During the Update method I'm just checking to see if the touch point is to the left or right of the center of the plane and move the plan one pixel closer to where ever the touch point is. I maintain the center point for the plane separate from the location of the plane (in a real app I wouldn't do this). They are always updated at the same time so I know they are always in sync. To add this functionality to your program declare a new field of type Vector2 named _planeCenter and a boolean field named _useTouch. Within the Initialize() method initialize the _useTouch with the following code.

protected override void Initialize()
 {
      base.Initialize();
      TouchPanelCapabilities touchCaps = TouchPanel.GetCapabilities();
     _useTouch = touchCaps.IsConnected;
     _useAccelerometer = (Accelerometer.GetCapabilities().IsConnected());
 }

The logic to change the position of the plane based on the touch point goes in the update method. It will look like the following.

if (_useTouch)
{
    TouchCollection touchList = TouchPanel.GetState();
    if (touchList.Count > 0)
    {
        var touchPoint = touchList[0];
        if (touchPoint.Position.X > _planeCenter.X)
        {
            ++_planeCenter.X;
            ++_planePosition.X;
        }
        else if (touchPoint.Position.X < _planeCenter.X)
        {
            --_planeCenter.X;
            --_planePosition.X;
        }
    }
}

If you run the program now the plane will move left or right depending on where you touch the screen. If you extend the logic a little further you can have it move up and down too.

Using the Accelerometer

If you've used the accelerometer class in version 3.x of XNA (or saw my Zune Level code)Game Studio forget what you've learned; the accelerometer isn't a part of XNA anymore. It's available in one of the Windows Phone specific assemblies and the way you access it is different.  Instead of probing a static class for it's state you will need to register for event notification. Start by adding a reference to Microsoft.Devices.Sensors to your class along with an appropriate using statement for it. Add a new field of type Accelerometer named _myAccelerometer and initialize it with the default constructor in the Initialize() method. After initializing it add an event handler for the ReadingChanged event. The event will received the X, Y, and Z readings for the accelerometer.

For those that have already written software in XNA and are porting it over this change woun't make a huge difference to your code. Instead of reading the accelerometer during each cycle of your game's loop you would could store the value you get from the ReadingChanged event into a variable and read from it in your game loop. I'm only interested with moving to the plane to the left and right only. So I'm going to change the accelerometer reading to a tilt direction. If the device is tilted by more than 45 degrees then I'll interpret that as an intentional move. Less than 45 degrees will be considered a "dead-zone" and won't affect the plane. Changing the accelerometer reading is a matter of simple math. I usually work in radians but for the sake of making this code more readable I'll work in degrees. 

void _myAccelerometer_ReadingChanged(object sender, AccelerometerReadingEventArgs e)
{
    float tiltDirection = (180f/(float)Math.PI)*(float)Math.Atan2(e.Y, e.X);
    if((tiltDirection>45)&&(tiltDirection<=135))
    {
        _planeMovement.X = 1;
    }
    else if((tiltDirection>225)&&(tiltDirection<=315))
    {
        _planeMovement.X = -1;
    }
}
	

To test this code you will need a physical Windows Phone device. I'v enot yet acquired one yet but hope to get my hands on one soon.

The GamePad Class

You'll find a GamePad class in the Windows Phone XNA library. It may seem a little strange at first given that Winows Phones don't have a game pad of any type. But since XNA applications can be recompiled for other platforms (Xbox 360 and Windows PC) the presence of the class makes the task of recompiling code for another platform easier. Without the presence of this class it would be necessary to add conditional compilation logic to ensure the class was only visible on platforms that supported it.

I won't go into details of the class here. If you'd like to read more about the GamePad class take a look at this article oon accessing the controller from the PC. The same concept works on the Xbox 360.

 

Part 2 of the article can be found here