Nick's .NET Travels

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

Getting Started: MvvmCross with Xamarin Forms

Over the past 6-12 months we’ve seen dramatic changes in Xamarin Forms and the support within Visual Studio. The most recent update, which I covered in my previous post, included a number of new features for cross platform developers. However, despite these updates, getting started with cross platform development is still quite complex. In this post I wanted to take the opportunity to reiterate how to start a new Xamarin Forms project. From there I’ll cover adding in MvvmCross and discuss the importance of having a framework that will make development that much easier (for the record MvvmCross isn’t the only option, there are plenty of great alternatives such as Prism and FreshMvvm).

Part 1: Getting Started with Xamarin Forms

Before getting started, make sure you’ve run the Visual Studio Installer and have upgraded to the latest stable release of Visual Studio. The team at Microsoft have been putting a lot of focus on stability and performance, so upgrading to the latest version does help (still not perfect but a marked improvement over this time last year!). Upgrading Visual Studio continually can be a bit of a pain, especially since Microsoft haven’t quite worked out how to automatically download updates in the background for VS – meaning that you have to stop whatever you’re doing whilst the updates download and then install. Recommendation is to run the installer periodically at the end of your day, or when you’re heading to a long meeting; hopefully the installation is complete by the time you return.

Now that you’re all up to date, let’s create a new solution by selecting the Cross-Platform App (Xamarin Forms) template from the New Project dialog. Note that if you don’t see this template, you may have to adjust the workloads you selected in the VS Installer so that you have all the cross-platform development components selected.


After clicking OK you should be presented with a second dialog that allows you to specify parameters for how your cross platform project should be setup. As you can see from the image, I recommend always selecting all three platforms (even if you’re only planning on targeting one or two of them initially); In this case we’re going with Xamarin.Forms with a simple Blank App; The last option I’m particularly passionate about – do NOT select Shared Project – for the good of your project, the team and general good programming practice, please select the .NET Standard option for Code Sharing Strategy. At time of writing the .NET Standard option is only available in the preview build of Visual Studio; the stable build uses a Portable Class Library, which is still preferable over using a Shared Project.


This time clicking OK will create a new solution.

Unexpected Error when Creating Solution

Unfortunately, at time of writing this post there is also a bug in the current cross platform template that results in the following error:


If you see this error, a quick Google will yield the following bugzilla issue ( which describes the issue, along with how to fix it yourself – you just need to edit the Android csproj file and remove the " from around the TargetFrameworkVersion ie:




After fixing up the csproj file you’ll need to add the existing projects into the solution file.

Assuming you didn’t run into any issues creating the solution, or you were able to fix up the Android csproj file, you should be able to build and run each of the head projects:



Note: When building the UWP project I was seeing a build warning stating “warning APPX0108: The certificate specified has expired.” which I thought was a bit odd since I had just created the project and normally the certificate that is used for debug builds is created alongside the new project. Double-clicking the package.appxmanifest and switching to the Packaging tab I see that the Publisher display name isn’t set correctly – I’m guessing at this point that the cross platform template contains an existing certificate, instead of creating one each time. You can easily fix this by changing the publisher display name, clicking Choose Certificate and then from the dropdown select “Create test certificate”.


Now when you build the project you won’t see this warning – I’m guessing this is also a bug in the preview version of the cross platform template.



For Android I’m using the Google Android Emulator that can now be installed using the Visual Studio Installer. This is significantly better than it used to be, and the images are much more recent than those for the Visual Studio Android Emulator which has been deprecated now.



For iOS, as I’m working from a Windows laptop, I use the Remote Simulator which works really well and means I don’t need to continually VNC to my MacMini or have to deploy to a real device.

Again there was an issue with the iOS template in that the MinimumOSVersion was set to “11.2” instead of just 11.2 in the Info.plist file.


Correcting the MinimumOSVersion will allow your application to run on a device or emulator.

Now that we’ve validated that all the platforms run, it’s time to make sure they’re setup correctly ready for us to add in Mvvmcross and to set the foundation of our application. Android and iOS should be setup correctly, although you may want to double-check to make sure Android is set to use the latest platform version (see Application tab of the Android project properties); UWP defaults to using the Fall Creators Update (FCU) as the minimum version, which is way to recent for applications wanting to target the widest set of customers. Our preferences is to set this back to the November Update


Note however, that this does preclude your application from using .NET Standard 2.0 libraries, as these are not compatible with UWP projects prior to the FCU. Unfortunately the .NET Standard library that holds the Xamarin Forms views for the solution is set to .NET Standard 2.0 by default. This is completely unnecessary, so it can be reduced back to 1.4 (or below, depending on your preferences)


Next, we want to make sure we’re using the latest NuGet packages – right-click on the solution node in Solution Explorer and select Manage NuGet Packages for Solution


After upgrading all the NuGet packages, double-check to make sure all platforms build and run. Now’s a great time to check your solution in to your repository of choice (Note: make sure you check in the pfx file that is part of the UWP solution. You’ll probably have to manually add this file to your repository as most repositories ignore pfx files by default).

Update: Part 2 is now available.

Hey, who moved my… Visual Studio Emulator for Android?

A while ago, in response to a common frustration from Xamarin developers, Microsoft released the Visual Studio Emulator for Android and it even made it into the Visual Studio installer:


As a long-serving Windows Phone developer I embraced this decision as the emulator was based on Hyper-V which meant that it played nicely with the Windows Phone emulators – I could now do cross platform development, even when I didn’t have real devices with me. Unfortunately, Microsoft have indicated that the emulator is no longer going to receive updates, so anyone wanting to dev/test on more recent builds of Android are out of luck. This was really frustrating as the emulator was both quick (relative to the out of the box emulators from Google – historically) and didn’t require another emulator sub-system (as it worked on Hyper-V).

Recently, Microsoft have actively discounted Windows Phone, making it very hard to justify any developer resources on building for Windows Phone…. it also makes me question the value proposition of UWP over WPF, but that’s a topic for a different post. The upshot is that there is no longer a reason for me to have the Windows 10 Mobile emulators installed, which means I have no need for Hyper-V, which means I can use any one of the great Android emulators out there that don’t play nice wiht Hyper-V.

What’s really cool is that Microsoft have included the Google Android Emulator in the Visual Studio installer. You need to make sure that both the Google Android Emulator and the Intel Hardware Accelerated Execution Manager are installed.


After installing the Google emulator you can launch your application on the emulator the same way you would to a real device – it appears in the devices dropdown. You can also access the different emulator images via the Android Emulator Manager.


Whilst the Android Emulator Manager is not a great looking dialog, it does allow you to customise and launch the different emulators.


I was so surprised when I launched the updated emulator. I was expecting an old, slow, crappy looking emulator but was surprised with an updated emulator shell with all the features that I’d come to expect from an emulator.


I’m a convert – Whilst I’ll still use a real device for most development work, having a good emulator is critical for those times when I don’t have a device with me. Cudos to Microsoft for firstly pushing Google to build a better developer experience and secondly making the Visual Studio installer so simple to install the emulator.

Sidenote: I did have to update one component from the Android SDK. Make sure you read the build output window in Visual Studio if you are running into issues as it pointed me to an out of date component.

Getting Started: Xamarin Forms with .NET Standard 2.0

In my earlier post Getting Started: Xamarin Forms with .NET Standard I covered how to create a new Xamarin Forms project which uses a .NET Standard 1.4 library to share the views between iOS, Android and UWP. At the time, whilst iOS and Android supported .NET Standard 2.0, support still wasn’t available for UWP. Almost immediately after publishing the blog post, Microsoft announced that Visual Studio 2017 preview 15.4 would allow UWP applications to reference .NET Standard 2.0 libraries. Unfortunately this didn’t work in the first drop, 15.4.0 Preview. This was just updated to 15.4.0 Preview 2 (Release Notes:, which brings with it the support we’ve been after. In this post, I’m going to repeat the previous post on getting started with .NET Standard, this time using .NET Standard 2.0 for the UI project.

Let’s walk through the basics – create a new Cross Platform App (same as before)


Select the Xamarin.Forms (UI Technology) and Portable Class Library (PCL) (Code Sharing Strategy) – Don’t pick the Shared Project option!


Select the Insider Preview version of UWP for both Minimum and Target version – this is required for .NET Standard 2.0 support. If you want to target earlier versions of Windows 10, you’ll have to stick with .NET Standard 1.4.


Next, we’re going to replace the PCL with a new .NET Standard library


I’ll copy the App.xaml, App.xaml.cs, MainPage.xaml and MainPage.xaml.cs from the PCL into the .NET Standard library, before deleting the PCL from the project (see for more detailed instructions).

The big difference is that I’m not going to change the default Target Framework, leaving it as .NET Standard 2.0.


Next I need to make sure I add and upgrade references to Xamarin.Forms to each of the projects – this isn’t actually required, since the stable release of Xamarin Forms will actually work with .NET Standard but I’ve been working with the pre-release version quite a bit lately, so I’ll go with that for this example.


I also need to remember to add a reference to the .NET Standard project to each of the head projects for iOS, Android and UWP.


If you attempt to build and run at this point iOS and Android should work without issue. UWP will most likely compile but will raise an exception “Could not load file or assembly ‘netstandard, Version=….” at runtime.


Essentially the UWP project structure has evolved a little, so you need to upgrade it. Now I think that you may be able to do this via package manager but I’ve never got it to work for UWP projects, so I will make the changes manually to the csproj file. Start by deleting the project.json file from the UWP project.

Next right-click the UWP project in Solution Explorer and select unload project. Next, right-click on the UWP project node and select Edit MySecondXamarinFormsApp.UWP.csproj.

Add a new PropertyGroup – this changes the way packages are referenced, eliminating the need for the project.json file, replacing it with references within the csproj file.



Next we need to add back the package references that were in the project.json – if you’re doing this on an existing project, you may want to keep the project.json file handy so you know which packages to add. In this case there are just two projects:

   <PackageReference Include="Microsoft.NETCore.UniversalWindowsPlatform">
   <PackageReference Include="Xamarin.Forms">


Now you can right-click on the UWP project in Solution Explorer and select Reload project. Trigger a rebuild and now you should be able to run the UWP project.


Getting Started: Xamarin Forms with .NET Standard

With the recent release of Visual Studio 2017 v15.3 (and subsequent patch release 15.3.1 and 15.3.2…. yes, it does say something about ship quality Sad smile) came the release and support for .NET Standard 2.0. The Xamarin team also made a lot of noise about support for .NET Standard 2.0; unfortunately this doesn’t yet translate into Visual Studio templates that easily get you started. My particular annoyance is the about of steps you need to go through in order to just spin up a new Xamarin Forms application that can reference .NET Standard libraries. I thought I’d piggyback of a post done a couple of months back by Pierce Boggan. Here goes:

Start by creating a new project in Visual Studio 2017, selecting the Cross Platform App (Xamarin) project template:


Next, select the template you want (I’m going with the Blank App), the UI Technology and Code Sharing Strategy. As I’m going to be walking through how to use Xamarin Forms, it makes sense to pick that as the option for UI Technology. Only select the Portable Class Library option. Don’t use the Shared Project – using a shared project will lead you down the evil road of using conditional compilation which will be a maintenance nightmare, just don’t use it. I don’t care how great you think it is, don’t use it. One last time, don’t use the Shared Project option.


Now that I’ve expressed my opinion on code sharing strategies, let’s click the OK button and get on with building our application. As the template goes through generating the head projects for iOS, Android and UWP, it will prompt you to select the target and minimum platforms for UWP. For the most part, unless you have specific target platform requirements for UWP, you can leave the default settings.


The generated solution will have four projects: three head or target platform projects (for iOS, Android and UWP) and a portable class library (PCL) which contains the XAML pages that will make up your Xamarin Forms application layout. In order to proceed with .NET Standard support we need to replace the PCL with a .NET Standard library. Whilst Visual Studio used to have a mechanism for upgrading a library from a PCL to a .NET Standard library, this has been removed. Now the easiest way is to simply create a new project, and copy the relevant files into the new project. From the Add New Project dialog, select the Class Library (.NET Standard) template.


I use the .UI naming convention for the library that will contain my XAML pages. Other developers use .Core but my preference is to separate my XAML pages away from my view models. Whilst technically with Xamarin Forms they can reside in the same library, I prefer to have a clean separation between them. I have <applicationname>.UI with my XAML pages in it and <applicationname>.Core with my view models, services, entities, essentially all the business logic for my application.

For this example I’m going to keep it simple and we’ll just create the .UI project for the moment.


I don’t need the default Class1.cs, so I’ll remove that. I’ll add a reference to the .NET Standard library to all the head projects.

I’m also going to drop the .NET Standard version back from 2.0 (now the default in Visual Studio) back to 1.4. Whilst the tooling has been updated for the head projects for iOS and Android to support .NET Standard 2.0, of course, UWP is still lagging the field, as so you won’t be able to use a .NET Standard 2.0 library until that’s fixed. To be honest though, not much is lost by lowering the version of the .UI project to 1.4 since all the features of Xamarin Forms are still there.


Next I’m going to copy App.xaml (and App.xaml.cs) and MainPage.xaml (and MainPage.xaml.cs) from the PCL into the newly created .NET Standard library. Once I’ve copied these files across I can remove the PCL project from the solution – this will remove the references to this library from each of the head projects. After coping these files across, you may well see a compilation error similar to the following:

1>------ Build started: Project: MyFirstXamarinFormsApp.UI, Configuration: Debug Any CPU ------
1>C:\Program Files\dotnet\sdk\2.0.0\Sdks\Microsoft.NET.Sdk\build\Microsoft.NET.Sdk.DefaultItems.targets(274,5): error : Duplicate 'EmbeddedResource' items were included. The .NET SDK includes 'EmbeddedResource' items from your project directory by default. You can either remove these items from your project file, or set the 'EnableDefaultEmbeddedResourceItems' property to 'false' if you want to explicitly include them in your project file. For more information, see The duplicate items were: 'App.xaml'; 'MainPage.xaml'
1>Done building project "MyFirstXamarinFormsApp.UI.csproj" -- FAILED.

If you do, you just need to edit the project file for the .UI project and remove the App.Xaml and MainPage.xaml EmbeddedResource elements. The new project format includes files by default and the tooling isn’t smart enough to realise that the sample files are being added multiple times. Removing these elements will fix the compilation:

   <EmbeddedResource Include="App.xaml">
   <EmbeddedResource Include="MainPage.xaml">

The last thing to do is to make sure that the .NET Standard library references Xamarin Forms. I’m going to do that by right-clicking the solution node in Solution Explorer and selecting Manage Nuget Package for Solution.


I’m going to select the new prerelease version of Xamarin Forms (which is the one where they’ve apparently added .NET Standard support). In addition to adding a reference to Xamarin Forms to the UI project, I also take this opportunity to upgrade all the package references in the application. Note that I’ve even selected the Android support packages – this used to be a big No-No but with the latest version of the tooling you can now go ahead and update them, and I would definitely encourage you to do so.


Now, go make yourself a coffee – Nuget is slow, so slow! The good news is that once you’ve done all these steps, you’re ready to go with a .NET Standard based Xamarin Forms project. If you’re following this post to get started on your own project, you can finish up here, as you’re good to go.

Ok, so all of that, and what can we do. We’ll for a starters, it makes it super easy to add nuget packages such as BuildIt Forms which has a bunch of helper controls and features to get you building richer applications. Let’s add a reference to the BuildIt.Forms Nuget package the project:


After adding the reference to BuildIt.Forms we can make use the added controls. For example the ContentButton allows us to easily add a button that contains any XAML content, whilst still maintaining the pressed and hover states:

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns=""
     <StackLayout VerticalOptions="Center"
         <Label Text="Welcome to Xamarin Forms!" />
             <Label Text="Press m!" />

I’ll cover more on the BuildIt.Forms library in coming posts.

Unable to Connect or Debug to Visual Studio Android Emulator with Visual Studio 2017 RC

Now I do appreciate that running prerelease software comes with some risk and I’m also aware that emulators are hard to get working 100% right on every machine. Ever since I can remember there have been connectivity issues with Windows Mobile, Windows Phone and now Windows 10 Mobile emulators; whether connectivity meaning to the internet, the local machine or being able to debug an application. So, it came as no surprise that after rebuilding my computer and installing Visual Studio 2017 RC that my installation of the Visual Studio Android Emulator was semi-broken. Turns out I had two issues I needed to overcome.

When I attempted to launch the emulator, I got the following notice, saying that the Internet Connection needs to be configured – this is pretty typical for first run as Hyper-V needs to setup the virtual switches that the emulator image will use.


After clicking Yes, the emulator is launched and my application is deployed. Unfortunately when Visual Studio attempts to launch the application and attach the debugger, the application closes immediately. This is again an issues I’ve seen before and in fact it appears on the troubleshooting web page for the Android Emulator (

- After you’ve run the emulator image the first time, close the Android Emulator

- Open Hyper-V Manager

- Select the virtual machine that matches the emulator you were attempting to run (make sure it’s in the Off state), and click Settings

- Under Processor –> Compatibility –> check the “Migrate to a physical computer with a different processor version” checkbox


- Click OK

- Important: Make sure you stop and restart the Hyper-V service, otherwise, for some reason the setting is lost the next time you run the emulator.

Having done this I can now deploy and run applications on the emulator. The next issue was that for some reason the emulator couldn’t access the internet. I took a look in the Virtual Switch Manager in Hyper-V Manager (click Virtual Switch Manager from the Actions list on the right side of the Hyper-V Manager management console) and there was only a single “Windows Phone Emulator Internal” switch.


I clicked on New virtual network switch, selected External Access and gave the switch a name:


Each emulator virtual machine needs to have access to both the internal and external switches, so after clicking OK to exit the Virtual Switch Manager, I clicked on the virtual machine that I want to assign the new virtual switch to. Make sure you’ve stopped the virtual machine (closing the Android emulator will do this). Click Settings, click Add Hardware and select Network Adapter and click Add.image

From the Virtual switch dropdown, select the virtual switch you just created (External Access in my case), and click OK.


Now launch the emulator (either via the Visual Studio Android Emulator interface that can be launched from the Start menu independently of Visual Studio, or by attempting to run an application from Visual Studio) and you should now have internet access – check via the web browser in the emulator if you’re in any doubt.

Cross Platform Visual States

Last year I posted on “Taking Visual States Cross Platform to iOS and Android with Xamarin” and is a topic that I often come back when discussing the design and development of mobile applications. Let’s start by discussing what visual states are and why they’re important when building applications (and this really applies to any application, not just mobile applications). During the design of an application it’s common to prepare wireframes and visual designs that document each page, the key elements on each page and any associated behaviour. This typically includes documenting when elements are hidden or shown, often in response to either data changes or user interactions. The following screenshots show a recent application we worked on for Hungry Jack’s for Windows 10. This is the same page of the same application, running on the same device, just with a different window size. As you can see the difference between the first two images is quite significant as the navigation bar switches from being at the bottom (similar to what you’d expect for mobile) to on the left side. The third image simply augments the position of elements further to make better use of the available screen size.

image image image

Thorough analysis during the design phase will reveal all possible layout combinations for a page; these combinations are what we refer to (at least in the Windows/XAML world) as visual states. In the case of the screenshots from the Hungry Jack’s application, each of these layouts represents a different visual state for this page. If you don’t take the time to determine what visual states exist on each page and what triggers a transition between visual states, during development you’ll find yourself toggling attributes on element on the page in an attempt to recreate each required combination. This lack of a structured approach makes it not only hard to layout each page, it also makes it hard to test as there is no definitive list of layouts that need to be verified.

On the Windows platform, Visual States are something we take for granted; they can be declared in XAML and Blend has support for designing each visual state. However, other platforms are not so blessed and have to resort to changing attributes manually in code. Some cross platform technologies make use of data binding to allow visual elements to be dynamically updated based on changes in the corresponding data (ie the view model). These include MvvmCross and Xamarin.Forms. However, data binding should be reserved for updating data values on a view, not controlling the visual states on a page.

Learning to develop for the Windows platforms, developers go through a series of learning steps.

  • Coding Changes: Most developers come from building applications or web sites where they’re used to having to set data values in code.
  • Data Binding: The first step along the progression is learning how to use data binding to update content on the page (eg Text on a Textblock)
  • MVVM: After seeing the benefit of data binding, the next step is to appreciate the separation of concerns that MVVM offers. At this point developers often look at what MVVM libraries there are out there and usually settle on something like MvvmCross, MvvmLight, Caliburn.Micro, Prism etc
  • Converters: Equipped with the new found power of data binding, developers often go nuts and start data binding everything, including using properties on the view model to control when items should be visible. This is where they look to use converters to adapt properties on the view model (eg XYZIsVisible which would be a bool) to attributes on visual elements (eg XYZ.Visibility which is a Visibility). The issue with this is that at design time, in a tool like Blend, it’s very difficult to see what the layout looks like. You can’t simply change the Visibility property on elements, since they’re now data bind. You can temporarily remove the data binding, but then of course you forget to put it back and then spend hours trying to work out why the application is broken.
  • Visual States: Enter Visual States…. instead of data binding attributes that control the layout of a page, it’s better to use visual states to define what elements are visible and any layout changes required for a particular layout. Blend supports design time editing of visual states and the ability to visualize any combination of visual states from different state groups
  • View Model States: Eventually developers realise that not only should they use visual states, they should track and control them from their view model, thus making yet another aspect of their application testable. I’ve talked about this a couple of times (,,

Ok, so now that you have the basics on what a visual state is, and some background on why I believe visual states are so important, let’s discuss the elephant in the room….. Visual States only exist in XAML on the Windows platform…. making it very difficult to use visual states when building cross platform applications. So, what can we use when building cross platform? Well let’s go through the progression that developers go through. As you’d expect, all platforms support developers being able to adjust values via code. Unfortunately, this is where most developer technologies end, for example neither iOS (Objective-C, Swift) or Android (Java) support data binding out of the box. There are some third party solutions that attempt to bridge this gap, such as the data binding support in MvvmCross and Xamarin.Forms. In fact both these options provide not only the ability to data bind, but also enable MVVM and support using converters as part of data binding.

In actual fact there’s no requirement to have data binding (and subsequently MVVM and the use of converters) in order to start using visual states to control layout. However, again there’s almost no platform, or even third party, support for defining visual states.Over the weekend, I was experimenting with Xamarin.Forms and was thinking about how to define and transition between visual states. Whilst it would be nice to do it declaratively in XAML, I thought I’d better walk before I run, so I figured I’d work out a way to define visual states in code. Before getting started I thought though the basic mechanics of how visual states should work:

- Visual States should be declared in groups, and each group can only have one active visual state at any given time

- A visual state should define any number of value actions

- A “value action” defines setting a property on an element to a specific value

- The visual state manager should be able to change to a specific visual state

- Changing to a specific visual state, should only adjust the current state of the group that the visual state belongs

I’ve always felt that one of the weaknesses of Visual states on the XAML platform is that they’re named using a string, and the only way to reference them when changing state, is using a string literal. So, for my attempt at a visual state manager I’m going to have my visual states defined as an enumeration. In fact, each group of states will use a different enumeration type – thus each visual state corresponds to a unique enumeration value. The end game is to be able to declare visual states in a relatively fluid manner, as shown in the following example which defines two groups based on the enumerations SecondStates and SecondStates2.

                .Change(x => x.TextColor, (x, c) => x.TextColor = c)
                .Change(x => x.FontSize, (x, c) => x.FontSize= c)
                .Change(x => x.TextColor, (x, c) => x.TextColor = c)
                .Change(x => x.FontSize, (x, c) => x.FontSize = c)
                .Change(x => x.TextColor, (x, c) => x.TextColor = c)
                .Change(x => x.FontSize, (x, c) => x.FontSize = c)
                .Change(x => x.TextColor, (x, c) => x.TextColor = c)
                .Change(x => x.FontSize, (x, c) => x.FontSize = c)

In my next post we’ll look at the different classes that make up the visual state manager and the extension methods that allow for the fluid declaration seen in this example.

Adding Azure Active Directory Authentication to Android Xamarin.Forms Project

In my previous post I covered adding authentication to the Xamarin Forms Windows Phone 8.0 project. Next step, add it to the Android project. I figured this would be much simpler. However after adding a reference to ADAL from NuGet my Android project failed to build with some esoteric error about some missing layout xml in a referenced component. A quick internet search later I figured it might be due to the path lengths of my projects. I’d been relatively descriptive in my project names (eg RealEstateInspector.XForms.Droid) which had resulted in some very long paths, particularly during the build process where components are added based on the compilation path, the referenced library path and of course the file name. The upshot was that I needed to shorten not the project names, just the physical paths of the projects (easily done via VSO and Source Control Explorer within VS).

After doing the path restructure, I then amended the login the MainActivity:

protected override void OnActivityResult(int requestCode, Result resultCode, Intent data)
    base.OnActivityResult(requestCode, resultCode, data);
    AuthenticationAgentContinuationHelper.SetAuthenticationAgentContinuationEventArgs(requestCode, resultCode, data);
protected override void OnCreate(Bundle bundle)

    global::Xamarin.Forms.Forms.Init(this, bundle);
    RealEstateInspector.XForms.MainPage.AuthenticateRequested += Authenticate;
    LoadApplication(new App());

public async void Authenticate(object sender, EventArgs e)
    var page = sender as RealEstateInspector.XForms.MainPage;
    var token = await AuthenticationHelper.Authenticate(this);
    (page.BindingContext as MainViewModel).LoadPropertyData(token);

You’ll notice that the activity is passed into the Authenticate method, which means I’ve had to make some minor changes to the AuthenticationHelper code:

public static async Task<string> Authenticate(
    Activity callerActivity
        var authContext = new AuthenticationContext(Constants.ADAuthority);
        if (authContext.TokenCache.ReadItems().Count() > 0)
            authContext = new AuthenticationContext(authContext.TokenCache.ReadItems().First().Authority);
        var authResult =
                new Uri(Constants.ADRedirectUri),
                new AuthorizationParameters()
#elif DROID
new AuthorizationParameters(callerActivity)
                    new AuthorizationParameters(PromptBehavior.Auto, false)
        Debug.WriteLine(authResult != null);

        return authResult.AccessToken;

    catch (Exception ex)
        return null;

At this point I also ran into an issue using my dummy redirect uri of, which is actually a real website and has an alternative mobile site which they redirect to. The issue was that after the user had authenticated the web view would redirect to but would then be redirected to the mobile site. I switched to using which I know doesn’t have a redirect. Don’t forget when doing this you also have to update the redirect uri in the Native application in Azure Active Directory.

Building the Xamarin.Forms Basic Layout Using XAML

The initial content page that was created when we created the XForms projects was done in code. Rather than doing the layout in code, I prefer to work in XAML – not only does this make the design more declarative, it is also miles easier to data binding. I’ll start by creating a new Forms Xaml Page.


Next we’ll add some XAML to the page (similar to what we added to the Windows MainPage):

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns=""
  <ListView ItemsSource="{Binding Properties}">
            <Label Text="{Binding Address}" />

And in the code behind for the MainPAge we’ll create, assign and load data into the MainViewModel:

protected async override void OnAppearing()

    var vm = new MainViewModel();
    BindingContext = vm;
    await vm.LoadPropertyData();

And of course I need to update the code in App.cs to use the new XAML MainPage, rather than the code created ContentPage:

public App()
    // The root page of your application
    MainPage =new MainPage();

When you go to run this you’re likely to see errors due to lack of references for the SQLite extensions. Most references will get added if they are used by referenced libraries. What makes SQLite different is that there are platform specific implementations which are only added to the platform specific project. As such you need to make sure all the client applications have the SQLiteStore NuGet package referenced. I ran into issues applying the NuGet package to the Android project as it seemed to not be able to find the HttpClient NuGet package – I had to add this NuGet package to the Android project first, before applying the SqliteStore NuGet Package.


After doing this I was able to run up the XForms applications on each of the platforms, each displaying the addresses of the properties in my local offline database.

Adding Xamarin.Forms Support

So far I’ve only had support for the new Windows platform clients (ie Windows and Windows Phone) for my Real Estate Inspector sample app. However, to make it successful we need to target more platforms. To this end I’m going to add support for iOS, Android and Windows Phone 8.0 using Xamarin.Forms.

After installing the Xamarin tooling for Visual Studio, I added a new project using the Blank App (Xamrain.Forms Portable) template. This actually look multiple attempts as I hadn’t updated the Xamarin tooling prior to creating the projects. I would highly recommend upgrading the tooling first!


This will give you three target projects Driod, iOS and WinPhone, in addition to a PCL which contains the common code and ui for the applications. You should be able to build and run each of these targets – however, you’ll need to either register for a trial or have a Xamarin Business subscription. Since the UI is help in the PCL project, it’ll be the same across all the targets, although there may be platform rendering differences.

Now that we have these three targets, we’re going to have to connect up our Azure Mobile Service, work out how we’re going to deal with navigation and structure our solution to maximise code reuse across our Windows platform projects.

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.

Getting Started with Design for Windows, Windows Phone, iOS and Android

Here’s a summary of some of the design guidelines for the various mobile platforms:

Windows Phone





Another great resource on user experience design is the UX Mastery website

In particular the book Everyday UX is worth purchasing: