Nick's .NET Travels

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

Updating the Windows and Windows Phone Applications with the new Azure Mobile Service Entities

In my previous post I extended the Azure Mobile Service to include two entities, RealEstateProperty and Inspection. I’m now going to return to the Windows platform projects (ie Windows and Windows Phone) and update them to use these new entities.Rather than duplicate the entity definition I’m going to reuse the entity definition I created previously. Unfortunately, the base class of the two entities is a class called EntityData which is specific to Azure Mobile Service SDK for the full .NET Framework (ie to power the .NET backend services). This means we can simply move these entities into a class library, or better still a PCL, and reference it. Instead we’ll need to make the base class conditional on where the entities are being used – this is a great use for a Shared Project.

We already have a Shared Project which is used to share common code between the Windows platform projects. One option would be to simply reference this project from the service project but this would mean we couldn’t include any shared XAML or Windows platform specific code. Instead I’m going to create a new Shared Project which will be used to contain the entities that are going to be shared across both the Windows platform projects and the service project. To do this I need to download and install the Shared Project Reference Manager which extends Visual Studio to allow for the easy creation and referencing of Shared Projects. After installing the extension I simply add a new project as I would any other project type – right-click the solution node in Solution Explorer and select Add –> New Project. Select the Shared Project and give it a name, in this case will keep it inline with the other Shared Project by naming it RealEstateInspector.Shared.Entities.


With the Shared Project created, I need to add a reference to the Shared Project to both Windows platform projects and the service project – right-click the References node under the project and select Add Shared Project Reference. The two Windows platform projects should have both shared projects selected, whilst the service project should only reference the new Shared Project.


Next I need to move my entities out of the service project and into the shared project. I’ll also take this opportunity to change the base class, which as you’ll see will allow us to provide a different base class implementation depending on whether the entities are being compiled into the windows platform projects or the service project.

public class RealEstateProperty : BaseEntityData
    public string Address { get; set; }

    public virtual ICollection<Inspection> Inspections { get; set; }

public class Inspection : BaseEntityData
    public string InspectedBy { get; set; }

    public string RealEstatePropertyId { get; set; }
    public RealEstateProperty RealEstateProperty { get; set; }


The BaseEntityData class looks like this:

using Microsoft.WindowsAzure.Mobile.Service;

namespace RealEstateInspector.Shared.Entities
    public class BaseEntityData
       : EntityData{}
        public string Id { get; set; }

You’ll notice that the BaseEntityData makes use of a compilation symbol to firstly control the base class (ie use the EntityData class if SERVICE is defined) and secondly whether the Id property is defined. The SERVICE symbol isn’t a predefined symbol so I’ll need to define that in my service project. I could have switched the logic to use one of the existing symbols, such as WINDOWS_APP but then if we ever extend this to other platforms, I’d have to modify the logic. It seems better to simply add a SERVICE symbol to the service project. Double-click the Properties node under the service project in Solution Explorer and then open the Build tab. Make sure you select All Configurations before adding SERVICE to the compilation symbols.


If I now go to the MainPage.Shared.cs (which I created in an earlier post) where we wrote the initial logic to query the TodoItems from the Mobile Service, I can update the code to instead use either, or both, the new entities we’ve defined:

protected async override void OnNavigatedTo(NavigationEventArgs e)

    var items = await MobileService.GetTable<Inspection>().ToListAsync();

Whilst I’ve refactored the service code, there’s no reason to publish the new version since we haven’t modified the structure of the entities. However, there should be no harm in doing so if you’d like to keep the service up to date.

Adding a Relationship to the Azure Mobile Service Entity Model

After removing the TodoItem table and replacing it with a simple RealEstateProperty table (see previous post), the next step is to look at how I can add another related entity. I’m going to leverage the default behaviour exposed by Entity Framework using the Fluent API (see more on this in the article Code First Relationships Fluent API). To this end my entities will look like:

public class RealEstateProperty : EntityData
    public string Address { get; set; }

    public virtual ICollection<Inspection> Inspections { get; set; }

public class Inspection : EntityData
    public string InspectedBy { get; set; }

    public string RealEstatePropertyId { get; set; }
    public RealEstateProperty RealEstateProperty { get; set; }

And I’ll of course need to update the realestateinspectorContext:

public DbSet<RealEstateProperty> RealEstateProperties { get; set; }
public DbSet<Inspection> Inspections { get; set; }

The last code change I need to make is to add the InspectionController required to expose the data for this new table. To do this I could have duplicated the RealEstatePropertyController, renamed it and changed the generic type but this leads to quite a lot of unnecessary duplicate code. Instead with a little bit of refactoring I can abstract nearly all the code into a base controller:

public class RealEstateBaseTableController<TEntity> : TableController<TEntity>
    where TEntity : class, ITableData
    protected override void Initialize(HttpControllerContext controllerContext)
        var context = new realestateinspectorContext();
        DomainManager = new EntityDomainManager<TEntity>(context, Request, Services);

    // GET tables/TEntity
    public IQueryable<TEntity> GetAll()
        return Query();

    // GET tables/TEntity/48D68C86-6EA6-4C25-AA33-223FC9A27959
    public SingleResult<TEntity> Get(string id)
        return Lookup(id);

    // PATCH tables/TEntity/48D68C86-6EA6-4C25-AA33-223FC9A27959
    public Task<TEntity> Patch(string id, Delta<TEntity> patch)
        return UpdateAsync(id, patch);

    // POST tables/TEntity
    public async Task<IHttpActionResult> Post(TEntity item)
        TEntity current = await InsertAsync(item);
        return CreatedAtRoute("Tables", new { id = current.Id }, current);

    // DELETE tables/TEntity/48D68C86-6EA6-4C25-AA33-223FC9A27959
    public Task Delete(string id)
        return DeleteAsync(id);

All I then need to do is inherit from this base class for my two controllers:

public class RealEstatePropertyController : RealEstateBaseTableController<RealEstateProperty> { }

public class InspectionController : RealEstateBaseTableController<Inspection> { }

With the updates to my data model I will of course need to add the appropriate migration by invoking the following in the Package Manager Console:

Add-Migration AddedInspections

