Nick's .NET Travels

Continually looking for the yellow brick road so I can catch me a wizard....

Code Obfuscation and Windows Phone 7 Application Protection

Today most developers registered with the Windows Phone 7 developer program would have received an email entitled Windows Phone 7 App Protection that talks about how to protect the intellectual property within your Windows Phone 7 application. In actual fact it talks very little about this and more about how applications can’t be side loaded (which we all knew anyhow). To draw a quote from the email:

“As a Windows Phone developer you can be assured that Windows Phone Marketplace is operating as designed in providing a level of protection that is in-line with industry practices and sufficient for our own valued content. You can learn about our protection model in the Windows Phone Marketplace Anti-Piracy Model white paper, which outlines our perspective on leak prevention and leak containment. “

To be honest if by “industry practices” you mean that they’re going to publish your application so that it is readily available for anyone interested to download via a web browser, decompress and view using reflector, then we live in a wow-ful industry indeed. In the white paper they acknowledge that Windows Phone 7 applications are not encrypted in any way on the CDN – this makes it a 20 second job to locate, download and open any application posted on marketplace.

They go on about how it’s not possible for someone to re-publish or side-load an application they have downloaded from marketplace. To me the obvious elephant in the room is the fact that anyone can download your application and view your IP.  This is a sad state of affairs and I for one hope that Microsoft have this well and truly on their radars for the first upgrade to Windows Phone 7.

Points to note:

- Don’t assume Microsoft will protect your intellectual property. You’re handing over your application for them to certify, which means your handing over valuable IP for a third party to review. In my mind that’s a BAD, BAD, BAD thing (irrespective of whether it’s available to everyone else).

==> Resolution – Store any valuable IP behind a service. This means that you can protect and/or change it as required

- Don’t include application keys/tokens in your application - Windows Phone 7: Where to store that application key? NOT in the Application(need I repeat this again?)

==> Resolution – Store app keys/tokens behind a service. Whilst not a perfect solution, it does make it slightly harder

- Accessing xaps off marketplace can be done using a proxy (such as fiddler) when you download an app to your phone via zune. I won’t give away too much other than you need to look at the xml file that is retrieved which discloses the direct download url for the xap.

==> Resolution – This information is posted here to put Microsoft on notice: this level of application protection is unacceptable. As a minimum I’d expect some form of encryption of xaps on the wire and something like one time download urls for the xaps. Don’t steal other people’s applications or IP – just because you can, doesn’t make it legal!

Hardware v’s Software

I just entered the Qantas club here in Brisbane on the way home from a fantastic weekend of Windows Phone 7 development with all the attendees of the Bizspark camp. I noticed that they’ve replaced all the computers in the lounge with Macs. After my initial cringe, I took a closer look and almost laughed out loud – they’re all running Windows 7. This seriously raises the question: who’s making the best hardware and who’s making the best software (ie the OS).

What’s more interesting is if you look at not only the desktop but also the phone space I think that Apple definitely excels in creating visually appealing and powerful hardware. Unfortunately the simpleton nature of their iOS operating system and the frustrating MacOS interface leaves a lot to be desired. It appears that Microsoft might be ahead in the desktop OS war at the moment and it’s anyone’s race in the mobile space at the moment. Perhaps we’ll see Windows Phone 7 running on an iphone soon….. oh wait, that wouldn’t work since the iphone is the only phone on the market with only one front facing button (good on Apple for insisting that users really only want a single button – just like the mouse on the desktop. As I said, it’s a simpleton design).

Windows Phone 7: Where to store that application key? NOT in the Application

Building Windows Phone 7 applications using Visual Studio 2010 and Expression Blend is so much easier than building for any other mobile platform it’s easy to get lulled into a false sense of security. For example to use the Bing Maps control you need to go and register in order to receive an application key that you use in order to remove the warning message that appears in the middle of the maps control. It’s simple to just add this directly into the application via Blend and walk away – job done. Wrong!

Let’s think about the implications of this. What you’ve done is enter an application key into your application, which is going to be distributed via marketplace to any number of devices. This application key identifies your application and permits you access to Bing Maps (which is free for WP7 applications). Now what happens if one of those devices is owned by a malicious user who has completed at least half a computer science degree. It’s highly possible that they can extract the contents of your application, retrieve the plain text key (that’s right, even if you obfuscate your code, chances are this application key is still going to be visible in plain text) and use it in his own applications. Now your account with Bing Maps is getting completely slammed and Microsoft come knocking on your door asking for money!

So, what did you do wrong? You followed the Microsoft samples blindly. You added a secret application key into an application where ALL the code is easily readable (there are countless threads on how to protect your IP within managed application, and by far one of the safest is to put sensitive code in native code but of course you can’t do that with WP7 applications).

