Apple Introduces SwiftUI; So What?

Shortly after Apple announced SwiftUI a twitter thread erupted discussing a hypothetical Sharp UI. It was positioned an alternative for declarative ui development, across Xamarin applications in C# or F#.

What’s interesting is that both Google, with Jetpack Compose, and now Apple, with SwiftUI, have joined the modern evolution of app development by introducing a declarative way to define user interfaces. Declarative UI development has been around for a long time. For example, take any of a number of XAML based frameworks that Microsoft has produced (something completely missed by Martin’s post on What SwiftUI Means for Flutter who incorrectly claims declarative ui development was invented in React by Facebook).

So why now? Why is it that Apple, Google and Microsoft have all recognised that declarative UI is the way forward?

XAML as a Declarative UI

The back history of XAML goes way back to the WinForms days. It was common for developers to fight the IDE in order to wrestle control of the window layout. XAML was supposed to fix everything. It is not designed for humans (much the same way storyboards weren’t designed to be manually coded). XAML id designed for developer tooling such as Blend.

A few XAML frameworks later and what we find ourselves in Xamarin.Forms. The XAML is non-standard version. It is similar, yet in ways dramatically different from every flavour of XAML that predates it. The industry has moved on from trying to get previewers, such as Blend, to work. The developer community favours hot reload and the ability to adjust layout within a running app.

I’m sure that Xamarin.Forms will get there with XAML but is it too much of a liability? Should we look for an alternative?

Declarative UI in Code aka #CSharpForMarkup

Following down the discussion on the SharpUI twitter thread we end up discussing an alternative to XAML, which is declaring UI in code. This sounds awfully familiar to what SwiftUI or Flutter is doing, except this is for Xamarin.Forms.

Normally I would be against using declarative ui development in code as I feel that it becomes harder to separate the UI logic from the application logic. However, having spent time reviewing CSharpForMarkup I feel that it is a viable alternative to XAML and perhaps even removes a layer or two of the cognitive load Adam talks about

Cross Platform is the Future

At Built to Roam we spend a lot of time discussing app strategy with our clients. We often talk about the spectrum of app development options ranging from native all the way through to web. Almost the first thing we do is to discount and remove from discussion both native and web. If the client wanted a web experience, they would have gone to a web development agency, instead of come to us. We’re not going to recommend building a native application, even in Xamarin, when we should be considering cross platform options.

If you’re following the announcements about SwiftUI, or Jetpack Compose, sure go ahead and read up on them. Then pack them into their single platform box and put them back on the shelf. Take our your cross platform tool of choice (React Native, Flutter, Xamarin.Forms etc) and get back to building high quality amazing apps for both iOS and Android.


Nick Randolph @thenickrandolph
If you have an app and want to go cross platform, or are just starting you app development journey, contact Built to Roam.


Fiddler Debugging Http/Https Traffic for Xamarin iOS, Android and Windows (UWP) Applications

Debugging Http/Https Traffic using Fiddler for Xamarin iOS, Android and Windows (UWP) Applications

One of the most frustrating things as a frontend developer is when you are receiving incorrect data. You don’t know whether the problem lies with your application, or the backend services. The easiest way to validate this is to pretend to be a hacker. You can stage a man-in-the-middle attack on your own application. Debugging using tools like Fiddler or Charles can be used to inspect the traffic from your application. Unfortunately, the same effort that goes into protecting apps from such attacks, also means that it is harder for developers to setup Fiddler debugging.

In this post I’ll walk through setting up Fiddler debugging for a Xamarin.Forms application. The same basic approach will work for a native or Xamarin iOS/Android application as well. For this post I’ve created an application using the Blank Xamarin.Forms template that comes with Visual Studio 2019. I’ve selected to target all three platforms.

In the OnAppearing method in the MainPage of the Xamarin.Forms application, I’ve added some basic code to retrieve a string for a Https endpoint. We’ll use a Https endpoint on the assumption that if we can intercept Https then we can also intercept Http traffic.

protected override async void OnAppearing()
{
     base.OnAppearing();
     var client = new HttpClient();
     var users = await client.GetStringAsync("https://reqres.in/api/users?page=0");
     Debug.WriteLine(users);
}

Setting Up Fiddler Debugging

Before we get started with the individual platforms, it’s worth checking your configuration for Fiddler:

  • You need to make sure you have setup Https traffic decryption. I’m not going to repeat the documentation, so check out how to Configure Fiddler to Decrypt HTTPS Traffic.
  • You’ll also need to setup Fiddler debugging for remote traffic. This can be done by opening the Options window. Under the Connections tab, make sure the “Allow remote computers to connect” checkbox is checked. If you’re running Skype, or some other communication tools, it may have jumped onto the default port configured in Fiddler. In this case you can adjust the “Fiddler listens on port”.
Fiddler Debugging Options Window
Enabling remote connection in Fiddler

Windows (UWP)

I’ll start with Windows, because it’s relatively straight forward to get setup. With Fiddler running, you can run the UWP project from within Visual Studio and Fiddler debugging will work. Fiddler will capture the Https traffic without any further configuration or setup.

Fiddler Debugging
Capturing network traffic in Fiddler

In some cases, you need to make sure your application is added to the exemption list, so that traffic can be routed to the local machine. For more information see the blog post Revisiting Fiddler and Win8+ Immersive applications. To check this, click the WinConfig button in the top left corner of the Fiddler interface.

WinConfig
Click WinConfig to adjust the exemption list for Windows 10 apps

Locate your application and confirm that there is a check in the box next to your application. If it’s not checked, check the box, and then click Save Changes

Exemption Utility
Locate your UWP application and check the box to add your application to exemption list

One other issue I’ve seen but can’t reproduce reliably, is that sometimes when you run your application from Visual Studio it unchecks the box in the WinConfig in Fiddler. If for some reason you no longer see traffic in Fiddler for your application, go back and double check the exemption list in Fiddler.

Diagnosing Issues with Fiddler on Windows

When configuring Https traffic decryption, you’ll be prompted to install and trust the Fiddler root certificate. If you don’t accept all the prompts, Fiddler debugging for Windows applications will not work. Windows traffic debugging works without any further configuration because the Fiddler root certificate is trusted on the machine running Fiddler.

If you’re attempting to run the Windows application on a different machine than the one running Fiddler, you’ll need to install and trust the Fiddler root certificate. This is in addition to setting the remote machine as a proxy, which is a topic for another post. Navigate to http://[ipaddress]:[port] where [ipaddress] is the ip address of the machine running Fiddler and the [port] is the port number that Fiddler is listening on. Do NOT use https as this site is http only. You should see a screen similar to the following image – if you don’t, make sure you check that Fiddler is running!!

Fiddler Debugging Echo Service
Click on the FiddlerRoot certificate to install the root certificate

Click on the FiddlerRoot Certificate and install as a Trusted Certificate Authority on the Local Machine. This should allow your Windows application to trust Fiddler.

iOS Fiddler Debugging

Next up is iOS and in this case we’re going to use the iOS simulator. The same process should work with any iOS device that’s on the same local network as the machine running Fiddler. There are two steps to setup iOS for traffic debugging:

  1. Trust the Fiddler root certificate, and
  2. Set the http proxy to use the machine running Fiddler.

To setup the simulator, first launch the iOS application from Visual Studio. If you’re on Windows, this will launch the remote viewer for the simulator. Once the simulator is running, stop debugging and we’ll setup the simulator for traffic debugging.

Trusting the Fiddler Certificate

Navigate to http:[ipaddress]:[port] (eg http://192.168.1.109:8888) to load the Fiddler echo page. Then click on the Fiddler Certificate link. Follow the prompts to download and install the certificate.

Fiddler Echo Service iPhone Download Certificate iPhone Download Profile iPhone

In addition to downloading the certificate you also need to install it. Go to Settings / General / Profile and click through on the FiddlerRoot profile in order to Install it.

image image image image image image image

The Fiddler root certificate needs to be trusted as a root certificate. Go to Settings / About / Certificate Trust Settings and toggle the switch next to the FiddlerRoot certificate. Fiddler generates a certificate for each site you go to that is derived from the root certificate, so the root certificate needs to be installed as a trusted certificate.

image image image image

The only difference between a real iOS device and the simulator is that on a real iOS device you can set a network proxy. There are online tutorials, such as this one, for instructions on setting a proxy. Unfortunately, setting up a proxy this isn’t configurable on the simulator. If you want to use a proxy in the simulator, you can set the proxy on the mac running the simulator but this would affect all traffic on the mac. Alternatively, when running on the simulator, we can adjust the HttpClient to use a WebProxy using the following code:

var handler = new HttpClientHandler();
handler.Proxy = new WebProxy("192.168.1.109", 8888);
var client = new HttpClient(handler);

Running the iOS application should show network traffic in Fiddler debugging window. You should still see the returned data printed out in the Output window (ie from the Debug.WriteLine statement).

Android Fiddler Debugging

For Android I’m going to use the Android Simulator. Real devices should behave similarly, assuming they’re connected to the same local network as the machine running Fiddler.

Unlike iOS, that will use any proxy configured for the device, for Android you need to explicitly opt in to use a proxy in your code. You’ll need to use code similar to the following on both emulator and real devices:

var handler = new HttpClientHandler();
handler.Proxy = new WebProxy("192.168.1.109", 8888);
var client = new HttpClient(handler);

What’s a little scary about this code is that it “just works”. You might be thinking that this is a good thing. However, it does raise the question of how much of the system security model does the Microsoft built HttpClientHandler respect. What I would have expected is an SSL fail exception because the Fiddler root certificate isn’t trusted by the emulator. Furthermore, the application is not configured to use any user certificates.

The other thing to point out here is that you should not be using the HttpClientHandler. I’ve discussed this in my previous post on working with the HttpClient. Let’s change our code by moving it into the OnCreate method of the Android head project. We’ll also change over to using the AndroidClientHandler.

protected override async void OnCreate(Bundle savedInstanceState)
{
     ...
     var handler = new AndroidClientHandler();
     handler.Proxy = new WebProxy("192.168.1.109", 8888);
     var client = new HttpClient(handler);
     var users = await client.GetStringAsync("https://reqres.in/api/users?page=0");
     System.Diagnostics.Debug.WriteLine(users);
}

When we run the application we see the very familiar SSL handshake exception being raised, which is what we should expect. To get things to work, we now need to install the Fiddler certificate and configure the application to use user certificates.

Install the Fiddler Root Certificate

To install the Fiddler root certificate, navigate to http:[ipaddress]:[port] (eg http://192.168.1.109:8888) to load the Fiddler echo page. Click on the Fiddler Certificate link in order to download the certificate. Follow the prompts to download and install the certificate

image image image image image  image

After installing the certificate go to Setting / Security and Location / Encryption & credentials / User credentials to inspect the certificate

image  image

With the certificate installed into the user store, you need to configure the Android project to allow the use of certificates from the user store. In my post Working with Self Signed Certificates (Certificate Pinning) in Android Applications with Xamarin.Forms, I covered this in detail. The quick summary is that you need to create a network_security_config.xml file which sets the trust-anchors property (set using the debug-overrides element) to include certificates from the user store. You then need to reference this xml file from the networkSecurityConfig attribute on the application element in the AndroidManifest.xml file.

After installing the certificate and adding the network security configuration to the Android application you should now see network requests from the application appear within Fiddler debugging window.

Self Signed Android Certificates and Certificate Pinning in Xamarin.Forms

Working with Self Signed Certificates (Certificate Pinning) in Android Applications with Xamarin.Forms

Next up is looking at working with self-signed certificates in an Android application. Previous posts in this sequence are:

In this post we’re going to briefly talk about non-secure services. Next, we’ll look at how to trust self signed certificates by adding them to the Android bundle. Then lastly we’ll look at intercepting the certificate validation process when making service calls.

One resource that is particularly useful is the network security documentation provided for Android developers. This lists the various elements of the network security configuration file that this post will reference.

Non-Secure (i.e. Http) Services

By default, Android, like iOS, doesn’t allow applications to connect to non-secure services. This means that connecting to http://192.168.1.107 or http://192.168.1.107.xip.io will not work out of the box. You’ll see an error similar to the following, if you attempt to connect to a non-secure service:

Java.IO.IOException: Cleartext HTTP traffic to 192.168.1.107 not permitted occurred

It’s important to note that this behaviour has changed between Android 8.1 and Android 9. Prior to Android 9 there were no default restrictions on calling non-secure, or plain text, services.

Adding Network Security Configuration

You can enable accessing Http/Plain text services by adjusting the network security configuration for the application. To do this we need to add an xml file to the Resources/xml folder which we’ve called network_security_config.xml:

<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
     <base-config cleartextTrafficPermitted="true" />
</network-security-config>

This adjusts the network security for the application both in debug and in production. If you want to access plain text services only during debugging, you should change the base-config open and close tags to debug-overrides (everything else remaining the same). The “Application (Debuggable = true/false)” assembly attribute controls whether or not the application runs in debugging mode.

#if DEBUG
[assembly: Application(Debuggable = true)]
#else
[assembly: Application(Debuggable = false)]
#endif

We also need to add a reference to the network_security_config.xml file. In the application manifest file (AndroidManifest.xml) add the networkSecurityConfig attribute.

<?xml version="1.0" encoding="utf-8"?>
< manifest http://schemas.android.com/apk/res/android%22">http://schemas.android.com/apk/res/android"
           android_versionCode="1"
           android_versionName="1.0"
           package="com.refitmvvmcross"
           android_installLocation="auto">
     <uses-sdk android_minSdkVersion="19"
               android_targetSdkVersion="28" />
     <application
         android_allowBackup="true"
         android_theme="@style/AppTheme"
         android_label="@string/app_name"
         android_icon="@mipmap/ic_launcher"
         android_roundIcon="@mipmap/ic_launcher_round"
         android:networkSecurityConfig="@xml/network_security_config"
         android_resizeableActivity="true">
         <meta-data
             android_name="android.max_aspect"
             android_value="2.1" />
     </application>
< /manifest>

You can change the filename of the network_security_config.xml file, so long as it matches the networkSecurityConfig attribute value in the AndroidManifest.xml file.

If you run the application it will connect to the Http/Plain text endpoint.

Plain-text on iOS

In addition to enabling/disabling Http/Plain text services across the entire application, it can also be controlled on a per-endpoint basis. See the documentation on the Network Security Configuration for more information.

Self Signed Certificate Endpoints

Switching the endpoint to a Https endpoint with a self signed certificate (eg https://192.168.1.107:5001) will raise the following error:

Javax.Net.Ssl.SSLHandshakeException: <Timeout exceeded getting exception details> occurred

Which of course is completely meaningless, except that we do know it’s related to establishing the SSL connection.

If we look to the Output window, we can find more information about the exception. Unfortunately when an Android app crashes it will spew a lot of mostly irrelevant data into the output window. I’m sure all that debug information is useful in a lot of cases. However, in this case it is a lot of irrelevant information that makes it hard to find the important information. The best way to find more information is to search for the error from the debug session (i.e. Javax.Net.Ssl.SSLHandshakeException). Once found, look at the next 10-15 lines of information. In this case we see

05-04 08:31:21.756 I/MonoDroid( 5948): UNHANDLED EXCEPTION:
05-04 08:31:21.768 I/MonoDroid( 5948): Javax.Net.Ssl.SSLHandshakeException: java.security.cert.CertPathValidatorException: Trust anchor for certification path not found. ---> Java.Security.Cert.CertificateException: java.security.cert.CertPathValidatorException: Trust anchor for certification path not found. ---> Java.Security.Cert.CertPathValidatorException: Trust anchor for certification path not found.

This points to the fact that the application hasn’t been able to verify the certificate path for the certificate returned by the service. This result is not surprising because the service is using a self signed certificate and neither the Android device or the application trust the certificate.

Trusting Self Signed Android Certificates

In this section we’re going to use the public key from the self signed certificate. This will allow the application to connect to the secure endpoint, without having to write code to intercept the certificate validation. We’ll cover two different ways but they amount to the same thing. In both cases it’s necessary to have the public key of the certificate authority available to the application. The application will use the public key to verify the certificate path of the certificate returned by the service.

Installing to the Android Certificate Store

The first option is to install the public key of the certificate authority onto the Android device. Android maintains two different certificate stores: system and user. We’re going to be adding the certificate to the user store. Aadding to the System store requires root access and can be done using ADB as shown in various posts, such as this one.

The public key that we need to use is the public key of the certificate authority. As discussed in previous posts, we’ve used mkcert to generate our self signed certificate. The public key of the certificate authority used by mkcert is available at C:\Users\[username]\AppData\Local\mkcertrootCA.pem

The first challenge is to get the certificate onto the device, which I typically find easiest via a download link. I add the public key to dropbox and then open the link in Chrome on the Android device:

image image

Installing the Public Key

After downloading the pem file, clicking on the file in the Downloads list does nothing. You actually need to go to Settings / Security & location / Encryption & credentials / Install from SD card

image

The name of the items under settings may vary from device to device. For example Install from SD card might be Install from storage. The quickest way is to search for certificate and go to the item that says something like Install from SD card.

image

Clicking on the Install from SD card/storage settings item will display a file picker. From the burger menu you can select Downloads which will reveal the pem file you’ve just downloaded. However, this item will be disabled, presumably because of some security related to downloaded items. I initially thought that I’d downloaded the wrong certificate format. In actual fact, if you go back to the burger menu and browse the contents of the device (see third image above) and click on Download, you’ll see the same rootCA.pem file but this time it’s not dimmed out and you can click on it.

image

Saving the Root Certificate

If you have a PIN setup on the device, when you click on the rootCA.pem, you’ll need to enter your pin. After entering your PIN you’ll be asked to enter a Name for the certificate and what the certificate is to be used for.

The Name isn’t particularly useful since it doesn’t show up anywhere. It doesn’t appear in either the Trusted credentials screen (second image, showing the added certificate), nor the Security certificate popup that appears if you click on the certificate for more information.

Since we want the certificate to be used by the app we leave the default use, “VPN and apps”. At this point if you open the service endpoint in the browser you should see that the certificate is trusted.

image

Accessing the Android Certificate Store

Now that we’ve installed the certificate, there’s just one change we need to make to the Android application itself. By default Android applications will only use certificates in the system store. However, you can adjust the application to make use of the user certificate store. To do this we need to add a trust-anchors and certificates elements to the network_security_config.xml with the following contents:

<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
     <debug-overrides>
         <trust-anchors>
            <certificates src="user" />
         </trust-anchors>
     </debug-overrides>
</network-security-config>

In this case, the certificates element will only be used when the application is running in debug mode (ie by using the debug-overrides element). Running the application now will return data from the Https endpoint.

image

The issue with this approach is that the public key for the certificate authority has to be installed on the device. Since the public key appears in the user store, it means that at any point the user could remove it. Whilst it is unlikely that the user will delete the individual item, they may decides to clear all cached credentials.

Clearing cached credentials has the unfortunate side effect of clearing out the user store, thus preventing the application from running. If you’re only connecting to endpoints for the purpose of development or debugging, this option may be sufficient and would minimise the changes required to the application.

Adding to Application Package

The second option is to add the public key of the certificate authority to the application package itself. We’ll use the DER format for the public key which we generated from the mkcert public key file in the previous post. Add the kestrel.der file to the Resources / raw folder, with Build Action set to AndroidResource, and the Custom Tool to MSBuild:UpdateGeneratedFiles.

image

You need to link the public key to the network security configuration file. Add the trust-anchors and certificates elements to the network_security_config.xml file as follows:

<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
     <base-config>
         <trust-anchors>
             <certificates src="@raw/kestrel" />
         </trust-anchors>
    </base-config>
</network-security-config>

If you only want to use the certificates in debugging, exchange the base-config with debug-overrides.

That’s all you need to do to be able to access a service that uses a self-signed certificate.

Validating Server Certificates (i.e. Android Certificate Pinning)

The other alternative to working with self signed certificates is to override the certificate validation that is done as part of each service request. On Android you can override the ConfigureCustomSSLSocketFactory and GetSSLHostnameVerifier methods on the AndroidClientHandler. For example, here’s a CustomerAndroidClientHandler that inherits from the AndroidClientHandler and overrides these methods:

public class CustomAndroidClientHandler : AndroidClientHandler
{
     protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
     {
         request.Version = new System.Version(2, 0);
         return await base.SendAsync(request, cancellationToken);
     }

    protected override SSLSocketFactory ConfigureCustomSSLSocketFactory(HttpsURLConnection connection)
     {
         return SSLCertificateSocketFactory.GetInsecure(0, null);
     }

    protected override IHostnameVerifier GetSSLHostnameVerifier(HttpsURLConnection connection)
     {
         return new BypassHostnameVerifier();
     }
}

internal class BypassHostnameVerifier : Java.Lang.Object, IHostnameVerifier
{
     public bool Verify(string hostname, ISSLSession session)
     {
         return true;
    }
}

We’ve also included the class BypassHostnameVerifier, which is a basic implementation of the IHostnameVerifier that needs to be returned from the GetSSLHostnameVerifier method. In the ConfigureCustomSSLSocketFactory method we’re returning a factory generated by the GetInsecure method. According to the method documentation the GetInsecure method “Returns a new instance of a socket factory with all SSL security checks disabled”. The documentation goes on to provide a warning “Warning: Sockets created using this factory are vulnerable to man-in-the-middle attacks!”.

I would like at this point to reiterate this warning. By providing your own handling of the SSL checks, you are effectively taking ownership and responsibility of making sure your application isn’t being hacked. As such, I would recommend only overriding these methods when you need to connect to a service that uses a self signed certificate. Make sure that in the Verify method you validate the service response to ensure only responses with self signed certificates that you trust are processed (ie check for man-in-the-middle attacks).

If you’re just interested in certificate pinning (i.e. ensuring that your application is connecting to a server that is returning a known certificate) you can simply override the GetSSLHostnameVerifier method. This will leave the default SSL verification/security in place but give you the opportunity to validate that the certificate being returned is what you expect.

Http2 Handling on Android

The bad news is that Http2 combined with self signed certificates doesn’t currently play nicely with the out of the box AndroidClientHandler. The AndroidClientHandler is the default and preferred handler on Android. When you attempt to connect to a service that is Http2 only and it uses a self signed certificate, you’ll probably see an error similar to the following:

Javax.Net.Ssl.SSLHandshakeException: Connection closed by peer occurred

Unfortunately there’s no simple solution without importing another library. Luckily, the ModerHttpClient library has the code necessary to do this and is updated slightly in the modernhttpclient-updated nuget package.

Please do not include the nuget package in your application as neither the original or the updated package are being actively maintained. Instead, copy the source code that you need (in this case the NativeClientHandler) and take ownership of maintaining it within your application logic.

To round this out, here’s an example that overrides the NativeMessageHandler to set the Http version to 2.

public class CustomNativeClientHandler : NativeMessageHandler
{
     protected async override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
     {
         request.Version = new System.Version(2, 0);
         return await base.SendAsync(request, cancellationToken);
     }
}

And when an instance of the CustomNativeClientHandler is created, the EnableUntrustedCertificates property is set to true. This effectively disables any of the SSL checking, so again opens up the risk of man-in-the-middle attacks.

Mvx.IoCProvider.LazyConstructAndRegisterSingleton<HttpMessageHandler, IServiceOptions>(options =>
{
     return new CustomNativeClientHandler
     {
         AutomaticDecompression = options.Compression,
         EnableUntrustedCertificates = true
     };
});

And when we run this, we can see that the Http protocol used is Http/2.

image

In this post we’ve touched on using both self signed certificates, as well as certificate pinning. This is not an easy topic but important for application developers to be across. If you come across issues with your application security, feel free to reach out on twitter or via Built to Roam’s contact page.


Nick Randolph @thenickrandolph

Built to Roam on building cross-platform applications


Self Signed iOS Certifcates and Certificate Pinning in a Xamarin.Forms application

Working with Self Signed Certificates (Certificate Pinning) in iOS Application with Xamarin.Forms

The next post in the app security series looks at working with self-signed certificates in an iOS application. Previous posts in this sequence are:

In this post we’re going to cover:

1) accessing non-secure services

2) trusting a self-signed certificate and

3) handling certificate validation.

This gives you all the options you should need when accessing which security option to use during development. It will also cover how to implement certificate pinning in the production version of your app.

Non-Secure (i.e. Http) Services

iOS is secure by default, which means that, by default, an iOS application can only connect to services over Https. The certificate will be verified against one of the well known certificate authorities. Most production services will use a certificate that has been issued by a well know certificate authority. For example, when you deploy a service to Azure App Service, the generated endpoint (eg myservices.azurewebsites.net) already has a Https endpoint with a certificate that is trusted.

In some cases being able to connect to plain-text services may useful. For example,when you’re running the services locally, or you’re attempting to connect to a service in an environment, where there is no https endpoint. In these cases, you can adjust the behaviour of the iOS application so that it can connect to a non-secure (ie http) endpoint.

Accessing Non-Secure Services

Let’s see this in action by changing our the endpoint of our service request to http://192.168.1.107:5000. The endpoint is configured for both https on port 5001 and http on port 5000. If you are trying on a new ASP.NET Core 3 project, don’t forget that the template comes with the line UseHttpRedirection in startup.cs so. If you want to expose an http endpoint you’ll need to remove that line.

image

In the iOS application if you simply change the endpoint to http://192.168.1.107:5000, the application will operate correctly. This is despite all the concern that http connections aren’t supported. This is because there’s a clear set of exceptions to the Https rule on iOS:

image

If you want to use http but instead of using an IP address (ie the exclusion we just saw) you have a domain name. Let’s try this by changing the endpoint to http://192.168.1.107.xip.io:5000. BIG shout out to the xip.io service which is super cool. You can enter any ip address before the xip.io and the returned ip address from doing a DNS lookup will be the same ip address.

image

When we run the iOS application and it attempts to make the service call we get the following exception raised within Visual Studio:

Unhandled Exception:
System.Net.WebException: <Timeout exceeded getting exception details> occurred

This isn’t very meaningful. However, in the Output window there’s much more information:T

Unhandled Exception:
System.Net.WebException: The resource could not be loaded because the App Transport Security policy requires the use of a secure connection. ---> Foundation.NSErrorException: Error Domain=NSURLErrorDomain Code=-1022 "The resource could not be loaded because the App Transport Security policy requires the use of a secure connection." UserInfo={NSLocalizedDescription=The resource could not be loaded because the App Transport Security policy requires the use of a secure connection., NSErrorFailingURLStringKey=http://192.168.1.107.xip.io:5000/api/values

Allowing Insecure Connections

This exception we can combat by including an exception in the Info.plist:

<key>NSAppTransportSecurity</key>
<dict>
   <key>NSExceptionDomains</key>
   <dict>
     <key>192.168.1.107.xip.io</key>
     <dict>
       <key>NSExceptionAllowsInsecureHTTPLoads</key>
       <true />
     </dict>
   </dict>
</dict>

Adding this to the plist will exclude the listed domain from the App Transport Security policy. Another alternative is to use the NSAllowArbitraryLoads attribute.  You should avoid using this attribute as it effectively disables the security policy for any endpoint that the app connects to.

<key>NSAppTransportSecurity</key>
<dict>
   <key>NSAllowsArbitraryLoads</key>
   <true />
</dict>

So that’s it for accessing non-secure, or Http, endpoints. Simply add the endpoint to the NSExceptionDomains element in the Info.plist file and you’re good to go.

Trusting Self-Signed Certificates

Now let’s go back to connecting to a secure endpoint. This time we’re going to keep with using a xip.io address to ensure any security policies are enforced. The secure endpoint would be https://192.168.1.107.xip.io:5001. I’ve reissued the certificate used by the ASP.NET Core application to include 192.168.1.107.xip.io in the alternative names section:

image

You would expect this to work since the endpoint domain is already listed in the Info.plist file (see earlier on doing this using the NSExceptionDomains). Unfortunately there is still an error similar to the following.

System.Net.WebException: The certificate for this server is invalid. You might be connecting to a server that is pretending to be “192.168.1.107.xip.io” which could put your confidential information at risk.

The information in this error is only partially correct. The certificate for the server is actually valid, it’s just that the app/device isn’t able to verify the integrity of the certificate.

Working with Public Keys

We need to find a way for the device to trust the certificate being returned by the server. By far the easiest way to get the certificate to be trust by applications running on an iOS device, is to install the public key for the certificate onto the device. To do this we need the public key, which we can extract from the pfx file used by the ASP.NET Core service, using the following openssl command (This site is very useful for Openssl commands):

openssl pkcs12 -in kestrel.pfx -out kestrel.pem -nodes

This extracts the public key in pem format. iOS needs der format. Luckily there’s again an openssl command for converting the files.

openssl x509 -outform der -in kestrel.pem -out kestrel.der

To get the public key to the device you can either share a hyperlink (ie upload the der file and share a link) or email the file to your self and open it on the device. My preference is just to add the file to my dropbox and then open the corresponding link using Safari on the device. Select the Direct Download option and the file downloads, extracts and attempts to installs the certificate

image

After clicking on Direct download you should see a prompt from the OS about installing a profile that has been installed from a website. We understand the risk so click on Allow. You will then see a confirmation prompt, indicating the Profile has been Downloaded.

imageimage

Installing iOS Root Certificate

It’s important to read the second prompt closely because what it’s saying is that you still need to go to Settings in order to complete the installation of the profile (which in this case is just a certificate). Open Settings / General / Profile and then select the profile for 192.168.1.107.xip.io you’ll see information about the certificate and the ability to Install (top right corner) the certificate.

image

After clicking Install and following the prompts you’ll be returned to this screen. The link to Install will change to Done. However, the certificate will be marked as Not Verified. This is because the root certificate, which in this case is the root certificate used by mkcert, is not trusted by the device.

image

Unfortunately since the certificate isn’t trusted, the application will still fail to connect to this endpoint. For the moment we’ll remove this certificate as it’s not helpful.

Trusting the Root iOS Certificate

Let’s repeat the process of installing the certificate but this time let’s install the root certificate used by mkcert. The public key can be found at C:Users[username]AppDataLocalmkcertrootCA.pem and when you attempt to install it on the device you should see something similar to

image image

Note the difference after the certificate has been installed – it is clearly marked as Verified in green.

To prevent profiles being accidentally downloaded and installed by users and for them to have full access to the device, it is necessary to manually trust certificates. The certificate settings can be found under Settings / General / About / Certificate Trust Settings. On this screen you can control which profiles (ie certificates) are fully trusted.

image

After toggling the full trust setting we’re good to try our application. We’ve not had to make any changes to the application itself. After installing the correct certificate onto the device, we’re able to connect to the secured services. Marking the root certificate as trusted on this device, also removes the need for the NSExceptionDomains section in the Info.plist file.

Validating Server Certificates (i.e. Certificate Pinning)

In this last section we’re going to look at how you can specify a certificate within the application itself. This will to allow requests to be made to the service with the self-signed certificate. Before proceeding you should removed any certificates that were previously installed.

Currently (at the time of writing) there is no way to override the certificate validation process for the out of the box NSUrlSessionHandler. There’s been work done in the past to provide a better alternative, such as the ModernHttpClient. However, most do not seem to work with self-signed certificates. They may have worked well with self-signed certificates back when the library was created but as it’s no longer maintained it appears to not support self-signed certificates.

Using the NSUrlSessionHandler

Even the sample project put together by Jonathan Peppers on SSLPinning doesn’t appear to work. Luckily with a minor tweak it’s possible to use the revised NSUrlSessionHandler to permit access to the self-signed service. Using the source code in the SSLPinning repository as the starting point, I’ve collated all the pieces of the alternative NSUrlSessionHAndler into a single file (Full source code). The main changes are:

- The addition of an UntrustedCertificate property which will accept the raw data from the .der public key

public NSData UntrustedCertificate { get; set; }


- Modification to the processing included in the DidReceiveChallenge method. This essentially installs the root certificate so that it can be trusted by the application.

if (sessionHandler.UntrustedCertificate != null)
{
   var trust = challenge.ProtectionSpace.ServerSecTrust;
    var rootCaData = sessionHandler.UntrustedCertificate;
    var x = new SecCertificate(rootCaData);

    trust.SetAnchorCertificates(new[] { x });
     trust.SetAnchorCertificatesOnly(false);
    completionHandler(NSUrlSessionAuthChallengeDisposition.PerformDefaultHandling, challenge.ProposedCredential);
}
else
{
    completionHandler(NSUrlSessionAuthChallengeDisposition.CancelAuthenticationChallenge, null);
}

In order to take advantage of the updated NSUrlSessionHandler we need to modify the setup.cs

Mvx.IoCProvider.LazyConstructAndRegisterSingleton<HttpMessageHandler, IServiceOptions>(options =>
{
     var handler = new Xamarin.SSLPinning.iOS.NSUrlSessionHandler
     {
         UntrustedCertificate = NSData.FromFile("kestrel.der")
     };
     return handler;
});

And of course we need to make sure we include the kestrel.der file in the Resources folder. Make sure the Build Action set to BundleResource.

image

Running this up and we get the response back from the service.

image

The big difference with this option is that there’s nothing outside of the application is modified. All the setting up of the trust is done within the application, making it much easier to deploy to any device without having to worry about configuring the device.

Summary of iOS Certificates

Note that we didn’t strictly do certificate pinning – we just allowed the application to connect to a self-signed endpoint. To carry out certificate pinning you can make changes to the DidReceiveChallenge method and determine whether the certificate should be trusted. The ModernHttpClient does have an implementation of a callback that the application can register for in order to determine whether the certificate, and thus the endpoind, should be trusted.

Working with Self Signed Certificates (Certificate Pinning) in Windows (UWP) Application with Xamarin.Forms

Working with Self Signed Certificates (Certificate Pinning) in Windows (UWP) Application with Xamarin.Forms

I’ve been doing a bit of progression talking about building and debugging ASP.NET Core services over https and http/2, coupled with using platform specific handlers to improve the way the HttpClient works on each platform. The following links provide a bit of a background on what we’ve covered so far.

Accessing ASP.NET Core API hosted on Kestrel over Https from iOS Simulator, Android Emulator and UWP Applications.
Publishing ASP.NET Core 3 Web API to Azure App Service with Http/2
Xamarin and the HttpClient For iOS, Android and Windows

In this post we’re going to pick up from the end of the previous post to discuss using self-signed certificates in a Windows (ie UWP) application. Previously we managed to get the ASP.NET Core API hosting setup in such a way that the services were exposed using the IP address of the host computer, meaning that it can be accessed from an app running on an iOS simulator, the Android emulator, or even a UWP app running locally on the computer. As we’ll see there’s still a bit of work to be done within the app on each platform to allow the app to connect to the API.

Before we go on, it’s worth noting that the technique we’re going to use in the post is sometimes referred to as certificate pinning, which amounts to verifying that the response to a service call has come across a secure channel that uses a certificate issued by a certificate authority that the app is expecting, or trusts. There are a variety of reasons for using this technique but the main one is to help eliminate man in the middle attack by preventing some third party from impersonating the service responding to the requests for an app. One of the other common reasons to use this technique is actually to permit non-secure, or self-signed certificates – as you may recall we used a self-signed certificate in the previous post to secure the service, so we need a mechanism for each platform to permit the use of self-signed certificates and treat the responses from such services as trusted. This will be done over a three part series of posts, starting with a Universal Windows Application (UWP) application in this post.

To get started, let’s take a quick look at what happens if we simply run up both the UWP application we had previously setup to use the WinHttpHandler. The only change I’m going to make to the UWP application initially is to change the BaseUrl for the service to https://192.168.1.107 (ie the IP address of the development machine) – note that it’s a https endpoint. Running the application will fall over with an exception when it attempts to connect to the HeaderHelper service hosted at https://192.168.1.107/api/value.

image

The extracted error message is as follow:

System.Net.Http.HttpRequestException
   HResult=0x80072F8F
   Message=An error occurred while sending the request.
   Source=System.Private.CoreLib
Inner Exception 1:
WinHttpException: Error 12175 calling WINHTTP_CALLBACK_STATUS_REQUEST_ERROR, ‘A security error occurred’.

Now if you search for this error information, you’re likely to see a bunch of documents talking about the 0x80072F8F error code as it seems to come up in relation to Windows activation issues. However if you google the 12175 error (ie the internal exception) you’ll see a number of articles (eg http://pygmysoftware.com/how-to-fix-windows-system-error-12175-solved/) that point at there being an SSL related error. In this case it’s because we accessing a service that uses a certificate that isn’t trusted and can’t be validated.

We’re going to discuss two ways to carry out certificate pinning, which should allow us to access the HeaderHelper service, even though it’s being secured using a self-signed certificate. In the previous post where we setup the ASP.NET Core service to use a new certificate when hosting on Kestrel, we generated a .PFX certificate that included both the public and private components using mkcert. In both of the methods described here, you’ll need the public key component, which is easy to grab using openssl thanks to this post. For example:

openssl pkcs12 -in kestrel.pfx -nocerts -out kestrel.pem -nodes

Look Dad, No Code

The first way to configure the UWP application to connect to the service with a self-signed certificate is to add the public key for the certificate into the UWP application and declare the certificate in the Package.appxmanifest.

– Open the Package Manifest designer by double-clicking the package.appmanifest

– Once opened, select the Declarations tab, and then from the Available Declarations, select Certificates and click Add.
image

– Click the Add New button at the bottom of the Properties section
image

– Set the Store name to TrustedPeople and click the … button to select the public key file generated earlier

image

If you’re interested as to what has been changed when you selected the public key in the manifest editor:

– The public key file (in this case kestrel.pem) was added to the root of the UWP project with Build Action set to Content so that the pem file gets deployed with the application

– The package.manifest file was updated to include an Extensions section, specifically a Certificate element that defines both the store and the certificate file name.

<Extensions>
   <Extension Category=”windows.certificates”>
     <Certificates>
       <Certificate StoreName=”TrustedPeople” Content=”kestrel.pem”/>
     </Certificates>
   </Extension>
</Extensions>

And that’s it – you can successfully run the application and all calls to the service secured using the generated self-signed certificate will be successful.

With Code Comes Great Responsibility

The second way to prevent man in the middle style attacks is to do some validation of the connection in code of the certificate returned as part of the initial all to the services.

If you read some of the documentation/blogs/posts online they sometimes reference handling the ServerCertificateValidationCallback on the ServicePointManager class. For example the following code will simply accept all validation requests, thereby accepting all response data, on the assumption that the caller is in some way validating the response.

ServicePointManager.ServerCertificateValidationCallback += (sender, cert, chain, sslPolicyErrors) => true;

Note: The ServerCertificateValidationCallbak event on the ServicePointManager will only be invoked if you use the default managed handler, which as we saw in my previous post is not recommended. I would discourage the use of this method for handling certificate validation challenges.

So, if ServicePointManager isn’t the correct place to intercept request, what is?

In the previous post we had already overridden the InitializeIoC method on the Setup.cs class, so it makes sense to route the NBN cabling through the roof cavity.

– A new method, CertificateCallacbk, has been set to handle the ServerCertificateValidatationCallback on the WinHttpHandler (not to be confused with the ServicePointManager callback).

protected override void InitializeIoC()
{
     base.InitializeIoC();


    Mvx.IoCProvider.LazyConstructAndRegisterSingleton<HttpMessageHandler, IServiceOptions>(options =>
     {
         return new WinHttpHandler()
         {
             ServerCertificateValidationCallback = CertificateValidationCallback,
         };
     });
}
private bool CertificateValidationCallback(HttpRequestMessage arg1, X509Certificate2 arg2, X509Chain arg3, SslPolicyErrors arg4)
{
     return true;
}

– Of course simply returning true to all certificate validation challenges, isn’t very secure, and it’s highly recommended that your certificate checking is much more comprehensive.

And that’s it; you can now ignore certificates that are self-signed, or that aren’t signed by a trusted certificate authority. Whilst the methods presented in this post are for UWP, they are equally applicable for a UWP application that’s been written using Xamarin.Forms.

Xamarin and the HttpClient For iOS, Android and Windows

Xamarin and the HttpClient For iOS, Android and Windows

In an earlier post that talked about using dependency injection and registering interfaces for working with Refit across both Prism and MvvmCross I had code that registered an instance of the CustomHttpMessageHandler class which internally used a HttpClientHandler for its InnerHandler. For developers who have spent a bit of time optimising their iOS, Android or Windows application, you’ll have noted that using the HttpClientHandler is generally not deemed to be best practice.  As I’m a big fan of trying to demonstrate best practices, I figured I’d expand on this a little into a post talking about the HttpClient and some of the options you have.

Firstly, a couple of bits of side reading:

– Docs on the HttpClient stack

– Mono blog post talking about the HttpWebRequest / HttpClient

– Jon’s post on Http Performance

What you should gather from these articles is that Microsoft is doing their best to set you up for success but not wanting to take any documentation for granted, let’s see what happens when we create a brand new Xamarin.Forms project and spin up an instance of the HttpClient. When creating the project I just picked the Blank Xamarin.Forms template and made sure that all three platforms were included. The code for creating the HttpClient just uses the zero-parameter constructor:

var client = new HttpClient();

Let’s run each platform and see what the HttpClient gives us (and at this point I haven’t updated any NuGet packages, framework versions or anything. This is just what VS2019 gives me when I create a new XF project).

UWP

image

Here we get the managed HttpClientHandler, rather than the newer (and arguably better) WinHttpHandler. Actually I didn’t find a definitive guide on which is better for UWP, although this stackoverflow post does seem to imply the WinHttpHandler would be the preferred choice, particularly if you want to leverage Http/2.

Android

image

Android is using the AndroidClientHandler which is what should give us the most up to date http experience.

iOS

image

iOS is using the NSUrlSessionHandler which is what should give us the most up to date http experience.

This all seems good (albeit that you might want to use the WinHttpHandler on UWP) so for a lot of developers they might never run into any issues. If you did want to adjust which handler is used on iOS and Android (again assuming you’re just using the HttpClient with the default constructor) you can do so via the properties dialog for the corresponding platform:

image

However, where things come unstuck is if you want to customise some of the http behaviour. In my previous post I demonstrated setting the compression flag but it could have equally been adding an additional header or changing the credentials that are sent as part of each request. In this case, it’s easy enough to use the overload of the HttpClient constructor that takes a HttpMessageHandler and use the managed HttpClientHandler implementation (as I demonstrated). As you’d have seen from the linked articles above, this isn’t ideal as the managed implementation doesn’t leverage the platform specific optimisations.

The better approach is for my application to register the platform specific handler, which in MvvmCross can be done via the Setup class (which is created by default when using MvxScaffolding):

UWP

public class Setup : MvxFormsWindowsSetup<Core.App, UI.App>
{
     protected override void InitializeIoC()
     {
         base.InitializeIoC();
        Mvx.IoCProvider.LazyConstructAndRegisterSingleton<HttpMessageHandler, IServiceOptions>(options =>
         {
             return new WinHttpHandler()
             {
                AutomaticDecompression = options.Compression
             };

         });
     }
}

Android

public class Setup : MvxFormsAndroidSetup<Core.App, UI.App>
{
     protected override void InitializeIoC()
     {
         base.InitializeIoC();


        Mvx.IoCProvider.LazyConstructAndRegisterSingleton<HttpMessageHandler, IServiceOptions>(options =>
         {
            return new AndroidClientHandler
             {
                 AutomaticDecompression = options.Compression
             };

         });
     }
}

iOS

public class Setup : MvxFormsIosSetup<Core.App, UI.App>
{
     protected override void InitializeIoC()
     {
         base.InitializeIoC();


        Mvx.IoCProvider.LazyConstructAndRegisterSingleton<HttpMessageHandler, IServiceOptions>(options =>
         {
             var nsoptions = NSUrlSessionConfiguration.DefaultSessionConfiguration;
             if (options.Compression == System.Net.DecompressionMethods.None)
             {
                 nsoptions.HttpAdditionalHeaders = new NSDictionary(“Accept-Encoding”, “identity”, new object[] { });
             }
             var handler = new NSUrlSessionHandler(nsoptions);
             return handler;

         });
     }
}

Note: for iOS the NSUrlSessionHandler enabled compression by default, so the code here illustrates how you could disable compression if you wanted by sending the identity Accept-Encoding header.

In this post I’ve shown you how you can register each of the native platform handlers to optimise the requests made when using the HttpClient. This post should be read in conjunction with my earlier post that registered the other classes necessary to create the HttpClient based on the registered handler. The only other change is that the HttpService constructor should accept an HttpMessageHandler instead of an ICustomHttpMessageHandler.

public class HttpService : IHttpService
{
     public HttpService(HttpMessageHandler httpMessageHandler, IServiceOptions options)
     {
         HttpClient = new HttpClient(httpMessageHandler as HttpMessageHandler)
         {
             BaseAddress = new Uri(options.BaseUrl)
         };
     }


    public HttpClient HttpClient { get; }
}

Update: It’s worth noting that the WinHttpHandler used in the UWP example isn’t part of the core framework. Instead it is accessible via the System.Net.Http.WinHttpHandler NuGet package. Visual Studio provides a handy way to find and install this package – selecting the WinHttpHandler reference (where there is a build error) and looking at the intellisense options, there is an option to Install the System.Net.Http.WinHttpHandler package.

image

Shell in v4 of Xamarin.Forms and Visual Studio 2019

Shell in v4 of Xamarin.Forms and Visual Studio 2019

Back in late 2018 I did a post on getting started with Shell where I did a “File-New-Project” with Xamarin.Forms Shell. In this post I’m going to do a quick update to that post looking at creating a new Shell application with Visual Studio 2019, and then upgrading to the preview of Xamarin.Forms Shell v4.

As all great projects start, let’s get going with the Create a new project dialog. Search for Xamarin and select the Mobile App (Xamarin.Forms) template.

image

Give some basic project information

image

Select Shell as the application template.

Note: The Windows (UWP) option has come back (removed in the initial release of Visual Studio 2019) when creating Xamarin.Forms applications. However, since Shell isn’t supported by UWP at the moment, the Windows (UWP) option is currently disabled.

image

And there you have it a new Xamarin.Forms application that you can build and run, that leverages Shell.

image

And looks a little like this with bottom tabs and an ADD button in the navigation bar.

image

But let’s see what v4 is going to give us. Select “Include prerelease” and update to the latest packages.

image

Xamarin.Forms Shell v4

One addition that is more of a cosmetic improvement is the naming of ShellItem and ShellSection – I think the initial intent of these were that they should be somewhat abstracted for the actual UI implementation. However, as Shell has matured, the reality is that ShellItem maps to an item that appears in the flyout and an ShellSection maps to a tab…..

Wow, hold on, what are these things ShellItem, ShellSection and ShellContent? If you haven’t been following what the Xamarin.Forms team have been working on then Shell might come as a bit of a surprise. However, as nearly every app developer will admit, one of the most painfully tedious parts of building an application is create and linking all the pages of the application so that the user can navigate between them. The cognitive load of how to do master-details or tabs even in Xamarin.Forms makes it hard for developers to get started. What Shell aims to achieve is to provide a declarative way for you to define how your application is structured.

Essentially Shell represents a hierarchy of navigation elements:

– Shell – this is represents the application as a whole

– ShellItem – these are the first level pages of the application. Currently if there are multiple ShellItems defined, they’ll automatically appear in a Flyout.

– ShellSection – a page can be broken into sections which essentially map to bottom tabs. If a ShellItem only has one ShellSection, no tabs will show.

– ShellContent – this is the actual page content that will be displayed within the bottom tabs. If a ShellSection has multiple ShellContent, tabs will appear at the top of the tab giving you a tab-sandwich display.

In v4, to make it easier for developers to clearly see what was going on, additional classes, FlyoutItem and Tab were added that sub-class ShellItem and ShellSection respectively. The following example layouts use the new element names – if you’re still on v3.6 of Xamarin.Forms you will need to stick with ShellItem and ShellSection.

Some examples:

Single Page Application

image

Notes:

For a single ShellContent there’s no need to include a Tab element, simply nest it directly under the FlyoutItem.

– The FlyoutBehavior attribute can be used to hide/show the flyout on different pages in the application, or (as in this case) across the whole application. Use Shell.FlyoutBehavior on individual FlyoutItem elements to hide the flyout on those pages.

<Shell … FlyoutBehavior=”Disabled”>
     <FlyoutItem … >
         <ShellContent … />
     </FlyoutItem>
</Shell>

Two Page Application With Flyout

image

<Shell …>
     <FlyoutItem Title=”Home” … >
         <ShellContent … />
     </FlyoutItem>
     <FlyoutItem Title=”Single Page” … >
         <ShellContent … />
     </FlyoutItem>
</Shell>

Looking at the different combination of FlyoutItem, Tab and ShellContent we can get different page behaviours:

Bottom Tabs

image

<FlyoutItem Title=”Bottom Tabs” … >
     <Tab Title=”Home” >
         <ShellContent … />
     </Tab>
     <Tab Title=”Activity” … >
         <ShellContent … />
     </Tab>
</FlyoutItem>

Top Tabs

image

<FlyoutItem Title=”Top Tabs” … >
     <Tab Title=”Activity” … >
         <ShellContent Title=”Shared” … />
         <ShellContent Title=”Notifications” … />
     </Tab>
</FlyoutItem>

Tab Sandwich

image

<FlyoutItem Title=”Tab Sandwich” … >
     <Tab Title=”Activity” … >
         <ShellContent Title=”Shared” … />
         <ShellContent Title=”Notifications” … />
     </Tab>
     <Tab Title=”Updates” … >
         <ShellContent Title=”Updates” … />
         <ShellContent Title=”Home” … />
     </Tab>
</FlyoutItem>

As you will have briefly seen, it’s possible to rapidly stand up the basics of an application using a combination of flyouts and tabs to structure your application. In this post we’ve referenced the preview of the next version of Xamarin.Forms Shell, so you can expect that some of the features, particularly around navigation are subject to change in the coming months.

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

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

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

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.

Design Time Data for Xamarin.Forms

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

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

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
             
             
              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).

Unboxing Xamarin.Forms Shell in Visual Studio 2019

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

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

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

———-

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

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>..LibraryMoqMoq.dll</HintPath>
   </Reference>
   <Reference Include=”Moq.Sdk”>
     <HintPath>..LibraryMoqMoq.Sdk.dll</HintPath>
   </Reference>
   <Reference Include=”Stunts”>
     <HintPath>..LibraryMoqStunts.dll</HintPath>
   </Reference>
</ItemGroup>


<ItemGroup Condition=”‘$(DesignTimeBuild)’ == ‘true'”>
   <Analyzer Include=”..LibraryMoqStunts.dll” />
   <Analyzer Include=”..LibraryMoqStunts.Sdk.dll” />
   <Analyzer Include=”..LibraryMoqRoslyn.Services.Test.Utilities.dll” />
   <Analyzer Include=”..LibraryMoqStunts.CodeAnalysis.dll” />
   <Analyzer Include=”..LibraryMoqStunts.CodeFix.dll” />
   <Analyzer Include=”..LibraryMoqnetstandard.dll” />
   <Analyzer Include=”..LibraryMoqMoq.Sdk.dll” />
   <Analyzer Include=”..LibraryMoqMoq.CodeAnalysis.dll” />
   <Analyzer Include=”..LibraryMoqMoq.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

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

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.

Getting Started with Xamarin.Forms and Device Customization using OnIdiom

Getting Started with Xamarin.Forms and Device Customization using OnIdiom

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

Last post I covered how to use OnPlatform to tailor resources and styles based on the target platform. However, there is an alternative dimension you can tailor the layout of your application and that’s using OnIdiom. If you look at the definition of the OnIdiom class you can see that it allows you to define different values for Phone, Tablet, Desktop, TV and Watch.

image

To use this in XAML is very similar to using OnPlatform:

<Label>
     <Label.Text>
         <OnIdiom x_TypeArguments=”x:String”>
             <OnIdiom.Phone>Hello from a phone app</OnIdiom.Phone>
             <OnIdiom.Desktop>Hello from a desktop app</OnIdiom.Desktop>
         </OnIdiom>
     </Label.Text>
</Label>

As you can see from the code snippet this provides different string values for when the application is run on a phone vs being run on a desktop.

Note: Tablet only works well for iOS and Android. Xamarin.Forms running on UWP currently doesn’t distinguish between Windows running in desktop or tablet mode, and as such will always use the Desktop idiom values.