Nick's .NET Travels

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

Taking Visual States Cross Platform to iOS and Android with Xamarin

Last Friday at the Windows Phone 8.1 developer training, run by Microsoft, Nokia Microsoft and Built to Roam, we asked the room how many people used Blend and knew about Visual States. I was shattered to see very few people even knew what a Visual State was, let alone use them in their code. Visual States have to be one of the most useful aspects of the XAML system allowing you to define different states for not only your pages but also controls and user controls that you create.

On Tuesday night before the Sydney Mobile .NET Developer Meetup I was talking with Lewis Benge about how developers on other platforms control aspects of their user interface. The consensus is that it’s very reactive in that as elements of their data model, or in the case of mvvmcross elements of the view model, change elements of the UI are adjusted. For example if you were displaying some form of a loading indicator whilst some data was being retrieved from a service, when the call was complete, the progress indicator would be hidden. In this simple case you might think that it’s just one line of code to show or hide the progress indicator but now repeat this two or three times and all of a sudden you have UI control code littered throughout your application logic. In the XAML world we’d simply define these as visual states and we’d move between those states as required. In fact, as you’ll see we can even represent these states within our view model so that the state, not the visual representation of the states, form part of our application logic (and can be isolated and tested independently as it can sit nicely within a PCL).

Ok, now for a more concrete example:

- File –> New Project –> Windows Phone application

- Add New Project –> Android application

(you can repeat for iOS if you want)

- Add New Project – Portable Class Library

- Manage NuGet –> Add Mvvmcross to all projects, and follow “ToDos” as required for each project

>> At this point, you want to make sure that both your Windows Phone and Android applications build and can be run. They should both launch FirstView and contain a textbox and label with databinding working so that you can change the text in the textbox and it is updated in the label.

Blending some Visual States

We’re going to add a progress bar and a piece of text to say “Loading….” whilst data is being loaded.

- Right-click the Windows Phone project and select Open in Blend

- Add a progress bar and texblock to the contentpanel element to give you the following xaml – note that both elements are currently collapsed

<Grid x:Name="ContentPanel"
    <ProgressBar x:Name="progressBar"
                    Visibility="Collapsed" />
    <TextBlock x:Name="textBlock"
                Visibility="Collapsed" />

- In the States tool windows, click the “Add state group” button in the icon bar. Call the state group “LoadingStates” (this name is somewhat irrelevant as it’s never used other than in Blend to allow you to differentiate if you have multiple state groups)

- Click the “Add state” button twice to generate states “Loading” and “Loaded”

- With the Loading state selected (there should be a red border around the main design surface indicating that you’re in state editing mode) set both textblock and progressbar to visible, and set the isindeterminate property to true. If you look at the xaml you should see the following states defined:

    <VisualStateGroup x:Name="LoadingStates">
        <VisualState x:Name="Loading">
                <ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="(UIElement.Visibility)"
                    <DiscreteObjectKeyFrame KeyTime="0">
                <ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="(ProgressBar.IsIndeterminate)"
                    <DiscreteObjectKeyFrame KeyTime="0">
                <ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="(UIElement.Visibility)"
                    <DiscreteObjectKeyFrame KeyTime="0">
        <VisualState x:Name="Loaded" />

- If you switch between the Loading and Loaded states in Blend you should see the elements show and hide as expected. Now we need to wire up some logic to switch between these states at runtime.

- Return to Visual Studio and go to the code-behind file for the FirstView (Windows Phone project).

- Add the following code to the OnNavigatedTo method:

protected async override void OnNavigatedTo(NavigationEventArgs e)
    VisualStateManager.GoToState(this, "Loading", true);
    await Task.Delay(2000);
    VisualStateManager.GoToState(this, "Loaded", true);

- Run the Windows Phone application and observe the application switching between the two states

- Now we need to move this logic one step further away from the UI layer and have it contained within our ViewModel. We’ll also try to eliminate those pesky string literals. To do this we’ll define an enumeration in code so that we can refer to our VisualStates – the name of the enumeration doesn’t matter but the name of the enumeration values needs to match the names of the states defined in Blend

public enum FirstStates

- To move our state logic into the ViewModel we’ll need a way to trigger the actual state change in the UI layer (ie the view). For this we’ll expose an event on the ViewModel which will include the name of the state that we want the view to transition to. We’ll start by defining a StateEventsArgs class which we’ll use to wrap the name of the state. This class includes a couple of helper methods to make it easy to generate an instance from an enumeration value, and to return an enumeration value. You might ask why we’re converting to and from strings – we’ll come back to this!

