Nick's .NET Travels

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

Windows Phone 7 Beta: My Application Won’t Start After Renaming Project

Yesterday I lost an hour or so tracking down a bug whereby I hit F5/Run in Visual Studio to debug a Windows Phone application. I’d been happily doing this all morning, then I decided to rename my application. You’d have thought this was just a matter of renaming the project, assembly name, default namespace, class/xaml namespaces, xap file and assembly information (to make sure they’re all consistent, rather than because they’re necessarily required in order to rename the application). It turns out that I’d completely forgotten to set the Startup object to the new xap file. We’ll it wasn’t all my fault – I’ve since then created a new project, changed the namespace in app.xaml, app.xaml.cs, mainpage.xaml and mainpage.xaml.cs and tried (unsuccessfully) to get Visual Studio to let me select NewApplication.App to be the startup object (as you can see in this image). Remember that it’s is the class (typically App) that inherits from Application that is the startup object for a Windows Phone application.

image


The symptoms (and this is true if the Startup object is set to “(not set)” or to an incorrect app name) is that Visual Studio deploys the application but when it goes to invoke the application it fails, so Visual Studio returns to the not running state (no errors!). If you attempt to run the application on the emulator you get the same thing – application goes to launch then crashes (again no error message/warning).

The fix is quite simple – Build the Windows Phone application (which shouldn’t have any errors, although in my opinion there should be to point out that the startup object doesn’t match a valid class), then Unload the project (by right-clicking the project and selecting Unload Project as the image below suggests). All you need to do now is to reload the project by again right-clicking the project node and selecting Reload Project.

.image

If you open up the project properties page you should be able to select the correctly named app as the startup object.

Windows Phone 7 Beta with Windows Live Messenger Connect

Recent Microsoft announced a major update to their Live platform. There are a number of updates that are currently in Beta including Messenger and Live Writer but what interests me is the new development platform, Messenger Connect. Go to the Windows Live developer portal for all the details. For anyone who has worked with any of the Live Id apis in the past it was difficult to get all the information you wanted. It appears that Messenger Connect is a great rationalisation of these apis and with libraries to support both rich and web client access, getting started should be easy.

Unfortunately, and for those getting into the Windows Phone space you’ll get used to this, there is no library available for accessing the Messenger Connect apis. Of course, the team has done a great job of making all the data available via REST  but honestly, that’s like trying to write a Windows Phone app in XAML when you have the power of Blend…. not something you want to have to do.

I figured it couldn’t be that hard to take the existing library for Silverlight, decompile it thanks to Reflector, update it to work for Windows Phone and we should be good to go. No so, after quite a painful day yesterday I have got a working library that’s able to authenticate and access contacts and activities (haven’t tested the other functionality yet). Unfortunately this meant not only reverse engineering the Microsoft.Live.dll but also the odata sdk library for Windows Phone (as they haven’t made the source available). Anyhow, enough complaining about the lack of source code publishing by Microsoft (please, please, please Microsoft, stop closed-sourcing these sdk libraries – all it does is frustrate us!).

So the SDK library is relatively easy to use:

- Start by adding a reference to the Microsoft.Live and System.Data.Services.Client (the one in the attached zip file, not the odata sdk version).

- Next, you’ll need a WebBrowser control on the page that you’re going to do the authentication on – this is used to display the Messenger Connect sign in prompt. The SDK library for Silverlight uses a ChildWindow but this isn’t available for Windows Phone so I’ve hacked around this for the moment. I’m sure there’s a better solution for this so feel free to modify it

- Add a button and some code to authenticate the user:

const string ClientId = "***Your-Client-ID***";
const string ClientSecret = "***Your-Secret-Key***";

LiveDataContext dataContext = new LiveDataContext();
AppInformation appInfo;

private void SignInButton_Click(object sender, RoutedEventArgs e)
{
    SignInButton.IsEnabled = false;

    try
    {
        appInfo = new AppInformation(ClientId, ClientSecret);
        appInfo.RequestedOffers.Add(new Offer()
        {
            Name = "WL_Contacts",
            Action="View"
        });
        appInfo.RequestedOffers.Add(new Offer()
        {
            Name = "WL_Activities",
            Action = "View"
        });
        appInfo.RequestedOffers.Add(new Offer()
        {
            Name = "WL_Photos",
            Action = "View"
        });
                
        this.dataContext.SignInAsync(this.SignInBrowser, appInfo, null);
    }
    catch (Exception ex)
    {
        ShowErrorDialog("Failed to sign in to Windows Live: {0}", ex.Message);
        SignInButton.IsEnabled = true;
    }
}

private void SignInCompleted(object sender, SignInCompletedEventArgs e)
{
    if (!e.Succeeded)
    {
        string authError = (e.AuthInfo.Error == null) ? string.Empty : e.AuthInfo.Error.Message;
        ShowErrorDialog("Failed to sign in to Windows Live! {0}", authError);
        SignInButton.IsEnabled = true;
    }
    else
    {
        MessageBox.Show("Welcome To Windows Live!", "Windows Live", MessageBoxButton.OK);
        this.Contacts.Visibility = System.Windows.Visibility.Visible;
    }
}

private static void ShowErrorDialog(string errMsg, params string[] paras)
{
    MessageBox.Show(string.Format(errMsg, paras), "Windows Live", MessageBoxButton.OK);
}

Essentially the process goes like this:

- the user clicks the SignInButton
- the WebBrowser control is displayed and navigates to the Messenger Connect sign in page
- the user signs in and grants appropriate privileges
- after sign in the WebBrowser is automatically hidden and the SignInCompleted event is raised

In action:

image

In the code to sign in you will have noticed that there are three Offers that have been requested. These correlate to the scopes of information that the user is going to grant this application. In this case View privileges to Contacts, Photos and Activities. To retrieve these sets of information we can kick of an odata service call.

private void FetchContactsButton_Click(object sender, System.Windows.RoutedEventArgs e)
{
    var qry= dataContext.ContactsQuery;
    qry.BeginExecute(Response, qry);
}
void Response(IAsyncResult result)
{
    var qry = result.AsyncState as DataServiceQuery<Contact>;
    var contacts = qry.EndExecute(result);
    this.Dispatcher.BeginInvoke(() =>
    {
        this.InformationList.Items.Clear();
        foreach (Contact c in contacts)
        {
            this.InformationList.Items.Add(c.ToString());
        }
    });
}

private void FetchActivitiesButton_Click(object sender, RoutedEventArgs e)
{
    var qry = dataContext.MyActivitiesQuery;
    qry.BeginExecute(ActivitiesResponse, qry);
}

void ActivitiesResponse(IAsyncResult result)
{
    var qry = result.AsyncState as DataServiceQuery<Activity>;
    var contacts = qry.EndExecute(result);
    this.Dispatcher.BeginInvoke(() =>
    {
        this.InformationList.Items.Clear();
        foreach (Activity c in contacts)
        {
            this.InformationList.Items.Add(c.ToString());
        }
    });
}

This code illustrates retrieving the list of contacts and activities for the currently signed in user.

Hopefully this will help you build a Windows Phone application that takes advantage of the new Messenger Connect apis. Oh, before I forget, to get the sample to work you’ll need to sign up for access to the Messenger Connect apis, then register your application (use the Windows Application option). Include the ClientId and ClientSecret at the top of the MainPage.xaml.cs (first code sample above).

Messenger Connect Sample: Download Sample

Update: It’s important that you read the licensing agreements that accompany the use of the apis. Angus posted on Messenger Connect saying the following:

    1. Public APIs: Our “Public APIs” are available to all developers and third parties to access in a self-service manner. Appropriate use is governed by our Terms of Use and Terms of Service, and is monitored for abuse reported by customers. Third parties can sign-up for access through our application management tool at http://manage.dev.live.com.

How’s my Windows Phone 7 application being used? Getting started with the Microsoft Silverlight Analytics Framework for Windows Phone development

Microsoft has just released an update to the Silverlight Analytics Framework which now includes support for Windows Phone development. This gives you a standard approach to include usage tracking within your Silverlight application that is somewhat independent of the tracking site/service you use. I say somewhat as each service requires a custom behavior to be created in order for it to be used with the framework. Luckily the major tracking services already have behaviors available for Silverlight 3 and 4.

To get started tracking usage within your Windows Phone application get the updated version of the Microsoft Silverlight Analytics Frameworkand run through the installer.

image

We’ll cover using the Console output and Google Analytics to track usage but you can use the behavior that corresponds to the tracking service you use (at the time of writing this only includes Webtrends, Google Analytics and the generic Service Oriented Analytics).

In this case we’re going to create a new Windows Phone application but there is no reason why you can’t add the event tracking to an existing application (just skip the first step of creating a new application).

image

Next, add the following references to your application:

ComponentModel
Composition.Initialization
Google.WebAnalytics (only required if you want to use Google Analytics to track events)
Microsoft.WebAnalytics
Microsoft.WebAnalytics.Behaviors
Microsoft.WebAnalytics.Navigation
System.Windows.Interactivity

image

Due to some of the limitations of the Silverlight implementation on Windows Phone there is an additional step that is required in order for the MSAF to work properly. Add a new class called AnaltyicsApplicationService to your project can update the code to look like the following:

using System.ComponentModel.Composition.Hosting;
using System.Windows;

public class AnalyticsAppplicationService : IApplicationService
{
    public void StartService(ApplicationServiceContext context)
    {
        CompositionHost.Initialize(new AssemblyCatalog(
            Application.Current.GetType().Assembly),
            new AssemblyCatalog(typeof(Microsoft.WebAnalytics.AnalyticsEvent).Assembly),
            new AssemblyCatalog(typeof(Microsoft.WebAnalytics.Behaviors.TrackAction).Assembly));
    }

    public void StopService() { }
}

Next, update your App.xaml to look like the following. If you are adding MSAF to an existing application the important part in this code snippet is the creation of the two additional ApplicationLifetimeObjects, AnalyticsApplicationService and WebAnalyticsService.

<Application 
    x:Class="MSAFSampleForWP7.App"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"       
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:phone="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone"
    xmlns:shell="clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone"
    xmlns:local="clr-namespace:MSAFSampleForWP7"
    xmlns:mwa="clr-namespace:Microsoft.WebAnalytics;assembly=Microsoft.WebAnalytics">

    <!--Application Resources-->
    <Application.Resources>
    </Application.Resources>

    <Application.ApplicationLifetimeObjects>
        <local:AnalyticsAppplicationService/>
        <mwa:WebAnalyticsService/>
        <shell:PhoneApplicationService 
            Launching="Application_Launching" Closing="Application_Closing" 
            Activated="Application_Activated" Deactivated="Application_Deactivated"/>
    </Application.ApplicationLifetimeObjects>

</Application>

We’re going to add some behaviors to the pages of the application so let’s jump across to Expression Blend. You can easily do this by right-clicking on the Windows Phone application project and clicking the Open in Expression Blend link

image

Make sure that you rebuild the application within Blend so that the various windows are all up to date. In the Assets window, under Behaviors > Analytics, you’ll see that there are a number of different behaviors that you can drag onto your application to track events.

image

Start by dragging both the ConsoleAnalytics and GoogleAnalytics behaviors on the LayoutRoot node in the Objects and Timeline window. In this example we’re also going to track a button click event, so you’ll have to add a button to the page. Then you can drag the TrackAction behavior onto the button. This should give you the following tree in the Objects and Timeline window.

image

There are some additional properties you will need to set on the GoogleAnalytics behavior. Whilst the Category isn’t required, it’s a good idea to set it so that you can easily filter the event data by category. I’d suggest at least making the Category application specific.

image

The Web Property ID is required and needs to correspond to the ID of your Google Analytics account. When you log into Google Analytics, you can find this ID on the first page, along side the list of profiles.

image

You also need to configure properties on the TrackAction behavior. In this case the behavior is responding to the Click event of the button. We’re also going to specify both a Category and Value that will be passed through to Google Analytics (don’t include any user information that can be identified unless you’re going to be using SSL!)

image

And that’s all there is to it. Run your application up and you will see a basic page where you can go ahead and click the button. The Google Analytics event tracking will record application start up and the button click event.

image

Now you might be wondering how you’re going to view the console output. Well there are two ways: Firstly, assuming the debugger is attached you can view the console output in the Output window in Visual Studio. Alternatively, if you’re running the application on the emulator you can enable the console output window. This is done by setting the \HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\XDE\EnableConsole registry key to 1 – you’ll most likely have to create this entry as it isn’t there by default.

image

With this registry key set, if you restart the emulator, you should see a command prompt window appear that lists the console output from the emulator.

image

Ok, now the last thing to do is to go back to Google Analytics and check that the events are coming through. Be warned that there can be a substantial delay between raising the events and them appearing in the Google Analytics window. To find the event tracking you have to drill into the Content > Event Tracking node on the left side of the page.

image

That’s all there is to getting started with the MSAF for Windows Phone.

________________________________________________________________________________________

Issues: At the moment the current installer doesn’t work as described above. There are a couple of issues, one relating to the binaries that are installed and the other relating to the Google Analytics implementation for WP7. The installer is also missing half the source files for the WP7 sample project

1 & 3) The first and third issues can be resolve by downloading the actual source for the MSAF. This includes all the source code for the sample project and will allow you to recompile the MSAF. Download the source from the Source Code tab of the MSAF codeplex site

2) The second issue relates to the way the code detects whether to use ssl or not for downloading the Google Analytics event tracking image. Essentially this code attempts to detect whether the uri for the current document uses ssl or not. Clearly for a WP7 app this isn’t going to work. The work around for this is to decompile the GoogleAnalytics assembly (not sure why this isn’t checked into codeplex), modify the code and recompile the source. The following link contains the Google Analytics assembly along with the working test project.

MSAF with Fixed Google Analytics Download

Windows Phone 7 beta: Debugging Tombstoned XNA Games with Visual Studio

In my previous posts on Windows Phone 7 I’ve been focussing on Silverlight. You can of course build applications and games using XNA – not being that familiar with XNA it’s going to take a lot of encouragement for me to invest serious time into learning another framework but if I was building games I think it’s a technology that is worth knowing since you can build games for Windows, XBox and now Windows Phone.

One of the things that you may notice when you build and deploy your XNA game to the emulator is that it doesn’t appear in the applications list. That’s because it is installed as a game, not an application. As such it appears in the Games hub, rather than in the applications list. If you use one of the hacked emulator builds you can see this hub and use it to relaunch your application without the debugger attached if you feel like it.

Ok, so onto the topic of this post. The last couple of posts have been about how you accommodate for the Windows Phone application lifecycle model, specifically the fact that your application may (and in the case of the current emulator, will) get terminated when it goes into the background. In these posts we used the Launching, Activated and Deactivated events on the Application (wired up in the App.xaml) and we relaunched Visual Studio when necessary in order to resume the debugging experience. This is essentially the same process for XNA with some minor differences.

Firstly, there is no App.xaml file, so you have to manually wire up these events. Also, by default there is no project reference to Microsoft.Phone.dll, so you’ll have to add that too. Then in the Game1.cs file (or in my case the MyGame.cs file, since I renamed the game from Game1 to MyGame) you need to attach the necessary event handlers. Note that I’ve wrapped the event wiring and the event handlers themselves with a check for the WINDOWS_PHONE conditional compilation symbol. Remember that you can target multiple platforms with the same XNA game – each target has a different compilation symbol: WINDOWS, XBOX, and now WINDOWS_PHONE.

public MyGame()
        {
            graphics = new GraphicsDeviceManager(this);

            //Set the Windows Phone screen resolution
            graphics.PreferredBackBufferWidth = 480;
            graphics.PreferredBackBufferHeight = 800;
            graphics.IsFullScreen = true;

#if WINDOWS_PHONE
            Microsoft.Phone.Shell.PhoneApplicationService.Current.Launching += new EventHandler<Microsoft.Phone.Shell.LaunchingEventArgs>(Current_Launching);
            Microsoft.Phone.Shell.PhoneApplicationService.Current.Deactivated += new EventHandler<Microsoft.Phone.Shell.DeactivatedEventArgs>(Current_Deactivated);
            Microsoft.Phone.Shell.PhoneApplicationService.Current.Activated += new EventHandler<Microsoft.Phone.Shell.ActivatedEventArgs>(Current_Activated);
#endif
            Content.RootDirectory = "Content";

            // Frame rate is 30 fps by default for Windows Phone.
            TargetElapsedTime = TimeSpan.FromSeconds(1/30.0);
        }

#if WINDOWS_PHONE
        void Current_Launching(object sender, Microsoft.Phone.Shell.LaunchingEventArgs e)
        {

        }

        void Current_Activated(object sender, Microsoft.Phone.Shell.ActivatedEventArgs e)
        {

        }

        void Current_Deactivated(object sender, Microsoft.Phone.Shell.DeactivatedEventArgs e)
        {

        }
#endif

 

Now, the second thing that you’ll have to do is to change the build configuration to prevent Visual Studio deploying your game every time. If you don’t do this the sequence goes like this:

Run Game > Press Start  (Game terminates in background) > Press Back (blank screen displayed) > Press F5/Run in Visual Studio (this builds, deploys and attempts to run game) > Game runs as if it wasn’t tombstoned (ie Launching event raised instead of Activated)

To get the Activated event to fire you need to adjust the build configuration so that it doesn’t deploy the game every time you press F5/Run. Right-click on the solution in Solution Explorer and select Configuration Manager. Uncheck the box in the Deploy column.

image

You can still deploy your XNA game to the device, you just need to right-click on the project and select Deploy (remember to do this each time you make changes to your XNA game to make sure you are debugging the latest version).

Run Game > Press Start  (Game terminates in background) > Press Back (blank screen displayed) > Press F5/Run in Visual Studio (runs game) > Game runs as if it were tombstoned (ie Activated event raised)

Windows Phone 7 beta: Application Crashes With No Exception In Visual Studio

Here’s a simple scenario: You have some code that gets invoked during application startup (for example creating instances of your view model, loading data from isolated storage etc). Whilst developing this code you place breakpoints in this code. When you run your application in the debugger the breakpoints get hit, you step through the code and it all works as expected. However, when you press F5 to continue, the application just terminates and Visual Studio stops debugging…. you’re left thinking what the?

What I suspect your seeing is the implementation of one of the Windows Phone 7 requirements around launching. If you read the Windows Phone 7 Application Certification Requirements you will see that 5.2.1 talks about launch time.

5.2.1 Launch Time
a. The application must render the first screen within 5 seconds after launch.
To meet this requirement, Microsoft recommends that the application provides a splash screen image in a file called SplashScreenImage.jpg in the root of the XAP package.
b. Within 20 seconds after launch, the application must be responsive to user input.

If you either allow your application to launch without breakpoints, or you quickly step through your breakpoints you should see that your application loads without any issues. If you stop the application on a breakpoint for a good 30 seconds, your likely to see your application terminated. This also applies to when you return to your application after it has been Tombstoned (ie Deactivated and then terminated in the background) – in this case you need to make sure you restart your application from Visual Studio quickly otherwise it will be terminated completely and you’ll have to restart your debugging again.

Windows Phone 7 beta: Launcher and Chooser Tasks Cludge

Firstly I have to apologise to any readers who experienced issues viewing my blog over the last 72 hours. This was a result of my awesome (not!) hosting provider webhost4life. Anyhow hopefully the issues have been resolved and life can continue.

In my previous post (Windows Phone 7 beta- Who Killed My Application) I talked about what happens when your application goes into the background. Specifically that in the current bits your application will be terminated. Now in actual fact the Windows Phone developer contract doesn’t state this, it only says that your application may be terminated any time between when your application receives a Deactivated event and when it receives an Activated event. In the case where it is terminated (which is always the case in the current dev bits) when the user presses the Back button your application will be relaunched and the Activated event raised (not the Launching event).

Here’s another scenario where you may be wondering what’s going on with Visual Studio. In your application you want to use the CameraCaptureTask to take a photo. You create an instance of the CameraCaptureTask, add an event handler for the Completed event (note that this is different from the April CTP where you overrode a method on the base class) and then call the Show method. For example the following code launches the CameraCaptureTask and then sets the photo as the source of an Image control.

using System;
using System.Windows;
using System.Windows.Media.Imaging;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Tasks;

namespace WindowsPhoneTasks
{
    public partial class MainPage : PhoneApplicationPage
    {
        CameraCaptureTask cameraTask = new CameraCaptureTask();
     
        // Constructor
        public MainPage()
        {
            InitializeComponent();

            cameraTask.Completed += new EventHandler<PhotoResult>(cameraTask_Completed);
        }

        void cameraTask_Completed(object sender, PhotoResult e)
        {
            var source = new BitmapImage();
            source.SetSource(e.ChosenPhoto);

            this.PhotoImage.Source = source;
        }

        private void TakeAPhotoButton_Click(object sender, RoutedEventArgs e)
        {
            cameraTask.Show();
        }
    }
}