So, what can you do to fix it? Well it’s simple really….. don’t put the application key into the application in the first place. Right, but then how can we use for example the Bing maps control? Ok, so this is the crux of the problem, there is no bulletproof way to do this given the application key model. The best you can do is to place the application key behind a service and then either request it each time the application needs it (no caching) or request it the first time and cache it. Not ideal but at least it adds a layer of indirection to wanna-be-hackers.

Pet Peeve: How to break the back button experience in Windows Phone 7

Over the past couple of weeks I’ve been downloading a number of the new Windows Phone 7 applications and one of the things that has come to annoy me is when developers think that they can outsmart the user. Microsoft has gone to great pains to include a dedicated hardware back button on all Windows Phone 7 devices. It has a very clear function which is to return the user to the previous experience. Within an application this typical means going back to the previous page or closing a modal style dialog/prompt. At the beginning of an application this means allowing the application to close, revealing the previous application (or the Start) the user was in.

Of course, there always have to be the one or two super-smart developers out there that thing that the user might accidentally hit the back button. We don’t want the user to leave our application, in fact the more time we can get them to spend in the application the better, so let’s include a prompt confirming that the user does indeed want to exit the application. WRONG, FAIL, GO BACK, DON’T DO THIS.

As a user if I press the back button I want to go back. If I didn’t mean to leave the application I’ll launch the application again. If the application is any good this shouldn’t be an lengthy process, so even if the user accidentally pressed the back button, they will acknowledge that they made a mistake and so there is no foul. Getting in the way of what the user has explicitly instructed (ie by pressing the back button) the application to do is bad.

There is one exception to this rule: if there is unsaved data, you may want to prompt the user to either save, discard or cancel the operation. To be honest, even this should be avoided – there is no harm in temporarily saving what they were working on and having it available the next time they run the application.

Promoting your Windows Phone 7 application

So you’ve got your Windows Phone 7 application certified and it’s available for download via marketplace. You think you’re done? No, you’ve just started. With more applications appearing in the marketplace all the time it’s important that you continue to promote and advertise your application. To do this Microsoft have come out with a series of buttons that you can use to promote application downloads directly from the website.

Here is a sample of the various sized buttons in blue. There are versions of the button in English, French, German, Italian and Spanish and in blue, red and green. Download for Windows Phone 7 Button


Don’t forget to read the included readme and policy documents that come in the download. Also, for the format of the download link, check out the MSDN Documentation on How to: Link to Windows Phone Marketplace Content

Brisbane: Windows Phone 7 Start Up Camp

Brisbane: 13th-14th November

Now you have the skills – it’s time to use them to Build an app! The weekend workshop is all about you building something that you’d like to take to market. You can work by yourself or in teams; Microsoft’s Evangelists Dave Glover, Catherine Eibner and myself, plus a handful of local technical experts will be there to help you! At the end of the weekend, present your work to the judging panel of experts & investors to receive feedback & prizes.


To attend you must: Have AT LEAST 1 developer in your team that has attended the Skills Ramp Up Pre day or who already has experience in developing Applications for Phone 7. Be a member of Microsoft BizSpark (You will be asked to provide your BizSpark ID in your registration).

The Startup Camp is being held at Microsoft Brisbane Office.

  • Brisbane: 13th-14th November
  • Theatre 2 | Level 9, Waterfront Place 1 Eagle Street Brisbane QLD 4000 | Map
  • Register Now >

Windows Phone 7 Launches in Australia

Microsoft Australia held it’s press events this morning in a rather obscure venue to officially launch Windows Phone 7 into the Australian market with devices to be available on the 21st of October. Whilst there were the usual presentations from Microsoft and the launch carrier Telstra, it was the feature demos that really took the show. Having worked with the platform for over 6 months now there wasn’t much new material but it was great to see the range of slick looking devices being rolled out later in the month.

What frustrates me is how useless the Australian telcos are. All three of the majors, Optus, Vodafone and Telstra are carrying Windows Phone 7 devices but not one of them has bothered to update their consumer website with information about the phones. To make matters worse, the main page of all three sites are still going on about the fact iphone 4 “changes everthing again” (no it doesn’t, Apple haven’t innovated in 4 generations of the phone….)

If you go to the Telstra site you get an iphone4 ad on the consumer pages. You do however get a Windows Phone 7 ad on the business page. Did I miss something? Isn’t this launch about the consumer, not the business user?

image image

Windows Phone 7: Jumping through the Back Stack

Having a Back Stack within your application is a mixed blessing. Whilst the navigation service will allow you to easily step the user from one page to the next, allowing the user to return to the previous page via the back key, it can often end up with applications that are 10 or more pages in length. If the user wants to exit the application, or to go back to the previous application they have to step through all the pages (Internet Explorer, one of Microsoft’s own applications, is probably the worst case I’ve seen of this and imho is a complete design failure).