public class StateEventArgs : EventArgs
    public string StateName { get; private set; }

    public static StateEventArgs Create<TState>(TState state) where TState : struct
        return new StateEventArgs {StateName = state.ToString()};

    public TState AsState<TState>() where TState : struct
        TState state = default(TState);
        Enum.TryParse(StateName, true, out state);
        return state;

- Update the FirstViewModel to raise a StateChanged event as follows:

public void OnStateChanged(FirstStates state)
    if (StateChanged != null)
        StateChanged(this, StateEventArgs.Create(state));
public override async void Start()
    await Task.Yield(); // Attach state changed event handler

    await Task.Delay(5000);
public event EventHandler<StateEventArgs> StateChanged;

- Now, in the code behind for our FirstView we can amend the OnNavigatedTo method to wire up a StateChanged event handler:

protected async override void OnNavigatedTo(NavigationEventArgs e)
    (ViewModel as FirstViewModel).StateChanged += FirstView_StateChanged;

void FirstView_StateChanged(object sender, StateEventArgs e)
    VisualStateManager.GoToState(this, e.StateName, true);

- When you run this, there is a 5 second delay during the Start method in the FirstViewModel during which the Loading state should be visible. There after it should revert to the Loaded state.

- Let’s flip across to our Android project and amend the FirstView to include the following xml.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android=""
        local:MvxBind="Text Hello" />
        local:MvxBind="Text Hello" />
        android:text="@string/Hello" />
        android:id="@+id/progressBar1" />

- Note that unlike in XAML for Windows Phone we can’t define the visual states in xml. Instead we define them as a set of Actions which will be invoked when transitioning to a particular state. In this case we’re setting the progress bar to indeterminate and changing the button color for Loading state. You’ll notice that unlike in XAML where we could rely on the state manager to revert state changes (ie Loaded state simply reverses any changes applied by the Loading state), here we have to be explicit about all changes we want to occur.

