1
2
3
4
5
6

A Cheat Sheet for Unit Testing Silverlight Apps on Windows Phone 7

I've been planning on writing a quick overview of the basics of unit testing in Silverlight for a while now. Since Windows Phone 7 is the hot topic now, and there are a few quirks with using the Silverlight Unit Test Framework with it, I figured now would be a good chance to write a blog entry covering both. If you're just looking for the cheat sheet relative to both Silverlight and WP7 unit tests, then skip the first section on setting up the test harness on WP7.

Setting up the Test Harness for WP7
To get started, you'll need the Silverlight Unit Test Framework tweaked for Windows Phone 7 from Jeff Wilcox's blog here. I've attached the binaries to this post as well (SL3_UTF_May.zip).

Once you have the binaries, you'll want to create a new test harness project. Do this by creating a new project in your solution of type 'Windows Phone Application'. In the sample attached to this post I'm calling my test project SampleTestProject.

Next, add references to the two Silverlight Unit Test Framework DLLs*:
Microsoft.Silverlight.Testing.dll
Microsoft.VisualStudio.QualityTools.UnitTesting.Silverlight.dll

* you will get a warning about referencing Silverlight 3 assemblies, click 'yes' when asked if you want to continue

Because of recent changes in WP7, you can no longer set the root visual in the App.xaml.cs like normal. Instead, you'll setup the test page in the Loaded() event of your MainPage.xaml.cs in your test project. The following code hides the SystemTray on the phone (the bar at the top of the screen) which otherwise would cover up the top of test results screen, and hooks up the back button to allow you to return back from drilling into test results.

using Microsoft.Phone.Shell;
using Microsoft.Silverlight.Testing;
void MainPage_Loaded(object sender, RoutedEventArgs e)
{
    SystemTray.IsVisible = false;

    var testPage = UnitTestSystem.CreateTestPage() as IMobileTestPage;
    BackKeyPress += (x, xe) => xe.Cancel = testPage.NavigateBack();
    (Application.Current.RootVisual as PhoneApplicationFrame).Content = testPage;            
}

(click 'read more' to keep reading..)

Creating a Windows Phone 7 XNA Game in Landscape Orientation

Update 07/14/2010: With the latest Beta release of the Windows Phone 7 Tools there is now built in support for landscape games in XNA Game Studio 4.0. I just put it into my landscape game and it works great - it even automatically supports both landscape directions. Check out this article for details.

I've been working on a game in Silverlight for Windows Phone 7 (WP7), but I have started thinking I should have gone the XNA route. I am now trying to recreate the game in XNA so that once I can get my hands on a device I can figure out for certain if the Silverlight version can perform as well as the XNA version for what I'm trying to accomplish.

In getting started in XNA it took me a bit to figure out how to draw my sprites and game in the landscape orientation on the phone. I also thought it was a bit tough to add a frame per second counter, something I heavily rely on when developing for Silverlight - this blog entry will show how to accomplish both.

How to create a landscape game in XNA for WP7
Keep in mind that according to this article by Shawn Hargreaves there will eventually be built in support in WP7 for handling the landscape orientation - this solution is just a temporary solution until then. Also, keep in mind that things like the X and Y positions for mouse and touch events will need to be inverted as well to support landscape.

First, we are going to create a RenderTarget2D - this is basically a buffer we are going to render everything to before rendering this buffer to the screen at a 90 degree rotation. We also want to define variables for the width and height of the game window instead of relying on GraphicsDevice.Viewport since we are flipping the X and Y coordinates to make the game landscape.

private RenderTarget2D renderTarget; // what game world is rendered on before being rotated
private int GameWindowWidth; // the width of the game window we are rendering to 
private int GameWindowHeight; // the height of the game window we are rendering to

Setup the GameWindow variables in the Initialize() method:

GameWindowWidth = graphics.GraphicsDevice.Viewport.Height;
GameWindowHeight = graphics.GraphicsDevice.Viewport.Width;

Initialize our RenderTarget variable in the LoadContent() method:

renderTarget = new RenderTarget2D(GraphicsDevice, GameWindowWidth, GameWindowHeight, false, 
    SurfaceFormat.Color, DepthFormat.Depth16);

(click 'read more' to keep reading..)

Example Pivot Control for Windows Phone 7

I know I said I was done trying to recreate the Pivot control, but I'm happy to be able to share a standalone Pivot control that I've been working on. Keep in mind that a real Pivot control from Microsoft should eventually be released, so this control is not intended to be used in your final production code.

First, download the attached SmartyPantsPivotLibrary_Release1.zip, extract it, and add a reference in your project to SmartyPantsPivotLibrary.dll. Next, add a reference in your MainPage.xaml to the library like this:

xmlns:spcoding="clr-namespace:SmartyPantsPivotLibrary;assembly=SmartyPantsPivotLibrary"

Next, add an instance of the PivotControl inside of the ContentGrid in your MainPage.xaml:

        <Grid x:Name="ContentGrid" Grid.Row="1">
            <spcoding:PivotControl>
                <spcoding:PivotControl.PivotPages>
                    <spcoding:PivotPage PageTitle="main">                        
                        <spcoding:PivotPage.Content>
                            <TextBlock>main section goes here</TextBlock>
                        </spcoding:PivotPage.Content>
                    </spcoding:PivotPage>
                    <spcoding:PivotPage PageTitle="options">
                        <spcoding:PivotPage.Content>
                            <TextBlock>options section goes here</TextBlock>
                        </spcoding:PivotPage.Content>
                    </spcoding:PivotPage>
                    <spcoding:PivotPage PageTitle="about">
                        <spcoding:PivotPage.Content>
                            <StackPanel Orientation="Vertical">
                                <TextBlock>about section goes here</TextBlock>
                            </StackPanel>
                        </spcoding:PivotPage.Content>
                    </spcoding:PivotPage>
                </spcoding:PivotControl.PivotPages>
            </spcoding:PivotControl>
        </Grid>

As you can see by the XAML definition above, you are basically adding a PivotControl, and then populating PivotPages with multiple PivotPage entries. A PivotPage is defined as having a PageTitle property (what appears across the pivot menu across the top) and a Content property (what shows up in the main content area for each pivot page).

One other thing you may want to use are two events that tell you when the pivot pages are being dragged around - by listening to these events you can make sure the user doesn't accidentally click on something while changing pages (more on this in the video below):

MainPivot.PivotPageMoving += (s, e) => { _ignoreClicks = true; };
MainPivot.PivotPageDoneMoving += (s, e) => { _ignoreClicks = false; };

Below is a quick video showing how to use the control and discussing a bit more about it, you'll find the example project attached to this post:

As a side note, I have been unable to get this control to work in a large project I had already been working on - for some reason an unhandled Application level exception occurs after changing pages from time to time - unfortunately the exception provides no details and the call stack only shows internal methods. So, this control is provided AS IS - I won't really know how well this works until others try and use it. I also am not committed to maintaining this control, but if you improve on the code and would like to have the code posted updated please feel free to let me know.

Get and Put Pixel in Silverlight 3 with WriteableBitmap


In my last blog entry I talked about how the new Bitmap API in Silverlight 3 gives you the ability to render controls to a WriteableBitmap, I also mentioned how it gives you direct access to editing pixels in a bitmap. I wanted to put together an example of what this ability can provide, and I wanted to show off how performant the get/put pixel abilities in Silverlight 3 actually are.

Get Microsoft Silverlight

(click it!)

In the demo above you can see a fire algorithm (previously done in WPF and hacked up in Silverlight 2) as well as a text scroller - both of these are being rendered pixel by pixel. The bitmap the text scroller is manipulating was created by rendering a TextBlock with a drop shadow effect to a bitmap (read more on how to render text to an image here). By clicking on the demo you can see some simple elastic transitions being done on the rendered WriteableBitmaps - I was pretty impressed to see that even though tens of thousands of pixels are being manually rendered, the transitions performed very well (at least on my machine).

The ability to get/put pixels is exactly the sort of thing that will allow things like doom/quake/etc. to be ported to Silverlight - because you can bypass all XAML and just use a WriteableBitmap to manually render all of your UI at the pixel level.

One of the issues with getting and putting pixels with the Bitmap API in Silverlight 3 is that the direct pixel access is done by setting a pixel's color - which is an integer. Converting a Color to an Int when putting, or an Int to a Color when getting isn't exactly intuitive, so I wanted to post examples of both for others who might be giving this great new ability a whirl.

(more after the break..)

Rendering Text to a WriteableBitmap with Silverlight 3's Bitmap API



One of the new features in Silverlight 3 (released on Friday) is the Bitmap API which provides the ability to render UIElements to a bitmap and provides direct access to the pixel level information of bitmaps. This type of functionality is very useful in a handful of situations, but perhaps the most notable is the ability to cache out a rendering of a UserControl and make use of it in complex transitions to reduce overhead, or to facilitate editing images or processing images through filters, etc.

I did a few searches tonight to get started playing with the Bitmap API and found several examples, but unfortunately none of them had any source code attached, and were written against previous SL3 betas which had different method signatures relevant to the bitmap rendering, so I wanted to go ahead and post a simple example of rendering out a UIElement to a bitmap. This example shows the output of rendering a TextBlock at various font sizes and image sizes and setting the resultant bitmaps as the source for three equal sized Image UIElements.

