Nick's .NET Travels

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

ViewModel to ViewModel Navigation in a Xamarin.Forms Application with Prism and MvvmCross

I’m a big fan of the separation that the Mvvm pattern gives developers in that the user interface is encapsulated in the view (Page, UserControl etc) and that the business logic resides in the ViewModel/Model. When structuring the solution for an application I will go so far as to separate out my ViewModels into a separate project from the views, even with Xamarin.Forms where the views can be defined in a .NET Standard library.

One of the abstractions that this lends itself to is what is referred to as ViewModel to ViewModel navigation – rather than the ViewModel explicitly navigation to a page, or bubbling an event up to the corresponding view to get the view to navigate to the next page, ViewModel to ViewModel navigation allows the ViewModel to call a method such as Navigation(newViewModel) where the newViewModel parameter is either the type of the ViewModel to navigate to, or in some frameworks it may be an actual instance of the new ViewModel.

MvvmCross

Let’s see this in action with MvvmCross first – I’m going to start here because ViewModel to ViewModel navigation is the default navigation pattern in MvvmCross. I’ll start with a new project, created using the MvxScaffolding I covered in my previous post, using MvvmCross in a Xamarin.Forms application. The single view template already comes with a page, HomePage, with corresponding ViewModel, HomeViewModel. To demonstrate navigation I’m going to add a second page and a second ViewModel. Firstly, I’ll add a new class, SecondViewModel, which will inherit from BaseViewModel (a class generated by MvxScaffolding which inherits from MvxViewModel that’s part of MvvmCross).

public class SecondViewModel : BaseViewModel
{
}

Next, I’ll add a new ContentPage called SecondPage (note the convention here that there is a pairing between the page and the ViewModel ie [PageName]Page maps to [PageName]ViewModel)

image

MvvmCross supports automatic registration of pages and ViewModels but it does require that the page inherits from the Mvx base class, MvxContentPage. I just need to adjust the root XAML element from

<ContentPage …

to

<views:MvxContentPage x:TypeArguments="viewModels:SecondViewModel" …

The inclusion of the TypeArguments means that the generic overload of MvxContentPage is used, providing a helpful ViewModel property by which to access the strongly typed ViewModel that is databound to the page.

Now that we have the second page, we just need to be able to navigate from the HomePage. I’ll add a Button to the HomePage so that the user can drive the navigation:

<Button Text="Next" Clicked="NextClicked" />

With method NextClicked as the event handler (here I’m just using a regular event handler but in most cases this would be data bound to a command within the HomeViewModel):

private async void NextClicked(object sender, EventArgs e)
{
     await ViewModel.NextStep();
}

And of course we need to add the NextStep method to the HomeViewModel that will do the navigation. The HomeViewModel also needs access to the IMvxNavigationService in order to invoke the Navigate method – this is done by adding the dependency to the HomeViewModel constructor.

public class HomeViewModel : BaseViewModel
{
     private readonly IMvxNavigationService navigationService;

    public HomeViewModel(IMvxNavigationService navService)
     {
         navigationService = navService;
     }
     public async Task NextStep()
     {
         await navigationService.Navigate<SecondViewModel>();
    }
}

As you can see from this example the HomeViewModel only needs to know about the SecondViewModel, rather than the explicit SecondPage view. This makes it much easier to test the ViewModel as you can provide a mock IMvxNavigationService and verify that the Navigate method is invoked.

Prism

Now let’s switch over to Prism and I’ve used the Prism Template Pack to create a new project. To add a second page I’ll add a SecondPageViewModel, which in the case of Prism inherits from ViewModelBase and requires the appropriate constructor that provides access to the INavigationService. Note that the naming convention with Prism is slightly different from MvvmCross where the ViewModel name is [PageName]PageViewModel (ie both the page and the viewmodel have the Page suffix after the PageName eg SecondPage and SecondPageViewModel)

public class SecondPageViewModel : ViewModelBase
{
     public SecondPageViewModel(INavigationService navigationService) : base(navigationService)
     {
     }
}

I’ll add a new ContentPage called SecondPage but unlike MvvmCross I don’t need to alter the inheritance of this page. Instead what I do need to do is register the page so that it can be navigated to. This is done in the App.xaml.cs where there is already a RegisterTypes method – note the additional line to register SecondPage.

protected override void RegisterTypes(IContainerRegistry containerRegistry)
{
     containerRegistry.RegisterForNavigation<NavigationPage>();
     containerRegistry.RegisterForNavigation<MainPage, MainPageViewModel>();
     containerRegistry.RegisterForNavigation<SecondPage, SecondPageViewModel>();
}

Similar to the MvvmCross example, I’ll add a button to the MainPage (the first page of the Prism application created by the template) with code behind to call the NextStep method on the MainViewModel

private async void NextClicked(object sender, EventArgs e)
{
     await (BindingContext as MainPageViewModel).NextStep();
}

Note that because the MainPage just inherits from the Xamarin.Forms ContentPage there’s no property to expose the data bound viewmodel. Hence the casting of the BindingContext, which you’d of course do null checking and error handling around in a real world application.

public async Task NextStep()
{
     await NavigationService.NavigateAsync("SecondPage");
}

The NextStep method invokes the NavigateAsync method using a string literal for the SecondPage – I’m really not a big fan of this since it a) uses a string literal and b) requires the the ViewModel knows about the view that’s being navigated to. So let’s adjust this slightly by changing the way that pages and ViewModels are registered. The RegisterForNavigation method accepts a parameter that allows you to override the navigation path, meaning we can set it to be the name of the ViewModel instead of the name of the page.

protected override void RegisterTypes(IContainerRegistry containerRegistry)
{
     containerRegistry.RegisterForNavigation<NavigationPage>();
     containerRegistry.RegisterForNavigation<MainPage, MainPageViewModel>(nameof(MainPageViewModel));
     containerRegistry.RegisterForNavigation<SecondPage, SecondPageViewModel>(nameof(SecondPageViewModel));
}

The navigation methods would then look like:

public async Task NextStep()
{
     await NavigationService.NavigateAsync(nameof(SecondPageViewModel));
}

But I think we an improve this further still by defining a couple of extension methods

public static class PrismHelpers
{
     public static void RegisterForViewModelNavigation<TView, TViewModel>(this IContainerRegistry containerRegistry)
         where TView : Page
         where TViewModel : class
     {
         containerRegistry.RegisterForNavigation<TView, TViewModel>(typeof(TViewModel).Name);
     }

    public static async Task<INavigationResult> NavigateAsync<TViewModel>(this INavigationService navigationService)
         where TViewModel : class
     {
         return await navigationService.NavigateAsync(typeof(TViewModel).Name);
     }
}

Using these extension methods we can update the registration code:

protected override void RegisterTypes(IContainerRegistry containerRegistry)
{
     containerRegistry.RegisterForNavigation<NavigationPage>();
     containerRegistry.RegisterForViewModelNavigation<MainPage, MainPageViewModel>();
     containerRegistry.RegisterForViewModelNavigation<SecondPage, SecondPageViewModel>();
}

And then the navigation code:

public async Task NextStep()
{
     await NavigationService.NavigateAsync<SecondPageViewModel>();
}

The upshot of these changes is that there’s almost no difference between the MvvmCross method of navigation and what can be done with a little tweaking with Prism.

Scaffolding Your Next MvvmCross Xamarin.Forms Project

One of the things I liked about the getting started experience with Prism was that there was a Visual Studio extension that made creating a new project super simple. Whilst I know that MvvmCross doesn’t provide something like that out of the box, I decided to take a look at some of the project/solution templates that the community have created. The Getting Started page on the MvvmCross website does maintain a list of MvvmCross templates but I must confess that some of these are a little dated. I just went through and opened each of the links, and there were only two that seemed to be recent, Mvx Toolkit and MvxScaffolding. I downloaded both extensions and just happened to try out MvxScaffolding first. Here’s a quick summary of creating a new Xamarin.Forms application using MvxScaffolding

Search for Mvx to find the scaffolding templates

image

Basic project details

image

Now we’re into the MvxScaffolding custom dialog – wow, look at how nice this is.

image

I went with the Single Item template – it’s a tad confusing that you have to click on the grey circle to pick each option, rather than clicking the whole card. Next up, pick the platform and which test projects you want generated.

image

I added UWP support, and asked for all the test projects

image

A quick summary before the projects are created

image

The final solution

image

And of course, the running application.

image

This was a bit mind blowing to be honest – the level of detail in this extension was awesome and I was able to generate the runnable application in under a minute. I like the way the projects are separated and that it can generate all the test projects.

Resolving Dependencies In Platform Pages, Renderers, Effects and Elements with Xamarin.Forms and Prism

We’ve been using Prism for a number of our Xamarin.Forms projects and for the most part we rely on the services being injected into our view models but a scenario came up recently where we wanted to access one of our services from within the platform implementation of a renderer. We were using DryIoC and needed to come up with a mechanism to resolve dependencies that had been registered with DryIoC via Prism. I recalled seeing in Brian’s What’s New in Prism 7.1 post that support had been added for the Xamarin.Forms Dependency Resolver and was wondering whether we could use that to allow us to resolve dependencies by calling Resolve on the static DependencyService that Xamarin.Forms exposes. In this post I’m going to walk through creating a simple Prism application, register a service and then retrieve it from the code behind of a UWP page (but the same process applies for any renderer, effect, page or element).

To get started with a new Prism application I’m going to make use of the Prism Template Pack that installs as a Visual Studio Extension and includes a variety of project and item templates. In Visual Studio 2019 when you launch the application you can select Create a New Project and be given the option to search for project templates.

image 

Once you’ve selected the Prism Bank App (Xamarin.Forms) you’ll then be prompted to specify the name and location of the project

image

The final step is a Prism specific dialog that allows you to specify which platforms and what IoC container you want to use

image

In this case we’re going with DryIoC but I think the technique will work equally well if you select AutoFac or Unity. After hitting Create Project our solution is setup with four projects: one for each target platform and a project that contains both our view and view models. 

image

My preference is to separate views and viewmodels further but for the timebeing we’ll leave the project structure as it is. The next step is to create and register the service that we want to retrieve from our platform specific code.

public interface IFancyService
{
     string WelcomeText { get; }
}

public class MyFancyService : IFancyService
{
     public string WelcomeText => "Hello Dependency World!";
}

The MyFancyService needs to be registered with the DI container, which we can do by adding a line to the RegisterTypes method in the App.xaml.cs

protected override void RegisterTypes(IContainerRegistry containerRegistry)
{
     containerRegistry.RegisterForNavigation<NavigationPage>();
     containerRegistry.RegisterForNavigation<MainPage, MainPageViewModel>();

    containerRegistry.Register<IFancyService, MyFancyService>();
}

Let’s switch across to the code behind of the MainPage in the UWP application – note that this page is different from the MainPage that’s in the Xamarin.Forms project which is the page that’s displayed on all platforms. The MainPage in the UWP project is used to host the Xamarin.Forms application when it’s run on Windows. I’m going to add the OnNavigatedTo override method and in it I’m going to attempt to resolve the IFancyService interface using the Xamarin.Forms DependencyService.

protected override void OnNavigatedTo(NavigationEventArgs e)
{
     base.OnNavigatedTo(e);

    var fancy = DependencyService.Resolve<IFancyService>();
}

Running this code we’ll see that the variable fancy is null, meaning that the Resolve method wasn’t able to find any registered implementation of the IFancyService.

image

To fix this, we need to tell Prism to register as a Dependency Resolver, which will mean that the Xamarin.Forms DepedencyService will use the same DI container when resolving instances. This is done by using the overloaded constructor of the PrismApplication class. In the App.xaml.cs of our application, change the call to base to include a second parameter which is set to true.

public App(IPlatformInitializer initializer) : base(initializer, setFormsDependencyResolver: true)
{
}

Running the application now and the fancy variable is set to an instance of the MyFancyService.

image

And there you have it – an easy way to use the Xamarin.Forms DependencyService in conjunction with Prism and DryIoC.

Deploying Uno Wasm using Blob Storage

Earlier today I posted about deploying Uno on Wasm to an Azure App Service (to which the Uno team replied on Twitter with an updated web.config). I was thinking a bit more about how I would deploy a real Uno Wasm app and I realised that of course, there’s no server side logic, so I could just go host it off Blob Storage.

I ran up the Azure Storage Explorer and created a new container within an existing Blob Storage account

image

As I’m going to be serving up content directly from Blob Storage I need to make sure that I enable public read access on the individual blobs (the default is that there’s no public read access on the container or blobs). Right-click on the container and select Set Public Access Level

image

Set access to Public read access for blobs only

image

Now you can simply copy the Uno Wasm application into the container by dragging the files from File Explorer into the right pane of the Azure Storage Explorer. I found that the best folder to copy is the folder that Visual Studio uses to deploy files when you do a Publish. For my project this is found at FirstUnoProject.Wasm\obj\Release\netstandard2.0\PubTmp\Out\FirstUnoProject.Wasm\dist\bin\Release\netstandard2.0\dist.

And that’s it – now I can run my Uno Wasm application by clicking the Copy URL from the tool bar and then switching to my browser and launching the corresponding URL.

image

The Uno Wasm application runs without any further configuration required.

image

Publishing Uno WebAssembly (Wasm) to Azure App Service

I figured that since I had Uno working in WebAssembly locally on my machine that I’d try publishing it out to an Azure App Service. I mean, how hard could it be since Visual Studio recognises that the Wasm project is a web project (nice job there team Uno!) and even gives me the option to Publish.

image

Stepping through the publish wizard I decided to create a new Azure App Service

image

I made use of an existing Resource Group and App Service Plan that I had lying around.

image

After hitting Create and publish Visual Studio went off thinking for what seemed like a long time with nothing happening. I knew it was probably busy packaging and deploying but I didn’t see anything appear in the Output window…… not surprisingly because Visual Studio pushes all the logging for the publish operation to the Web Publish Activity window.

image

Once it was done Visual Studio launches a browser window displaying the root of the newly created App Service. Unfortunately, this is not my Uno project.

image

After investigating a little I realised that the publish operation was uploading the Wasm project to a sub folder of the wwwroot folder within the App Service (eg  wwwroot\FirstUnoProject.Wasm\bin\Release\netstandard2.0\dist\index.html). I validated this by using the Advanced Tools from the Azure portal.

image

From the Advanced Tools, select Files

image

Browsing the files you can locate the index.html that gets published with the Wasm project. This is the file that hosts the wasm

image

Unfortunately just adding the appropriate path to the index.html to the site url doesn’t seem to work (ie this doesn’t work: https://firstunoproject.azurewebsites.net/FirstUnoProject.Wasm/dist/bin/Release/netstandard2.0/dist/index.html). However, you can easily set up a new application to point to the dist folder. Go to Application Settings and under the section Virtual  applications and directories, create a new mapping. In this case I’ve mapped /uno to the site\wwwroot\FirstUnoProject.Wasm\dist\bin\Release\netstandard2.0\dist folder (you can get the folder from the “path” shown in the Kudo – Files explorer) and I’ve made it an Application.

image

If you now attempt to go to the index.html page in your new mapped folder (eg https://firstunoproject.azurewebsites.net/uno/index.html) you’ll find that you’ll see the “Loading…” text that comes with the Uno project template but your application won’t load. If you spin up the Chrome debugging tool you’ll see that it’s not able to find the mono.wasm file with a 404 being raised. Don’t bother trying to work out whether the file exists or not because the issue is that whilst the file exists, the Azure App Service isn’t going to serve it because it’s not a known file type. Luckily there’s a simple solution. Add the following Web.config to your Wasm project and publish your application again.

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
   <system.webServer>
     <staticContent>
       <remove fileExtension=".clr" />
       <remove fileExtension=".dll" />
       <remove fileExtension=".json" />
       <remove fileExtension=".wasm" />
       <remove fileExtension=".woff" />
       <remove fileExtension=".woff2" />
       <mimeMap fileExtension=".dll" mimeType="application/octet-stream" />
       <mimeMap fileExtension=".clr" mimeType="application/octet-stream" />
       <mimeMap fileExtension=".json" mimeType="application/json" />
       <mimeMap fileExtension=".wasm" mimeType="application/wasm" />
       <mimeMap fileExtension=".woff" mimeType="application/font-woff" />
       <mimeMap fileExtension=".woff2" mimeType="application/font-woff" />
     </staticContent>
     <httpCompression>
       <dynamicTypes>
         <add mimeType="application/octet-stream" enabled="true" />
         <add mimeType="application/wasm" enabled="true" />
       </dynamicTypes>
     </httpCompression>
   </system.webServer>
</configuration>

Now you should be able to launch your Uno wasm-based application hosted in Azure App Service

image

Design Time Data for Xamarin.Forms

In my previous post I showed how to switch between Visual States using the tooling that comes with the BuildIt.Forms library. One of the other features of the tooling is the ability to load mock data that can assist with visualising how a page might look like with certain data. Rather than try to guess at what data your page might require, the tooling simply allows you to define a series of design actions. Each design action will appear within the BuildIt.Forms flyout, allowing you to invoke the action.

Let’s demonstrate this with an example. I’m going to change the layout of my page slightly so that in the DataLoaded state a ListView is displayed that takes up the entire screen. The XAML for the ListView is as follows:

<ListView x:Name="DataList" IsVisible="false">
     <ListView.ItemTemplate>
         <DataTemplate>
             <ViewCell>
                 <Label Text="{Binding Name}" />
             </ViewCell>
         </DataTemplate>
     </ListView.ItemTemplate>
</ListView>

As I don’t have any actual data at the moment, when I run up the application and click the Load Data button I see the following for the DataLoaded state:

image

This isn’t great as I’ve got no idea what my ListView is going to look like. So let’s fix this by adding a design action. I do this by calling the AddDesignAction method (it’s an extension method which is why I can access it on the MainPage) and providing a name, “Mock Data”, and the action to perform when the design action is run.

public MainPage()
{
     InitializeComponent();

    var groups = VisualStateManager.GetVisualStateGroups(this);
#if DEBUG
     this.AddDesignAction("Mock Data",
         () =>
         {
             var data = from i in new[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }
                        select new { Name = $"Item {i}" };
             DataList.ItemsSource = data;
         });
#endif
}

In this case I’m creating an IEnumerable of an anonymous type that has a property Name, which aligns with the data binding in the ListView XAML shown earlier. I’m assigning this directly to the ItemsSource of the ListView – at this stage I’m just creating the layout of the pages of my application so I might not even have View Models, which is why I’m assigning directly to the ItemSource property in place of data binding it.

Now when I run the application I see:

imageimage

imageimage

The final image shows the list of items being displayed in the ListView – clearly this layout could do with some work!

Visual State Manager Tooling in Xamarin.Forms With BuildIt.States

Back in the days of Silverlight/Windows Phone Microsoft launched a tool called Expression Blend that allowed developers and designer to work in harmony with developers doing their thing (ie write code) in Visual Studio and designers creating the user experience in XAML using Expression Blend. Fast forward a few years and Expression Blend has been rebadged to Blend for Visual Studio and most of the features of Blend have now been migrated to Visual Studio. With the demise of Windows Phone and the lack of developer interest in building for just Windows, Blend is now a tool that most developers have all but forgotten. So, why am I bringing this up now? Well, one of the features I missed from Blend is the ability to have design time data that allows you to build out the entire user interface, with the design time data being replace by real data when the application is run. Whilst there have been some attempts at providing a design time experience for Xamain/Xamarin.Forms, the reality is that it comes no where close to what Blend was able to do in its heyday.

If we look at other platforms, such as React Native, there has been a shift away from design time experience, across to an interactive runtime experience. By this I mean the ability to adjust layout and logic of the application whilst it’s running, which relies on the platform being able to hot-reload both layout and logic of the application. There are some third party tools for Xamarin.Forms that partially enable this functionality.

One of the challenges I found when working with Visual States is that you often need to get the application to a certain point, or follow a particular sequence of steps in order to get a specific Visual State to appear. Take the example I provided in my previous post on page states where I provided DataLoaded and DataFailedToLoad states – in the example the appearance of these states was completely random, so you might have to click the button a couple of times in order to get the state to appear. Luckily, the BuildIt.Forms library has a slightly-hidden feature that allows you to manually switch between states. I say it’s slightly-hidden because if you connect your Visual States to a StateManager in your ViewModels (shown in either this post or this post) you’ll see this feature automatically. In the example I covered in my previous post I needed to add the following line to the end of the MainPage constructor:

public MainPage()
{
     InitializeComponent();
    var groups = VisualStateManager.GetVisualStateGroups(this);
}

Now, when I run the application I see a small dot appear in the bottom left of the screen.

image

Clicking on the dot reveals a flyout that allows you to switch states:

App14UWP20190317125937

Note that this is only shown when the Visual Studio debugger is attached so will not impact the way your application works in release mode.

Page State with the Visual States Manager for Xamarin.Forms

One of the current limitations of the Xamarin.Forms implementation of the Visual State Manager (VSM) is that it only works for setting properties on an individual control. Whilst this is great for control state management (think button states like disabled, pressed etc), its incredibly limiting and makes it unsuitable for some typical visual state scenarios. The one that often comes up in a mobile application is for pages that load data. In this scenario you typically have a least three states: Loading, DataLoaded, DataFailedToLoad. In some cases you might even extend this to have states such as Refreshing or LoadingMoreData. For these states you probably want to show/hide different elements on the screen, which is why the current Xamarin.Forms implementation of the VSM isn’t a great option.

Luckily there’s an alternative, which is the Visual State Manager that’s part of the BuildIt.Forms library. Here’s a quick example of it in action:

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
              xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
              xmlns:vsm="clr-namespace:BuildIt.Forms;assembly=BuildIt.Forms.Core"
              x:Class="App14.MainPage">
     <vsm:VisualStateManager.VisualStateGroups>
         <vsm:VisualStateGroups>
             <vsm:VisualStateGroup Name="LoadingStates">
                 <vsm:VisualState Name="Loading">
                     <vsm:VisualState.Setters>
                         <vsm:Setter Value="True" Element="{x:Reference LoadingLabel}" Property="IsVisible" />
                     </vsm:VisualState.Setters>
                 </vsm:VisualState>
                 <vsm:VisualState Name="DataLoaded">
                     <vsm:VisualState.Setters>
                         <vsm:Setter Value="True" Element="{x:Reference LoadedLabel}" Property="IsVisible" />
                     </vsm:VisualState.Setters>
                 </vsm:VisualState>
                 <vsm:VisualState Name="DataFailedToLoad">
                     <vsm:VisualState.Setters>
                         <vsm:Setter Value="True" Element="{x:Reference FailedLabel}" Property="IsVisible" />
                     </vsm:VisualState.Setters>
                 </vsm:VisualState>
             </vsm:VisualStateGroup>
         </vsm:VisualStateGroups>
     </vsm:VisualStateManager.VisualStateGroups>

     <StackLayout VerticalOptions="Center">
         <Label Text="Loading..." x:Name="LoadingLabel" HorizontalOptions="Center"  IsVisible="False" />
         <Label Text="Success: Data Loaded!!" x:Name="LoadedLabel" HorizontalOptions="Center" IsVisible="False" />
         <Label Text="Failure :-(" x:Name="FailedLabel" HorizontalOptions="Center" IsVisible="False" />
         <Button Text="Load Data" Clicked="LoadClicked" />
     </StackLayout>
</ContentPage>

In this case we’ve defined three Visual States that correspond to showing the LoadingLabel, LoadedLabel and FailedLabel respectively. The code behind for the LoadClicked method illustrates how easily you can switch between the states:

private readonly Random rnd = new Random();

private async void LoadClicked(object sender, EventArgs e)
{
     var success = rnd.Next(0, 1000) % 2 == 0;
     await VisualStateManager.GoToState(this, "Loading");
     await Task.Delay(2000);
     await VisualStateManager.GoToState(this, success ? "DataLoaded" : "DataFailedToLoad");
}

Ok, so one last thing we can add in is a bit of animation to make the transition between states a little smoother. Let’s fade our labels in and out:

<vsm:VisualState Name="Loading">
     <vsm:VisualState.ArrivingAnimations>
         <animations:AnimationGroup>
             <animations:AnimationGroup.PostAnimations>
                 <animations:FadeAnimation Opacity="1"
                                           Duration="500"
                                           Element="{x:Reference LoadingLabel}" />
             </animations:AnimationGroup.PostAnimations>
         </animations:AnimationGroup>
     </vsm:VisualState.ArrivingAnimations>
     <vsm:VisualState.LeavingAnimations>
         <animations:AnimationGroup>
             <animations:AnimationGroup.PreAnimations>
                 <animations:FadeAnimation Opacity="0"
                                           Duration="500"
                                           Element="{x:Reference LoadingLabel}" />
             </animations:AnimationGroup.PreAnimations>
         </animations:AnimationGroup>
     </vsm:VisualState.LeavingAnimations>

     <vsm:VisualState.Setters>
         <vsm:Setter Value="True" Element="{x:Reference LoadingLabel}" Property="IsVisible" />
     </vsm:VisualState.Setters>
</vsm:VisualState>

The XAML adds a fade in after the state transition has occurred (Post animation) when transitioning to (Arriving at) the the Loading state, and a fade out before the state transition has occurred (Pre animation) when transitioning from (Leaving) the Loading state. As you can see the XAML gets fairly verbose but it’s structured this way to allow for complex combinations and sequences of animations:

<animations:AnimationGroup.PostAnimations>
     <animations:SequenceAnimation>
         <animations:ParallelAnimation>
             <animations:FadeAnimation Opacity="1" Duration="500" Element="{x:Reference LoadingLabel}" />
             <animations:ScaleAnimation Scale="5" Duration="500" Element="{x:Reference LoadingLabel}" />
             <animations:SequenceAnimation>
                 <animations:RotateAnimation Rotation="10" Duration="250" Target="LoadingLabel" />
                 <animations:RotateAnimation Rotation="0" Duration="250" Target="LoadingLabel" />
                 <animations:RotateAnimation Rotation="-10" Duration="250" Target="LoadingLabel" />
                 <animations:RotateAnimation Rotation="0" Duration="250" Target="LoadingLabel" />
             </animations:SequenceAnimation>
         </animations:ParallelAnimation>
         <animations:ScaleAnimation Scale="1" Duration="500" Element="{x:Reference LoadingLabel}" />
     </animations:SequenceAnimation>
</animations:AnimationGroup.PostAnimations>

And let’s see this in action:

App14UWP20190317022241

Hopefully you can see from this short post how you can leverage the BuildIt.Forms Visual State Manager to do complex page state management as well as animations. We’ve just released a new beta package compatible with the latest Xamarin.Forms v3.6 and would love feedback (https://www.nuget.org/packages/BuildIt.Forms/2.0.0.27-beta).

Updated Uno Visual Studio Extension

I just noticed that the Uno Visual Studio Extension has been updated, so I figured I’d give it a go in Visual Studio 2019. After installing the extension I used the new startup dialog on Visual Studio to “Create a new project”. I searched Uno but Cross-Platform or any of the target platforms would show you the templates.

image

After selecting the Cross-Platform App (Uno Platform) template I had to enter a few details before hitting Create

image

Seconds later I had a brand new solution with five projects giving me the ability to target iOS, Android and Wasm all from the code I write in a UWP app.

image

Selecting the Wasm project I set it as the startup project and hit F5 to run. After a few minutes of building (the first build is slow as it downloads packages etc) it launched Chrome with my fancy Hello World project running.

image

Note: Small confession that I had to run the project twice because the first time failed without error. On second attempt it ran successfully. However, it’s been a bit hit and miss in terms of getting it to run. I added “<MonoRuntimeDebuggerEnabled>true</MonoRuntimeDebuggerEnabled>” to the csproj file and that seems to have got it to run more reliably.

Adding Content

I wanted to add some content to my page but figured I’d start off slow – how about a couple of labels and a button:

<Page
     x:Class="FirstUnoProject.MainPage"
     xmlns="
http://schemas.microsoft.com/winfx/2006/xaml/presentation"
     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
     xmlns:local="using:FirstUnoProject"
     xmlns:d="
http://schemas.microsoft.com/expression/blend/2008"
     xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
     mc:Ignorable="d">
   <Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
     <StackPanel>
       <TextBlock Text="Hello, world !" Margin="20" FontSize="30" />
       <TextBlock Text="Hello, world !" Margin="20" FontSize="30" />
       <TextBlock Text="Hello, world !" Margin="20" FontSize="30" />
       <Button Content="Press Me!" Click="IveBeenPressed" />
     </StackPanel>
   </Grid>
</Page>

and a bit of code behind:

public async void IveBeenPressed(object sender, RoutedEventArgs e)
{
     await new MessageDialog("I've been Pressed!", "Pressed").ShowAsync();
}

Now tell me you don’t expect this to work on the web, right? Sure enough works a treat.

image

It’d be great if the message box had “Pressed” as the title instead of “localhost:5210 says” but I’m still mind blown that this still works?

One thing to be aware of is that I’ve had some mixed experiences with Wasm as the resoluts seem to vary depending on which combination of Uno packages are referenced. This is definitely a work in progress but I feel that this is probably in line with where WebAssembly support is at across the board.

Web Development with NO JavaScript; Is Uno the Future Web Platform?

This is probably stating the obvious but I’m a big advocate for rich client applications. With the recent advances in PWAs I’m looking down the barrel of having to concede to all those fellow developers that have jacked themselves up on as many JavaScript frameworks they can find and now charge through the roof because they’re one of only a handful who actually understand the difference between == and ===. I’m sure the time will come but for now, it may be that the Uno Platform can help me leverage my UWP skills in building apps for iOS, Android and the Web (via WebAssembly).

In my previous post I covered Getting Started with Platform Uno where I simply used the extension to create a new project and discussed running it on various platforms. One of the features of UWP that I really like is that ability to gracefully handle different screen sizes through the use of Visual States. So I figured I’d give states a go in my basic Uno app. Here’s the XAML (note there’s no code behind) for my MainPage:

<Page x:Class="UnoGettingStarted.MainPage"
       xmlns="
http://schemas.microsoft.com/winfx/2006/xaml/presentation"
       xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
       xmlns:local="using:UnoGettingStarted"
       xmlns:d="
http://schemas.microsoft.com/expression/blend/2008"
       xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
       mc:Ignorable="d">
     <Grid>
         <VisualStateManager.VisualStateGroups>
             <VisualStateGroup x:Name="SizeGroup">
                 <VisualState x:Name="Small">
                    <VisualState.StateTriggers>
                         <AdaptiveTrigger MinWindowWidth="0" />
                     </VisualState.StateTriggers>

                     <VisualState.Setters>
                         <Setter Target="MainContent.Visibility"
                                 Value="Collapsed" />
                     </VisualState.Setters>
                 </VisualState>
                 <VisualState x:Name="Large">
                    <VisualState.StateTriggers>
                         <AdaptiveTrigger MinWindowWidth="1000" />
                     </VisualState.StateTriggers>

                 </VisualState>
             </VisualStateGroup>
         </VisualStateManager.VisualStateGroups>
         <StackPanel VerticalAlignment="Stretch"
                     x:Name="MainContent"
                     HorizontalAlignment="Stretch">
             <TextBlock Text="Hello, world !"
                        Margin="20"
                        FontSize="30" />
             <Button Content="Test"
                     Click="TestClick" />
         </StackPanel>
     </Grid>
</Page>

This XAML shows two Visual States, “Small,” hides the MainContent StackPanel, and “Large” which has no setters, so is the default states of the page. I’ve added an AdaptiveTrigger to both states for clarity. The “Small” Visual State for window sizes from 0; The “Large” Visual State for window sizes over 1000.

Whilst this is a relatively simple example, when I build and run this, it not only works on UWP (expected) but also on Wasm. The image below shows the output – the red text has been added afterwards to indicate which Visual State the page is in.

image

Serious props to the Platform Uno team, this is awesome.

Getting Started with Platform Uno

A while ago I posted on Building a TipCalc using Platform Uno and at the time there was quite a few steps to jump through to get a basic application running from scratch. In this post I’m going to cover off how incredibly easy it now is to get started with the Uno Platform. Before I get into the steps, I want to give some background on why after almost a year am I coming back to looking at Uno. For those who have been reading my blog or have worked with Built to Roam you’ll know that we specialise in building cross-platform applications, whether it be a mobile app spanning iOS and Android, a Windows app targeting desktop and Xbox, or an enterprise solution that’s available across web, mobile and desktop. With a deep heritage in the Microsoft ecosystem we have seen the emergence of technologies such as Xamarin.Forms – historically this was rudimentary framework for rapidly developing forms based applications, primarily for line of business solutions. We’ve also seen other frameworks emerge such as React Native, Flutter and of course PWAs. Each framework has its advantaged and disadvantages; each framework uses a unique set of tools, workflow and languages. The question we continually ask ourselves is which framework is going to provide the best value for our customers and that will allow us to build user interfaces that include high fidelity controls and rich animation.

We also evaluate frameworks based on the target platforms that they support, which is what has led me to this post. One of the amazing things about Xamarin.Forms is that it has provided support for the three main platforms, iOS, Android and Windows, as part of the core platform. In fact the tag line is currently “Native UIs for iOS, Android and Windows from a single, shared codebase”.

image

What’s mind blowing is if you look at the Other Platforms page you’ll see that there is also support for GTK, Mac, Tizen and WPF. Unfortunately, these other platforms do not get the same love as the core platforms, so don’t expect them to be kept up to date with the latest releases.

At this point you might be thinking, why stray from Xamarin.Forms? Well in recent times there has been a shift away from supporting UWP as a core component of Xamarin.Forms. When asked on Twitter about UWP support for Shell, David Ortinau’s response was just another nail in the coffin for UWP app developers who are already struggling an up hill battle to convince customers of the value proposition of building for Windows.

image

So this leads me to again revisit other frameworks but we find the situation isn’t much better:

  • React Native – iOS and Android only – There is a React Native for Windows but again, it’s not part of the core offering, so it will trail (perhaps not by much but the commit history indicates a difference between 1 day ago for the main Reach Native repo and 26 days ago on the Windows repo, for the most recent commit).
  • Flutter – iOS and Android only – There is work on desktop embedding and having Flutter work on the web, so perhaps we’ll see more support beyond Google I/O
  • PWAs – varying level of support on different platforms – Clearly Microsoft sees this as the path forward for some of their Office suite of apps but the lack of native UI I think is still a limitation of PWAs.

At this point I remembered that Uno provided an interesting take on cross platform development. I also remembered that they’ve been doing a lot of work to support WebAssembly, so perhaps this could be the perfect solution. In the simplest form, the Uno Platform is #uwpeverywhere (an initiative that I’ve long believed Microsoft should have championed, after all it’s called Universal for a reason, right?) but beyond that Uno is about being able to “Build native apps for Mobile and Web using XAML and C#”.

image

Let’s get cracking with building a Uno application and see how it pans out. If you're on the Uno Platform homepage and wondering how to get started, don’t worry, you’re not alone – I was looking for a big “Get Started” button but instead I see links to sample apps and to the source code. If you find yourself across at the source code, you’re about to embark down the wrong path – you don’t need to grab their source code as everything is distributed via nuget! So where do you go? Well you need to find the Uno Documentation and then click the link to Getting Started – now we’re cooking with gas! Unfortunately most of this page is pretty useless until you come to want to debug your application on WebAssembly. Instead what you really want to do i install the Uno Visual Studio Extension and use that to create your application.

Getting Started

  • Install the Uno Visual Studio Extension
  • Open Visual Studio and select File, New, Project
  • Search for “cross platform” and select the Cross-Platform App (Uno Platform) template

image

  • Important: Update nuget package references – if you don’t do this, it’s unlikely that your application will run as a WebAssembly (check the “Include prerelease” to get the latest update for Wasm support)

image

  • For WebAssembly in the csproj file:
    • Add <DotNetCliToolReference Include="Uno.Wasm.Bootstrap.Cli" Version="1.0.0-dev.214" /> into the same ItemGroup as the PackageReference for Uno.Wasm.Bootstrap
    • Add <MonoRuntimeDebuggerEnabled>true</MonoRuntimeDebuggerEnabled> to the initial PropertyGroup
    • Change the Project element to <Project Sdk="Microsoft.NET.Sdk.Web">
  • Build and run each platform – I’m showing UWP, Android and WebAssembly here but iOS works straight from the template too

image

So, now that we have a UWP application that runs on iOS, Android, Windows and Web, are we satisfied with this as a cross platform solution? I think I’m enjoying working in UWP again but it’ll take a bit more investigation to see if this is a viable solution or not.


----------

Contact Built to Roam for more information on building cross-platform applications

----------

Flutter at MS Ignite | The Tour - Sydney

This year I was lucky enough to be able to present at MS Ignite | The Tour, which has just concluded here in Sydney. What amazed me was that I got to present on a fledgling technology recently released by Google, Flutter. Of course, this by itself wouldn’t have been sanctioned at a Microsoft event, so the important part was that I was presenting on connecting Flutter to Azure, and highlighting just how powerful the Azure options are for mobile app developers on any platform.

Using Flutter to develop cloud enabled mobile applications

Flutter is one of the newest cross-platform mobile application development frameworks and brings with it the ability to generate high-fidelity applications that look amazing on every device. This session begins with a very brief overview of Flutter, covering the tools and resources required to get started. The remainder of the session connects a Flutter application to key Azure services such as Identity and App Center. The key takeaway from this session is how Azure accelerates the development of mobile applications irrespective of what technology or framework the app is developed with.

In this post I’m going to walk through the demo portion of the session, which revolved around the creation of a very simple task style application.

Getting Started – New Project

Let’s get started by creating a new project in VS Code (If you haven’t already got the Flutter SDK installed, go to https://flutter.io and follow the Get Started button in top right corner). In VS Code in you press Ctrl+Shift+P and type Flutter you’ll see all the available options.

image

Select “Flutter: New Project” and you’ll be prompted to give your project a name – I was short on inspiration for a name for the project, hence “World’s Best Flutter App”. Note that the name of your project needs to be all lowercase.

image

You’ll need to select a folder to put your new project in, and then VS Code will generate a default application that consists of a basic UI which includes a button that increments a counter on the screen. We’re going to start by removing most of this and replacing it with:

import 'package:flutter/material.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
   // This widget is the root of your application.
   @override
   Widget build(BuildContext context) {
     return MaterialApp(
       title: 'World\'s Best Flutter App',
       theme: ThemeData(
         primarySwatch: Colors.blue,
       ),
       home: MyHomePage(title: 'World\'s Best Flutter App'),
     );
   }
}

class MyHomePage extends StatefulWidget {
   MyHomePage({Key key, this.title}) : super(key: key);

  final String title;

  @override
   _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
   @override
   Widget build(BuildContext context) {
     return Scaffold(
       appBar: AppBar(title: Text(widget.title)),
     );
   }
}

As with all new projects, at this point I’d highly recommend running the application to make sure everything has been correctly created and that you have a running application – there’s nothing worse than investing hours into crafting an amazing solution only to have to debug it for hours because of some issue that happened early in the process. At this point there’s not too much to the application other than the title bar

image

Basic Task List

The first piece of functionality we’re going to add is the ability to enter a tasks and see them appear in a list. To do this we need a text entry (TextField widget) and a list (ListView widget) and we’re going to present them with the text entry above the list in a vertical stack (Column widget). Before adding the widgets I’m going to add a couple of instance variables to the _MyHomePageState class (note that this is the state that goes with the MyHomePage stateful widget):

class _MyHomePageState extends State<MyHomePage> {
   /////////////  Controller for TextField and List of tasks /////////////
   final TextEditingController eCtrl = new TextEditingController();
   List<String> tasks = [];

Now we can add our widgets to the body property on the Scaffold widget:

return Scaffold(
   appBar: AppBar(title: Text(widget.title)),
   /////////////  Body of the app is made up of a single column /////////////
   body: new Column(
     children: <Widget>[
       /////////////  TextField to capture input /////////////
       new TextField(
         controller: eCtrl,
         onSubmitted: (text) {
           tasks.add(text);
           eCtrl.clear();
           setState(() {});
         },
       ),

      /////////////  Expand ListView to remaining space /////////////
       new Expanded(
         child: new ListView.builder(
           itemCount: tasks.length,
           itemBuilder: (BuildContext ctxt, int index) {
             return Padding(
               padding: EdgeInsets.fromLTRB(10,10,5,5),
               child: Text(tasks[index]),
             );
           },
         ),
       ),
     ],
   ),
);

A couple of things to note here:

  • It appears that I’ve added a couple of trailing commas – this is by design and lets the auto formatter know to position things on new lines. This is really important as Flutter code can get really messy if you don’t keep an eye on the layout of the code
  • Pressing Shift+Alt+F in VS Code will apply the auto formatter and makes the code much more readable – take a look at the following image to see how VS Code presents the above code

image

At this point we have a working app where a user can enter a task and it’s added to a list of tasks that is presented in the lower area of the screen. There are plenty of online tutorials etc that talk about layout and how setState works so I’m not going to cover that here. If you’re unfamiliar with Flutter/Dart code I would suggest at this point taking the time to go and understand what’s going on in the code – we’re going to build on it, so it’s important you understand how things work before we move on.

Visual Studio App Center

Before adding any more functionality to the app, I want to first take a side step to discuss the use of Visual Studio App Center which has been specifically created by Microsoft to support app developers, providing capabilities for building, testing, distributing apps, along with services such as analytics, crash reporting and push notifications. Currently support for Flutter is via a third party plugin which only provides analytics and crash reporting but we can expect this to grow as more developers take on Flutter and put pressure back onto Microsoft to provide official support, similar to what’s already provided for React Native and other cross platform technologies.

For our tasks app we’re going to make use of the analytics and crash reporting, as well as the support for distributing the application via App Center. To do this we first need to go to App Center and register two applications: one for iOS and one for Android. Got to either https://mobile.azure.com or https://appcenter.ms and sign in using your preferred credentials – my preference is to use my Office 365 (ie Azure Active Directory) account as this plays nicely into the way I sign into the rest of Azure and makes things like billing etc really easy. After creating your account, if you locate the apps list, then in the top right corner you should see an Add new button, which gives you the option to Add new app

image

In the Add new app flyout, you need to provide an App name and provide information about the OS and Platform – these are more important if you’re going to use App Center to build the application but is also relevant to the distribution process, so it’s important that you set these correctly. Since the App name needs to be unique within your App Center instance, it makes sense to use some sort of platform identifier as part of the name so it’s easy to identify the iOS and Android apps in the list.

image

After creating the app, you’ll be presented with some platforms specific getting started documentation. Most of this can be ignored as it’s not relevant to our Flutter application. However, you do need to extract the id that’s been assigned to your application. This can be found as part of the code samples eg:

image

After creating the app registrations in App Center, we now need to add in the Flutter plugin into our application and initialize it with the app id. Note that because App Center issues a different app id for each platform, you need to include some conditional platform logic to determine which app id to use. There are three plugins you need to add to your pubspec.yaml file under the dependencies section:

https://pub.dartlang.org/packages/appcenter
https://pub.dartlang.org/packages/appcenter_analytics
https://pub.dartlang.org/packages/appcenter_crashes

All packages are based on the source code at https://github.com/aloisdeniel/flutter_plugin_appcenter developed by Aloïs Deniel and Damien Aicheh

dependencies:
   flutter:
     sdk: flutter
  appcenter_analytics: ^0.2.1
   appcenter_crashes: ^0.2.1
   appcenter: ^0.2.1

After adding in the packages, we also need to import the relevant types to the top of our main.dart file:

/////////////  Imports for platform info /////////////
import 'package:flutter/foundation.dart' show defaultTargetPlatform;
import 'package:flutter/foundation.dart' show TargetPlatform;

/////////////  Imports for App Center /////////////
import 'package:appcenter/appcenter.dart';
import 'package:appcenter_analytics/appcenter_analytics.dart';
import 'package:appcenter_crashes/appcenter_crashes.dart';

Next we need to initialise the App Center plugin but adding code to the _MyHomePageState class

class _MyHomePageState extends State<MyHomePage> {
   /////////////  Identifier used for initialising App Center /////////////
   String _appCenterIdentifier = defaultTargetPlatform == TargetPlatform.iOS
       ? "3037d80f-XXXXXXXXXXX-adb968c67880"
       : "f6737675-XXXXXXXXXXX-be38b29b0f89";

And then a call to the AppCenter.start method when the class initialises – we’re overriding the initState method to call this logic when the instance of the _MyHomePageState is first created:

/////////////  Override Initialise State /////////////
@override
void initState() {
   super.initState();
   initAppCenter();
}

/////////////  Initialise AppCenter /////////////
void initAppCenter() async {
   // Initialise AppCenter to allow for event tracking and crash reporting
   await AppCenter.start(
       _appCenterIdentifier, [AppCenterAnalytics.id, AppCenterCrashes.id]);
}

The last thing we’re going to do is to add a call to the trackEvent method for when an item is added to the tasks list. For this we’re going to modify the onSubmitted callback on the TextField

onSubmitted: (text) {
   /////////////  Tracking event /////////////
   AppCenterAnalytics.trackEvent("Adding item", {"List Item":text});

Now when you launch the app, and start adding tasks you’ll see some tracking of app related activity appear within the Analytics tab of App Center:

image

You can see information about events raised by the app

image

Including the ability to drill down into the event and see more information, in this case you can see the List item that were added to the task list – note that this is an application specific key-value combination specified as part of the call to trackEvent.

image

Build and Release Automation

Before we can start distributing our app via App Center we typically setup a build and release (aka a DevOps) pipeline for our application – at Built to Roam this is one of the first things we encourage all our clients to do as it significantly cuts down on the manual steps involved, resulting in fewer errors and less wasted time. For this, we rely on Azure DevOps, and again a big shout out to Aloïs Deniel who’s created an extension for Azure DevOps - https://marketplace.visualstudio.com/items?itemName=aloisdeniel.flutter

image

After adding this extension to your Azure DevOps tenant, you can easily setup a build and release pipeline – there are a few steps involved in this, so I’ll keep this for a follow up post. The build steps involve tasks for Installing Flutter, Building the app with Flutter, Copying the generated app to the artefacts folder and the Publishing the artefacts. The release steps simply involves uploading the generated app to App Center. You can of course adjust these to add functionality and perhaps target different environments for testing, and of course uploading to the relevant stores directly from your release pipeline.

Once you have your build and release pipelines in place, you should start to see your releases appear in the Distribute / Releases tab in App Center

image

If you open App Center on your iOS or Android device you can install each release for testing.

Azure App Service

Right now we actually have a pretty useless app since all it does is record tasks in memory. When you restart the app, your list of tasks will be gone. Plus there’s no way to have your list of tasks appear on another device etc. We’re not going to complete the entire app in the blog post but what we do want to do is show how easily you can connect a Flutter app to some backend services hosted in Azure.

First up, let’s take a look at the backend service we’re going to connect to. In the demo I used an ASP.NET Core application that was published to an Azure App Service but I could just have easily used a Functions app. The application consistent of a single controller that currently only supports a Get operation to retrieve a list of tasks, which for the moment are hardcoded.

[Route("api/[controller]")]
[ApiController]
public class TasksController : ControllerBase
{
     // GET api/values
     [HttpGet]
     public ActionResult<IEnumerable<Task>> Get()
     {
         return new[]
         {
             new Task {Title = "Task 1", Completed = true, },
             new Task {Title = "Task 2", Completed = false,},
             new Task {Title = "Task 3", Completed = true, },
             new Task {Title = "Task 4", Completed = false,},
             new Task {Title = "Task 5", Completed = true, },
         };
     }
}

public class Task
{
     public string Title { get; set; }
     public bool Completed { get; set; }
}

Swagger

It’s also worth noting that in the Startup.cs of this application I added in the logic to generate Swagger information for the service:

public class Startup
{
     …
     public void ConfigureServices(IServiceCollection services)
     {
         …

        services.AddSwaggerGen(c =>
         {
             c.SwaggerDoc("v1", new Info { Title = "Simple ToDo", Version = "v1" });
         });

        …
     }

    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
     {
         …
        app.UseSwagger();

        app.UseSwaggerUI(c =>
         {
             c.SwaggerEndpoint("/swagger/v1/swagger.json", "Simple ToDo V1");
         });

        …
     }
}

This application was published to a new Azure App Service which meant that both the /api/tasks endpoint, as well as the swagger endpoints were publically available. We’ll come back to securing these in a bit. To be able to call the tasks endpoint we could have gone ahead and created a raw http request and then have to worry about decoding the returned json into a series of entities, for which we’d have to write, or generate, the decoding logic. Instead I went over to SwaggerHub and imported the swagger endpoint:

image

After selecting “Import and Document API” I entered the url for the swagger endpoint on the Azure App Service eg https://simpletodonick.azurewebsites.net/swagger/v1/swagger.json

image

After hitting Import SwaggerHub will convert your json formatter swagger into YAML – we’re not really interested in this piece, since what we’re after is some generated Dart code. However, before we can go ahead and generate the Dart code we first have to configure the generator options for Dart. Click on the Export button in the top right of the SwaggerHub page, followed by Codegen Options.

image

Locate “dart” in the left hand tree, and then set the browserClient property to false – by default the Dart generator creates code suitable for Dart being used for web development. For Flutter you need to set this property to false.

image

Going back to the Export menu, now select “dart” from under the Client SDK option.

image

This will automatically generate and download a package that will include a strongly typed set of classes for accessing the tasks endpoint. I extract this folder and place the contents of the generated zip file into a new sub-folder called “tasks” at the root of the Flutter application.

image

After adding the files into the folder, I then needed to update the pubspec.yaml file for my application to include the package as a dependency, as well as the http package:

dependencies:
   flutter:
     sdk: flutter
   appcenter_analytics: ^0.2.1
    appcenter_crashes: ^0.2.1
    appcenter: ^0.2.1
    http: '>=0.11.1 <0.12.0'
   swagger:
     path: tasks

(note that “swagger” correlates to the name of the imported package which is defined with the pubspec.yaml file within the tasks folder)

Now to make use of the generated code in our application, I also needed to add a imports statement to the main.dart file.

/////////////  Import for Swagger /////////////
import 'package:swagger/api.dart';

As we’re going to be using the Task entity described by the Swagger I need to update the list variable from a List<string> to List<Task>. I also added the base url for the app service.

/////////////  Change List to use Task /////////////
List<Task> tasks = [];

/////////////  Base url for the Simple ToDo service /////////////
final _baseUrl = 'https://simpletodonick.azurewebsites.net';

At this point I also needed to fix up the existing task list functionality which expected a string, to use a Task entity. This was in two places, firstly when creating a new task I needed to create a new Task:

tasks.add(
   Task()
   ..title = text
,
);

And then when displaying the tasks in the list

child: Text(tasks[index].title),

Now with the app back up and running, we can go ahead and call the service in order to retrieve the tasks when the app launches.

void loadData() async {
   /////////////  Calling App Service /////////////

  // Setup api client with base url and token returned by auth process
   var client = ApiClient(basePath: _baseUrl);

  var tasksApi = new TasksApi(client);

  var downloadedTasks = await tasksApi.callGet();
   setState(() {
     tasks = downloadedTasks;
   });
}

Running the app at this point should return a list of tasks on startup and then allow subsequent tasks to be added (of course at the moment those tasks aren’t saved anywhere!)

Authentication with Azure B2C

Currently there is no security applied to the app service, which is clearly not only bad practice, it also means that it is impossible to personalise the task list to the individual user, since everyone will be returned the same list of tasks. The good new is that we can add authentication to our service without writing a single line of code. To do this we’re going to choose to use Azure B2C. However, Azure App Services can also use a variety of different social credential providers to authenticate the user.

For this application I created a new instance of Azure B2C and setup the default B2C_1_signupandin user flow (aka policy). After creating the instance and the user flow, you still need to associate the Azure B2C instance with the app service and vice versa. To do this, start by creating a new application registration within the Azure B2C portal – go to Applications tab and click Add button.

image 

In creating the application registration we want to enable both web app/api and native client. You’ll notice that under the Native Client area there is a Custom Redirect URI specified. To do authentication using the flutter_appauth plugin (which I’ll come to in a second) the Custom Redirect URI should be in a similar format ie <reverse domain>://oauthredirect.

After creating the application registration, take note of the Application ID – you’ll need this when we update the Authentication on the App Service that requires a Client Id.

The next thing to do, also in the Azure B2C portal is to navigate to the User flows (policies) tab and then click the Run user flow button.

image

From the Run user flow dialog, copy the link at the top (eg https://worldsbestflutterapp.b2clogin.com/worldsbestflutterapp.onmicrosoft.com/v2.0/.well-known/openid-configuration?p=B2C_1_signupandin)

Now we need to switch across to the App Service in the Azure Portal and click on the Authentication tab. Initially App Service Authentication will be set to Off and there is a warning that anonymous access is permitted.

image

Switch the App Service Authentication to On and under Authentication Providers, click through on the Azure Active Directory settings.

image

Use the Application Id captured when setting up the Azure B2C as the Client ID. Use the link recorded from the Run user flow dialog as the Issuer Url. Click OK to commit the Azure Active Directory settings.

Back in the Authentication / Authorization settings, make sure that the “Action to take when request is not authenticated” dropdown is set to “Log in with Azure Active Directory” – this will enforce sign in if no Authorization token is presented.

image

After hitting Save, if you attempt to access the app service you’ll find that you get a security exception (if sending raw requests), or redirected to the sign in prompt if attempting to load the endpoint in a browser.

Authentication in Flutter using Flutter_AppAuth

After setting up authentication on the app service, if you attempt to run the application it won’t be able to retrieve the list of tasks as the requests are unauthenticated. In order to create a request that is authenticated (ie supplies a validate Authorization header in this case) we need to get the user to sign into the application. Luckily there is a Flutter plugin, flutter_appauth (source code), that has been created by Built to Roam colleague Michael Bui, that wraps AppAuth iOS and Android libraries.

image

There are a few steps involved in getting our application setup to use flutter_appauth. We’ll start by adding the package reference to the pubspec.yaml file:

dependencies:
   flutter:
     sdk: flutter
   flutter_appauth:
  ….

Next, we need to upgrade the Android application to use the AndroidX libraries instead of the older support libraries. To do this we need to open the Android part of the flutter application in Android Studio. Right-click on the android folder in VS Code and select the Open in Android Studio option.

image

When prompted to “Import Project from Gradle” you can accept the defaults and click Ok. The application may take a few minutes to open in Android Studio and you’ll need to allow a bit of extra time for Android Studio to finish processing the application before the Migrate to AndroidX option becomes enabled in the Refactor menu:

image

Side note: The first couple of times I tried this whilst preparing this demo Android Studio kept saying that there was nothing to update. It turns out that there was an update to the Flutter plugin to Android Studio that was waiting to be installed – I did this, which resulted in Android Studio reloading. After reloading the folder structure under Project expanded to show the referenced flutter plugins as well as any external libraries. At this point running Migrate to AndroidX worked.

When Migrate to AndroidX does work for you it’s not immediately obvious that something has changed…. which is because it hasn’t. Instead Android Studio will have opened up a tool window at the bottom of the screen, prompting you to confirm the Refactoring Preview. Click Do Refactor to complete the migration.

image

If you look in the /android/app/build.gradle file you should see that the dependencies list at the end of the file have been updated.

dependencies {
     testImplementation 'junit:junit:4.12'
     androidTestImplementation 'androidx.test:runner:1.1.0-alpha4'
     androidTestImplementation 'androidx.test.espresso:espresso-core:3.1.0-alpha4'
}

At the point of writing this post the migration process references alpha versions. You can update this to reference the stable versions now:

dependencies {
     testImplementation 'junit:junit:4.12'
     androidTestImplementation 'androidx.test:runner:1.1.0'
     androidTestImplementation 'androidx.test.espresso:espresso-core:3.1.0'
}

Whilst in the build.gradle file the compiledSdkVersion and targetSdkVersion should be increased to at least 28. Lastly, update the defaultConfig element to include manifestPlaceholder

defaultConfig {
     applicationId "com.example.worldsbestflutterapp"
     minSdkVersion 16
     targetSdkVersion 28
     …
    manifestPlaceholders = [
             'appAuthRedirectScheme': 'com.builttoroam.simpletodo'
     ]

}

Note that the appAuthRedirectScheme should match the reverse domain part of the Custom Redirect URI property set when setting up Azure B2C earlier.

For iOS open the /ios/Runner/Info.plist file and add the CFBundleURLTypes key/value as follows.

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "
http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
     ...
     <key>CFBundleURLTypes</key>
     <array>
         <dict>
             <key>CFBundleTypeRole</key>
             <string>Editor</string>
             <key>CFBundleURLSchemes</key>
             <array>
                 <string>com.builttoroam.simpletodo</string>
             </array>
         </dict>
     </array>

</dict>
</plist>

We’re now ready to write the code to authenticate the user within the application. Start by adding an imports to bring in flutter_appauth

/////////////  Import for Flutter_AppAuth /////////////
import 'package:flutter_appauth/flutter_appauth.dart';

Next, add in some constants that are needed for the authentication process to the beginning of the _MyHomePageState class, as well as an instance of the FlutterAppAuth class.

class _MyHomePageState extends State<MyHomePage> {
   /////////////  Attributes required for authenticating with Azure B2C /////////////
   final _clientId = '7c57c3a6-bedb-41d6-9dcd-318224013a26';
   final _redirectUrl = 'com.builttoroam.simpletodo://oauthredirect';
   final _discoveryUrl =
       '
https://worldsbestflutterapp.b2clogin.com/worldsbestflutterapp.onmicrosoft.com/v2.0/.well-known/openid-configuration?p=B2C_1_signupandin';
   final List<String> _scopes = [
     'openid',
     'offline_access',
   ];

/////////////  Instance of FlutterAppAuth /////////////
FlutterAppAuth _appAuth = FlutterAppAuth();

At the beginning of the loadData method we created earlier, add a call to the authorizeAndExchangeCode method on the _appAuth instance.

void loadData() async {
   /////////////  Authenticate with Azure B2C /////////////
   var result = await _appAuth.authorizeAndExchangeCode(
       AuthorizationTokenRequest(_clientId, _redirectUrl,
           discoveryUrl: _discoveryUrl, scopes: _scopes));

Now, the only thing left to do is to pass in the token that gets returned from the authentication process into the call to retrieve the tasks. To do this we actually need to make a minor change to the swagger generated code to tell it to use OAuth credentials. Locate the api_client.dart file, which for my project is at /tasks/lib/api_client.dart and change the ApiClient constructor as follows:

ApiClient({this.basePath: "https://localhost"}) {

// Setup authentications (key: authentication name, value: authentication).

_authentications['Bearer'] = new OAuth();

}

This sets the ApiClient to use OAuth which means that you can then call the setAccessToken method on the instance of the ApiClient, which should be the code that immediately follows the call to authorizeAndExchangeCode.

var client = ApiClient(basePath: _baseUrl);

client.setAccessToken(result.idToken);

And there you have it, your application should be good to go. When you launch the application, it will redirect to the Azure B2C sign in page. After authenticating it will redirect back to the application and load the task list.

image

Big shout out to the community for rolling so many great plugins for Flutter. The world of cross platform development is progressively becoming easier to make high quality applications through frameworks such as Xamarin.Forms and Flutter.


----------

Contact Built to Roam for more information on building cross-platform applications

----------

Why are Developers Not Developing Applications for Windows?

The actual answer to this question is that basic premise of the question is wrong – developers are and will continue to develop for Windows. The question is a bit like saying “Why are all web developers using React?” and is driven by the typical over-hyped communities that latch onto the latest shiny thing that some developer has hacked together in their spare time (or equally as bad the latest language/framework/library released by Microsoft, Google, Facebook etc). Now, I’m not going to write here that Microsoft has made it easy for Windows developers, nor that the latest incarnation of their developer platform, Universal Windows Platform, has been in any form successful. What I do want to point out is that there are a massive number of applications still written, maintained and even created for Windows every day, and that building applications for Windows allows you to target an astonishingly large market (think of the total number of Windows based devices that are targetable).

So if there are so many developers still writing applications for Windows, why does the market think that Windows isn’t worth targeting? and why are there so few developers wanting to invest into learning the latest features of UWP?

I was doing a bit of trawling today looking for some content on why developers should build for Windows and came across this post entitled “Choose Your Platform” which kind of confuses me – I typically use “platform” to refer to the operating system an application is to run on but interestingly Wikipedia defines a computing platform as something more generic that can be applied at different levels. Interestingly enough, from the url of the page you can see it was originally called “Choose your technology” which I guess is even more vague.

What’s interesting about the “Choose Your Platform” page is that it dumps UWP, WPF and WinForms into one bucket and Win32 API into another…. I feel this is kind of weird. It also completely negates all the higher level frameworks/technologies (Electron, PWAs, Xamarin Forms, React Native etc) that could be used to build applications for Windows (and other platforms).

I clicked around a bit and went back up to the parent page “Develop Windows desktop applications” – here, as you can see from the image, the situation gets even more laughable…. In all seriousness, did Microsoft find some programmer out of the late 90’s to write this: “Create Windows desktop applications that your customers can use at work and play using Win32 and COM APIs to leverage features of the operating system”.

image

Over the last couple of years it’s been evident that Microsoft views Windows, and the associated app platform, as playing second (or perhaps third) fiddle to everything they’re selling that starts with Azure. Furthermore, what cycles have been invested in the Windows developer platform have been retrained on uplifting all those WinForms and WPF applications so that they can be distributed via the Store, take advantage of all the security/identify context that comes with Windows 10, and of course all the new APIs that are being added to UWP.

What’s missing is any form of marketing that explains in clear terms why companies, and developers, should care about Windows development? It’s not enough to say "you can build an app that uses ink” or “you can build an app that connects to Azure” – seriously I can build an iOS/Android app that does both of those just as quickly as I can for Windows. The big value proposition of UWP was it’s ability to write once and run anywhere – this all but died when Windows Phone was buried (RIP). Xbox requires so much hackery and patching the user interface and interaction model that it’s almost quicker to build a separate app, and Surface Hub (v1) doesn’t support .NET Standard 2.0. Seriously, and we wonder why Windows is such an after thought.

So, let’s adjust my opening question to “Why are companies ignoring Windows when building applications?” – and the answer is because they don’t see any benefit over what they can build via a responsive website. It’s as simple as that. Microsoft, lift your game. Fix your online presence and start promoting your developer platform again.


----------

Contact Built to Roam for more information on building applications for Windows

----------

Unboxing Xamarin.Forms Shell in Visual Studio 2019

In my previous post, Unboxing Visual Studio 2019 for Xamarin.Forms, I covered creating a new Xamarin.Forms project in Visual Studio 2019. The Xamarin.Forms project template hasn’t really changed much and the default application you get is the same as what we were seeing in the most recent updates for Visual Studio 2017. However, there are some big updates coming down the line for Xamarin.Forms developers, not the least is Shell, which is covered in the introductory post.

I’m going to take Shell for a bit of a spin, and to do so, I’m going to use the new project templates that are available for download – These will only install into Visual Studio 2019, so if you want to try them out, you’ll first need to install Visual Studio 2019

image

An hours or so later…

image

After installing the new templates I went about creating a new project

image

It seems that the new templates must have completely replaced the previous templates – not a great start, considering I’m likely to want to be able to create a non-shell based Xamarin.Forms application.

image

Ummm…. Where’s the UWP support? Seriously, as if UWP wasn’t failing hard enough as it is, the fact that there doesn’t appear to be UWP support in the initial Shell release it a bid depressing.

After that the new project screens all look familiar, so the next thing we’re looking at is the default solution structure.

image

My first comment (as usual) is that the view models are stuck in the same project as all the UI elements – I consider this to be incredibly bad practice as it means you end up with a mess of dependencies and it’s way to easy to break the separation of concerns between view and view models. Having said that, this is a getting started templates, so I guess if they’d added another project it would probably alienate other developers who prefer to have everything in a single project.

The great thing is that I can select either iOS or Android as my startup project and hit run – a minute or two later after the emulator has started up the app has been deployed and is running.

Side Note: This post actually took me a couple of sessions because I got interrupted and it took a couple of days for me to get back to it. When I did, I accidentally opened the XamShell app I’d created in Visual Studio 2017, where it builds and runs without issue. Of course I don’t have the Shell templates.

Here are a couple of screenshots from the running app – Firstly I love that they’re replaced the Xamarin logo added to the new project, as shown in the splashscreen. Note that this is not actually a splashscreen and that in fact they’re setting the background on the main activitiy. There’s so debate about whether this is best practice, or whether it’s still good to use a splashscreen to improve the perceived boot time of the app.

image

This is the master-details template, so we get things like the burger menu. The main screen includes a basic list and an add button in the navigation bar – pretty stock look and feel.

image

The about page is a little more interesting but again nothing mind-blowing.

image

If we look in the main XamShell project we notice that in addition to the usual App.xaml, which is required for Xamarin Forms, there is now also an AppShell.xaml. At this point I did in fact switch back to Visual Studio 2019 because opening AppShell.xaml in VS2017 seemed to be a bit of a broken experience.

Opening AppShell.xaml the first thing I noticed is that styles have been setup and a combination of implicit and explicit styles defined – yes!!! this is great to see in a template. Next I noticed that two pages have been defined: Browse and About – this confused me as there are actually 4 pages included in the project. On checking the code, it appears that the other pages are dynamically created as needed. The introductory documentation on Shell provides a good overview of the key elements that make up the Shell hierarchy.

My initially impressions are that this is going to be great for jump starting basic mobile applications. I’m interested to see how far this can be taken and how it can handle more complex navigation patterns and applications. I’ll explore further the various aspects of Shell but I’d encourage all Xamarin Forms developers to give Shell a chance – let’s see whether this can be made into something amazing by providing constructive feedback to the XF team.


----------

Contact Built to Roam for more information on building cross-platform applications

----------

Unboxing Visual Studio 2019 for Xamarin.Forms

I’ve just installed the preview for Visual Studio 2019 and wanted to share the experience of creating a new Xamarin.Forms application.

Firstly, the startup screen. Whilst I’m disappointed not to have the news feed, the new startup screen gives you a quick launching pad for whatever it is you want do in VS2019.

image

Let’s go with “Create a new project”. The search/filtering works well to quickly find the right project template

image

Now let’s provide some generic project information.

image

Ah and now we’re back to a familiar dialog for creating Xamarin.Forms applications. Hooray!!! there’s no option to use a shared library any more – good riddance. As you’ll see we get a .NET Standard 2.0 project where our XF pages and other logic will go.

image

And now we have the usual solution structure for an out of the box XF application containing the project that’ll house the pages (ie VS2019XFProject) and then head projects for iOS, Android and UWP.

image

Let’s hit run and check out the newly created project – notice I picked the Master-Detail template early so we get a basic layout with a hamburger button in top left.

image

And that’s it. BTW the chrome around the edge of the coding window seems to be progressively shrinking with each progressive release of Visual Studio. Eventually it’ll be carved back to what Visual Studio Code offers.


----------

Contact Built to Roam for more information on building cross-platform applications

----------

Screenshots for Xamarin.Forms with MvvmCross Article

A while ago I wrote an article for Visual Studio magazine that details getting started with Xamarin.Forms and MvvmCross. Whilst some things have changed since then, the process for getting started is still basically the same. To verify this process I followed the article and took screenshots along the way – these mostly correspond to the screenshots that are in the article, with a couple of extras thrown in to ensure good coverage of the steps. Please follow the instructions in the article Build a Xamarin.Forms Application with MvvmCross:

Create the new solution

image

Pick the Blank template using the .NET Standard library

Note that the order of the Code Sharing Strategy has changed, placing .NET Standard as the default (about time!!!)

image

Add a new Core library

image

Add reference to the Core library to each project

image

Update existing NuGet packages

image

Add reference to MvvmCross to ALL projects

image

Add reference to MvvmCross.Forms to all EXCEPT the Core project

image

Add App class to Core project and add necessary using statements

image

Update the MainPage to use the MvxContentPage as base class and in Views namespace

image

Don’t forget to update the code-behind file – Remove base class and update namespace

image

UWP: Change MainPage to inherit from MvxFormsWindowsPage and fix using statement

image

UWP: The updated MainPage

image

UWP: The updated MainPage code-behind file

image

UWP: Update the App class to inherit from ProxyMvxApplication

image

UWP: The ProxyMvxApplication class and the App code-behind

Note: I cheated here for the screenshot and had these in the same file. I would recommend having the ProxyMvxApplication in a separate file

image

Android: Error when building

image

Android: Add reference to Mono.Android.Export

image

Android: Change MainActivity to RootActivity and inherit from MvxFormsAppCompatActivity

image

iOS: Update AppDelegate to inherit from MvxFormsApplicationDelegate

image


I hope these screenshots help anyone who runs into issues getting started when following the Visual Studio Magazine article



----------

Contact Built to Roam for more information on building cross-platform applications

----------

Android Emulator Exception after updating to Visual Studio 15.9 preview 3

I noticed earlier this evening that there was an update available for Visual Studio 15.9. Normally I wait a few days to update as I’m not in any particular hurry but I noticed in the blog post and release notes that work had been done on the Android build and execution. I also remembered that I hadn’t updated Visual Studio or my emulator images since updating my Surface Book 2 to the latest Windows update – it contains a fix for the awful performance of the Android emulator running on Windows hypervisor. Anyhow, the upshot is that I updated Visual Studio to the latest preview….

I decided to drop my existing emulator images and create new ones. Unfortunately this was a bad idea as I was then unable to start the new emulator images. When I attempted to start the emulator I would get an error stating “The requested operation requires elevation. (Exception from HRESULT: 0x800702E4)".

image

Turns out I’m not the only person seeing this, as someone had already reported this issue.

It also turns out that there’s a simple solution…. close the Android Device Manager and just hit Run from within Visual Studio. Turns out that this causes the emulator image to boot, deploy and run the application. And all the updates seem to do the trick, debugging is back to an acceptable speed.

Getting Started with Xamarin.Forms and Unit Testing with xUnit and Moq (II)

Previous posts in this sequence on Getting Started with Xamarin.Forms:
Multi-Targeting in Visual Studio, SDK Versions, MvvmCross, Authenticating with ADAL
Refactoring MvvmCross and Services, Effects, Navigation with MvvmCross
Presentation Attributes in MvvmCross, Resources and Styles, Resource Dictionaries
Platform Specific Resources with OnPlatform, Device Customization using OnIdiom
Unit Testing with xUnit and Moq

One of the hardest aspects of testing is implementing and executing platform specific unit tests. As I was putting together a post covering platform specific testing I got side tracked looking at the use of Moq, which I posted about previously. On closer inspection of the csproj of the xUnit test project that I created as part of that post, the target framework is set to netcoreapp2.1. In order to test platform specific features I need to adjust the csproj to be multi-targeted covering android, ios and uwp. By making the test project multi-targeted the code can access platform specific APIs in order to be able to verify the platform specific code in our Core library.

<TargetFrameworks>netcoreapp2.1;Xamarin.iOS10;MonoAndroid90;uap10.0.16299</TargetFrameworks>

If we compare the target frameworks with those used by the Core project of our application, we can see that we have netcoreapp2.1 instead of netstandard2.0. In order to take advantage of the xUnit test runner, the test project does need to target netcoreapp2.1. We don’t really need to add netstandard2.0, since we don’t have a test runner that is only based on netstandard2.0 and our application never actually runs as a .NET Standard application (i.e. it runs as an iOS, Android or UWP application)

After changing the target frameworks the test project doesn’t build for a couple of reasons:

- The Visual Studio xUnit test runner isn’t compatible with the platform specific target frameworks

- xUnit has a platform specific test running that needs to be referenced. I’ll cover the platform specific test runners in future posts

The csproj of the test project should be updated to selectively include package references:

<PropertyGroup>
   <TargetFrameworks>netcoreapp2.1;Xamarin.iOS10;MonoAndroid90;uap10.0.16299</TargetFrameworks>
  <IsNetCoreApp>$(TargetFramework.StartsWith('netcoreapp'))</IsNetCoreApp>
</PropertyGroup>

<ItemGroup Condition=" '$(IsNetCoreApp)' != 'true' ">
   <PackageReference Include="xunit.runner.devices" Version="2.4.48" />
   <PackageReference Include="UnitTests.HeadlessRunner" Version="2.0.0" />
</ItemGroup>

<ItemGroup Condition=" '$(IsNetCoreApp)' == 'true' ">
   <PackageReference Include="Microsoft.NET.Test.Sdk" Version="15.8.0" />
   <PackageReference Include="xunit.runner.visualstudio" Version="2.4.0">
   <PrivateAssets>all</PrivateAssets>
   <IncludeAssets>runtime; build; native; contentfiles; analyzers</IncludeAssets>
   </PackageReference>
</ItemGroup>

<ItemGroup>
   <PackageReference Include="xunit" Version="2.4.0" />
</ItemGroup>

Even after changing the package references to make them conditional, there were issues referencing the stable release of Moq. Unfortunately the current release of Moq uses some features around reflection that aren’t supported by all platforms, and whilst it’s compatible with netcoreapp2.1, it’s not compatible with netstandard2.0. I went looking for other mocking options and almost immediately came across the work being done on the next iteration of Moq – this is a major change that does more of the heavy lifting at compile time, rather than dynamically at runtime.

At the time of writing, the next release for Moq is currently available only as source code from https://github.com/moq/moq

Once the source code has been built, the assemblies can be added as a direct reference to the test project.

<ItemGroup>
   <Reference Include="Moq">
     <HintPath>..\Library\Moq\Moq.dll</HintPath>
   </Reference>
   <Reference Include="Moq.Sdk">
     <HintPath>..\Library\Moq\Moq.Sdk.dll</HintPath>
   </Reference>
   <Reference Include="Stunts">
     <HintPath>..\Library\Moq\Stunts.dll</HintPath>
   </Reference>
</ItemGroup>

<ItemGroup Condition="'$(DesignTimeBuild)' == 'true'">
   <Analyzer Include="..\Library\Moq\Stunts.dll" />
   <Analyzer Include="..\Library\Moq\Stunts.Sdk.dll" />
   <Analyzer Include="..\Library\Moq\Roslyn.Services.Test.Utilities.dll" />
   <Analyzer Include="..\Library\Moq\Stunts.CodeAnalysis.dll" />
   <Analyzer Include="..\Library\Moq\Stunts.CodeFix.dll" />
   <Analyzer Include="..\Library\Moq\netstandard.dll" />
   <Analyzer Include="..\Library\Moq\Moq.Sdk.dll" />
   <Analyzer Include="..\Library\Moq\Moq.CodeAnalysis.dll" />
   <Analyzer Include="..\Library\Moq\Moq.CodeFix.dll" />
</ItemGroup>

In addition to assembly references, the Moq libraries are also added as Analyzers – this is to allow for the design time generation of code. Which brings me to the next step which is to adjust our test case to make use of the new Moq syntax. Currently the new version of Moq requires the manual inclusion of Mock.cs and Mock.overloads.cs (content files in the output folder that are generated by building the Moq source code) which include a bunch of helper methods that you’ll need.

The basic process for testing with a mock hasn’t changed – you still need to create and setup your mock entities, invoke a series of methods and then verify actual vs expected output:

[Fact]
public async Task AuthenticateTest()
{
     var credentialsMock = Mock.Of<ICredentialService>();
#pragma warning disable CS4014 // Don't await - we're calling Authenticate so that we can train the Mock to return a specific value
     credentialsMock.Authenticate().Returns(()=>Task.FromResult("SomeRandomAccessToken"));
#pragma warning restore CS4014

    var mainViewModel = new MainViewModel(
         null,
         null,
         credentialsMock);
     Assert.True(await mainViewModel.Authenticate());
}

I’ve bolded the lines that are worth reviewing in the amended test method:

- Where previously we created a new instance of Mock<ICredentialService>, now we’re using the method Mock.Of<ICredentialService>.

- Previously we called Setup to define the mocked behaviour. Now, we call the actual method we want to mock and then use the Returns method to define what the behaviour should be. Since we actually want to mock the Task that is returned by the Authenticate method, it’s important that we don’t attempt to await it. Hence the #pragma statements

This code will not currently compile, showing an error stating that there’s currently no mock implementation on ICredentialService. This error is generated by the Moq analysers we added to the csproj.

image

Expanding the help tooltip

image

Following the tooltip suggestion we can go ahead and create the mock for the ICredentialService. This will be added to a “Mocks” folder and appropriately named ICredentialServicesMock.

With that we can go ahead and run the test case.

image

In this post we’ve taken a quick look at getting started with the next version of Moq. We’ll take this further in the next post to cover running platform tests.

Intercepting the Android Software Back Button in Xamarin.Forms

Recently an issue was raised on MvvmCross that claimed there was an issue intercepting the back button in a Xamarin.Forms + MvvmCross application running on Android. I spent a bit of time investigating the issue as I didn’t believe MvvmCross was doing anything that would prevent an application from intercepting the back button. In this post I’ll walk through my investigation and demonstrate a solution that I came up with. Just for clarity, the issue was referring to intercepting the software back button that appears in the navigation bar.

In the comments someone had referenced a solution proposed by Udara Alwis (https://theconfuzedsourcecode.wordpress.com/2017/03/12/lets-override-navigation-bar-back-button-click-in-xamarin-forms/) which states that the OnOptionsItemSelected method can be overridden in the Activity that hosts the Xamarin.Forms application. Further comments indicated that this solution didn’t work for a Xamarin.Forms application that was using MvvmCross. My starting point was to of course validate this assertion. Using the Playground sample in the MvvmCross source code I attempted to override the OnOptionsItemSelected method in the MainActivity of the Android application. I ran the application and sure enough, the OnOptionsItemSelected method does not get invoked when tapping the software back button.

Having validated that the MvvmCross Playground was indeed broken, I next wanted to test to see if it was an issue with Xamarin.Forms itself. To do this, I started by creating a new Xamarin.Forms application (I’m just going to build for Android, since this is just a sample).

image

The Blank application template comes with a single page, MainPage. I added a second page to the application:

image

Onto the MainPage I added a Button and in the Clicked event handler added code to navigate to the page I just added:

private async void Button_Clicked(object sender, EventArgs e)
{
     await Navigation.PushAsync(new Page1());
}

In order to get the navigation bar to appear, I changed the App constructor to make use of a NavigationPage:

public App()
{
     InitializeComponent();

    MainPage = new NavigationPage(new MainPage());
}

Lastly, I needed to add the OnOptionsItemSelected override to the MainActivity.

public override bool OnOptionsItemSelected(IMenuItem item)
{
     return base.OnOptionsItemSelected(item);
}

Unfortunately, after doing all this, the OnOptionsItemSelected method was still not called. Looks like the issue sits with Xamarin.Forms, so it’s time to start trawling through the source code.

After an initial inspection it appears that the FormsAppCompatActivity does override the OnOptionsItemSelected method, but that doesn’t explain why overriding it in my application wouldn’t work. However, further inspection revealed that the NavigationPageRenderer (the renderer for the NavigationPage) implements the IOnClickListener interface and registers itself with the ActionBar (which corresponds to the navigation bar). Doing this prevents the call to the OnOptionsItemSelected method, which is why we were not seeing it called.

I figured that I would try extending the default renderer and provide my own implementation of the IOnClickListener interface:

[assembly: ExportRenderer(typeof(NavigationPage), typeof(HackBackButton.CustomNavigationPageRenderer))]
namespace HackBackButton
{
     public class CustomNavigationPageRenderer : NavigationPageRenderer, IOnClickListener
     {
         public CustomNavigationPageRenderer()
         {
         }

        public CustomNavigationPageRenderer(Context context) : base(context)
         {
         }

        public new void OnClick(Android.Views.View v)
         {
             Element?.PopAsync();
         }
    }
}

This works and the OnClick method is invoked when the software back button is tapped. Of course, we then need to route this to the current page so that it can decide if it should allow the back navigation.

Turns out that it’s nothing to do with MvvmCross and that the issue lie entirely with Xamarin.Forms. There needs to be a better way to intercept the back navigation. Someone has already listed a issue with Xamarin.Forms, so add a comment and make sure this issue gets some attention.

Getting Started with Xamarin.Forms and Unit Testing with xUnit and Moq

Previous posts in this sequence on Getting Started with Xamarin.Forms:
Multi-Targeting in Visual Studio, SDK Versions, MvvmCross, Authenticating with ADAL
Refactoring MvvmCross and Services, Effects, Navigation with MvvmCross
Presentation Attributes in MvvmCross, Resources and Styles, Resource Dictionaries
Platform Specific Resources with OnPlatform, Device Customization using OnIdiom

When we kicked off this project we separated out the business logic from the user interface into Core and UI projects respectively. The main aim was to ensure clear separation of context and to allow for the business logic to be developed, and more importantly, tested, independently of the UI. In this post we’ll get started with unit testing our Core library using xUnit. I’ll also touch on using the mocking library, Moq, to make our testing lives easier.

To get started we’ll add another project to our solution, this time based on the xUnit Test Project (.NET Core) from the Add New Project dialog.

image

If we inspect what gets added we’ll see that it’s a regular single targeted project with references to xUnit and the Microsoft test library.

image

After creating the project, don’t forget to do the obligatory NuGet package update. If you open the UnitTest1 class you can right-click within the Test1 method and select Run Test(s).

image

When you execute tests within Visual Studio you can see the execution progress in the Output window. If it doesn’t automatically switch, you may need to select Tests for the “Show output from” dropdown.

image

Before we can write tests for our Core library, we need to add a reference to the Core library to the Testing library.

image

Now we’re ready to start creating our own tests (you can delete UnitTest1.cs since we won’t be needing it). Everyone has their own naming convention and structure for testing library. I tend to mirror the layout of the project I’m testing. So in this case I've created a ViewModels folder within the test project and have created a class MainViewModelTest class.

At this point I’m also going to add a reference to Moq (https://www.nuget.org/packages/Moq) which I’ll use as part of the test method

public class MainViewModelTest
{
     [Fact]
     public async Task AuthenticateTest()
     {
         var credentialsMock = new Mock<ICredentialService>();
         credentialsMock.Setup(x => x.Authenticate()).Returns(() => Task.FromResult("SomeRandomAccessToken"));

        var mainViewModel = new MainViewModel(
             new Mock<IMvxLogProvider>().Object,
             new Mock<IMvxNavigationService>().Object,
             credentialsMock.Object);
         Assert.True(await mainViewModel.Authenticate());
     }
}

Here I’ve kept the AuthenticateTest method relatively straight forward – I created a mock instance of the ICredentialService which returns a predefined access token; this is then used along with two other mock objects when creating the MainViewModel instance. I then assert that calling the Authenticate returns true (i.e. because the Authenticate method on the ICredentialService instance returns a not-null access token).

Right-click within this test method to run the test returns a positive outcome in the Output window. You can also run and see the results of running test cases via the Test Explorer window.

image

And that’s it, you can now write as many test cases as you feel are necessary for your services, viewmodels and other Core classes.