private IDictionary<FirstStates, Action> states;
protected override void OnCreate(Bundle bundle)

    var button = FindViewById<Button>(Resource.Id.MyButton);
    button.Click += (s,e) => ViewModel.Start();

    var progress = FindViewById<ProgressBar>(Resource.Id.progressBar1);

    states = new Dictionary<FirstStates, Action>()
        {FirstStates.Loading, () =>
            progress.Indeterminate = true;
            button.SetTextColor(new Color(0,255,0));
        {FirstStates.Loaded, () =>
            progress.Indeterminate = false;
            button.SetTextColor(new Color(255,0,0));

- The final piece is to wire up an event handler to the StateChanged event, the same as we did for Windows Phone:

protected override void OnViewModelSet()

    (ViewModel as FirstViewModel).StateChanged += FirstView_StateChanged;

void FirstView_StateChanged(object sender, StateEventArgs e)
    var state = e.AsState<FirstStates>();
    var change = states[state];

- When the StateChanged event is trigger, we find the appropriate Action by looking in the state Dictionary. The Action is then invoked to apply the appropriate visual changes.

In this post I’ve walked you through the basics of how you can use visual states across both Android and Windows Phone, controlled from within your view models. This same model can be applied to iOS and of course the code for wiring up the state changed event can be abstracted into base view models and base views so you don’t need to add it to every page.

Using Universal Share Projects for Windows Phone Silverlight 8.0 and 8.1 Upgrade Path

Of course with the announcement of Windows Phone 8.1 XAML applications (ie applications for WP8.1 written in Windows XAML) and support for Universal applications, not everyone is going to immediately rebuild their Windows Phone application. Instead, existing developers need a mechanism to upgrade to the new runtime to leverage the new features without having to redeveloper all their pages. This is where Silverlight 8.1 applications come in.

There is only minimal support within Visual Studio to support developers upgrading to Silverlight 8.1, allowing them to “Retarget to Windows Phone 8.1”.


Retargeting works well and typically your application will continue to run. However, in most cases you’ll want to maintain both a Silverlight 8.0 and 8.1 versions of your application. An alternative is to create a copy of your Silverlight 8.0 application and upgrade that – now you have two versions of your application that you have to support. Luckily this is an area where the new Shared project support, added to enable universal applications across Windows Phone and Windows, can be used to maintain code that is used by both a Silverlight 8.0 and 8.1 application (sort of Linked files on steroids).


- Install the Shared Project Reference Manager ( – this makes creating Shared Projects much easier

- Create a new Shared Project eg MyApplication.Shared

- Unload you Windows Phone project

- Edit your Windows Phone project file

- Add a Shared Project Reference via the right-click shortcut menu on your Windows Phone project (Note: for some reason adding a shared project reference isn’t supported for Windows Phone projects, so we need to do it the manual way)

- Add Import to end of project file which references the shared project file eg

<Import Project="..\MyApplication.Shared\MyApplication.Shared.projitems" Label="Shared" />

- Reload your Windows Phone project – you should see a reference to your Shared project under References node


- Move as many files as possible from your Windows Phone project into the Shared project

- Note that you may experience some of these issues:

> AppResources.resx doesn’t move easily. You’ll need to make sure that both the resx and the designer.cs file are moved and that the Build Action is correct (resx file should have a Build Action of Embedded Resource and a Custom Tool of PublicResXFileCodeGenerator). You also need to remove the “.Resources” from the name of the resource being loaded and the namespace.

> You need to keep any images referenced in the WMAppManifest.xml file in the Windows Phone project. This is ApplicationIcon.png and FlipCyleTileMedium.png by default

> You still need an App.xaml file in your Windows Phone project

- Check that your Windows Phone application builds and runs (fix any build errors!)

- In Windows Explorer take a copy of your Windows Phone application and rename the folder and project files eg MyApplication.SL81

- Add the copied project into the same solution

- Right click on the project you just added and select “Retarget to Windows Phone 8.1”. Your solution structure should now look similar to the following


- Build and run your new Windows Phone 8.1 application

The upshot after all this is that you have a Shared project where you can store shared files across your Windows Phone Silverlight 8.0 and 8.1 applications.

Sqlite for Universal Windows and Windows Phone applications

I hadn’t tested using Sqlite with the new universal projects introduced with Visual Studio 2013 Update 2 (which includes the Windows Phone 8.1 SDK). Luckily there is already quite a bit of info out there on the bits you need to get this to work.

  1. Firstly, you need a copy of the Sqlite Extensions library updated for WP8.1. At this point this hasn’t been officially release but Tim Heuer has posted a link to his “works on my computer” version of the library. His post is Using SQL/library references in Universal Windows Apps and includes a link to the extensions library
  2. The next thing to do is to create yourself a Universal project
  3. Add a reference to the sqlite extensions library to each of the head projects (ie the Windows and Windows Phone projects, not the shared project).
  4. Next, add a nuget reference to sqlite-net (use the package with that id)
  5. In the previous step you’d see sqlite.cs and sqliteasync.cs being added to both head projects. You can copy these files into the shared project and delete them from both head projects
  6. Lastly, add some sqlite code to your shared project which can then be used by both your Windows and Windows Phone projects…. simply done!

Here’s a sample project where I followed these steps

XAML and Databinding Debugging for Windows and Windows Phone

A question that came up today during the //learn/ event was how to debug data binding in Windows and Windows Phone projects.Normally I start by checking out the Output window – in most cases any issue with data binding is usually a naming issue, which will result in a bindingexpression path error in the Output window as follows:

Error: BindingExpression path error: 'test' property not found on 'App4.MainViewModel, App4, Version=, Culture=neutral, PublicKeyToken=null'. BindingExpression: Path='test' DataItem='App4.MainViewModel, App4, Version=, Culture=neutral, PublicKeyToken=null'; target element is 'Windows.UI.Xaml.Controls.TextBlock' (Name='null'); target property is 'Text' (type 'String')

I was reminded that Xmlspy is a great tool for diagnosing XAML issues, as well as data binding expressions. I downloaded the latest version and was surprised to see that there is full support for all types of Windows Phone 8.1 applications. The only issue I saw was getting it to attach to Windows Phone applications but this was due to my firewall getting in the way. Here’s how you can check and fix this issue:

  • Open the XAML Spy Explorer window (View menu–> Other Windows –> XAML Spy Explorer)
  • Click on the “cog” icon in the window toolbar
  • Find the “Enable remote debugging” option and set it to Yes. You’ll be prompted to permit elevated privileges (I assume to configure firewall).


Now you should be good to debug your application on the emulator/device. The XAML Spy Explorer window will automatically populate with information about your application


Note that you can debug much more than just XAML, including sensors, storage and package deployment information.

//LEARN/ Sessions for Tomorrow

Tomorrow (24th April) we kick off the //LEARN/ event with 9 sessions delivered in English, in the Australian EST time zone. If you haven’t already registered, make sure you follow these instructions to locate the right event information on

I wanted to quickly share the schedule for tomorrow – you don’t need to attend the whole thing, just drop in for the sessions you want to watch. A reminder these times are for Australian Eastern Standard Time on April 24th (tomorrow from 11am!)


Start AEST Duration Session Presenter
11:00 AM 50mins Introduction to Windows Phone 8.1 Michael Samarin
12:00 PM 50mins Getting Started Building Windows XAML Apps William Wegerson
1:00 PM 25mins Page navigation and Data Binding Kelly White
1:30 PM 25mins Page Layout Controls & Transition Animations Nico Vermeir
2:00 PM 25mins Adapting UI for Different Screens Lwin Maung
2:30 PM 25mins Windows Runtime XAML App Lifecycle Andrei Marukovich
3:00 PM 25mins Localization, Globalization in Windows XAML Apps SENTHIL KUMAR
3:30 PM 50mins Tiles, badges and toasts and Action Centre Rob Keiser
4:30 PM 25mins Background Tasks Andrej Radinger

Debugging WebView in a Windows Phone application

In a previous post, Debugging Internet Explorer on Windows Phone 8.1, I covered how you could use the new debugging support for IE on Windows Phone to diagnose rendering issues. What I didn’t cover is how you could debug web pages when they’re hosted within an application using the WebView control.

As we’re now building for Windows XAML, we can actually use the same mechanism that’s available for Windows 8 applications (see for instructions). All we need to do is change the Application process option under Debug.


Set this to Script and when you debug your XAML application Visual Studio will attach to the WebView allowing you to debug your script and DOM.

//learn/ Windows Phone – How to Register

Following a conversation with another developer last week I realised that it’s not particularly obvious how to register for the upcoming //learn/ Windows Phone event. If you haven’t heard about this event it’s an online webcast series hosted by Microsoft and delivered by MVPs in a number of different languages (hopefully one that suits you!). Over 6 hours you’ll learn about a lot of the key new features of Windows Phone 8.1 and how you can build awesome Universal applications for the Windows platform. If this sounds interesting, here’s how you register.

Step 1:    Go to

Step 2:    Scroll down until you find the section entitled “Find events and consulting times”


Step 3:    Select your preferred language (in this case English)


Step 4:    Select “Online” from the second dropdown


Step 5:     DON’T select Country as this will most likely eliminate all online events


Step 6:     Scroll down to see the list of available events and click through on the appropriate Register button for the //learn/ event


Note:    If you want to see the full list of languages available for //learn/ reset the Language dropdown, whilst leaving the middle dropdown set to “Online”.


Look forward to seeing you all online on the 24th April.

Important: Please make sure you have the correct times in your calendar – The English series starts at 11am Australian EST on the 24th (which is 6pm US PST on the 23rd!!!)

Debugging Internet Explorer on Windows Phone 8.1

The desktop version of Internet Explorer now has quite a good selection of developer tools available on any site by just pressing F12


Unfortunately on Windows Phone it’s been quite difficult to debug websites and so developers typically had to resort to alert(‘hello’); style debugging. With Update 2 for Visual Studio 2013 there is a new Debug menu item “Debug Windows Phone Internet Explorer”


This gives you the option to select the device/emulator and specify a launch site to debug.


The debugging experience is pretty cool as it’s actually in Visual Studio and includes the ability to set breakpoints and inspect variables.


Do also get the DOM Explorer


And the Javascript Console


This has got to make our jobs easier!

Upcoming Windows Platform Events for Windows and Windows Phone

Hot off the heals of //Build/ are a whole slew of local activities to get you updated and building for the new Windows platform (aka Windows and Windows Phone). Here they are:

24th April 2014    //Learn/ 

Whether you are a New Windows App Developer or an Experienced one- we have something for you!

Join us and take a deep dive into the latest features and technologies for Windows Phones, PCs and Tablets.//learn/ from our community in this “to the community, for the community and by the community” event where our MVPs and Expert Developers will help you better understand all that’s new with Windows.

Want to learn how to easily share code between store apps of different form factors? or Want to build your own Universal App? You are at the right place. These sessions will cover all the basic concepts to develop Universal Windows apps –One App for all form factors (PC, Table and Phone), Windows Phone 8.1 apps: the new application lifecycle, the new XAML etc.-with live chat and Q&A with our speakers

No need to dress up or step out you can watch and learn from the comforts of your home/office in this online webcast of informative sessions delivered by our community experts. That’s not all, our local experts will deliver these sessions in not 1 but 8 languages from across the globe(each accommodating the local time zone) to help you learn and leverage the new features and technologies.

So get started and Register Now!

17th May 2014    //Publish/

Locations TBA but Sydney, Melbourne and Brisbane are likely – more announcements to come

Whether you’re looking for expert guidance to help you get started or to cross the finish line at a local event, Microsoft experts are here to help you out every step of the way.

You can even win awards and prizes just for publishing before June 1, 2014.

Windows Phone 8.1 Developer Community Workshop

2nd May 2014 – Melbourne
9th May 2014 – Sydney
16th May 2014 - Brisbane

The Windows Phone 8.1 SDK is now available, and with it brings a wealth of new features and capabilities to take your Windows Phone applications further than before.

We've taken the best from //Build, it'll be a big day, jam packed with topics including:-

  1. The new WP 8.1 runtime
  2. Universal applications and building across WP 8.1 and Windows 8.1
  3. Bluetooth and NFC and the internet of things
  4. People Hub
  5. Notifications
  6. Javascript WinJS comes to phone Geofencing And more...

With trainers from Nokia, Microsoft, Build To Roam, and your local Windows Phone super stars, you don't want to miss out. Seats are limited, so get in fast.

Speed up Blend for Visual Studio with TFS (Visual Studio Online) using a Firewall Rule

So for the longest time I’ve complained about how unusable Blend for Visual Studio is on projects that use TFS, specifically instances of TFS that are on the other side of the internet (yes, I’m looking at you . The issue is that every time you try to modify a file it goes off to TFS to check something…. I’m not quite sure what, but it hangs for a couple of seconds before deciding that you’re ok to make the change. This is particularly bad when you’re working with sample data.

It turns out there is a stupidly simple fix – don’t let Blend access the internet. Due credit to Dave who works with me at Built to Roam as he was the one that told me to just create a firewall rule.

Now, it’d show you some pictures of how to create the firewall rule using MMC but for some reason MMC crashes for me when I go to view the outbound rules. Anyhow, here’s the command for doing it via the command line:

netsh advfirewall firewall add rule name="Blend" dir=out action=block program="C:\Program Files (x86)\Microsoft Visual Studio 12.0\Blend\Blend.exe"

Blend will now complain when you first open a TFS connected project but there after it won’t miss a beat as you work with files as if there is no TFS connectivity.

Built to Roam website gets a facelift with interactive Windows and Windows Phone shells

Yesterday we finally released the new version of the Built to Roam website. As most of you are aware over the last couple of years we have done a lot of work with a number of customers to help them release, or update, their Windows and/or Windows Phone applications. We wanted to showcase these as part of our interactive website, so the phone and tablet you see when the website loads are designed for you to interact with; simply tap on the phone, or swipe across and tap on the tablet, to get started


In interactive mode the devices move to the centre of the screen and allow you to tap through to explore information about the apps we’ve enjoyed working on. The experience for each device has been designed to reflect the interaction model of the respective platform eg the back button steps you back to the previous page.

image    image

As with all projects, there was a limit to what we could fit in the first release. As such, we made some compromises when it came to the mobile experience. Whilst the site should function correctly, particularly in portrait, the website doesn’t make good use of the available screen space. Over the coming weeks we’ll be looking to optimise the mobile experience to make it easier to browse the information on the site.

Windows Phone 8.1 Emulator

In my previous post on Windows Phone 8.1 Developer Power Tools I looked at the developer power tools that are available from within Visual Studio. In this post we’ll look at the new Windows Phone 8.1 emulator and how it is an enabler for building better applications. The first thing to note is that there are a number of different emulator images available:


In this brave new world of varying screen sizes Windows Phone 8.1 departs from the fixed addressable width of 480 units. Instead each device has a scale factor which results in an effective resolution – in essence this means that two devices of the same size but differing hardware resolution will display the same amount of content, whereas two devices with the same resolution but differing size, will show more/less content depending on their relative size. What this means is that we now need emulators that not only vary in resolution but also in size.


Here you can see both the WVGA 4inch and the 1080p 6inch alongside each other – the beauty of it being in an emulator is that it can then be resized on the screen. The thing to notice is that the 1080p emulator has an additional column of tiles which will be a typical behaviour within applications when dealing with a higher effective resolution.

The next thing to note are the additional tools that are available. Here is a quick set of screenshots – we’ll go into more details on each of these in coming posts:

image image

image image

image image

 image image

Developing for Windows Phone 8.1 using XAML

By far the most common way to build Windows Phone applications is to use XAML and C# (or VB). In this case the XAML is a variant on Silverlight, which made it very easy for developers building Silverlight applications to switch across to building Windows Phone applications. 4 years on and the number of Silverlight developers has dropped (well at least the appeal of being a Silverlight developer has), and all the focus now is on becoming a Windows developer.

Unfortunately somewhere along the lines the Windows team decided that having three XAML frameworks (WPF, Silverlight and WP) wasn’t enough and that they needed to come up with another, only marginally different, framework. This we’ll refer to as Windows XAML.

With the announcements around Windows Phone 8.1 we’re entering a new time of convergence between phone and desktop applications where we can reuse not just the code (eg Portable Class Libraries and code file sharing) but also the XAML markup. This doesn’t come for free and relies on migrating our applications, or starting new applications, using Windows XAML instead of Silverlight.

So where does this leave us? What it means is that there are now three ways to develop for Windows Phone 8.1:

1) Windows Phone 8.0 Silverlight

Use this if you want maximum reach from a single application package; you don’t need or want to use any of the new platform features. This type of application will run on all Windows Phone 8.0 and 8.1 devices.

2) Windows Phone 8.1 Silverlight

By running the  “Retarget to Windows Phone 8.1” option after right-clicking on your application in Solution Explorer, your application will be migrated forward and will run against the new runtime. This means you can take advantage of some of the new platform features without having to redevelop your application. Whilst in most cases the retargeting process doesn’t modify the behaviour of your application, you will need to verify your application functionality before publishing the new version.

Once retargeted your application will only run on Windows Phone 8.1 devices, so it is recommended that you take a backup or a branch of your code and keep the 8.0 version alive to support those users who haven’t upgraded.

3) Windows Phone 8.1 Windows XAML

New applications, not wanting to maintain backward support for Windows Phone 8.0, can be created using Windows XAML. Ideally this would be all new applications as it allows for reuse across phone and tablet. The Universal projects concept introduced into Visual studio makes it easy to share code between projects, whilst still having platform specific functionality included in the “head” projects (ie the Windows and Windows Phone projects).

There is one thing that isn’t being highlighted is that each option has some limits on what you can and can’t do. 8.0 SL projects can’t access any of the new platform features. Windows XAML can’t do things like lock screen background provider….. it’s worth reading up on this before you make a decision

Windows Phone 8.1 Developer Power Tools

Last week at BUILD, Microsoft announced the availability of Visual Studio 2013 Update 2 RC, which includes the new Windows Phone 8.1 SDK.

I’m sure there will be a lot of blog posts talking about the new Universal project, the additional capabilities introduced in Windows Phone 8.1, Windows Phone XAML applications, the new application lifecycle model etc. I want to take a different approach and talk about some of the additional tools that come with the SDK.

One of the benefits Windows Phone development aligning with Windows app development is that more of the experiences along the development lifecycle will be similar. For example from the Project menu, Windows Phone developers now have the Store sub-menu with the ability to Create App Package.


One of the other additions is under the Tools menu, where there is a Windows Phone 8.1 sub-menu. This includes the Developer Power Tools, Developer Unlock and the Application Development tools. Whilst the last two are not new to Windows Phone development, they can now be reached from within Visual Studio.


The Developer Power Tools, not to be confused with the Windows Phone Power Tools, is a standalone tool which can be used to inspect what’s going on across either emulator or device. Help is available via MSDN


One of the most interesting thing about these tools is that you can start them, disconnect your device, put your application through its paces in real world scenarios, then reconnect and review the data at a later stage. For example, using the Performance Recorder you can check the data you want to record (eg CPU and Power) and hit Start. You can then disconnect the device, or in this case the emulator, open and run your application, and then reconnect and Stop the recording. This will prompt you to save a .etl file which includes all the data recorded.


The .etl file can then be opened using Windows Performance Analyzer (just double-click the file in Windows Explorer).


Hopefully these tools will help you track down issue in performance and usage of your application

Coded Design Time Data using Mvvmcross for Windows and Windows Phone

A question came in today regarding the use of design time data in conjunction with Mvvmcross. My initial response was “it just works” because I assumed that everyone does design time data in Blend….. and I’m still not sure why you won’t do this, since it promotes better design by giving designers the freedom to dictate the information architecture of each page. As it happens what they were really after was a way to plug in design time data that is generated in code. Without using mvvmcross this was relatively easy using a ViewModelLocator pattern – as part of serving up the view models, you could simply change the data source to be design time data when running in the dev tools. Because mvvmcross abstracts a lot of the work involved in associating pages with view models, it also means that it’s a bit harder to wire up coded design time data. In this post I’ll provide a summary (read “crude”) way I found to do this:

The assumption here is that your Mvvmcross project follows how Stuart describes a typical project in any of his getting started videos. Essentially this means a UI project (eg a Windows Phone project), that would contain your views (eg pages) and a Portable Class Library, that would contain your view models. There is also an App class in the PCL which is used to initialise mvvmcross. In this example we’re just going to work with the FirstView and its corresponding FirstViewModel but we’re going to add in support for a service which is used to populate data. Here’s the FirstViewModel:

public class FirstViewModel
    : MvxViewModel
    private IDataService Data { get; set; }

    public FirstViewModel(IDataService data)
        Data = data;

    public string Hello
        get { return Data!=null?Data.TestData:"Missing"; }

The IDataService has two implementations: DataService and DesignData, as illustrated here:

public interface IDataService
    string TestData { get; }

public class DesignData : IDataService
    public string TestData
            return "Designtime";

public class DataService:IDataService
    public string TestData
            return "Runtime";

At runtime we don’t need to worry about creating an instance of the DataService as it is automatically picked up by mvvmcross and injected into the FirstViewModel constructor. However, the DesignData is a little harder to use. At design time we somehow have to coerce mvvmcross to generate the FirstViewModel and populate it with an instance of DesignData. One option would be to go down the ViewModelLocator path again and use it only at design time to create our view model using design time data. However, this is rather clumsy given we have a perfectly good DI framework that we can leverage. The other thing is we’d have to continually update it to expose properties for each view model we want.

An alternative is to use a Factory pattern coupled with a Converter to dynamically create the appropriate view model. This is a bit of a chicken-and-egg thing to describe so I’ll start with how we wire it up in the UI project. Firstly, in the App.xaml we need to create both the Factory and Converter as resources:

   <codedDesignTimeData:DesignFactory x:Key="Factory"/>
    <codedDesignTimeData:DesignTimeConverter x:Key="DesignConverter" />

Next, in the page we set the d:DataContext (ie the design time data context) as follows:

    d:DataContext="{Binding Source={StaticResource Factory}, Converter={StaticResource DesignConverter}, ConverterParameter=FirstViewModel}"
    ... >

Let’s read through what this is saying – at design time, the DataContext for this page is going to be the Factory, passed through the Converter with the parameter “FirstViewModel”. As you can imagine what we’re really saying is that we’re asking the Factory to produce an instance of the FirstViewModel that we can data bind to.

Ok, so now we know what it’s saying, let’s look at the implementation of firstly the Converter, and then the Factory itself:

public class DesignTimeConverter:IValueConverter
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        var typeName = parameter as string;
        if (string.IsNullOrWhiteSpace(typeName)) return null;

        var factory = value as DesignFactory;
        return factory.Create(typeName);

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        return value;

There isn’t much to the converter, it simply passes the parameter (ie the type of the view model to be created) into the Create method on the Factory object.

public class DesignFactory
    private Core.App app;
    public object Create(string typeName)

        if (app==null)

                app = new Core.App();


        var type = app.FindViewModelTypeByName(typeName);

        if (type == null) return null;

        var req = MvxViewModelRequest.GetDefaultRequest(type);
        if (req == null) return null;
        var locator = app.FindViewModelLocator(req);
        if (locator == null) return null;

        IMvxViewModel vm;
        if (locator.TryLoad(type, null, null, out vm))
            return vm;

        return null;

The factory is where all the smarts are. The first thing we do is make sure that mvvmcross is initialized – this is similar to what happens in your app. We then call FindViewModelTypeByName (see below for implementation) to exchange the view model type name with a reference to the actual type. Next we invoke the view model locator infrastructure within mvvmcross to retrieve an actual instance to the view model we’re after, which we then return (and is subsequently set as the DataContext for the page).

public Type FindViewModelTypeByName(string typeName)
    return CreatableTypes().FirstOrDefault(t => t.Name == typeName);

Ok, but wouldn’t is just be better to create an instance of the view model, once we have a reference to the type? No, because that view model may have any number of dependencies, which is why we need to rely on the DI framework provided by mvvmcross. You’ll notice I skipped over one quite important line, which was that we register the type DesignData as the implementation of IDataService we want to use. By default the Initialize method on our App class will look for types that end in “Service” and register them, which is why our DesignData doesn’t end in “Service”, but it also means we have to manually register it.

The upshot of this is that an instance of the DesignData class will be used to service up design time data for our view models in Blend. I hope this helps anyone working with mvvmcross.

Building Apps for OneNote for Windows Phone, Windows Store and other platforms

There are newly published apis for accessing OneNote that you can get started building apps for today.

WPCentral has good coverage on the new OneNote features that were recently announced:  Microsoft introduces new OneNote APIs, free desktop apps for Mac and Windows

Personally the one I find most interesting is the [email protected] feature where you can simply send an email and have the contents appear within OneNote (yeh I know Evernote’s had that for years). What I love is the simplicity – it detects which Microsoft account based on which email address you send it from. All you have to do is remember [email protected]”. To get started:

* Go to 

* Click through to “Email to OneNote”

* Enrol your email address.

* Start sending emails to [email protected]

Build it Beta gets Isolated Storage Exploring in Feedback Tool

If you haven’t already started Windows Phone Application Testing with Build it Beta then I’d encourage you to check it out and start using it to deploy test builds of your Windows Phone applications and gather feedback from users.

If you’re already using Build it Beta then you hopefully realise how easy it is to push out new builds of your application by either emailing them, or simply double-clicking the XAP file and using our Windows 8 application.One thing you may not have found is that you can create feedback items directly from within the application you’re testing. After launching the application your testing, swipe down from near to the top of the screen. After a second or so (as we capture a screenshot of the current screen) you’ll see the feedback form:


The feedback form allows you to enter basic feedback information (bug, new feature etc) as well as attaching information about the navigation history (see navigation tab) and a screenshot (see screenshot tab). The feedback will be associated with this particular version of the application in Build it Beta.

This morning we’ve improved the feedback form to include a storage tab – this iterates through all files and folders currently in Isolated Storage and lists them. Folders are marked in bold and you can tap on a file to launch it for viewing (this is really only useful for known files types: xml, png, doc etc).


We’d love feedback on whether this is something that’s useful.

Windows Phone Application Testing with Build it Beta

Yesterday I announced that Build it Beta is now public for Windows Phone app developers, but what is Build it Beta? Well it’s all about Windows Phone Application Testing. There are a number of existing mechanisms available to Windows Phone application developers but none of them offer the simplicity and ease of deployment as say TestFlight. Build it Beta fills that gap, providing a mechanism to allow any Windows Phone application to be deployed for testing to any Windows Phone 8 device*.

Build it Beta 

Firstly, why the name?

Well it’s a bit of a play on words – we’re always looking to build better apps and of course during development we often release “beta” versions of the app. Hence the origin of “Build it Better Beta”.

Next, how does it work?

Windows Phone 8 included the ability to deploy applications within the enterprise without going through the Windows Phone Store. This is referred to as enterprise deployment and involves signing an application (ie the packaged application file .xap) with an signing certificate. The same certificate needs to be distributed to the devices that the application is to be tested on. Then the signed xap can be installed on the devices either via code or by distributing the application to the device via email or via a url link. Build it Beta uses this mechanism to deliver a testing tool which eliminates the complexity for both developers and testers.

Ok,  so how do I get started?

The first step is to get Build it Beta from the Windows Phone Store, but we’ve got a simple set of setup instructions that will get you up and running in no time at all. If you’re not on your Windows Phone, scan the following QR with your Windows Phone (Search button, Vision app bar button) to jump straight to the instructions.

Once you’ve completed the setup, all you need to do is to start sending your .xap files to upload @ Make sure you send them from the same email address that you registered with when setting up Build it Beta. We’ll ingest your xap and send you a confirmation email. You should also get a toast notification on your Windows Phone device letting you know that a new version of your application is available for testing. Click on the link in the email, or tap on the toast notification to download and install the signed version of your application.

* Build it Beta relies on enterprise deployment to install applications. This is a feature that was introduced with Windows Phone 8 which means Build it Beta cannot install applications to earlier versions of the Windows Phone operating system. If you need to deploy applications for testing on earlier versions of Windows Phone you can do this using the Windows Phone Store Beta process.