Enterprise-ready testing in Xamarin

As focus moves towards mobile-first development, enterprise developers should also focus on automated testing. In an enterprise setting, we like to test for merge conflicts, sync issues, authentication failures, etc and we need to test this on hundreds of devices.

In this post, we will look at how we can set UI test project and application code so that we can test against scenarios that we face in a real-life situation (no connection, sync issues, authentication failures). We will achieve this by utilizing mock application services in the application. The project is a Xamarin Forms application, where most of the application code resides in a .NET Core project. It does not matter which application pattern we use, e.g. MVC, MVVM or MVP.

In a basic unit test, we test various method of a library by mocking all services that it might depend upon and check against expected behaviour.

In UI tests, our aim is to check that UI layout works across multiple devices, and the fact the data displayed by the view is correct. We also check that the application behaves as expected in scenarios such as password expiration, where there is no connection, a failure to get device location etc. Using the same principles as above, we should be able to simulate multiple conditions/data sets for the UI and test against expected results.

All of the code for the below application is available for download at Sample UI Automation.


The first service to mock will be a network service, i.e. a service that is responsible for interacting will back-end APIs. Like any other project, we have a basic network service contract inside our application, defined as:

Assuming we already have an implementation for the above service called NetworkService (along with its unit tests), we are going to add a mocked service. The below code works in 2 modes, RECORD, and MOCK. In RECORD mode, the service acts similar to a real network service, but also saves those interactions (mostly JSON/XML payloads) to a file. These interactions are then used to replay the scene inside a UI test.


The RECORDING mode is used with an Android device so that we are able to save the file on the file system and retrieve it using ADB shell tool.

Project Setup

Before we use the above service, let’s define a new configuration for our solution called ‘Automation’.

Right click on your project solution and click ‘Options’. Then under Build -> Configurations, select the ‘General’ tab. Now Click ‘Add’. Enter the name as ‘Automation’. Do this for each platform i.e. Any CPU,  iPhone, and iPhoneSimulator.

Screen Shot 2018-04-23 at 3.29.51 pm.png

Now go to your main iOS and Android projects and define symbols for ‘Automation’ configuration. Here I have added ‘ENABLED_TEST_CLOUD’ and ‘AUTOMATION’.

Screen Shot 2018-04-23 at 3.40.00 pm.png

For this project, we are using Autofac for IoC. When the configuration selected is Automation, the mock network service will be injected into the application.

The mock service, in the RECORDING mode, behaves like the real service and also save those interactions. After loading the service, all that is left to do is test your screen manually. Once the manual testing of the application is finished, we should be able to retrieve the MockRecoding.json file (name defined in the service above) from the Android device. This file will have all the data that we will need while writing our UI tests.

Retrieve the file using ADB tools as shown below

Screen Shot 2018-05-03 at 10.56.33 am

Here is the structure of the recording that we have saved.


Screen Shot 2018-05-04 at 9.03.05 am

Backdoor methods

Next, we will see how we can use the above-saved interaction file and use it in our tests. UI tests are mostly commands that we send to the application, such as button clicks and gestures, and we then test the UI for expected results. We need to write backdoor methods in our application that we can later invoke from a UI test.

Below is a ‘LoadApiData’ method, which injects data into mock service using its exposed public methods. Again, this code only works when the selected configuration is ‘Automation’.

Consider a scenario where we swipe down a list view to refresh it. For testing this scenario, we want to first set the data that the list initially has, then we will want to set the refreshed data, then perform the swipe gesture, and finally check that the list has the expected data in it.

Add the recording file that we saved earlier inside a folder in our UI test project. To use the above recording, add it to your test project inside a folder named ‘Data’. Then right-click on the file and set its ‘Build Action’ to ‘EmbeddedResource’. For more about the embedded resource, check out this blog.

The test can be as simple as this. Note how it uses the backdoor method before moving to list screen. Using Xamarin test cloud (now App center), we can run the below test on hundreds of devices and check for UI specifics.

With mocking and utilizing test cloud we are able to able to test the same scenario on hundreds of devices. Not only that – since we are mocking it, the same MockNetworkService can be used to perform development too, such as when APIs are under development. All we need is the JSON payload, and we can manually edit the recording file.




Accessing to Geolocation on Mobile Devices from ASP.NET Core Application in Vue.js and TypeScript

In the previous post, we used HTML5 getUserMedia() API to access camera on our mobile devices. In this post, we’re using geolocation data on our mobile devices.

The code samples used for this post can be found here.

navigator.geolocation API

Unlike getUserMedia() API, geolocation API has a great level of compatibility of almost all browsers.

Therefore, with a simple TypeScript code, we can easily use the geolocation data.

NOTE: In order to use the geolocation API, the device must be connected to the Internet. Also, each browser vendor uses its own mechanism to get geolocation data, which will cause different result even in the same device. This article gives us more details.


  • ASP.NET Core App from the previous post
  • Computer or mobile devices that can access to the Internet through Wi-Fi or mobile network

NOTE 1: We use vue@2.2.2 and typescript@2.2.1 in this post. There are breaking changes on VueJs for TypeScript, so it’s always a good idea to check out the official guideline.

NOTE 2: Code samples used in this post were from the MDN document that was altered to fit in TypeScript.

Updating Hello.vue

In order to display latitude, longitude and altitude retrieved from the geolocation API, we need to update the Hello.vue file:

That’s pretty much self descriptive – clicking or tapping the Get Location button will display those geolocation data. Let’s move onto the logic side.

Updating Hello.ts

The Get Location button is bound with the getLocation() event, which needs to be implemented like below:

First of all, we need to declare properties for latitude, longitude and altitude, followed by the getLocation() method. Let’s dig into it.

  • First of all, we check the navigator.geolocation isntance if the web browser supports geolocation API or not.
  • Call getCurrentPosition() method to get the current position. This method then passes two callback methods and an option instance as its parameters.
  • Callback method, success(), passes the position instance containing current position details and binds co-ordinates to the browser.
  • error() callback handles error.
  • options instance provides options for the geolocation API.

NOTE Each callback method has its return type, according to the type definition, which is not necessary. Therefore, we just return null

The options instance used above is actually an interface type of PositonOptions that needs to be implemented. Its implementation might be looking like below:

We completed the TypeScript part. Let’s run the app!


When we use a web browser within our dev machine, it firstly asks us to get a permission to use our location data:

Click Allow and we’ll see the result.

This time, let’s do it on a mobile browser. This is taken from Chrome for iPhone. It also asks us a permission to use geolocation data.

Once tapping the OK button, we can see the result.

So far, we’ve briefly looked at the geolocation API to populate current location. That’s not that hard, isn’t it?

If we have more complex scenario, need more accurate location details, or need constant access to the location data even we’re not using the app, then native app might have to be considered. Here’s a good discussion regarding to these concerns. But using HTML5 geolocation API would be enough in majority of cases.

Mobile Application Management (MAM)

The biggest challenge for BYOD devices is data security and leakage, a common method to enforce data protection is through Exchange ActiveSync and/or Mobile Device Management (MDM) tools such as AirWatch, Intune and others.

Both ActiveSync and MDM comes with the option of device wipe and enforcing device PIN. If the device is lost or the employee is terminated, the company could remote wipe the device to protect its data. While device wipe is great from the company’s perspective, it is almost always met with resistance from the employees because everyone fears the company has the power to wipe their personal data such as photos and contacts from their own personal devices.

What are the options when users do not use MDM:

Option 1: block access if not using a managed device, which makes sense from a security perspective but not so good from a productivity perspective.

Option 2: allow user to access using a thin client, for example OWA for email where the user enters the OWA URL into their browser and then their credentials, the email is stored on the server rather than on the client. The risk with this approach is:

  1. on a personal device many users do not use PIN or encrypt the device, anyone may be able to access the device if stolen
  2. user often saves the credential on their personal device so they don’t have to enter the password each time, this will also allow unauthorised users to see the previously browsed sites such as OWA.
  3. while Multifactor Authentication (MFA) can be enabled, if the smart phone is the 2nd factor, effectively the phone factor is bypassed when the same device is compromised.

Option 3: utilise Mobile Application Management (MAM). The security policy is applied at the application level instead of the device level. Data wipe will now be performed at the application level (AKA selective wipe). This will remove the corporate data while leaving the personal data intact.

MAM with Microsoft Intune allows a company to control:

  • cut/copy/paste restrictions
  • prevent “save as”
  • prevent cloud backup
  • jailbroken or rooted devices
  • PIN requirement
  • selective wipe of the application data

The screenshot below illustrates some of the security options available:


Some of MAM supported apps are show below, for the complete list go to Microsoft Intune Partners page.



To deploy Intune MAM, users will need either Intune or EMS licenses.