When you run this you will notice something weird. The following screenshot sequence illustrates this. Initially the emulator is at the Start screen (1). You run the application from Visual Studio and then you click the Take Photo button (2). This launches the camera capture dialog (3) and you’ll notice that your application has been terminated – this dialog is a bit buggy at the moment so you may need to click around the screen in order to find the button to take a picture; it’s in the top right corner! When you click “accept” you will see a blank screen(4). If you recall from my previous post, this is what happened when the user clicked the Back button to return to your application. You’re seeing a blanks screen because your application isn’t there any more. Press F5 or Run your application from Visual Studio and the Completed event will be fired, displaying the photo in the Image (5).

 

image[4]

Here’s the cludge (as if having to restart Visual Studio wasn’t enough of a cludge): In order for the Completed event to work the instance of the CameraCaptureTask has to be an instance variable where the event handler is wired up in the constructor of the page. As you can imagine there is some additional logic that gets performed as part of the add event handler operation (using Reflector):

 

public event EventHandler<TTaskEventArgs> Completed
{
    add
    {
        if ((this._completed == null) || (Array.IndexOf<Delegate>(this._completed.GetInvocationList(), value) == -1))
        {
            this._completed = (EventHandler<TTaskEventArgs>) Delegate.Combine(this._completed, value);
            InvokeReturningEventArgs args = null;
            if (ChooserListener.IsChooserCompletePending(this._genericChooser, value, out args))
            {
                this.OnInvokeReturned(args.returnBuffer, value);
            }
        }
    }
    remove
    {
        this._completed = (EventHandler<TTaskEventArgs>) Delegate.Remove(this._completed, value);
    }
}

Windows Phone 7 beta: Who Killed My Application

If you hadn’t already noticed Microsoft have released the first beta of the Windows Phone 7 developer tools. There are some significant, breaking, changes from the previous release from April. These have been quite well documented in this migration post however there are some gotchas that aren’t pointed out. The first of these is what happens when your application goes into the background.

As most of you will be aware Microsoft has been avoiding the question as to what the behaviour is when your application goes into the background (eg the Start is displayed and/or another application loaded). This is in part because they don’t want developers to develop according to the current Windows Phone implementation. Rather they want developer to develop against a contract which states that “should your application go into the background, it should assume that it will be terminated at any point in the future by the operating system”. What this means in practice is that Windows Phone has the option of leaving your application in memory, effectively running in the background, or terminating it immediately or at a later stage.

Let’s take a look at what happened in the April CTP – in this case when your application went into the background there was a Paused event raised on the Application which you could intercept and persist any information about the current state of your application. However, your application wasn’t actually terminated when the user presses the Start button (on the emulator that is).

Now, let’s look at the behaviour in the beta of the tools. Now, when you run your application, then click on the Start button you will notice that your application is terminated (this is evident because you will notice Visual Studio is no longer attached to the running process). However, when you click the Back button, your application should reappear, right? Wrong! Well, at least, without you doing anything that will be the case. What you actually see when you press the Back button is a blank screen. At this point if you run your application from Visual Studio 2010 it will start as if the user had pressed the Back button.

Take the following scenario:

1) Application loads and displays page 1
2) User navigates to page 2
3) User clicks Start (application is terminated)
4) User clicks Back (application is not running)
>> Press F5 or Run in Visual Studio
5) Application loads and returns to page 2.

Note that when the application loads for the second time, page 1 is never loaded. However, if the user presses the Back button again page 1 will again be displayed.

You should also be aware of the events that get raised within your application (these are exposed by the PhoneApplicationService and are wired up by default in App.xaml to methods in the App.xaml.cs file)

Launching – This event is raised when the application is launched from the Start screen. This event is not raised when the application is reloaded when the Back button is pressed.

Activated – This event is raised when the application is returned to by clicking the Back button. This event is not raised when the application is launched from the Start screen

Deactivated – This event is raised when the application is sent into the background. This might be due to the user clicking the Start button, or launching a task. You should save both persistent (between application sessions) and transient (for the current application session) at this point. You should assume that your application may get terminated at will by the operating system. You will not get another opportunity when this happens to persist information.

Closing – This event is raised when the application is closed by the user pressing the Back button when at the home/first page of the application.

I can’t reiterate this enough: When you get the Deactivated event, make sure you save both the persistent and transient state of your application. This should also include information about the visual state of the current page (eg what text the user may have entered, perhaps even which control has focus). When the user clicks the Back button, they will want to see the same page that was there when they pressed the Start button, irrespective of whether the application was terminated and relaunched, or not.

Windows Phone 7 Environment.DeviceType = Un-Blendable code

So, you’ve decided to be really inventive and build some helper classes that work around the limitations of the Windows Phone 7 emulator (eg inability to simulate network connectivity, accelerometer, location, actually anything that isn’t in Silverlgiht for the desktop). Of course you don’t want this code to be used when the application runs on a real device so you have some code that looks like:

if (System.Environment.DeviceType == DeviceType.Device)
{
    // Device code
}
else
{
    // Emulator code
}

This compiles and runs fine when working in Visual Studio and Blend. However, if this code is invoked as part of building the UI to be displayed in the designer (remember that both Visual Studio and Blend run a bit of code in the background to make sure things are created properly and that data contexts are created to facilitate data binding), you will likely see a message similar to the following.

image

“Method not found: ‘System.DeviceType System.Environment.get_DeviceType()’.

Right, you think, simple enough to fix, I just need to wrap this in a check to see whether it’s running in the designer or not:

if (!DesignerProperties.IsInDesignTool && System.Environment.DeviceType == DeviceType.Device)
{
    // Device code
}
else
{
    // Emulator code
}

Unfortunately you’d be horrified to note that this does NOT get the error to disappear. The error is actually an error raised by the JIT compiler when it goes off looking for DeviceType property. Unfortunately there is no such property on the desktop so it throws an error. Typically JIT compilation is done on an “as required” and “method-level” basis which means that the whole method you are working in will be JITted together, resulting in the error even if the code will never be executed. The workaround…. just move the erroneous  code to a method that won’t get JITted:

 if (!DesignerProperties.IsInDesignTool )
{
    DoRuntimeCode();
}
else
{
    // Designer code
}

private static void DoRuntimeCode()
{
    if (System.Environment.DeviceType == DeviceType.Device)
    {
        // Device code
    }
    else
    {
        // Emulator code
    }
}

Problem fixed…. happy coding.

(FWIW this is a trick that Windows Mobile developers have used for years to build libraries that work across both .NET Framework and .NET Compact Framework where there are features on either platform that aren’t available on the other)

Windows Phone 7 Applications Running Under the Locked Screen

The new Application Certification Requirements document for Windows Phone 7 Marketplace has been published by Microsoft and includes a couple of interesting points:

Firstly, Microsoft, like Apple, have a stupid clause in their Application Policies to the effect that you can’t charge a subscription basis for access to your application. Well, you could it Marketplace gave you the ability to charge a subscription – they don’t, and since 2.1 forbids you from using an external payment gateway (eg PayPal), you can’t do it.

image