I can now run the service project and when I invoke a GET on either controller the database will be upgraded using the new migration code.

One mistakes I came across in writing this post is that I had made the RealEstatePropertyId an int instead of a string. This of course meant my initial migration code setup a column that was an int which clearly couldn’t accept the guid id of the RealEstateProperty. There are two ways to handle this. I could have corrected the data model and run Add-Migration to create another migration. I find this to be a bit messy as the migration code will forever keep a record of my mistake. At this point, since I haven’t pushed this migration into production, I can easily undo the update to the database (essentially a backward/downward migration) and regenerate the AddedInspection migration. To undo the database update I have to invoke the following in the Package Manager Console:

Update-Database -TargetMigration 201501051134554_AddingRealEstatePropertiesToSchema

Here I’m specifying the last migration I want the database to roll back to, which in this case is the migration I created in my previous post. Once I’ve done this I call Add-Migration again:

Add-Migration AddedInspections –Force

Note that I’m including the –Force switch which will force the migration code to be fully regenerated, rather than just the designer code.

That’s all – I can re-run the application and it will apply the new migration (or you can just run Update-Database to migrate the database forward with the corrected migration).

Lastly, to create a Inspection I can again use Fiddler to invoke a POST method:

Content-Type: application/json
X-ZUMO-APPLICATION: wpxaIplpeXtkn-------------------------cg12


This includes the RealEstatePropertyId of a property that exists in the database (since it’s a relationship) – if you attempt to use a value that doesn’t exist, you’ll get a 400 error back with an error which effectively says you’re attempting to violate the database schema.

Updating the Data Model with Azure Mobile Service

Whilst template and samples are great, often one of the hardest things is adapting the code to your particular scenario. One such example is with Azure Mobile Service when you decide that you want to change your data model for the first time. Firstly, the initial template that you download and publish to get an initial service up and running will create a ToDoItems table. Unless you happen to be building a ToDo task system then it is unlikely that you’ll want this table. So, how do we get rid of this table out of our Azure Mobile Service (and of course the SQL Server database that backs it)?

At this point a word of caution – this table was created by the Mobile Service, so don’t go messing with the table directly. For example you could use SQL Management Studio to connect to the SQL Azure instance and just delete the table but I think you’ll find that you run into some issues when you next run or attempt to deploy new versions of your Mobile Service. In fact, the Mobile Service template already provides a facility to do that. In fact, with any change to the Entity Framework data model the entire database structure will be dropped and recreated. This makes it really easy to remove the ToDoItems table, simply by commenting out the following line in the RealEstateInspectorContext:

//public DbSet<TodoItem> TodoItems { get; set; }

All I need to do now is publish and invoke the Mobile Service – I can do this by either running the Windows/Windows Phone applications wired up in the previous post or I can invoke it using Fiddler, as I did in an earlier post. It’s important to invoke the Mobile Service (even though it will fail with a 500 internal error because that’s what triggers the database initializer to kick in and restructure the database).

The next thing we need to change is that we don’t want to be dropping and recreating the database each time the data structure changes – this is a sure fire way in production to delete all that great app data! In the WebApiConfig.cs file there is a line which specifies the initializer for the database. In the template I downloaded this was already set as follows:

Database.SetInitializer(new realestateinspectorInitializer());

The realestateinspectorInitializer inherits from the generic class, ClearDatabaseSchemaIfModelChanges, which as you can imagine from the name is designed to clear up and recreate the database schema if the model changes (for example the above where we dropped the ToDoItems table). I’m going to change this to prevent the database being recreated; I’m going to start to apply migrations as I deploy new versions of my Mobile Service.

Note: In order to create the migrations that need to be applied you can use the tooling provided by the Entity Framework NuGet package via the package manager console. However, before you do this, make sure you run your Mobile Service locally with the TodoItems table comments out (don’t forget to invoke the service – just change the url in Fiddler to use localhost:XXXX where XXXX is the port number your service is running at). This will ensure you have a clean database to work from.

The first thing to do is to invoke Enable-Migrations from the package manager console (full details of the commands are available online - This will create a Migrations folder with a Configuration class and an initial migration, which assuming you have removed the TodoItems table will contain two empty methods, Up and Down.

Note: Make sure the Mobile Service project is the startup project for the solution when attempting to use the package manager console for generating migrations.

To use the Configuration class and the associated migrations I need to replace the following line:

Database.SetInitializer(new realestateinspectorInitializer());


var migrator = new DbMigrator(new Configuration());

At this point you can run your Mobile Service but you will still see a 500 error since there is still no TodoItems table. In fact at this point we’re going to introduce a RealEstateProperty entity that we’ll be working with:

public class RealEstateProperty : EntityData
    public string Address { get; set; }

I need to add this to the realestateinspectorContext as follows:

public DbSet<RealEstateProperty> RealEstateProperties { get; set; }

At this point if I attempt to run the Mobile Service I’ll get an AutomaticMigrationsDisabledException and if I look further at the description it indicates that there are pending model changes that haven’t been applied to the database via a migration. Essentially it’s detected that my model doesn’t align with the database schema.

Rather than hand craft the migration, which would be time consuming and rather mundane, I can again return to the package manager console and issue the Add-Migration command:

Add-Migration AddingRealEstatePropertiesToSchema

The “AddingRealEstatePropertiesToSchema” is a friendly name for this migration and a date-time stamp will be appended to the front of the newly created migration file eg 201501051134554_AddingRealEstatePropertiesToSchema.cs. This command in itself doesn’t update the database schema, all it does is determine the migration that needs to take place. To update the local database I can either call Update-Database, or simply run and invoke the Mobile Service. However, to do the latter I need to add a RealEstatePropertyController which will be the endpoint I’ll be invoking – the easiest way to do this is to simply rename the TodoItemController to RealEstatePropertyController, and change the generic parameter from TodoItem (this class can now be deleted) to RealEstateProperty.

When I run this I can now test the service by invoking a GET to http://localhost:51539/tables/realestateproperty (you may need to change the port number for your Mobile Service) which will of course return no data at this point but it doesn’t generate a 500 which means that it has run the migrations and that the model is aligned with the database schema. I can now publish this into my Azure Mobile Service and make a similar GET request to Don’t forget that you’ll need the X-ZUMO-APPLICATION header when calling a Mobile Service in Azure, whereas it is not required when running the Mobile Service locally.

The last thing I wanted to point out is that you can easily add data by issuing a POST command (don’t forget the Content-Type header)

X-ZUMO-APPLICATION: wpxaIplpeXtkn-------------------------cg12
Content-Type: application/json

{'Address':'123 Sample Avenure, Random City'}

This should generate a 201 response if successful with a JSON body similar to the following (viewed using the JSON pane in Fiddler)


My service is starting to feel like it is more realistic now, although very simplistic. I’ll need to extend this model quite a bit more and then update the applications to access the data from it.

Connecting Windows/Windows Phone Apps to Azure Mobile Service

In my previous post I created Windows and Windows Phone applications using the universal app template, and created and published a Mobile Service, The next step is to connect the apps to the Mobile Service using the Windows Azure Mobile Service NuGet package. In my solution I simply right-click on the solution node and select manage NuGet Packages. Locate the NuGet package by searching for “azure mobile service” and click Install next to the SDK package. Add the SDK to both Windows and Windows Phone projects but not the Service project.


Add a new file to the Shared project, MainPage.shared.cs and replace the MainPage class definition with the following:

public partial class MainPage
    public static MobileServiceClient MobileService = new MobileServiceClient(

    protected async override void OnNavigatedTo(NavigationEventArgs e)

        var items = await MobileService.GetTable<TodoItem>().ToListAsync();

public class TodoItem
    public string Id { get; set; }
    public string Text { get; set; }
    public bool Complete { get; set; }

I can run either the Windows or Windows Phone application and see that the items variable gets populated with the contents of the TodoItems table. Of course we need to switch out this table with one that is more applicable to the property inspector application I’m building but this demonstrates how easily you can retrieve data using the Azure Mobile Service SDK.

Creating Your Solution and Your Azure Mobile Service

As I discussed in my initial post there are a number of components that make up the property inspection tool. In this post we’ll start by creating the initial solution structure, create and add in the Azure Mobile Service, and publish the Azure Mobile Service.

Initial Solution Structure

A lot of blog posts will start by creating the Azure Mobile Service and then use the template projects provided on the home page of the newly created Mobile Service. Sometimes this isn’t an option and you want to be able to integrate a Mobile Service into an existing application. For this reason I’m going to start with a new project creating Visual Studio using the Blank App Universal template.


This will create Windows and Windows Phone projects, with a Shared code project to handle files shared between the two applications.



Creating the Azure Mobile Service

The next step is to create the Azure Mobile Service. This can actually be done by right-clicking on the Mobile Services node in the Server Explorer window in Visual Studio but I’m going to have to go to the management portal to download the initial project for the Mobile Service anyhow. To create the Azure Mobile Service, navigate to the Azure Management Portal and select New >> Compute > Mobile Service > Create from the toolbar at the bottom of the screen. Complete the setup wizard – make sure you select the .NET backend.


After completing the setup wizard, a few moments later the new Mobile Service will be available. However, before I can use it I need to publish the set of services -  you can think of what I’ve done so far as just setting up a placeholder for where the services will live.

Publishing the Mobile Service

To publish the Mobile Service I expand out the Get Started section on the home page of my newly created Mobile Service, and click on the Download link. I save the downloaded zip file, unblock and then extract the zip file.


I then copy the service folder (in my case realestateinspectorservice) into the solution folder of the solution I created earlier. Back in Visual Studio I then add the existing realestateinspectorservice project into the solution.


Right-click on the services project and select Publish. Select Microsoft Azure Mobile Services as the publish target


At this point if you’re not already signed in, you’ll need to sign into you Azure subscription with your Microsoft Account in order to select the previously created Mobile Service:


After selecting the Mobile Service to publish to, click OK and then the Publish button. This will cause the project to be compiled (and any required NuGet packages to be downloaded) and then published up to the Mobile Service. This may take a few minutes the first time as all referenced libraries will have to be copied up. However, future publish operations will be significantly quicker as they are by default differential.

After publishing the Mobile Service I can test that it’s operational using Fiddler (or curl etc) to simulate a GET request. I need two pieces of information: firstly the url of the Mobile Service I created. This can be found either in the Output window of Visual Studio at the end of publishing the Mobile Service, or from the dashboard pane of the Mobile Service in the Azure portal. The second thing is that I need one of the two assigned access keys. This again comes from the Azure management portal by clicking on the Manage Access Keys button in the toolbar at the bottom of the page. This key needs to be added to the request as the X-ZUMO-APPLICATION header. The following images show the request and response samples





So this gets me part of the way through setting up my solution – the next thing to do is to connect the Windows and Windows Phone applications so that they can call out to the Mobile Service…..

Field Engineer Sample for Azure Mobile Services

Over on the Windows dev center there is a code sample, Field Engineer, which covers a good portion of the application scenario I painted in my previous post. I won’t be delving into the sample in too much detail but I did want to do a quick review of the solution structure so that you get an idea of what’s there and what I’ll be adding to my scenario that extends this sample.


The sample solution in made up of four projects and only offers a Windows application frontend (in contrast to my scenario where we want to support both native apps and a web frontend). The mobile services are in the Services project which has an accompanying Test project. The interesting thing about the test project is that it does raw httpclient calls to validate that the services work as expected, instead of using the Azure mobile service client wrapper classes. Lastly there is a Setup project which is simply a command line utility that is designed to assist in the setup of the Azure components required in order to run this sample.

I’d highly recommend downloading this sample, setup and run it (follow all the instructions otherwise it’s not likely to work), before we move onto exploring my scenario in the coming posts.

Mobile First, Cloud First and How it Applies to Line of Business Software

I’m going to start the year by dissecting a typical business scenario which will demonstrate how the use of Windows, Windows Phone and Azure can be plugged together to quickly deliver a line of business solution. Throw in a bit of Xamarin and a web front end and you have a solution that will enable employees to use any device they choose in order to access the software.

The first thing to cover is the scenario, which in this case is going to be a property inspection tool that could be used by a property manager to do periodic property inspections required under most rental agreements. At first glance this appears to be a tool that is specific for the real estate industry but as we’ll see there are a number of components that make it similar to any task, defect or issue tracking system:

- Property managers will have a number of properties assigned to them to manage
- Properties will have a history of inspections which may include images and/or videos
- Property information, and perhaps most recent inspection, needs to be available offline (just in case there is no internet inside a property being inspected)

- Inspections need to be able to be created, edited and submitted from a mobile device

This will probably do for the time being; as we go we may introduce other elements to demonstrate the use of various platform components. What’s interesting to note at this point is that properties can be switched out for projects, and inspections for tasks, if this scenario were a task/issue/defect tracking system.

At a high level let’s discuss the major components:

- Mobile devices – Naturally as .NET developers we gravitate to what’s easiest so we’ll include Windows and Windows Phone applications based on the universal app template which uses a shared code project to prompt reuse. However, we shouldn’t neglect the other platforms so we should include iOS and Android projects, using the Xamarin tooling. Our business logic we’ll abstract into a portable class library (PCL) to attempt to give us maximum reuse.

- Services – Azure Mobile Services will give us the raw scaffolding to stand up a SQL Server backend with services exposed to surface data to our mobile applications. These services support synchronisation which we’ll use to give the mobile applications offline support.

- Blobs – Azure Blob Storage will be used to store the images and videos collected as part of the solution. Whilst the service tier will be used to control access to Blog Storage (by issuing Shard Access Signatures) the upload will be done from the mobile applications directly into blob storage

- Authentication – As this is a line of business solution we’d prefer users to not have to remember another set of credentials. To this end the solution will use Azure Active Directory (AAD) to authenticate users and grant them access to the software. The users can be synchronised from the corporate AD into AAD so as to maintain a single set of credentials for any user.

- Web application – An Azure Website will be used to provide desktop and mobile solution for those unable to use the mobile applications. Whilst this could go directly to the SQL Server backend, it will in fact be routed via the service tier to ensure a common authentication pattern and usage model for the data.

- Scheduling – A scheduler will be setup in Azure for use by the solution in order to schedule particular jobs or operations to be carried out. For example the periodic generation and sending of reports.

- Push Notifications – When new data is available, push notifications can be sent out to the mobile applications to either alert the appropriate user, or perform a background synchronisation of the new data.

I’ll use this post as a reference for the components that I’ll be discussing in the coming posts. The components aren’t in any particular order and the posts won’t focus on individual components, rather how they connect together and what you need to know to get them to work together.

“Ello” who built this rubbish

So after requesting an invite so long ago that I’d forgotten I had a passing interest in the site, I final received in invite via an email from someone called Todd, who I can only assume is related to the site somehow. Anyhow, after signing up on my mobile I wasted a couple of minutes attempting to browse the site and work out how to do simple things like post. In the end I figured I must be missing something, or that perhaps the site wasn’t rendering properly on my Windows Phone. That was a day or so ago; today I remembered that I was supposed to go back and take a look on my laptop. In doing this, again I was woefully disappointed. So much so that I went out looking to see what others had said about the site. The good news is that I’m not alone – for example a post by the Lion of the Blogosphere ( sums it up nicely:

But now let’s get to the part about Ello that sucks. The website is a confusing buggy piece of crap. It took me an hour to figure out how to post a photo and two paragraphs of text under it.

I couldn’t have said it better myself. What a complete waste of my time. The site might look ok but the UX is dreadful – there’s no clear call to action; nowhere to start on the page; no obvious way for someone new to get started.

Anyhow, I think I’ve hated enough on this site – needless to say I won’t be going back in a hurry.

Visual Studio GenerateResource Error Building on Windows 10

A couple of weeks ago when I installed Windows 10 on my primary machine I ran into an issue where Windows Phone/Windows/Universal applications stopped building due to a rather cryptic error relating to trusted network resources…. which was bizarre since the projects were all local on my machine. This is the same error reported on the Windows Dev Center -

The good news is that there’s a relatively simple fix as indicated in the error message ”please enable the loadFromRemoteSources switch". Of course this shouldn’t need to be applied but that’s the danger of running on the edge with a pre-release product. What’s not obvious is where the switch should be applied – if you follow the link to MSDN it seems to indicate that the switch needs to be added to Devenv.exe.config, which does nothing to fix the issue. Turns out you need to add it to the MSBuild configuration file (eg C:\Program Files (x86)\MSBuild\12.0\Bin\ MSBuild.exe.config).

<?xml version ="1.0"?>
        <section name="msbuildToolsets" type="Microsoft.Build.BuildEngine.ToolsetConfigurationSection, Microsoft.Build.Engine, Version=, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
    <startup useLegacyV2RuntimeActivationPolicy="true">
        <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.1"/>
    <loadFromRemoteSources enabled="true"/>

Demo rule #1 practice again and again and again, particularly the night before….

Tomorrow is round 2 of TechEd Australia and after my demos all seemed to go well in Melbourne I figured I was all set. However as I usually do I wanted to double check that everything was going to work (particularly since I’m running the Windows 10 preview build). Anyhow, it’s a good thing I did because the wonderful Azure team have changed the syntax of one of the manifest files I have to manually edit mid-way through my first session. The step I walk through is actually taken from a post over on Azure Mobile Services site ( and includes this change:


Well, no more – if you try to do this you’ll find that the appPermissions node doesn’t exist in the manifest file. Luckily I have a working mobile service with this change already applied, so I figured if I download the manifest file I should be able to see what’s changed. It turns out that the syntax has changed and that instead of replacing the appPermissions node, you now have to replace the oauth2Permissions node ie change:

"oauth2Permissions": [],


"oauth2Permissions": [
      "adminConsentDescription": "Allow the application access to the mobile service",
      "adminConsentDisplayName": "Have full access to the mobile service",
      "id": "b69ee3c9-c40d-4f2a-ac80-961cd1534e40",
      "isEnabled": true,
      "origin": "Application",
      "type": "User",
      "userConsentDescription": "Allow the application full access to the mobile service on your behalf",
      "userConsentDisplayName": "Have full access to the mobile service",
      "value": "user_impersonation"

The upshot of this is that had I just assumed that my demos would all just work tomorrow I would have been fighting this fire on stage (argh). Moral of the story is practice, practice and practice some more – you never know when the demo gods will strike, and it’s best to be prepared when they do.

TechEd Australia – Sydney and Melbourne 2014


This year I’m delivering two sessions in both Melbourne (7-8th October) and Sydney (27-28th October):

Using Visual Studio and Blend to build Beautiful Universal Applications (WPD307)
The new Universal Application project promises to reduce the amount of code you need to write, but does it reduce the amount of design work you have to do? In this demo-heavy session, XAML guru Nick Randolph explores the tooling available in Blend and the patterns you’d use to produce stunning Universal Applications with a minimum amount of work.

Building and Migrating Modern Enterprise Line of Business Applications (WPD304)
Mostly, when we build enterprise applications, we’re not starting from scratch. Deciding what to build, what to reuse and what to keep is an important part of the enterprise software development decision process. In this session, Nick will explore the conditions and requirements that might lead you to decide which of these approaches to take. He’ll also demonstrate some techniques for taking an existing Line of Business application and lighting it up with a modern, touch-friendly UI.


If you’re attending in either session, come along and chat about the direction of the Windows platform and how to take advantage of it in your business.

Errors Installing and Running Windows Phone 8.1 Appx

Last week we ran into a couple of issues installing and running a Windows Phone 8.1 Appx application. Here are some of the symptoms:

  • Application deploys and runs fine in the emulator
  • Application deploys and runs fine on some phones running Windows Phone 8.1 but refused to install on other phones. The error given by Visual Studio when attempting to install the application was a rather cryptic, and overly useless, error code
  • Application package could be successfully signed using the signing tool as part of the SDK
  • Signed application package refuses to install on some retail phones running Windows Phone 8.1

It turns out that we were referencing the Active Directory Authentication Library which in turn was making a native call that only showed up when we ran the WACK test. As we weren’t planning to deploy via the Windows Store we hadn’t run the WACK test recently and it was only by chance that I ran it to see if it threw up any errors. Fixing the errors and warnings not only addressed the installation issue it also highlighted some issues with the project structure (incorrect images sizes etc).

Recent Posts at Visual Studio Magazine

For those who don’t know, I contribute a monthly segment over at Visual Studio Magazine called the Mobile Corner. Here are a couple of the most recent articles – I’ve cc’d them here because I feel that particularly the Enterprise Distribution article is of great value to companies looking to deploy applications internally.

  • Enterprise Distribution of Windows Phone Applications
  • Windows Phone and Windows 8.x: Designing Once for Both with XAML
  • How To Use the Windows Phone 8.1 GridView and ListView Controls
  • Multiple Flyout Templates for ComboBox and Changing the Header

    Following my previous post Breaking apart the Windows Phone 8.1 ComboBox Style and Colors a reader asked me:
    - How to vary the flyout template so that each combobox could have a different appearance
    - Change the header on the flyout from the default “CHOOSE AN ITEM”

    The ComboBox uses the default style for the ListPickerFlyoutPresenter which means that in order to vary the template for each ComboBox you need to change the default style. Luckily you can do this in code. Take the following XAML which declares two Styles based on the same base style for the ListPickerFlyoutPresenter with the background color varying.
        BasedOn="{StaticResource CustomListPickerFlyoutPresenter}">
            Value="Purple" />
        BasedOn="{StaticResource CustomListPickerFlyoutPresenter}">
            Value="Green" />

    In order to switch between templates you just need to change the default template using the type as the key:

    private void PurpleClick(object sender, RoutedEventArgs e) {
        var purple = Application.Current.Resources["PurpleBackgroundListPickerFlyoutPresenter"];
        Application.Current.Resources[typeof (ListPickerFlyoutPresenter)] = purple;

    private void GreenClick(object sender, RoutedEventArgs e) {
        var green = Application.Current.Resources["GreenBackgroundListPickerFlyoutPresenter"];
        Application.Current.Resources[typeof(ListPickerFlyoutPresenter)] = green;

    The second part is a little harder to track down because it doesn’t appear that the text “CHOOSE AN ITEM” is set anywhere but it’s being set on the TitlePresenter TextBlock in the ListPickerFlyoutPresenter template. Often by removing named items in the default template you can raise an internal exception. Luckily in this case you can simply remove the TitlePresenter element and replace it with a similar TextBlock containing the header you want. Setting the TitlePresenter to Collapsed doesn’t work as it’s set to Visible by the ComboBox so you actually need to either remove the item or set the Opacity to 0.

    Breaking apart the Windows Phone 8.1 ComboBox Style and Colors

    Yesterday I had an interesting, if not a little frustrating, time pulling apart the default style of the Windows Phone 8.1 ComboBox. Before I start I’ve put together a series of images showing various states of the ComboBox:

    A – The default unfocused state of the ComboBox, showing the placeholder text
    B – The state when an item has been selected (focused and unfocused look the same)
    C – The pressed state, prior to items selection showing
    D – The expanded state when only a few items (5 or less) in the list using one of the default TextBlock styles (we’ll discuss this in a minute)
    E – The expanded state when only a few items (5 or less) in the list using a TextBlock without the Foreground color set (no selection)
    F – The expanded state when only a few items (5 or less) in the list using a TextBlock without the Foreground color set (item selected)
    G – The disabled (ie IsEnabled=false) state
    H – The expanded state when more than 5 items, which is same regardless of whether an item is selected or not (ie no selection shown)



    Don’t Use Any of the Built In TextBlock Styles!!!

    Before we jump into look at the ComboBox styles and colors in more detail, let me briefly discuss D in more detail. For this particular scenario the combobox has 3 items in it which means that the expanded view will show the items in situ (same behaviour as the ListPicker from Windows Phone 8/8.1 Silverlight). The ItemTemplate for the ComboBox looks like the following:

    <DataTemplate x:Key="ItemsItemTemplate">
        <TextBlock Text="{Binding Property1}" Style="{StaticResource BodyTextBlockStyle}" />

    On face value this looks great – we have a simple TextBlock which is data bound and we’re using one of the out of the box styles, BodyTextBlockStyle. Unfortunately this inherits from BaseTextBlockStyle which sets the Foreground based on the current theme, as the following XAML snippet illustrates.

    <Style x:Key="BaseTextBlockStyle" TargetType="TextBlock">
        <Setter Property="Foreground" Value="{ThemeResource PhoneForegroundBrush}"/>

    <Style x:Key="BodyTextBlockStyle" BasedOn="{StaticResource BaseTextBlockStyle}" TargetType="TextBlock">
        <Setter Property="LineHeight" Value="24"/>

    The issue with this is that the in situ expanded view relies on Foreground being inherited from the host control, which doesn’t happen if it is explicitly set on an element (such as this case where the Foreground is being explicitly set in the TextBlock Style). The work around is simple – don’t use the built in styles, start by taking a copy of them and working with those instead eg:

    <Style x:Key="NoForegroundBaseTextBlockStyle" TargetType="TextBlock">
        <Setter Property="FontFamily" Value="{ThemeResource PhoneFontFamilyNormal}"/>
        <Setter Property="FontSize" Value="{ThemeResource TextStyleLargeFontSize}"/>
        <Setter Property="TextTrimming" Value="Clip"/>
        <Setter Property="TextWrapping" Value="WrapWholeWords"/>
        <Setter Property="LineHeight" Value="21.5"/>
        <Setter Property="LineStackingStrategy" Value="BaselineToBaseline"/>
        <Setter Property="TextLineBounds" Value="Full"/>
        <Setter Property="OpticalMarginAlignment" Value="TrimSideBearings"/>
    <Style x:Key="NoForegroundTextBlockStyle" BasedOn="{StaticResource NoForegroundBaseTextBlockStyle}" TargetType="TextBlock">
        <Setter Property="LineHeight" Value="24" />

    When I use the NoForegroundTextBlockStyle instead of D, when I expand the ComboBox I see E (no item selected) or F (item selected) instead. Note how they pick up the foreground colour, including the accent colour for the selected item.


    Now for the Colors

    You’d have thought that adjusting the colors throughout the combobox would be relatively straight forward. Unfortunately this is not the case but let’s start with what we can adjust without tweaking the Template of the ComboBox. Selecting the ComboBox and looking at the Properties window (VS or Blend) I can adjust the Background, Foreground and BorderBrush, as shown in the following image where I’ve set each of these to a distinct color so that we can see where they appear in the ComboBox:


    The impact on the ComboBox is as follows (see image below):

    1 – In the unselected state, the Foreground color has no impact on the color of the placeholder text but the background and border colors can clearly be seen
    2 & 3 – In the selected and pressed states, again, the Foreground color has no impact
    4 – In the expanded state there are no color changes
    5 – In the selected state, when there are 5 or fewer items, the Foreground color is evident in the text
    6 – No change to the disabled state
    7 – The Foreground color is used to highlight the selected item


    Clearly the use of these three colors hasn’t been applied consistently through the ComboBox states so we’re going to have to dig deeper in order to tweak things. I’ll start by looking at the Template for the ComboBox by right-clicking on the ComboBox, selecting Edit Template, Edit a Copy.


    There are three components of the Template being the presenter for the header, a button and the border which will house the expanding list for when there are five or fewer items.


    The Button is what is displayed when there are 5 or more items. Selecting the Button we can see that both Background and BorderBrush are set but the Foreground is inherited. I’ll update this to be data bound using Template Binding to the Foreground button.


    We’ve sorted out the inconsistency in 1. This actually also sorted out the foreground color in 2 and 3. However, when the button is pressed, we still see the accent color coming through, which in most cases conflicts with the branding of our app. The question is what to replace it with…. this is an issue for another day; for now, let’s just change it to use a different static resource. Right-click on the button, select Edit Template, Edit a Copy, which will take a copy of the button template and put Blend into template editing mode. From the States window, select the Pressed state.


    In the Objects and Timeline we can see that the Background on the Border element has been set to the accent color. I’ll select the Border and from the Properties window select Convert to New Resource from the Background.


    I’ll name the new resource ComboBoxPressedBrush and set the color to Pink so it stands out.

    Solving 4 includes fixing a few things: Background, Border, Foreground and Selected Foreground. First things first, let’s change the white background to the background set on the ComboBox. Looking at the template it would appear that the background is already set using data binding through Template binding to the Background being set on the ComboBox. However, at least two of the States in the template are adjusting the background – in fact the error shown in Blend is the result of some developer not understanding how visual state groups work, or being too lazy to establish a working set of states. Anyhow, what we want to do in this case is actually to adjust both states to remove any changes to the background property.


    In this case we need to remove the Background property from the following states:

    CommonStates - Pressed
    CommonStates - Disabled
    CommonStates – Highlighted
    DropDownStates - Opened

    Expanding the ComboBox now shows the expanded view with the correct Background color. Now onto Foreground for both the unselected and selected items. The Foreground color of the selected item is actually set correctly – it makes sense for this to be the Foreground color set on the ComboBox. However, the unselected Foreground color is currently set to a theme color, ComboBoxHighlightedForegroundThemeBrush. To override this color you can simply define another brush resource with the same name eg:

    <SolidColorBrush x:Key="ComboBoxHighlightedForegroundThemeBrush" Color="#FF00F3FF"/>

    We do also want to address the conflicting visual states by removing the Foreground property from the DropDownStates – Opened. Also, remove the BorderBrush from the CommonStates – Highlighted state, which will fix the border on the expanded area. That solves number 4.

    5 requires no changes

    Addressing 6 requires two steps. The first is to overwrite some of the built in colors that control how the ComboBox appears when it is disabled. To do this we simply create new brush resources with the same name in our application. The following resources use the same Border, Background and Foreground that I set earlier on the ComboBox, except the Opacity is set to 40%

    <SolidColorBrush x:Key="ComboBoxDisabledBorderThemeBrush" Color="#9900FF00" />
    <SolidColorBrush x:Key="ComboBoxDisabledForegroundThemeBrush" Color="#990000FF" />
    <SolidColorBrush x:Key="ComboBoxDisabledBackgroundThemeBrush" Color="#99FF0000" />

    The other part is to adjust the Disabled state of the FlyoutButton. As I did earlier I needed to edit the Template for the Button and set the disabled BorderBrush, Background and Foreground to the corresponding ComboBoxDisabled brush.

    7 requires a bit more exploration of what happens when the ComboBox expands to full screen in order to see the list of items. When this happens a flyout is displayed using the ListPickerFlyoutPresenter. The template for this control can be found in C:\Program Files (x86)\Windows Phone Kits\8.1\Include\abi\Xaml\Design\generic.xaml. Copying this template into the application resources means we can make changes, in this case to the Foreground and Background colors:

    <SolidColorBrush x:Key="ComboBoxFullScreenExpandedBackgroundThemeBrush" Color="DarkGray" />
    <SolidColorBrush x:Key="ComboBoxFullScreenExpandedForegroundThemeBrush" Color="Orange" />

    <Style TargetType="controls:ListPickerFlyoutPresenter">
        <Setter Property="Foreground" Value="{StaticResource ComboBoxFullScreenExpandedForegroundThemeBrush}" />
        <Setter Property="Background" Value="{StaticResource ComboBoxFullScreenExpandedBackgroundThemeBrush}" />

    The only thing this doesn’t affect is the header on the flyout page which still appears in white. To get this to use the Foreground value I just set I need to modify the FlyoutPickerTitleTextBlockStyle built in style (which is also in the generic.xaml file) by copy it into the application resources and altering the BasedOn value to use the NoForegroundBaseTextBlockStyle defined earlier.

    <Style x:Key="FlyoutPickerTitleTextBlockStyle" TargetType="TextBlock" BasedOn="{StaticResource NoForegroundBaseTextBlockStyle}">

    With these changes made we’ve got much better control over how the ComboBox displays text and how the border, background and foreground colors are applied.



    Hopefully in this post you’ve seen how you can jump in and alter colors throughout the ComboBox templates. There are a series of built in colors both in generic.xaml and themeresources.xaml (C:\Program Files (x86)\Windows Phone Kits\8.1\Include\abi\Xaml\Design) which can be overwritten to do simple changes but sometimes you need to modify the underlying templates.

    When Lists aren’t Vertical or Horizontal – Going Diagonal with Windows ListView Control

    The designer for a project we’re currently working on just pitched an idea where there would be a list of items that were presented along a diagonal. Back in Silverlight this probably would have been accomplished using a PathListBox but of course that doesn’t exist in the Windows 8 world. So this got me thinking …. and actually I had to reach out to UX guru Shane Morris for some inspiration. Whilst I’m not using the viewbox suggestion he had, the solution was much easier than I initially thought and essential revolves around rotating the ListView one direction and the items in the list back the other way (so they’re still horizontal).

    My first pass was literally just that. A rotate transform of 27 degrees on the ListView and then a –27 degree rotate on the first item in the ItemTemplate:

                Rotation="27" />

                    Rotation="-27" />
            <!--     .... -->

    Unfortunately this didn’t work particularly well as it ended up with too many layout issues (see below image). There was incorrect header/footer spacing but more importantly the hover effect (ie the grey background) wasn’t being rotated.


    My next attempt involved still rotating the ListView but instead of rotating a child of the ItemTemplate I instead rotated the ListViewItemPresenter which is found by right-clicking on the ListView and selecting Edit Additional Templates, Edit Generated Item Container (ItemContainerStyle), Edit a Copy (first time only).


    <ListViewItemPresenter .... RenderTransformOrigin="0.5,0.5">
            <CompositeTransform Rotation="-27"/>

    Now we’re getting closer – the hover aligns with the item as they’re both being correctly rotated. I still had issues with the positioning on the screen to ensure items scroll all the way to the edge of the screen and that all of them can still be scrolled completely into view. Firstly, I had to adjust the position of the ListView so that after rotating the trailing corner is flush with the top and bottom of the screen.


    Doing this will prevent the first and last item being able to be scrolled into view. This can be fixed by adding a spacer into the header and footer template of the ListView.

    The last issue to overcome is that the scroll bar goes off the screen at the bottom.


    This can be fixed by tweaking the template of the scrollviewer, setting a bottom margin to lift the vertical scrollbar back onto the screen. To get to this template you have to edit the template of the ListView (not one of the additional templates), then edit the template of the ScrollViewer (which itself is part of the ListView template).

    The result is that we have items that are presented, and scroll, along a diagonal line.


    Windows Phone 8.1 APPX Code Signing Weird Error When Installing

    Over the last couple of days I’ve been trying to diagnose what we were doing wrong when code signing a Windows Phone 8.1 APPX file in preparation for enterprise distribution. The signing process completes successfully. However, when we go to install the application on either device or emulator we were seeing weird errors (see image below that quotes an exception code of 0x80073CF9).


    SOLVED: It turns out that there is an issue with the signing process but nothing related to what we were doing. It’s actually related to the version of the tools we’re using. Here’s a list of the toolsets that apparently work/don’t work:

    Visual Studio 2013 with Update 2 RC – WORKS
    Visual Studio 2013 with Update 2 RTM – DOESN’T WORK
    Visual Studio 2013 with Update 3 RC – WORKS

    So you either need to regress to the RC of Update 2, or go to the RC of Update 3.

    Side Note: If you see errors relating to a missing token, you’re probably attempting to install the package by calling AddPackageAsync from within an application that isn’t signed (ie a developer build pushed out using either the application deployment tool, or via Visual Studio). If you sign the application doing the installation and then install it, you should see the the call to AddPackageAsync will work for correctly signed XAP and APPX. This is a breaking change from Windows Phone 8.0 where this method worked regardless of whether the installer app was signed or not.

    Using Build it Beta to Test and Deploy your Windows Phone Applications

    Over the last year we’ve been working on Build it Beta to assist Windows Phone developers deploy and test their applications. To get started, follow the setup instructions for Build it Beta


    Here’s a bit more information on each step:

    Step 1: The Build it Beta application is available in both the Windows and Windows Phone Stores. In order to test an application on your Windows Phone device, the first step is to download the Build it Beta application from the store.

    Step 2: After downloading and installing Build it Beta you then need to run and sign into Build it Beta. You can choose between one of the supported social network providers (Facebook, Twitter, Microsoft, Google) and use an existing or create a new set of credentials. You need to supply a valid email address so that we can identify your account. When you want to test and application you can simply send your application to upload @ from the email address you entered. We’ll send you a confirmation after the application is available for testing. After signing in, you should be prompted to return to the setup instructions. Alternatively press and hold the back button and switch back to Internet Explorer where you should still have the setup instructions.

    Step 3: Install the Built to Roam enterprise deployment certificate. This certificate is required in order to install applications you want to test. Rather than deploying applications via the Windows Phone store, where they’re signed with a pre-trusted certificate, in Build it Beta all applications are currently signed using the Built to Roam enterprise deployment certificate. Installing this certificate won’t affect your ability to install applications from the Windows Phone store, nor does it affect any other enterprise enrolment you may have (eg via an MDM provider).

    Step 4: Install the Build it Beta Installer. Due to both technical and policy limitations on applications installed from the Windows Phone Store, Build it Beta relies on a secondary application to install the applications you want to test. Clicking the link in the setup instructions should prompt you to install this application. Unfortunately there isn’t a progress indicator or confirmation that it has been installed successfully – give this step a minute or two before moving on.

    Step 5: Launch the Build it Beta Installer. This will run the installer and pair it with the main Build it Beta application. Once you’ve completed this process you’re good to go – start sending your applications to Build it Beta to test them.


    Testing an application

    When you have an application that you want to test you can send it to Build it Beta a number of ways:

    Email – Simply email your xap or appx file to upload @ You’ll get a confirmation message back once the application has been ingested.

    Upload – If you have Build it Beta for Windows installed you can simply double-click your xap file. The application will be uploaded to Build it Beta.

    Attachment – Rename your xap file to .betaxap and email it to someone you want to test your application. Clicking the attachment will upload the application via Build it Beta for Windows Phone and make it available for the tester.

    The Danger of Setting CacheMode to BitmapCache on Windows 8

    This week has been full of interesting challenges as we worked to release another Windows 8 application for a client. Credit must go to the client who has set the expectation bar at an incredibly high level – I truly wish all clients had this level of respect for their brand, identity, apps, website etc. One of the challenges we came up against was with a very persistent image that refused to display correctly. By correctly I mean without any distortion, blurring, pixelation etc that happens when you incorrectly resize images. Now we only really saw this on the Surface 2 which runs at a scale factor of 140 and it was clearly evident that the image that was displayed was blurry. Following all the documentation and guidance we provided images at 100, 140 and 180 scale factors and validated that the correct image was being show by tagging each image to make them slightly unique. We also ensured that the image element was the correct size for the image and that Stretch was set to None (interesting side note – it appears that even if the element size matches the image size, if you leave Stretch to its default value of Uniform you end up with some visual distortion).

    Even after doing all of that we still ended up with an image that was slightly blurry – enough that you’d have thought the image had been blown up slightly. It turns out that we had set CacheMode=BitmapCache on a parent element to ensure that when we animated the elements they would animate together. Removing the CacheMode attribute resulted in the image appearing crystal clear.

    Ok, so here’s the original.



    Here’s an image where the left side is taken from an element with CacheMode=BitmapCache, the right side is from an element without this attribute – spot the difference (hint, look at the edge of the spiral towards the centre)



    Here’s an image where the top is taken from an element with CacheMode=BitmapCache, the bottom side is from an element without this attribute – again you should be able to see the difference.



    Call out to mobile developers out there – do you care this much about your apps? If not, then you need to re-evaluate your quality bar.

    Remove Tap/Mouse Down Animations on GridView and ListView for Windows 8.1

    <disclaimer> The reason that the GridView and ListView have built-in animations for when a user taps or mouse-downs on an item is to provide feedback that they have indeed tapped/mouse downed on an item. I highly discourage the removal of these built-in animations as it will detract from your user experience. That said, there are times where you may need to remove these animations. For example if you nest a ListView within an item of a GridView, then, depending on what you want tappable, you’ll need to remove the animations on either the GridView or ListView.</disclaimer>

    *If you’re building for Windows 8.0 then I suggest taking a look at some of the existing posts out there on how to remove storyboards from the ItemContainerStyle (eg

    A lot of the discussion on the web is on how to remove various transitions from elements in Windows 8/8.1. For example setting the Transitions property to an empty TransitionsCollection. However, after setting virtually every transitions property I could find, I was still seeing the tap animation. It turns out that one solution is much simpler than I’d thought, and can be useful if you want to get rid on all the built in GridView/ListView item effects. Be warned, this will remove all those built-in effects!

    Let’s walk through a simple example:

    - Create a new Windows application based on the Hub App template – this will give us a GridView to work with. You can also use the Grid App if you want.

    - Open the application in Blend (right-click the project and select “Open in Blend”)

    - Locate a GridView to modify – we’re going to use the GridView in Section 3 of the Hub

    - Right-click the GridView and select Edit Additional Templates –> Edit Generated Item Container (ItemContainerStyle) –> Edit a Copy


    - Switch to code mode (I prefer split mode) and delete (or comment out) the GridViewItemPresenter element.

    - Add an empty ContentPresenter element.

    <Style x:Key="GridViewItemStyle1" TargetType="GridViewItem">
        <Setter Property="FontFamily" Value="{ThemeResource ContentControlThemeFontFamily}"/>
        <Setter Property="FontSize" Value="{ThemeResource ControlContentThemeFontSize}"/>
        <Setter Property="Background" Value="Transparent"/>
        <Setter Property="TabNavigation" Value="Local"/>
        <Setter Property="IsHoldingEnabled" Value="True"/>
        <Setter Property="Margin" Value="0,0,2,2"/>
        <Setter Property="Template">
                <ControlTemplate TargetType="GridViewItem">
                    <ContentPresenter />

    - Run the application – you’ll notice that there is no tap animation on the GridView in section 3, yet it still responds to tap or mouse click on the item (just no visible feedback).

    Note: If you have a GridView or ListView that isn’t interactive you can always either disable it or set the IsHitTestVisible property to false.