It is also possible to deploy both Intune MDM and MAM at the same time. A scenario for this is to allow corporate devices to be managed by MDM, and offering BYOD users a choice between MDM and MAM.

Microsoft TechNet has further information on Intune MAM

How you can protect app data

Create and deploy mobile app management policies with Microsoft Intune

End user experience



Taking Advantage of The (iOS 9) Universal Links on Xamarin iOS apps

What is Scheme URI?

In the context of mobile apps, Scheme URIs are used for communicating between mobile apps. Mobile developers can register a unique URI for each app in the application manifest (info.plist). The operating system would then use that to launch your application once the user clicks on a link that matches your uri. For instance, I could have my-cool-app:// as my scheme uri. I could then generate links (should start with my-cool-app://) to send in my email to my app’s users and once clicked, my app will be launched. These have become standard and they are widely supported on iOS, Windows, and Android.

What is Universal Links?

Universal Links is a new feature that was introduced by Apple in iOS 9. The idea is instead of registering a scheme Uri, you could use your own website domain name (which is inherently unique) and associate this domain name with your mobile app. Once the user clicks on a http/https link that links to your domain name, iOS would then launch your mobile application instead of opening the link in Safari. More details about Universal Links could be found in in this WWDC session and Apple’s official documentation.

Why Do we need Universal Links?

If you have used Scheme URIs before to open your mobile apps, you would know the pain of trying to keep your links valid to open your app (when installed) and fallback to the web links when your app is not installed. You would also know this was not a simple task, and there was no guarantee that this would work exactly the way you want. Therefore, Apple has introduced Universal Links, which is great. Imagine how many times you get a URL link via email and you click it to end up in a web browser asking you for username and password. Most people do not remember their accounts (at least not for all accounts), or they want to see this content on the mobile app instead of Safari. This new feature (Universal Links) solves this problem.

How Can we Enable Universal Links?

To enable Universal Links, you need to follow the following steps:

1. Enable “Associated Domains” on your Application Id (in Apple Developer portal).

Enable Associated Domains in your App Identifier settings - Apple Dev Portal

Enable Associated Domains in your App Identifier settings – Apple Dev Portal