The second and more interesting item is that Windows Phone 7 applications can continue to run even after the Lock screen has appeared.  Apparently there will be (and I say will be as it’s not in the current SDK bits) a method called Microsoft.Phone.Shell.PhoneApplicationService.ApplicationIdleDetectionMode which has to be invoked to allow the application to continue to run.

image

Windows Phone 7 Data: Json WCF Data Service with IIS 7 Compression

Today I was thinking about the way I consume data within my Windows Phone 7 applications, specifically how I can get a large amount of data into my application. Attempting to send 100Mb worth of uncompressed data across the wire when I could send the same thing compressed at around 25Mb wasn’t really appealing to me. This got me thinking…. “how did I do this on Windows Mobile?”…. surprisingly the answer is blindingly obvious: IIS  compression. In this post I’ll walk you through exposing your data via a WCF Data Service, enabling IIS compression (for IIS 7) and then how you can leverage this on the client side.

Let’s start by creating a simple WCF Data Service to consume:

WCF Data Service

In an ASP.NET project, create a new ADO.NET Entity Data Model, mine is called YoLoModel.edmx (YoLo stands for You only Live once, which was the name of the sample application I built as part of my Remix Australia presentation last week).

image

Next add a new WCF Data Service, and fill in the blanks with the name of your data context (In my case it’s YouOnlyLiveOnceEntities) and enable read access – you should come back later and tighten security!!

using System.Data.Services;

namespace CompressedService
{
    public class YoLoData : DataService<YouOnlyLiveOnceEntities>
    {
        public static void InitializeService(IDataServiceConfiguration config)
        {
             config.SetEntitySetAccessRule("*", EntitySetRights.AllRead);
        }
    }
}

At this point you should run up your ASP.NET project to make sure you get data when you view the data service. You should also make sure that your project is running on IIS, rather than using the Visual Studio Development Server. To do this go to Web tab of the project properties and change to “Use Local IIS Web server” (you need to hit the Create Virtual Directory to create the virtual directory so your application will run on IIS, and don’t forget to save the project properties). In my case IIS is running on port 8080 – this has no bearing on being able to use compression, just happens to be how I have IIS configured on my development machine.

image

Test this using either the browser or Fiddler.

image

IIS Compression

Setting up IIS 7 Compression isn’t that difficult once you know what to do. Start by using either the Web Platform Installer  or Programs and Features. Locate and check the box next to Dynamic Content Compression and hit Install – this adds the module to support dynamic compression into IIS.

image

Next, open up IIS Manager and locate your ASP.NET application. From the Feature View select Compression and then ensure both static and dynamic compression is enabled.

image

Next you have to enable dynamic compression for specific mime-types. Make sure you have the Server node (not your virtual directory or the web site nodes) selected and then select the Configuration Editor from the Feature View.

image

Locate the webServer/httpCompression node and find the dynamicTypes list.

image

Add any missing mime-types to cover SOAP, ATOM, JSON etc (you might as well enable them whilst you’re there). Whilst there is a trade off between performance and compression, dynamic compression only happens when the client requests it, so I’d turn it on for these mime-types and then make sure the clients only use compression appropriately (it’s up to you how you do this).

image

Don’t forget to hit the Apply button!!!

Don’t forget to RESTART IIS, make sure all your web processes restart otherwise you won’t see compressed output.

image

Now, go to Fiddler and use the Request Builder tab to create a GET request. I this case I’m requesting the url http://nickwp7dev:8080/CompressedService/YoLoData.svc/Patients. You need to specify the following headers:

Accept: application/json       -       This will cause WCF Data Services to give you the output in json format which is much trimmer than the bloated xml it usually generates. If you do want to work with xml then you can omit this header.

Accept-Encoding: gzip, deflate       -       This is what tells IIS to generate compressed data.

When you Execute this request you should see that Fiddler detects compressed data – If you don’t then go back and make sure you’ve hit Apply and restarted IIS as this seems to be the problem I came up against when experimenting with this.

image

If you click the yellow bar, Fiddler is kind enough to decompress the data so you can see the json output (or xml if you’ve omitted the Accept header).

image

Windows Phone

Right, so that’s the server side done. Now you need to implement decompression on the client. Unfortunately, unlike true rich client technologies such as WPF or WinForms, Silverlight and Windows Phone are somewhat crippled when it comes to dealing with data. However, with a little help you can work with the data quite easily.

In order to decompress the data coming from IIS I use SharpZipLib. Well actually I used a slightly hacked together version of it. Essentially there are things that need to be updated to be compatible with Silverlight/Windows Phone.

Hacked SharpZipLib for Windows Phone available here

Once you have SharpZipLib, decompressing the data is relatively straight forward:

using System;
using System.IO;
using System.Net;
using System.Windows;
using ICSharpCode.SharpZipLib.GZip;
using Microsoft.Phone.Controls;

namespace WindowsPhoneApplication1
{
    public partial class MainPage : PhoneApplicationPage
    {
        public MainPage()
        {
            InitializeComponent();

            SupportedOrientations = SupportedPageOrientation.Portrait | 
                                     SupportedPageOrientation.Landscape;
        }

        private void DisplayDataButton_Click(object sender, RoutedEventArgs e)
        {
            var request = HttpWebRequest.Create("http://nickwp7dev:8080/CompressedService/YoLoData.svc/Patients");
            request.Headers["Accept"] = "application/json";
            request.Headers["Accept-Encoding"] = "gzip, deflate";
            request.BeginGetResponse(RequestCallback, request);
        }

        void RequestCallback(IAsyncResult response)
        {
            var request = response.AsyncState as HttpWebRequest;
            var resp = request.EndGetResponse(response);
            var strm = resp.GetResponseStream();

            string data;
            using (var gzip = new GZipInputStream(strm))
            using(var reader = new StreamReader(gzip))
            {
                data = reader.ReadToEnd();
            }

            this.Dispatcher.BeginInvoke(()=>{
                this.DataText.Text = data;
            });
        }
    }
}

Run this, an there you go – compressed data from IIS 7 to Windows Phone!

image

Don’t forget you can use the json deserializer to then parse this into objects.

Remix Australia 2010: I’m speaking on Windows Phone 7

Speaking_at_remix_au_2010_large Next week is the Australian reincarnation of the sensation MIX event held earlier this year in Vegas. This year remix Australia is being held in Melbourne over not one but two whole days. As you probably know I’m not a “web-guy” so you might be wondering what I’m doing showing up at a web event. Well here’s the catch, it’s all about rich internet-enabled applications. I don’t care if it’s written in HTML 5, Silverlight, WPF or hey, even WinForms, so long as you’re doing intelligent things like client side storage, offline support and rich UI then you’re talking my language.

This year my focus is almost exclusively on Windows Phone 7. My session, entitled Windows Phone 7: The emperor has got some new Threads, showcases the tools and technologies that make up developer story for Windows Phone 7. Immediately following my session is Luke Drumm’s session on Windows Phone 7: Debauchery on the silicon seas : High adventure in a small amount of code. I’m really looking forward to this session to watch Luke smash the Phone around a bit using the XNA Framework.