The guidance for building applications for Windows Phone 7 essentially suggests caution in opening up a new page for every activity the user does. Rather than a new page for everything, you can simply adjust the content rendering in the current page. This leads to another discussion on what’s appropriate use of the Back Button.

This morning I had a conversation with Shane ( regarding an application where the user had to step through a wizard. At the end of the wizard they effectively want to remove the wizard pages (ie the steps in the wizard) from the Back Stack, returning them to the page that they were on before the wizard. My thoughts are that the Wizard should be a single page where each step is essentially just a different visual state. The Back Button could still be used within the page, allowing the user to still step through the steps in the wizard. When they have completed the wizard it would then close the page, returning them to the previous page.

If my suggestion isn’t an option, then there are two ways (that I can think of) to return to the initial page:

- Throw an exception (eg GoHomeException) which is trapped by the Application_UnhandledException method. This could then navigate back to the initial page

- Set a global flag (eg GoingHome) and then use GoBack to return to the previous page. Essentially each page in the wizard would look for the global flag, and if it is set to true then it would automatically call GoBack until the initial page is found.

Both of these strategies can be seen in the following example

Windows Phone 7: Beating the Boot-time Blues

One of the things that you may have noticed when doing Windows Phone development is that it’s very easy to cause the startup or boot time of your application to blow out to a couple of seconds. This of course is the reason why there is built in support for a splash screen (add a 480x800 image called SplashScreenImage.jpg set as Content in order to have a splash screen appear for your Windows Phone 7 application). However a good application shouldn’t require a splash screen as it should start up almost instantly. This unfortunately is very hard to achieve – if you have an even moderately complex page as the first page of your application then startup time will be in the order of a second or so.

There are a number of things that affect the time it takes your application to start. One of the most significant things is the size of the initial assembly and any other assembly that is required at startup. The last part of this comment is just as important and often overlooked. If you move pages, classes etc into a secondary assembly, and your initial page references them (even if you have an instance variable of a type that is in the secondary assembly) that assembly will too be loaded into memory before your application starts!

Another thing that can cause a lot of pain (and in actual fact is a derivative of the above situation) relates to setting a background image for your page. There is a lot of guidance out there that states that all images should be added to your application with a build action of “Content”. This will ensure that they don’t blow out the size of your assembly and thus affecting the time your application takes to load. In most cases this guidance should be followed. However, if the image you are including is the background image for your page and you are setting the background image in the xaml of your page then the image should be included with build action of Resource. Why?….

Scenario 1 - Image as Content
- Application Starts
- Main Assembly is loaded (quick because image isn’t included)
- Page XAML loads
- Image is loaded from disk

=> Upshot is that both the assembly and image are in memory but it requires two round trips to disk, one to load the assembly, the other to load the image

Scenario 2 – Image as Resource
- Application Starts
- Main assembly is loaded (slower because image is loaded as it’s a resource)
- Page XAML loads

=> Upshot is that both assembly and image are in memory but now only one trip to disk to load the image, which is going to be quicker than two trips to load the same data into memory.

This is ok for applications where the main page is a simple page and the background graphics is relatively small. The impact on load time will be quite low (although will probably warrant the use of a splash screen). But what about applications that use the panorama on the initial page. If you include a large background image (say 800x800) so that is looks great when the user is scrolling left and right, all of a sudden you might have not one but perhaps 2 images that are almost 1Mb is size (2 images so that you can dynamically switch them between dark and light themes).

What to do?

Well, you should start thinking about delay loading them. The issue here is that you have to dynamically load the background on the Panorama control, which it doesn’t, out of the box, support. Dave has a great post on using XAML to set your background. Use this as a starting point and change the background layer to include an Image control. This will mean that you can data bind the Source property  to your view model. On startup set the Image source property to null (ie don’t load an image), then once the application has started set the source property to the uri of the background image (at this point you can decide whether to serve up a dark or light image depending on the theme set on the device). Don’t forget to set the build action of the images to Content, other wise you won’t see the savings.

If you simply set the new image Uri after startup the user is going to see the background image just appear – clearly not a great experience, so you can get creative and play around with animations to fade the background image in (change the Opacity from 0-100 over 2-3 seconds). Warning – Make sure you keep an eye on when the background image is loaded from disk. It’s very easy when playing with this stuff to accidentally force the image to load from disk at startup, rather than when you are transitioning in the background.

Happy boot time optimising….

Windows Phone 7 Passing Data Between Applications

So you really want to transfer data between application in Windows Phone 7? If so, then here’s how you can do it by leveraging the pictures hub. Essentially the pictures hub is exposed to your application through the MediaLibrary class that forms part of the xna namespace. One of the things you can do with the pictures hub is that you can save an image into the “saved pictures” folder using the medialibrary.SavePicture method. It doesn’t take a rocket scientist to realise that an image is just an arrangement of bytes and that you can of course include data embedded in the image.

Now I’m not an expert in the field of embedding data into an image, so I’m sure there are much better/cleaner and more efficient mechanisms for doing this but here’s a simple code snippet that will embed a text string into an image returned from the CameraCaptureTask:

void camera_Completed(object sender, PhotoResult e)
    var buffer = new byte[e.ChosenPhoto.Length];
    e.ChosenPhoto.Read(buffer, 0, buffer.Length);
    var bytes = Encoding.UTF8.GetBytes(this.TextToSend.Text + new string(' ',20-this.TextToSend.Text.Length));
    Length.Text = bytes.Length.ToString();
    for (int i = 0; i < bytes.Length; i++)
        buffer[i+100] = bytes[i];

    var x = new MediaLibrary();

Essentially we’re writing a string of 20 character into the image (there is an indent of 100 characters to avoid the image header). To read this string back out, either in the same or a different application you simply reverse the process.

private void ReadDataButton_Click(object sender, RoutedEventArgs e)
    var x = new MediaLibrary();

    var pict = x.SavedPictures.First((pic) => pic.Name == "SendDataImage.jpg");
    var strm = pict.GetImage();
    var buffer = new byte[strm.Length];
    strm.Read(buffer, 0, buffer.Length);
    var len = 20;
    var bytes = new byte[len];
    for (int i = 0; i < len; i++)
        bytes[i] = buffer[i + 100];
    TextSent.Text = Encoding.UTF8.GetString(bytes, 0, bytes.Length);

Windows Phone 7 Deep Dive Workshop visiting Perth

Brian’s already blogged thisbut I’d thought I’d reiterate the point. The Windows Phone 7 Deep Dive Workshop I’ve been running in the capital cities is coming to Perth. Get in early to secure your place at this workshop. Anyhow, here are the details:

Date/Time:     14 & 15th October

Cost:                FREE

Venue:             Enex100 Perth, Seminar Room, Level 3, 100 St Georges Terrace

Registration:  Click this link...


To get involved, you need Silverlight/WPF, C# .NET Framework skills and you should have completed a subset of hands on labs from the following:

The workshop will be run by Nick Randolph (that’s me!) from Built to Roam.  In case you’ve been wondering I’ve been working with Windows Phone for quite some time and have just a few blog posts talking about developing for Windows Phone. You can find my blog, here (  and my public profile at

Course Content (approximate schedule):
Day 1
  • Session 1: Introduction and Windows Phone User Experience Overview
  • Session 2: Animation, Orientation and Overlays
  • Session 3: Application Lifecycle, Navigation, Application Tiles and Notification
  • Session 4: Tasks and Touch
  • Session 5: Working with the Accelerometer, Sounds and Location
Day 2
  • Session 6: Connecting and Consuming the Web
  • Session 7: Retrieving, Storing and Synchronizing Data
  • Session 8: Silverlight Analytics, Unit Testing and other Frameworks
  • Session 9: Security, Authentication and Performance

Resco MobileLight Toolkit Beta download available for Windows Phone 7

On the eve of the release of the development tools for Windows Phone 7, Resco have released a beta version of their MobileLight Toolkit. I posted a while ago on a prototype wheel control I built. I’m happy to say that Resco have a similar control for date and time picking that absolutely rocks – it behaves just like the real date/time selectors on the device.


For more information check out the Resco MobileLight Toolkit website

Samsung Galaxy S: Android messes things up

One of the things I’ve struggled with over the last couple of months is that I have never owned or developed for Android. Whilst I don’t see this as a limitation, I do feel that I’ve become somewhat overly biased against Android – it is quite common to dismiss what we don’t know. Over the weekend I decided to take action, so I’m now the owner of a shiny new Samsung Galaxy S (Oh, did I mention I’m also paying $30 less per month on my new phone plan!). This post covers some initial thoughts I’ve had in the few hours that I’ve been using it.

Firstly, the hardware, whilst significantly lighter, is very reminiscent of the iphone 3G. In fact, the Samsung experience in general is very much an iphone knock off. That said, it’s much snappier than the iphone 3G I have running iOS4. I’m yet to see what the final Windows Phone 7 hardware will be like.

My complaint about Android has always been that it was designed for the tech crowd. Unfortunately the Galaxy S didn’t disappoint. Like HTC, Samsung have opted for a black box, which opens up to reveal the device. The screen was covered with protector that was coloured with a mess of icons. After digging through the rest of the box to find the battery I managed to boot the device, only to see another mess of icons, this time on the home screen.

The user experience of the Galaxy S is actually not that bad, but it does require a bit to get used to. There are all sorts of things that you can tweak and configure, ranging from the 7 home screen panels through to which services (eg GPS, WiFi) are running. I definitely like having the program meter widget which you can click on to give you a list of running apps and the ability to kill them. Of course, this does bode the question as to why you need this – wouldn’t it be better to control how apps can use the resources of the device?

Connecting the device to the desktop was another challenge in itself. Why do all these phones insist on having heavily desktop companion software? After a lengthy install process and some painful digging to update drivers I managed to get the device connected and syncing. One big thing for me over the prototype WP7 device I’ve been working with was the ability to do internet sharing (aka tethering). This actually worked pretty smoothly and was quick!

Personally my overall feeling about the Galaxy S is that it’s a great device for the technically inclined but to be honest way way way way too complex for the average consumer out there. “Long live the Google geek” – it’s a bit of a myth that everyone likes technology, a bit like “pervasive connectivity” . Like all the hype around Linux, Android will only make it big once they get that building a great phone is about end user simplicity. I should turn it on and it should work!

Windows Phone 7 Deep Dive Workshop (Adelaide) and the SQL Server User Group (Conor Cunningham)

For those interested in attending the Windows Phone 7 Deep Dive workshop in Adelaide later this month but also want to attend the SQL Server User Group where Conor Conningham (Query Optimizer guru) will be presenting, fear not. As part of the WP7 workshop we will make sure we align the lunch break so that you can attend the user group session.

Full details for the Windows Phone 7 Deep Dive Workshop (follow link for all cities and to register):

Date: 27th-28th September
Venue: Board Room | Level 26, Santos House, 91 King William Street Adelaide SA 5000

Day 1
  • Session 1: Introduction and Windows Phone User Experience Overview
  • Session 2: Animation, Orientation and Overlays
  • Session 3: Application Lifecycle, Navigation, Application Tiles and Notification
  • Session 4: Tasks and Touch
  • Session 5: Working with the Accelerometer, Sounds and Location
Day 2
  • Session 6: Connecting and Consuming the Web
  • Session 7: Retrieving, Storing and Synchronizing Data
  • Session 8: Silverlight Analytics, Unit Testing and other Frameworks
  • Session 9: Security, Authentication and Performance


Full details for the SQL Server User Group (Adelaide):

Venue: L2 Westpac House (91 King William St, cnr Currie St) 
Duration 12:00-14:00
On: Tuesday, 28 September 2010

So how does SQL Server pick which plan to run? If you've ever wanted to get a better understanding of how the Query Optimizer works, this is the talk to attend. Come listen to a member of the Query Processor development team explain how a query goes from SQL to the final plan. This talk will cover conceptual topics like how query trees are built and how the optimizer stores all of the alternatives it is considering. Additionally, the talk will examine examples in areas including index matching, parallel query generation, and update processing so that you can apply these concepts to better debug your own queries using the same techniques.

Conor Cunningham is a Principal Software Architect at Microsoft on the SQL Server Query Processor Team. He's worked on database technologies for Microsoft for over 10 years and is holds numerous patents related to Query Optimization and Query Processing. Conor is the author of a number of peer-reviewed articles on query optimization techniques. Recently, he authored a chapter for the book "Microsoft SQL Server 2008 Internals" on how the Query Optimizer works. He publishes a blog called "Conor vs. SQL" (where he answers questions about databases.

Conor will be joining us via LiveMeeting. If you are unable to attend in person, please ask Rob Farley for the link so that you can join remotely.

Windows Phone 7 Deep Dive Workshops (Melbourne, Sydney, Adelaide and Brisbane)

Update: This event is FREE! Register by clicking the links below but please make sure that you read the prerequisites and only register if you 110% able to make it for the two days in your city.

…coming to a city near you

Are you interested in Windows Phone 7 Development? Are you keen to get ahead of the competition to create apps for the Windows Phone 7?

Windows Phone 7 is a fresh exciting mobility platform and potentially a land of opportunity for killer apps! These “Free of Charge” workshops are designed to take your skills to the next level beyond the online training kits and helps you explore some more complex scenarios.


To get involved, you need Silverlight/WPF, C# .NET Framework skills and you should have completed a subset of hands on labs from the following:

The workshop will be run by Nick Randolph (that’s me!) from Built to Roam.  In case you’ve been wondering I’ve been working with Windows Phone for quite some time and have just a few blog posts talking about developing for Windows Phone. You can find my blog, here (  and my public profile at

Course Content:

Day 1
  • Session 1: Introduction and Windows Phone User Experience Overview
  • Session 2: Animation, Orientation and Overlays
  • Session 3: Application Lifecycle, Navigation, Application Tiles and Notification
  • Session 4: Tasks and Touch
  • Session 5: Working with the Accelerometer, Sounds and Location
Day 2
  • Session 6: Connecting and Consuming the Web
  • Session 7: Retrieving, Storing and Synchronizing Data
  • Session 8: Silverlight Analytics, Unit Testing and other Frameworks
  • Session 9: Security, Authentication and Performance

When/Where and Registration:

  • Melbourne: 20th-21st September
    • Exhibition Room| Level 5, 4 Freshwater Place, Southbank VIC 3006 | Map
    • Register Now >
  • Sydney: 23rd-24th September
  • Adelaide: 27th-28th September
    • Board Room | Level 26, Santos House, 91 King William Street Adelaide SA 5000 | Map
    • Register Now >
  • Brisbane: 29th-30th September
    • Theatre 2 | Level 9, Waterfront Place 1 Eagle Street Brisbane QLD 4000 | Map
    • Register Now >

We look forward to seeing you there!

Windows Phone Team

Microsoft Australia

PS – please register soon as places are limited

Fighting the Lock Screen in Windows Phone 7 by disabling IdleDetectionMode

One of the things you may experience with your Windows Phone application is that it will get suspended when the lock screen is displayed. As the lock screen appears after a relatively short period of time this can be particularly frustrating if you have to synchronize a large quantity of data, or you have created a game that only requires the accelerometer (no user input on the screen can result in the application appearing to be idle). To get around this you can disable idle detection by setting one of two properties.




Essentially setting the UserIdleDetectionMode to disabled will prevent the lock screen automatically appearing, whilst setting ApplicationIdleDetectionMode to disabled will allow the application to continue to operate whilst the lock screen is active. Note that there is a clause in the application certification requirements that stipulate the conditions with which you must comply when setting these properties.

Windows Phone 7 and Compression using Accept-Encoding Header

As a few of my readers have commented on my post  Windows Phone 7 Data: Json WCF Data Service with IIS 7 Compression, there is a breaking change between the CTP and Beta versions of the Windows Phone developer tools that prevents you from setting the Accept-Encoding header. One could argue that the fact you could set this at all in the ctp was a bug, since Silverlight 3 doesn’t permit this. Unfortunately not being able to set this header is a major pain if you want to take advantage of the built in IIS dynamic and/or static compression. I would really like to see this fixed before the tools ship but given we’re only a couple of weeks away from the ship date of the tools I doubt very much if it will be.

Having spent a few days at TechEd Australia thinking about this issue I went digging to see if we could either force IIS to compress all data (ie that way we wouldn’t have to set the Accept-Encoding header) or better still try to apply compression based on some other request attribute. In the end the fix was actually surprisingly simple.

Firstly, I have to call out a post by Ted Jardine on IE6 gzip bug solved using IIS7's URL Rewrite Modulewhich put me on the right track. Essentially the process goes like this:

- In the request we set a different header (I chose one called “Compress-Data” and set it to a value of  “true”)
- On the server we define a rewrite rule that will detect this header and set the Accept-Encoding header to gzip,deflate for all matching requests.
- The server would then serve up compressed data – Woot!

Ok, so these are the steps you need to follow:

1) Update the applicationHost.config file to allow you to modify the allowedServerVariables element. This file is typically found at C:\Windows\System32\inetsrv\config

        <sectionGroup name="system.webServer">
            <sectionGroup name="rewrite">
                <section name="allowedServerVariables" overrideModeDefault="Allow" />

2) Add a rewrite rule to the web.config file for your application. Note that you have to include allowedServerVariables element in order for the HTTP_ACCEPT_ENCODING server variable to be set by the rule.

                <add name="HTTP_ACCEPT_ENCODING" />
                <rule name="RewriteUserFriendlyURL1" patternSyntax="Wildcard" stopProcessing="false">
                    <match url="*" />
                        <add input="{HTTP_COMPRESS_DATA}" pattern="true" />
                    <action type="None" />
                        <set name="HTTP_ACCEPT_ENCODING" value="gzip,deflate" />

This will match all urls, looking for the HTTP_COMPRESS_DATA variable set to true. When working with rewrite rules you have to remember that headers are converted to variables by a) making them upper case, b) replacing “-“ with “_” and c) adding HTTP_ as a prefix. In this case when a match is found the HTTP_ACCEPT_ENCODING variable (ie the Accept-Encoding header) is set to gzip,deflate, as if you had specified this in the header when making the request.