2. Create an apple-app-site-association file on your domain. This is just a text file that contains a JSON object to describe your universal links. You could associate multiple link paths with multiple apps. Notice that your app id needs to have your full app identifier (TeamName.Appid). I’ve shown a sample of the JSON content below:

        “applinks”: {
            “apps”: [],
            “details”: [
                    “appID”: “ABC-Team-Id.com.my.bundle.id“,
                    “paths”: [ “/”, “*” ]

This file needs to be served over HTTPS and have no file extension – it must be named “apple-app-site-association”. Apple will try to retrieve this file from your domain before it launches your app for the first time. This is to verify the authenticity of your domain ownership before starting the app. If you are hosting this file on an Azure Web App, you might also need to add a static content mapping in your web.config.

The bottom line is you need to make sure that you can navigate to this file as https://your-domain.com/apple-app-site-association. There is also a small app that helps you verify your Apple association file, you could find it here. Do not worry about the last 2 errors that it displays concerning signing your file. I have my Universal Links work without signing the association file, but this web page is still good to verify other aspects of the association file.

3. Add the Universal Links Entitlement to your info.plist. This can be done very simply by navigating to your Entitlements.plist and add the new applinks as follows:

Applinks in Entitlments-plist file

Applinks in Entitlments-plist file

4. Regenerate your provisioning profiles. This is very important since we changed our app id entitlements. If you don’t do this you will get an error message when trying to build the app saying that you have entitlements that are not permitted by your provisioning profile.

5. OPTIONAL: Override ContinueUserActivity method in your app’s delegate to capture the URL link that the user clicked on. This is necessary when you want to take the user into the particular screen in your application. For instance, if the user clicked on a link to view a product on your website, you could capture the link in this method and once your app opens up, view the details of that product on your mobile app.

public override bool ContinueUserActivity (UIApplication application, 
     NSUserActivity userActivity, 
     UIApplicationRestorationHandler completionHandler)
	Console.WriteLine ("ContinueUserActivity method has been called...");
	// you can get the url that the user clicked on here.		
	return true;

Once all the above is done, you can build and deploy to your device. I have tested my implementation by creating a link to my associated domain and sent it via email to the device. When I click on the link, I get redirected to my app directly (without going through Safari).

Applinks in the mobile app - screenshot

Applinks in the mobile app – screenshot

Notice that Apple give the user the option to stay on my app, go directly the browser (upper right link) or go back to the email that launched my app. I really like this design because it keeps the user in charge. Also, there are few posts that suggest once the user taps on the link to go to the browser, Apple would then bypass your app for this link and take the user directly to the website in the future. I have not verified this but you could find the details on this Stackoverflow post.

How about devices that are still using older versions of iOS?

What we have seen above is very cool stuff and I have been hoping for this for years. However, this only solves the problem on a subset of devices. Remember there are still lots of devices out there that are not using iOS 9. If you are like me and are required to support iPhone 4, then you need to have a fallback mechanism for these devices. For this scenario, we could have simple JavaScript code that helps us redirect to our mobile app, if this redirection fails, then we assume that the app is not installed and we redirect the user to our web URL. A sample of this is below, and more details can be found on Stackoverflow:

// this could needs to sit in your website page
setTimeout(function() {
  window.location = "http://my-domain-app"; // or your could put  link to your app on iTunes
}, 25);

// If "my-cool-app://" is installed the app will launch immediately and the above
// timer won't fire. If it's not installed, you'll get an ugly "Cannot Open Page"
// dialogue prior to the App Store application launching
window.location = "my-cool-app://";


It will be very interesting to see how Apple will use this to integrate apps more with the web. Apple has already done a great work in terms of search and user activity that is bridging the gap between web and native apps. Universal Links is another step in the right direction.

How about Android?

Although most of the contents of this post is related to iOS, Android’s implementation is quite similar. Google introduced this in Android M and you can read more about it on the Android developer documentation site.

Handling Complex Object Persistence and Messaging on Mobile

Data persistence and messaging is a very common task that you almost certainly need in your apps. Mobile platforms have come a long way in supporting data persistence mostly through the SQLite engine which has become the standard on all mobile platforms. However, SQLite is (as it’s name suggests) a lightweight engine and does not offer as many features as a full RDBMS.

This should not be a problem on a mobile device where persisting data is intended mostly for caching until the data reaches its ultimate destination on a backend server. With this in mind, how do we go about persisting complex objects on a mobile platform? How do we handle complex objects messaging? This is exactly what I will discuss in this blog post. This is not an introduction on how to use an ORM (Object Relational Mapping) to store objects in a database, it is rather how to handle the complex relationships between a data object and its children or siblings when storing or messaging that piece of data.


I have been developing for mobile platforms for quite sometime and I have been really enjoying the use of SQLite.Net PCL. This is a very simple ORM built on top of SQLite.NET that adds support for PCLs (Portable Class Library). This library has made it very easy to store data in the database on a mobile device and it gives you a unified API on all platforms to do all data persistence related tasks. If you have not used this before, I would highly encourage you to have a look at it, and this blog post will assume the use of this framework for storing data locally.


If your mobile application is intended for building a to-do list, then it might not be a major issue if you loose a single entry here or there, or you simply resolve conflicting items by taking the latest one. I am saying this and knowing that you might loose some customers if you take this approach :).

However, what if your mobile app was being used for emergency management, or used by health practitioners? This makes it a requirement to pre-define the logic for how items are stored, and how conflicts are resolved, and you are required to always keep all bits of information on all devices. I had a similar requirement where I needed to maintain the versioning of all items and define how a conflict will be resolved. Thus, I decided to use versioning for my data objects. This design incorporates the following decisions:

  1. Any change will be applied to the data objects as a change log.
  2. Change logs are globally and uniquely identifiable via unique IDs.
  3. Data objects will have a VERSION attribute, which is unique. This VERSION attribute will refer to the most recent Change Log Id.
  4. Each data object will have a list of Change Logs in an ordered list. The ordering of these logs represents the timeline of when these change logs were applied.
  5. For the sake of simplicity, we will assume that a data object has a list of properties/attributes that will be represented as table of key/value pairs.
  6. Other decisions/assumptions of the design will be ignored for the sake of this blog post. Such decision could include storing the type of change logs (changes created by a user, a result of data merge, etc), storing other security (authentication/authorisation) data on each data item, storing other metadata on each data object such as who changed what and when.

With that in mind, our data object diagram will look something like the following:

UML Diagram of our basic Item (versioning) design

UML Diagram of our basic Item (versioning) design

Enforcing Version-based Changes

Now that we have put together our basic design, we need to implement it in a way that is safe for a team of developers to work on. We cannot assume asking team members “hey, can you please use this method when you try to apply some changes? because it is necessary”, think that would work? :). I know you’re probably thinking this is absurd, but I have seen this sort of behaviour in some teams. If they do not say it this way, they would rely on comments in the code or other wiki/documentation to enforce the design logic. My approach is to make it fool-proof and to let the design document itself. I should not be required to explain this for people. Developers (my team members) should be able to use this without worrying about the internal implementation. So to do that we need the following:

1. Read Only Properties

To ensure that we are not going to change any property of our data object without using change logs, properties need to be read-only. This ensures that we cannot create a new version of the item without either using the applyChangeLog(log) method or using a constructor.

2. Fully defined constructor(s)

We cannot provide a constructor that would allow the consumer of our framework to create/instantiate a data object without specifying all its attributes. Therefore, our constructors should define all properties of an object at creation time.

3. Easy composition

Our framework needs to have an easy way to construct objects from a serialised version or from another version of the item. This is necessary when storing these data objects to the database or when trying to message them over the network.

With all that out of the way, our basic object implementation could look something like this:

  // our change log first
  public class ChangeLog 
     public string Id {get;set;}
     public int Order {get;set;}
     public string CreatedBy {get;set;}
     public ChangeLogType Type {get;set;}
     public DateTime CreatedOn {get;set;}
     public string ParentId { get; set; }
     public Dictionary<string, object> ChangingAttributes {get;set;}

   public class RegisterItem : ModelBase
     public RegisterItem (string id, string name) 
             : this(id, name, string.Empty, new Dictionary<string,object>(), new List<ChangeLog>())

     public RegisterItem (string id, string name, 
                          string version, Dictionary<string, object> attributes, List<ChangeLog> changeLogs)
        Id = id;
        name = name;
        _version = version;
        _attributes = attributes;
        _changeLogs = changeLogs;

     // This is needed for the internal use (serialisation/De-serialisation, and db storage).
     // Bcoz this ctor is Obsolete, it will through a warning and the warn will be escalated to an error if used.     
     [Obsolete("This ctor is only for the deserialiser and the db layer. Use other ctor with full params")]
     public RegisterItem ()

     public string Version { get {return _version;} private set { _version = value;}  }
     private string _version {get; set;}

     public string Name { get{ return _name; } private set { _name = value;}  }
     private string _name { get; set; }

     public List<ChangeLog> ChangeLogs { get { return _changeLogs; } private set { _changeLogs = value;}  }
     private List<ChangeLog> _changeLogs { get; set; }

     public Dictionary<string, object> Attributes {get{return _attributes; } private set { _attributes = value;}}
     private Dictionary<string, object> _attributes { get; set;}

So far so good!

Thus far we have implemented our data objects with its basic versioning its children objects. Now the question is how do we store this in the database and how to serialise/deserialise the object to send it over the network. This is actually the second tricky part 🙂 because if you have worked with SQLite.Net before you would know that it is designed to enable mobile developers to store simple objects and basic typed attributes to the database. For our scenario, we have complex objects with children objects and other complex attributes (Dictionary).

Storing in the SQLite database