There is just so many awesome features to discuss, but here are a few of the points to watch out for in my session.
- Notification Services
- Location
- Emulator Automation
- Accelerometer
- Panoramic and Pivot controls
- Voice synthesis, transcription and translation

All this in a hour! Don’t forget if you like what you see you should pre-order the book I’m working on (yes, another one): Professional Windows Phone 7 Application Development: Building Windows Phone Applications Using Silverlight. The title on Amazon is a little misleading at the moment as it won’t be covering much on games development or XNA (one chapter on this) but it is a deep dive on everything that makes building Windows Phone applications in Silverlight so great.

What to do with an audio recording using the microphone on Windows Phone 7?

Most of the examples that you see for working with the microphone on Windows Phone 7 usually take the resulting byte array and either play it back (using the XNA audio namespace) or save it in its current form to IsolatedStorage. Unfortunately, the byte array isn’t much use by itself as it can’t be played back directly using say Media player. What you need to do is actually convert it to a wav file by wrapping the raw sample data in the appropriate header information. Following the WAV specifications you end up with a set of helper methods that look similar to the following:

using System;
using System.Text;

namespace MediaHelper
{
    public static class SoundUtilities
    {
        public class WaveFormat
        {
            public int Encoding { get; set; }
            public int AverageBytesPerSecond { get; set; }
            public int BlockAlign { get; set; }
            public int Channels { get; set; }
            public int SamplesPerSecond { get; set; }
        }

        public static byte[] ConvertRawSamplesToWav(
           byte[] samples, WaveFormat format)
        {
            var ascii = Encoding.UTF8;
            var byteArrayLength = 36 + samples.Length;
            var byteArray = new byte[byteArrayLength+10];
            var index = 0;

            // Specify that this is a RIFF file and the length of the file in bytes
            index += byteArray.CopyInto(index, ascii.GetBytes("RIFF"));
            index += byteArray.CopyInto(index, byteArrayLength.AsFixedByteArray(4));

            // Specify that this is a WAVE and start the format header
            index += byteArray.CopyInto(index, ascii.GetBytes("WAVE"));
            index += byteArray.CopyInto(index, ascii.GetBytes("fmt "));

            // Format header is fixed size of 16
            index += byteArray.CopyInto(index, (16).AsFixedByteArray(4));

            // Encoding: "1" for PCM
            index += byteArray.CopyInto(index, (format.Encoding).AsFixedByteArray(2));

            // Number of Channel
            index += byteArray.CopyInto(index, (format.Channels).AsFixedByteArray(2));

            // Samples per second
            index += byteArray.CopyInto(index, (format.SamplesPerSecond).AsFixedByteArray(4));

            // Average bytes per second
            index += byteArray.CopyInto(index, (format.AverageBytesPerSecond).AsFixedByteArray(4));

            // Block Align
            index += byteArray.CopyInto(index, (format.BlockAlign).AsFixedByteArray(2));

            // Bits per sample
            index += byteArray.CopyInto(index, ((8*format.AverageBytesPerSecond)/format.SamplesPerSecond).AsFixedByteArray(2));

            // The Samples themselves
            index += byteArray.CopyInto(index, ascii.GetBytes("data"));
            index += byteArray.CopyInto(index, samples.Length.AsFixedByteArray(4));
            index += byteArray.CopyInto(index, samples);

            return byteArray;

        }

        public static int CopyInto(this byte[] byteArray, int offset,byte[] bytes )
        {
            bytes.CopyTo(byteArray, offset);
            return bytes.Length;
        }

        public static byte[] AsFixedByteArray(this int number, int fixedByteArraySize)
        {
            int remainder, result;
            var returnarray = new byte[fixedByteArraySize];
                
            result = DivRem(number, 256, out remainder);

            if (result >= 1)
            {
                returnarray[0] = Convert.ToByte(remainder);
                var tmpArray = result.AsFixedByteArray(fixedByteArraySize - 1);
                tmpArray.CopyTo(returnarray, 1);
            }
            else 
            {
                returnarray[0] = Convert.ToByte(number);
            }
            return returnarray;
        }

        public static int DivRem(int a, int b, out int result)
        {
            result = a % b;
            return (a / b);
        }
    }
}

Of course, in order to make use of this code you need to know what the format of the raw samples are. This can be obtained by looking at the Microphone instance that you are using to record the audio. The following screenshot illustrates the various properties you will need to know

image

Windows Phone 7 Emulator Themes and Resources

If you’ve been looking at building Windows Phone 7 applications using Silverlight you will probably have come across the set of styles and resources that are defined within the App.xaml file. For example the following section defines the foreground and background colors to be used.

<Application 
    x:Class="Sounds.App"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"       
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:system="clr-namespace:System;assembly=mscorlib"
    xmlns:mpc="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone.Controls"
    xmlns:phoneNavigation="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone.Controls.Navigation">
    
    <!--RootFrame points to and loads the first page of your application-->
    <Application.RootVisual>
        <phoneNavigation:PhoneApplicationFrame x:Name="RootFrame" Source="/MainPage.xaml"/>
    </Application.RootVisual>

    <!-- Resources for following the Windows Phone design guidelines -->
    <Application.Resources>
        <!--************ THEME RESOURCES ************-->
        <!-- Color Resources -->
        <Color x:Key="PhoneBackgroundColor">#FF1F1F1F</Color>
        <Color x:Key="PhoneContrastForegroundColor">Black</Color>
        <Color x:Key="PhoneForegroundColor">White</Color>
        <Color x:Key="PhoneInactiveColor">#FF666666</Color>
        <Color x:Key="PhoneDisabledColor">#FF808080</Color>
        <Color x:Key="PhoneSubtleColor">#FF999999</Color>
        <Color x:Key="PhoneContrastBackgroundColor">#FFFFFFFF</Color>
        <Color x:Key="PhoneTextBoxColor">#FFBFBFBF</Color>
        <Color x:Key="PhoneBorderColor">#FFCCCCCC</Color>
        <Color x:Key="PhoneTextSelectionColor">Black</Color>
        <Color x:Key="PhoneAccentColor">#FF1BA1E2</Color>

One thing to note here is that if you change the theme background or accent (see image below: Start –> Settings, Theme) this will NOT be reflected by your application the next time your run it. This is because the colors have been hard coded in the App.xaml file

image

The solution to this is to remove the appropriate resources from the app.xaml file. Of course, this will break your designer experience within Visual Studio and Blend but will mean that your application reflects the theme settings of the emulator. But here lies the problem, which resources do you remove? Well of course, you can remove all the resources that are going to be defined by Windows Phone…. ok, but how do we know what they are?

Justin has been releasing a number of awesome posts on connecting to the emulator using the managed wrapper. In particular the article on Emulator Automation is definitely worth studying closely. Using the hacked emulator image I went trawling through the Windows directory and notices a number of xaml files that looked interesting. Using Justin’s post as a starting point I decided to rip a couple of these xaml files off the emulator and take a look at what’s inside. The process for doing this is relatively straight forward:

- Create a Windows application (WinForms or WPF, doesn’t matter)