3) Now all we need to do is to call this from our Windows Phone application, specifying the appropriate header.

private void MakeRequestButton_Click(object sender, RoutedEventArgs e){
    var request = HttpWebRequest.Create("<request url>”) as HttpWebRequest;
    request.Accept = "application/json";
    request.Headers["Compress-data"] = "true";
    request.BeginGetResponse(RequestCallback, request);

private void RequestCallback(IAsyncResult result){
    var request = result.AsyncState as HttpWebRequest;
    var response = request.EndGetResponse(result);
    using(var strm = response.GetResponseStream())
    using (var reader = new StreamReader(strm)){
        var data = reader.ReadToEnd();
        // data will be compressed

Although this example specifies the Accept header to request JSON (as per my previous post on compression), this is not required and you can apply the Compress-data header to any request you make. Of course you should also examine the Content-Encoding header on the response to make sure you only decompress a response that is compressed. If the server ignores the Compress-data header (which will be the default case if the rewrite rule is missing or fails) you will get back uncompressed data.

Windows Phone 7 Sessions at TechEd Australia with Prizes

As a reminder – come check out my two sessions at TechEd Australia. The Windows Phone sessions will have a number of giveaways including three copies of the Professional Visual Studio 210and two MSN Subscriptions.

DEV354     Shake, Rattle and Roll with Windows Phone 7
Thursday 09:45 - 11:00 : Breakout Session : Nick Randolph : 300

What distinguishes a Windows Phone 7 application from a regular desktop application is that it can make use of the features of the phone. In this session you'll learn how to initiate tasks to capture photos from the camera, save a phone number, make a call and send an sms. The hardware integration goes much further with built in support for an accelerometer and FM radio tuner. When combined with the rich media aspects of Silverlight on the device, your Windows Phone 7 application will be set to keep you rocking all night long. .

DEV356     Advanced Windows Phone Services
Thursday 17:00 - 18:15 : Breakout Session : Nick Randolph : 300

Building Windows Phone 7 applications is all about combining the power of Silverlight on the device with services in the cloud. You can offload long running processes to a worker process hosted in Windows Azure, and receive a push notification when it completes. Your application can also leverage the location services to provide more context rich information. This session walks through how you can consumer a number of cloud-based services such as Messenger Connect, Windows Azure storage and OData WCF Data Services from within your Windows Phone 7 application. Of course, this wouldn't be complete without the mandatory discussion on how to handle connectivity issues, such as caching and synchronization.

Windows Phone 7 and Image Overlays

If you’ve taken a read through the interaction and design guidelines that Microsoft has published on building for Windows Phone 7, or if you’ve listened to some of the recordings from the recent developers days, you may have picked up on a little trick that they use on the Start screen that you might want to take advantage of. On the Start screen the text on the tiles is white but what’s interesting is that no matter what you set the background image to, the text is always readable. How do they do this, well they apply an overlay to the image before applying the text. Depending on whether you are using white (light) or black (dark) you will use either a light or dark overlay.

Let’s look at what happens if you don’t apply an overlay. The following image contains a dark image (ie the TV on the left) and a light image (ie the modem on the right). The top row has text in white, whilst the bottom has text in black. As you can see white text on a dark image works well, as does black text on a light image. One option would be to do some fancy analysis of the image and then determine what color text to use – this is both requires a lot of precious cycles and ends up with a non-uniform (aka messy) interface.


The other alternative is to pick either white or black for the text and then apply an appropriate overlay to the images. In the following image we’ve applied a 20% black overlay to the top row (making the white text readable on both images) and a 20% white overlay to the bottom row (making the black text readable on both images).


So, enough of the mocked up images, show me how to do this in XAML:

<Grid Width="200" Height="200" >
    <Image Source="{Binding SourceImage}" />
    <Border Background="Black" Opacity="0.2"/>
   <TextBlock Text="{Binding ImageTitle}" Foreground=”White”/>

Relatively straightforward – all we need to do is add a Black overlay (in this case I’ve used a Border element) with 20% opacity between the image itself and the White text.

Windows Phone 7: Monitoring Application Startup Performance

If you’ve taken a look at the guidance for Windows Phone 7 applications you might be aware of the requirement for your application to startup within a certain period of time and for it to be responsive within another time period (I’m intentionally being vague he as I don’t want to be misquoted – you want the details, go checkout the marketplace requirements via In addition to it being a requirement, you should always seek to minimise the startup time of your application. But during your development cycle, how do you ensure that the startup time of your application doesn’t slowly creep up? If you get to the end of the development and realise that your application takes a minute to load, you’re going to have to do a lot of work to cut this back to an acceptable level.

The answer to this question is to have a way to automatically time how long your application takes to launch. Of course you’d want to run this multiple times to get an average startup time. The Windows Phone emulator supports automation which you can use to deploy and launch your application. All you need is a way to start a timer before launching your application and then for it to stop when the application is launched.

Let’s take a console application and use that to deploy and launch our Windows Phone application. We can start a StopWatch before we launch the application but how are we going to know when to stop it? One way would be to simply stop the clock when the Launch() method returns. Unfortunately this probably won’t give us the flexibility we need to be able to record how long it takes for the application to be responsive. What we need is a way for the application itself to indicate that it has finished loading.

To solve this we add a simple WCF Service to our console application. The Windows Phone application will call this service to let it know that startup is complete. Although this will add a little overhead to the startup time itself, because we are really only interested in the regression analysis of the startup time (ie how it varies over time) this isn’t important. To make it easy to add and remove this functionality from your application  I’ve moved the service reference into a separate assembly.

The steps for measuring startup time for your application:

- Add a reference to BuiltToRoam.StartupTime.dll to your Windows Phone application
- Add the ServiceReference.ClientConfig file to your Windows Phone application which includes the BasicHttpBinding_IStartupTimeService endpoint information
- Call Startup.EndStartupTimer when your application has finished loading. For example in the Loaded event handler:

private void PhoneApplicationPage_Loaded(object sender, RoutedEventArgs e){

- Update the ProductId, XAPFileName and AppIconFileName settings in the app.config file of the BuiltToRoam.StartupTimeRunner console application to match your Windows Phone application.

<setting name="ProductId" serializeAs="String">
<setting name="XAPFileName" serializeAs="String">
<setting name="AppIconFileName" serializeAs="String">

NB: The ProductId comes from the WMAppManifest.xml file under the Properties node in your Windows Phone application.

- Run the BuiltToRoam.StartupTimeRunner application


When you run the StartupTimeRunner you should see a console window launched showing the progress of the runner. It will launch the emulator and then deploy your XAP file to it (Assuming you got the path right). Once deployed it will attempt to launch your application 20 times (this can be adjusted in the app.config file too), each time recording how long it takes to start (see image for sample output).


Once it has finished it will give you an average startup time. As you build out your application I’d suggest that you periodically run this to make sure you aren’t significantly lengthening the startup time.

The Code

Ok, so I guess you want to see how this works. Well I’ll leave you to go through the details but the bulk of it is in the Main method of the console application which is as follows:

static AutoResetEvent endTestRunEvent = new AutoResetEvent(false);
static void Main(string[] args){
    Guid applicationGuid = Properties.Settings.Default.ProductId;
    Console.WriteLine("Application Id: " + applicationGuid);
    string xapFile = Properties.Settings.Default.XAPFileName;
    Console.WriteLine("XAP Filename: " + xapFile);
    if (!File.Exists(Path.Combine(Environment.CurrentDirectory, xapFile))){
        Console.WriteLine("Unable to locate XAP file. Press Enter to exit");
    string iconFile = Properties.Settings.Default.AppIconFileName;
    Console.WriteLine("Application Icon Filename: " + iconFile);
    if (!File.Exists(Path.Combine(Environment.CurrentDirectory, iconFile))){
        Console.WriteLine("Unable to locate Icon file. Press Enter to exit");

    DatastoreManager dsmgrObj = new DatastoreManager(1033);
    Platform WP7SDK = dsmgrObj.GetPlatforms().Single(p => p.Name == "Windows Phone 7");

    Device device = WP7SDK.GetDevices().Single(d => d.Name == "Windows Phone 7 Emulator");

    // Use the following if you want to retrieve a reference to the actual device
    // Device device = WP7SDK.GetDevices().Single(d => d.Name == "Windows Phone 7 Device");

    using (ServiceHost host = new ServiceHost(typeof(StartupTimeService))){
        Console.WriteLine("Connecting to Windows Phone 7 Emulator/Device...");
            Console.WriteLine("Windows Phone 7 Emulator/Device Connected...");

            device.InstallApplication(applicationGuid, iconFile, xapFile);

            Stopwatch sw = new Stopwatch();
            List<long> startupTimes = new List<long>();
            var exiting = false;
            for (int i = 0; i < Properties.Settings.Default.StartupIterations; i++){
                if (endTestRunEvent.WaitOne(Properties.Settings.Default.StartupTimeout * 1000)){
                    Console.WriteLine("Run " + i + " - Startup time(ms): " + sw.ElapsedMilliseconds.ToString());
                    Console.WriteLine("Unable to startup application within specified startup timeout. Press Enter to exit.");
                    exiting = true;

            if (!exiting){
                var averageStartupTime = startupTimes.Average();
                Console.WriteLine("Average startup time (ms): " + averageStartupTime);
                Console.WriteLine("Press Enter to Exit");
        finally {

public static void ApplicationStarted(){

Download Source Code