Our database will store basic information about the data objects (name, id, version) along with a full copy of the object that is serialised to a basic type like string (or could be a binary if you like). To make this smooth and simple to our consumers (developers who use this api), we added a property to the data object that is called AsJson. This property will serialise and store the full copy of the object when the object is stored to the database, and when the object is constructed from its basic attributes, it will populate the other properties (like children objects and other complex properties (ie Dictionary). A simple implementation of this property could be something like this:

public string AsJson 
     var json = MySerialiser.ToJson(this);
     return json;
     var json = value;
     if (!string.IsNullOrEmpty(json))
         var originalObject = MySerialiser.LoadFromJson<RegisterItem>(json);
         if (originalObject != null)
            //We could use something like AutoMapper here
            _changeLogs = originalObject.ChangeLogs;
            _attributes = originalObject.Attributes;

As you can see the property itself (AsJson) is ignored when serialising to JSON. Plus, our developers would not need to do anything when storing to or pulling from the database. Our AsJson property would do the work and get our items saved/constructed to/from the database. Also, notice how we had the [Ignore] attribute on our complex children objects. This belongs to our ORM (SQLite.Net) which will be understood as no need to store these objects to the database.


A couple of months ago, I gave a talk at DDD Melbourne regarding messaging in Peer-2-Peer scenarios on mobile devices, you can find the slides deck here. And for this exact project, I needed to be able to serialise/deserialise my data object to send them over my P2P connections. This has been made much easier by the property that we discussed earlier which is called AsJson. The only tricky part is that when serialising, you need to modify the default settings of your JSON serialiser as it needs to be able to serialise/deserialise private properties of the data objects. Assuming that we use something like Newtowonsoft.Json, our serialiser will be something like this:

   var resolver = new PrivateSetterContractResolver();
   var settings = new JsonSerializerSettings{ ContractResolver = resolver };
   var obj = JsonConvert.DeserializeObject<T>(input, settings);

And that’s it. Hope you find this useful and you have picked a few ideas on how to handle storing and messaging of complex data objects on the mobile. If you have a question, comments, or maybe a suggestion to do things in a different/better way, I would love to hear from you, so get in touch.

Azure Applications Insights for Xamarin iOS

Azure Application Insights (AI) is a great instrumentation tool that can help you learn about how your application is doing during run-time. It is currently in Preview mode, so bear that in mind when developing production ready apps. It gives you the ability to log lots of different kinds of information like tracing, page views, custom events, metrics and more.

Azure AI supports multiple platforms, but unfortunately they have not released a Xamarin package yet. There is one library which is for Xamarin.Forms since it uses the DependencyResolver. I have taken that and removed that dependency to make it compatible with Xamarin.iOS. You could do the same thing to use it for Xamarin.Android too if you like.

It’s very simple to use, all you need is your instrumentationkey which you can get from your Azure portal. Follow the steps from the MSDN tutorial as you can see here to create the Azure AI instance and get your key. Once done, you could download and reference the repository that I have created on GitHub, as you can find it here.

To start Azure AI on your Xamarin iOS app, you could do:




The implementation of the AzureAIManager is as follows:

	public static class AzureAIManager
		public static void Setup(string appKey = "your-azure-AI-instrumentation-key")

			var ai = new AI.Xamarin.iOS.ApplicationInsights ();
			ApplicationInsights.Init (ai);

			TelemetryManager.Init(new AI.Xamarin.iOS.TelemetryManager());


		public static void Start()

		public static void Configure(string userId = "" )

			if (string.IsNullOrEmpty(userId))

		public static void RenewSession()

I have not put this as a Nuget package because I am sure Microsoft will release one very soon, so until that happens, you can use this bindings to play around with Azure AI and you could even use it on your small projects.

Sharing HTTP sessions between WebView requests and HttpClient on Windows Phone


I have been working on a hybrid mobile application that requires displaying/containing a few mobile apps in a WebView control. In the background, some HTTP requests need to go through to collect data and do further processing. We need to maintain the same session in all of the web requests going through the mobile app. This means all web (HTTP) requests originated by the Webview as well as our background (HttpClient) requests need to share cookies, cache, etc. So how can we achieve this?


HttpClient has become the go-to class for all things HTTP, especially with the support of HttpClient in PCLs (Portable Class Library), who can resist it? So my first thought when I considered this requirement was to use HttpClient with a HttpClientHandler, preserve the session cookies, and share them with the WebView. I started my initial research, and I found that somebody has done exactly that, you can find it here. This gave me some more confidence for a successful solution.

This first approach would mean using HttpClient (along with a HttpClientHandler) to hold cookies and share them with the WebView. However, this would be error-prone because I will need to continuously monitor both cookies and update the other group of requests. Plus, sharing the data cache between the WebView and HttpClient would still be an issue that I was not sure how to address.


Before going further, I thought I would look for an alternative, and I found Windows.Web.HttpClient. This one seemed very similar to System.Net.Http.HttpClient, but the implementation is quite different, regardless of the exact matching of the name :). I found this video (below) from Microsoft’s //Build conference that refers to this different implementation of HttpClient for Windows specific development.

Five Great Reasons to Use the New HttpClient API to Connect to Web Services

Five Great Reasons to Use the New HttpClient API to Connect to Web Services

Apparently the Windows implementation of HttpClient gives you the ability customise all aspects your HTTP requests. The video above lists the following five reasons why you should use Windows.Web.HttpClient:

  1. Shared Cookies, Cache, and Credentials
  2. Strongly Typed headers => fewer bugs
  3. Access to Cookies and Shared Cookies
  4. Control over Cache and Shared Cache
  5. Inject your code modules into the processing pipe-line => cleaner integration.