- Add references to c:\Program Files\Common Files\microsoft shared\Phone Tools\CoreCon\10.0\Bin\Microsoft.Smartdevice.Connectivity.dll

- Write some code to receive the files you want from the emulator

// Get CoreCon WP7 SDK
DatastoreManager dsmgrObj = new DatastoreManager(1033);

Platform WP7SDK = dsmgrObj.GetPlatforms().Single(p => p.Name == "New Windows Mobile 7 SDK");

// Get Emulator / Device
bool useEmulator = true;
Device WP7Device = null;
if (useEmulator)
    WP7Device = WP7SDK.GetDevices().Single(d => d.Name == "Windows Phone 7 Emulator");
else
    WP7Device = WP7SDK.GetDevices().Single(d => d.Name == "Windows Phone 7 Device");

// Connect to WP7 Emulator / Device
WP7Device.Connect();

try{
    ICcConnection phone = WP7Device.GetType().GetField("mConmanServer", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(WP7Device) as ICcConnection;

    f.ReceiveFile(@"\windows\0000_system.windows.xaml", @"c:\temp\0000_system.windows.xaml", true);
    f.ReceiveFile(@"\windows\0000_themeresources.xaml", @"c:\temp\0000_themeresources.xaml", true);

    WP7Device.Disconnect();
}
catch (Exception ex){
    WP7Device.Disconnect();
}

When you execute this code (you need to have the Windows Phone 7 emulator already running) it will download the two files 0000_system.windows.xaml and 0000_themeresources.xaml to the c:\temp directory. You can then open them up and inspect which resources are defined. For example the themeresources.xaml file starts as follows:

<ResourceDictionary
  xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  xmlns:System="clr-namespace:System;assembly=mscorlib">

  <Color x:Key="PhoneBackgroundColor">White</Color>
<Color x:Key="PhoneContrastForegroundColor">White</Color>
<Color x:Key="PhoneForegroundColor">Black</Color>
<Color x:Key="PhoneInactiveColor">#ffcccccc</Color>
<Color x:Key="PhoneDisabledColor">#ffcccccc</Color>
<Color x:Key="PhoneSubtleColor">#ff999999</Color>
<Color x:Key="PhoneContrastBackgroundColor">Black</Color>
<Color x:Key="PhoneTextBoxColor">#ffbfbfbf</Color>
<Color x:Key="PhoneBorderColor">#ff999999</Color>
<Color x:Key="PhoneTextSelectionColor">White</Color>
<Color x:Key="PhoneAccentColor">#FF339933</Color>

If you look at the \windows directory on the emulator (using the hacked emulator you can used the shortcuts application but you need to select Options-> Show All Files) you will see that there are system.windows.xaml and themeresources.xaml files numbered 0000, 0001, 0002 and 0003, and then also 0100, 0101, 0102 and 0103. As you can guess these correspond to the eight themes (light/dark with orange/blue/red/green). You can download all of these xaml files and take a look at the resources that are defined.

Disclaimer: Don’t make any dependencies on the values of these resources as they could/might/probably will vary before Windows Phone ships.

Windows Phone 7 Emulator Launch Time versus Notification Services

I’ve got a bit of a dilemma as to which emulator image to work with for Windows Phone 7.  As you are no doubt aware there is a hacked emulator image available that opens up some of the hidden functionality of Windows Phone 7. For example most of the built in applications such as the hubs and Office are available in the hacked build.

Here’s a couple of things you might not know:

- The official build is SLOW and I’m not talking slow whilst running applications (I think this is about the same speed), I’m talking about the boot and time to launch/connect debugger to your application. This is a royal pain and has caused me to go back to the hacked build because it’s so much quicker to debug your application on.

- The hacked build will NOT work with Notification services. If you are seeing any issues with notification services, make sure that you a) use the official build and b) make sure you check your proxy settings. Even if you think your proxy settings won’t make a difference, try turning them off and seeing whether notification services work.

Here’s the dilemma – I want to use notification services in my application but I don’t want to have to wait up to 5 minutes for Visual Studio to launch and debug my application……

Windows Phone Hacked Emulator Not Working With Notification Services

For the last week I’ve been trying to work out why my sample application for the Windows Phone Notification API had stopped working. And yes, before everyone chimes in with “have you set the publisher” and “have you updated the capabilities list” I’d already done all that and had fully working samples showing tile, toast and raw notifications. About a week ago all these samples stopped working. Thinking I must have done something wrong I tried all the available samples on the web that I could find. None of them worked either – the symptom is that you never get a Channel Uri back, if you locate and existing channel it’s uri is always null.

The fix was….. switch back to the official emulator image. That’s right, I’d been using the hacked emulator ROM image (the one that was released based on the April emulator). Turns out there must be something screwy going on because the notification services seem to have stopped playing nice with it. I switched back to the official emulator image and everything works again. Ho Hum… I wonder if that was intentional by Microsoft, or just a result of them tightening security around the notification services.

Windows Phone 7 Flicker Viewer

Firstly, I need to point out that Dave Glover was the original person to put together the code for this example Windows Phone 7 application. I just tidied it up and did the screencast (no audio).

This was actually delivered (with audio) yesterday during the webdu keynote. I figured it would be worth doing a quick screencast of it this morning and making it available for anyone interested.

Windows Phone 7 – Photo Extras Application Extensibility

One of the things we heard about at MIX was the ability for you to register your application as a photo editing application. A registered application would appear in the Extras list when viewing a photo on the device, allowing the user to launch a third party application to edit, modify, manipulate a photo. The documentation released at MIX provided the necessary instructions (latest version is here) but it wasn’t until the April update to the WP7 developer tools that it was actually possible to see this in action.

The steps are super simple:

1) Create a new xml file in the root of your Windows Phone 7 project called Extras.xml (don’t worry about changing any of the build properties).

2) Change the contents to the following:

<?xml version="1.0" encoding="utf-8" ?> 
<Extras> 
  <PhotosExtrasApplication>true</PhotosExtrasApplication> 
</Extras>

 

3) Build and run your application. Your application will now appear in the Extras list.

Ok, but how do I see it in action. Well the easiest way is actually to use the unlocked emulator image. You can then just open the Pictures hub and look at any of the sample images. Expand the Application Bar (somewhat hidden but if you click the image you’ll see it appear) and then select extras.

image image

I can’t seem to work out how you then access the image that’s been selected from within your application but it’s either something I haven’t found yet, or not in this build yet.

Windows Phone 7 Notification Service Updates

There are some changes that you need to make if you want Windows Phone 7 notifications to work with the April refresh of the developer tools (from readme):

Update Publisher

You need to specify a publisher in the WMAppManifest.xml file. Default value is “”. Can be anything, so long as it’s not empty (or missing)

<?xml version="1.0" encoding="utf-8"?> 

<Deployment xmlns="http://schemas.microsoft.com/windowsphone/2009/deployment" 
            AppPlatformVersion="7.0"> 
  <App xmlns="" ProductID="{b2a3afee-70be-40c7-8dc1-81ac8c14163e}" 
          Title="Notifications" RuntimeType="SilverLight" 
          Version="1.0.0.0"  Genre="NormalApp"  
          Author="Nick Randolph" Description="Notification App"  
          Publisher="BuiltToRoam">