Get Microsoft Silverlight

(nothing exciting, at least for now)

In the attached code sample you'll see a method which creates a WriteableBitmap, and the resulting WriteableBitmap is set as the source for an Image UIElement. The code to render the bitmaps is very simple, the key (to not wasting your time) is to make sure that you always call Invalidate() on the WriteableBitmap before making use of it, otherwise you will never see anything in the created bitmaps. Here is the main rendering method:

(more after the break..)

Old School Fire Algorithm in Modern Day WPF

A month or so ago before I got too far into my WPF research I wanted to figure out how the performance of WPF compared to - say a 486DX 33mhz from 12-13 years ago. That was about the time I really got into coding, and about the time one of my buddies showed me how to code a fire algorithm in inline assembler in Borland Pascal. So, I looked online for some way to render bitmaps in memory and display them in WPF - and that led to the WPF Fire application whose source is attached (.exe can be found in the bin folder of the attachment as well).

The fire algorithm is pretty simple. You have a color palette of 0 through 255 representing black to white with reds and oranges in between (or you can do black to white with gray shades to make it look like smoke). The way it works is that the bottom row of pixels has their colors randomly assigned to either 0 or 255. All the other pixels on the screen have their colors based on the average of the colors of the pixels to the left, right, and directly beneath - we also decrease the value of this average a bit too so that the fire gradually fades out from bottom to top. Since we are averaging the values around each pixel and the pixel below it makes it appear as though the flames are moving from the bottom to the top. What is neat about this simple algorithm is that you could use it in conjunction with other things. For example, you could remove the randomly assigned pixels at the bottom which fuel the fire, and instead have white balls bouncing around the screen for example which would appear to have fire trails based on the averaging pixel passes.

Now that .Net 3.5 SP1 is out there is a DirectX panel you can use in WPF - I'm sure that would be 10x better for coding something like this - but since I have no real intention of revisiting this playtime app I figured I would share it and see if anyone out there might hax0r it into something cool (please let me know if you do).

CodingTags: 

Simple UI Example Numero Uno

A few weeks ago I mocked up a UI and tried to create it. I got it pretty far but put it aside after one night and thought I had lost my work. Tonight I found it and was pretty surprised to see how much I already wanted to refactor after just a couple of weeks of continued reading.

I am publishing the UI as a click-once app so it can be run online, and I am posting the source too for anyone that might want to hax0r at it. The app shows off a simple reflection as well as a series of custom textboxes which grow when they gain focus. There are tons of things I would like to improve in this UI mockup, but I would rather get it posted now and move on to something more challenging.

Click the screenshot below to play with the app online

Update: Source code now attached.

Recreating Simple Windows Forms in WPF and XAML (Part 4)

Last time we covered breaking our theming out into an external file, and how to style all instances of a given UI element. We left off needing to know the details of how to style more complicated items like buttons and their mouse-over and mouse-down appearances - that is what we will cover in this final part of the series.

The biggest thing we need to keep in mind with items like buttons or comboboxes is that their appearance can drastically differ based on a computer's operating system. You can get a feel of this by changing the Foreground of a button in Vista and seeing how when a button has focus its fill actually pulsates from the normal appearance to the mouseover appearance and back - this animation is unique to Vista and not seen in XP.

(click 'read more' for the rest of the article..)

Recreating Simple Windows Forms in WPF and XAML (Part 3)

Last time we covered how to break out colors from our XAML dialog into separate color definitions in the Page.Resources section of our XAML. After doing this the next question is something like "how do I break out the color, font size, font face, etc. from each of my textbox definitions", and "how can I break these styling definitions out to a separate file" - those are what we will cover in this part of the series.

After breaking out my colors last time my footer definition ended up something like this:

    <!-- bottom panel (ok & cancel buttons) -->
    <StackPanel DockPanel.Dock="Bottom" Orientation="Horizontal" 
            FlowDirection="RightToLeft" Height="32" 
            Background="{StaticResource footerFillBrush}">
      <Button Width="72" TabIndex="45" Margin="2,2,2,2">Cancel</Button>      
      <Button Width="72" TabIndex="40" Margin="2,2,2,2">OK</Button>      
    </StackPanel>

It's cool that my background color isn't hard-coded now, but all the other styling elements are still hard-coded - that is where Style definitions come in. Style definitions basically allow you to define all the properties that should be set on an element in one spot. You can then assign the Style you created to a textbox, or a label, or any other UI element you might want to style. You give the Style a Key name just like you would a color definition and then tell the UI element to make use of that Style (there is another way to use styles across all items of a given type instead of specifying which one to use for every UI element - we will cover that towards the end of this article).

(click 'read more' to read the full article..)