When I read the first statement above, I really thought that this is too good to be true :), just exactly what I am looking for. So I decided to give it a go. As you can see some of the features listed for this HttpClient (Windows implementation) are similar to what we have in the System.Net world, but this gives us extra capabilities.

HttpClientHandlers vs HttpBaseProtocolFilter

It is worth mentioning that Windows.Web library does not have HttpClientHandlers that we are familiar with in System.Net, instead it gives you the ability do more with HttpBaseProtocolFilter, and this is a key point. HttpBaseProtocolFilter enables developers to customise/manipulate HTTP requests (headers, cookies, cache, etc) and the changes will be applied across the board in your application. This applies whether you are making a HTTP request programmatically using HttpClient or via the user interface (using a WebView for instance).

Code Time

  // creating the filter
  var myFilter = new HttpBaseProtocolFilter();
  myFilter.AllowAutoRedirect = true;
  myFilter.CacheControl.ReadBehavior = HttpCacheReadBehavior.Default;
  myFilter.CacheControl.WriteBehavior = HttpCacheWriteBehavior.Default;

  // get a reference to the cookieManager (this applies to all requests)
  var cookieManager = myFilter.CookieManager;

  // make the httpRequest
  using (var client = new HttpClient()) 
     HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, "your-url-address"); 
     // add any request-specific headers here
     // more code been omitted

     var result = await client.SendRequestAsync(request);

     var content = await result.Content.ReadAsStringAsync();

     // now we can do whatever we need with the html content we got here 🙂
     // Debug.WriteLine(content);

  // assuming that the previous request created a session (set cookies, cached some data, etc)
  // subsequent requests in the webview will share this data
  myWebView.Navigate(new Uri("your-url-address"));

Hopefully this short code snippet gives you a good idea of what you can do with Windows Implementation of HttpClient. Notice that myWebView automatically shares the CookieManager implicitly.

Other Apps?

One might ask about how will this impact other apps? It doesn’t. The Windows.Web library was designed to work across all requests in one app. Therefore, you do not need to be concerned about impacting other apps or leaking your data to other external requests.


Someone wise once said “with great power, comes great responsibility”. This should be remembered when using HttpBaseProtocolFilter with your HTTP requests as it can (as mentioned above) impact all your subsequent requests. Hope you find this useful and I would love to hear your comments and feedback.


Azure MFA Server – International Deployment

Hi all – this blog will cover off some information to assist with multilingual/international deployment of Azure MFA server. There are some nuances of the product that make ongoing management of language preferences a little challenging. Also some MFA Methods are preferable to others in international scenarios due to carrier variances.

Language Preferences

Ideally when a user is on-boarded, their language preferences for the various MFA Methods should be configured to their native language. This can easily be achieved using MFA Server, however there are some things to know:

  1. Language settings are defined in in Synchronisation Items.
  2. Synchronisation Items can be set in a hierarchy so that settings in the most precedent Synchronisation Item apply.
  3. Language settings set explicitly in Synchronisation Items apply at FIRST SYNC ONLY. Adding, removing or changing Sync Items with explicitly set language configurations will have no effect on existing MFA Server users.

I’ll cover off how to get around item 3 a bit later with non-explicitly configured language settings. To demonstrate hierarchical application of Sync items – first create two Sync Items with different explicitly set language settings as below. I’ve used Active directory OUs to differentiate user locations, however AD security groups can be used too, as can an LDAP filter:

Add Synchronization Item Dialog - Australia

Add Synchronization Item Dialog - Italy

Then set them in the required hierarchy, in this case our default language is English for the Aussies, then we have an overriding Sync Item for the Italians – easy:

Multi-Factor Authentication Server - Syncrhonization tab

The above is all well and good if you are 100% guaranteed that users will be in the correct OU, group, or have the user filter apply when MFA server synchronises. If they are subsequently modified and a different Sync Item now applies, their language settings will not be updated. I’ll now cover how to get around this next.

Use of Language Attributes to control Language Settings

MFA Server has the option to specify a language attribute in user accounts to contain the short code (e.g. en = English) for language preferences. When the account is imported, the user’s default language can be set based on this attribute. Also unlike explicitly configured language settings, when a Sync Item is configured to use language attributes it will update existing users if the language short code in their account changes.

To use this feature, first define an AD attribute that stores the language short code within the Attributes tab in the Directory Integration. Shown below I’m using an AD Extension attribute to store this code:

Multi-Factor Authentication Server - setting Attributes