Toast Notification Format

Format of the message has changed from:

var messageTemplate = "Content-Type: text/xml\r\n" + 
    "X-WindowsPhone-Target: toast\r\n\r\n" + 
    "<?xml version=\"1.0\" encoding=\"utf-8\" ?>" + 
    "<wp:PushNotification  xmlns:wp=\"WindowsPhonePushNotification\">" + 
      "<wp:Toast>" + 
        "<wp:Text1>{0}</wp:Text1>" + 
        "<wp:Text2>{1}</wp:Text2>" + 
      "</wp:Toast>" + 
    "</wp:PushNotification>";

To:

var messageTemplate = "Content-Type: text/xml\r\n" + 
    "X-WindowsPhone-Target: toast\r\n\r\n" + 
    "<?xml version=\"1.0\" encoding=\"utf-8\"?>" + 
    "<wp:Notification xmlns:wp=\"WPNotification\">" + 
       "<wp:Toast>" + 
          "<wp:Text1>{0}</wp:Text1>" + 
          "<wp:Text2>{1}</wp:Text2>" + 
       "</wp:Toast>" + 
    "</wp:Notification>";

 

Tile Notification Format

Format of the message has changed from (which I could never get to work):

var messageTemplate = "Content-Type: text/xml\r\n" + 
    "X-WindowsPhone-Target: tile\r\n\r\n" +  
    "<?xml version=\"1.0\" encoding=\"utf-8\" ?>" + 
    "<wp:PushNotification  xmlns:wp=\"WindowsPhonePushNotification\">" +  
       "<wp:Token wp:TokenID=\"{0}\">" +  
          "<wp:TemplateType5>" +  
             "<wp:BackgroundImageURI>{1}</wp:BackgroundImageURI>" +  
             "<wp:Count>{2}</wp:Count>" +  
             "<wp:Title>{3}</wp:Title>" +  
          "</wp:TemplateType5>" +  
       "</wp:Token>" +  
    "</wp:PushNotification>";

To:

var messageTemplate = "X-WindowsPhone-Target: token\r\n\r\n" + 
    "<?xml version=\"1.0\" encoding=\"utf-8\"?>" + 
    "<wp:Notification xmlns:wp=\"WPNotification\">" + 
       "<wp:Token>" + 
          "<wp:Img>{0}</wp:Img>" + 
          "<wp:Count>{1}</wp:Count>" + 
          "<wp:Title>{2}</wp:Title>" + 
       "</wp:Token> " + 
    "</wp:Notification>";

This format does work, except for some reason I can’t get remote image backgrounds to work. If you specify a local image for the Img value it should work. Note that you need to pin your application to the Start in order to see the application tile update – check out this post which covers how to pin your application to the Start area.

image

A last comment:

If you are wondering why your notifications are not being received on the emulator you may also see the following exception in the debugger output window:

A first chance exception of type 'System.Collections.Generic.KeyNotFoundException' occurred in mscorlib.dll

This usually happens if the notification message you are trying to send is corrupt or ill formed (I’m not sure of the exact cause). At the moment the only way I’ve found to recover from this exception is to reboot the emulator. If you attempt to restart the application you will simply continue to see this exception for every notification you try to send.

Windows Phone 7 Application Tiles

With the April update of the Windows Phone 7 developer tools, which adds compatibility with Visual Studio 2010, you also get an update to the Windows Phone 7 emulator. One of the things that was missing in the previous build was the ability to pin your application to the Start. In this build you can go to the application list (click the right arrow from the Start), tap and hold on the application you want to pin to Start. This will display a drop down list of actions, including “pin to start”, select this item and return to Start to see your application.

 image

If you want to remove your application from Start, you need to tap and hold on the application on the Start. You will notice a little pin with a line through it appear on your application. Tapping the pin will remove the application from the Start. Note that the pin is a change in this build from the little broken heart that we saw in the previous build.

You can also check out the unlocked emulator image to see a few more of the updates in this build. Note that you can actually replace the emulator image installed with the Windows Phone 7 developer bits (ie C:\Program Files\Microsoft SDKs\WindowsPhone\v7.0\Emulation\Images\wm70C1.bin) as the new unlocked image supports debugging from within Visual Studio 2010/Blend. I would take a copy of the official rom image just to be safe!

Upgrading Windows Phone 7 Projects to April CTP

If you open a Windows Phone 7 project that was created with the initial release of the developer tools you will see a prompt similar to:

image

Essentially one of the updates in the April CTP is related to the enforcement of security policies for applications that want to make use of device capabilities. I’m expecting that this will be integrated into the Marketplace experience so that users who download your application will have to acknowledge that the application will have access to capabilities on the device.

Anyhow, to get your application to run, you may need to add the appropriate capabilities, as instructed in the warning message. From the previous release of the dev tools, your WMAppManifest.xml file (located under the Properties node of your Windows Phone 7 project) probably looks similar to the following:

<Deployment xmlns="http://schemas.microsoft.com/windowsphone/2009/deployment" AppPlatformVersion="7.0">
  <App xmlns="" ProductID="{b2a3afee-70be-40c7-8dc1-81ac8c14163e}" Title="Notifications" RuntimeType="SilverLight" Version="1.0.0.0" Genre="NormalApp"  Author="" Description="" Publisher="">
    <IconPath IsRelative="true" IsResource="false">ApplicationIcon.png</IconPath>
    <Capabilities>
    </Capabilities>
    <Tasks>
     ...

Note that the Capabilities section is empty. Update this with the list of capabilities your application requires – you don’t need to include all of them but you may want to start by including all of them to make sure your application runs. Before you submit your application to marketplace (when we’re able to do so) I would recommend that you trim back on all the capabilities that you don’t require. After adding the capabilities your manifest file should look similar to:

<Deployment xmlns="http://schemas.microsoft.com/windowsphone/2009/deployment" AppPlatformVersion="7.0">
  <App xmlns="" ProductID="{b2a3afee-70be-40c7-8dc1-81ac8c14163e}" Title="Notifications" RuntimeType="SilverLight" Version="1.0.0.0" Genre="NormalApp"  Author="" Description="" Publisher="">
    <IconPath IsRelative="true" IsResource="false">ApplicationIcon.png</IconPath>
    <Capabilities>
      <Capability Name="ID_CAP_NETWORKING" />
      <Capability Name="ID_CAP_LOCATION" />
      <Capability Name="ID_CAP_SENSORS" />
      <Capability Name="ID_CAP_MICROPHONE" />
      <Capability Name="ID_CAP_MEDIALIB" />
      <Capability Name="ID_CAP_GAMERSERVICES" />
      <Capability Name="ID_CAP_PHONEDIALER" />
      <Capability Name="ID_CAP_PUSH_NOTIFICATION" />
      <Capability Name="ID_CAP_WEBBROWSERCOMPONENT" />
    </Capabilities>
    <Tasks>

Jaime Rodriguez has a good post on Windows Phone 7 capabilities security model