Then create a Sync Item that covers all your users, and configure “(use language attribute)” instead of explicitly setting a language – it’s the last item on the list of languages so unless you’re Zulu it’s easy to miss. By the way, those are the short codes for the language attribute for each language listed in this drop down list. Once user accounts have been configured with the language short code in the specified attribute, on next sync their language will be updated.

Edit Synchronization Item Dialog

Other Stuff to Keep in Mind

When dealing with international phone carriers, not all are created equal. Unfortunately, Microsoft has little control over what happens to messages once they’re sent from Azure MFA Services. Some issues that have been experienced:

  1. Carriers not accepting two way SMS, thus MFA requests time out as user One Time Password responses are not processed.
  2. Carriers not accepting the keypad response for Phone call MFA, again resulting in MFA request time out.
  3. Carriers spamming users immediately after SMS MFA has been sent to users.
  4. Users being charged international SMS rates for two-way SMS (makes sense, but often forgotten).

In my experience SMS has proven to be the least reliable, unless the Mobile MFA App/OATH can be used Phone is the better method for International users.

Often overlooked is the ability to export and import user settings using the MFA Server Console. You can export by selecting File/Export within the console. The CSV can then be updated and re-imported – this will modify existing user accounts including MFA Method preference and language defaults.

One Last Thing

For Apple iPhone users, Notifications must be enabled for the MFA Mobile App as the App will fail to activate with a timeout error if Notifications are disabled. Notifications can be enabled in iOS via navigating to Settings/Notifications/Mulit-Factor and enabling “Allow Notifications”. Changing this setting can take a little while to apply, so if the Mobile App still does’t activate after enabling Notifications, wait a bit then try again.

Let’s Hack It: Securing data on the mobile, the what, why, and how

Our solution to secure the mobile app data

Our solution to secure the mobile app data. It uses open source libraries and took a very minimal effort to implement

Here is the presentation of tonight’s talk. It was great to see so many passionate developers and business people at Melbourne Mobile. I have embedded the slides below and I hope you find it useful.

Talk Summary

This presentation is basically a summary of what I have learned and the experience I have had going through my recent project. In trying to secure the users data on the mobile device, I have come to learn quite few common flaws in the security implementation, I have learned more reasons why you need to protect the data on your mobile app, and have come to know and use few useful open source projects. I share my experience from this project hoping that it would help you gain some insight and protect your mobile app data easily.

I said in the presentation that you could start securing the app data by a couple of lines of code and I do mean it. In fact, if you use SQLCipher, then you could do that by only changing one line of code :). I have put the links to all my reference and the libraries I have used at the end of the slides.

Let's Hack It Presentation

Let’s Hack It Presentation

Finally, just in case you do not like Prezi, here is the slides as a PDF file:
Let’s Hack It, the presentation as PDF

Announcing KeyChain.NET: a unified API for using KeyChain on many platforms

Storing and accessing private keys and passwords can be a tricky task. How far do you need to go to protect your (and the user’s) data? This is where KeyChain on iOS comes in handy. It allows you to store keys in a (arguably) secure database. This has seen great improvements since iOS 8 and iOS devices (since iPhone 5S) equipped with a special A7 chip designed particularly for holding your keys. More on iOS KeyChain can be found on Apple’s website here. Android, on the other side has its KeyStore, which also gives you some level of protection, but leaves a major part of the implementation to your (the developer). Details of Android KeyStore can be found on Android SDK here.

While working on recent projects, I found myself needing to have a unified way of accessing the KeyChain on both platforms. I implemented the generic library and it’s been working very well, so I thought it would be nice to share the love with the community, so here it comes 🙂

KeyChain.Net offers developers a unified, simple-to-use api for storing, accessing, and deleting keys from the keyChain (or KeyStore). It also offers further customisation capabilities based on what the platform supports. For instance, iOS KeyChain supports seamless sync (of your private keys) with other iOS devices using iCloud. This can be achieved using KeyChain.Net by turning ON the autoSyncToiCloud setting.

The package is open source and it is hosted on GitHub here. Currently, I am supporting Xamarin iOS and Xamarin Android. I might add Windows Phone depending on the feedback I get.

Keychain nuget package

Keychain nuget package

The library can be found on Nuget here. I have put some sample code on the read.me file on GitHub, and you could also look at the unit tests for information on how to use it. Tests are also available on Github.

Feel free to fork the repo on github and use it in any way you like or simply pull the nuget package to your project and enjoy it :). I would appreciate all feedback and if you have any issues or feature requests then please log them on Github.