Thursday, June 2, 2016

Web Services made easy with HttpClient & JSON.NET

I have intended to write this for a while. As a Sales Engineer for Xamarin, and now Microsoft, I go through a lot of the same scenarios when working with companies to get up and running with Xamarin and mobile development. As one example, there is almost a 99% guarantee that the first apps these companies plan to build will communicate with an external data source in some way, almost always using web services.

Now, there is a high likelihood this is not a new topic to those who read this blog, but as a believer in the "Lucky 10,000" from xkcd, I figure this information is still worth sharing. To those of you who were unaware of today's content, congrats as you are one of the lucky 10,000 today! What I have to share should make your mobile journey all the easier.

Now it should be noted that I recognize web services are a broad topic, lots of solutions out there. One quick hop over to the Xamarin documentation alone lists a few:

The main three built into the Xamarin tooling are on consuming RESTful, SOAP and WCF services. For the remainder of this post I will focus on REST as I find it to be the most straightforward to consume.

Consuming REST services really falls down to two main parts. Consumption of the service itself, and then consumption of the data received. As you likely have guessed, there are two tools available to help make this process much more straightforward. For the service, Microsoft's HTTP Client libraries and for the data, JSON.NET. When combined, it can be as simple as three lines of code to communicate with an external service and acquire data. Below is a sample of what that code would look like:

var httpClient = new HttpClient ();
var json = await httpClient.GetStringAsync ($"");
var result = JsonConvert.DeserializeObject (json);

What you see above is both parts. Line one creates the HttpClient followed by actually making a REST call to grab you data. The third line is part two, parsing the resulting json into something more C# readable. If you have not used JSON.NET before, it really is something of magic under the hood. Basically, all you need to do is provide it a valid json file, and then pass a constructed C# object for it to parse into. In the above example, it will try to parse your json into the class "MY_DATA_OBJECT". 

To use a more "practical" example, I am a big fan of Blizzard games and recently wrote an app to play with some of the community API's available, found here The main goal was to just do a bit of poking and write a simple Warcraft character display app. Nothing complex, make some calls to load character data, item sets, etc. In  order to grab the basic character profile in my app, I have the following code:

var httpClient = new HttpClient (new NativeMessageHandler ());
var json = await httpClient.GetStringAsync ($"{
Constants.APIKEY}" );

var res = JsonConvert.DeserializeObject (json); 

In this case, I am pulling the data for my Paladin, Deaus, from the Muradin server. The resulting JSON looked like this:

     "lastModified": 1426370270000,
     "name": "Deaus",
     "realm": "Muradin",
     "battlegroup": "Vengeance",
     "class": 2,
     "race": 3,
     "gender": 0,
     "level": 100,
     "achievementPoints": 7620,
     "thumbnail": "muradin/10/119640842-avatar.jpg",
     "calcClass": "b",
     "faction": 0,
     "totalHonorableKills": 1961

On the C# side, I would create a class called CharData which would look something like this:

public class CharData
    public long lastModified { get; set; }
    public string name { get; set; }
    public string realm { get; set; }
    public string battlegroup { get; set; }
    public int class { get; set; }
    public int race { get; set; }
    public int gender { get; set; }
    public int level { get; set; }
    public int achievementPoints { get; set; }
    public string thumbnail { get; set; }
    public string calcClass { get; set; }
    public int faction { get; set; }
    public int totalHonorableKills { get; set; }

JSON.NET does the rest of the work, taking advantage of the json tags and matching them to the appropriate C# properties, and instantiates/populates my data for me. The best part of all of this? All of this is PCL compliant so it is located 100% inside my shared code!

One useful tool to expedite the process even more is the website This website will take json data and auto generate the resulting C# class for you, at least at a base level.

As a note, not all REST end points are so easily configured, but HttpClient is actually quite flexible. I was also recently poking around a community made Hearthstone API,, and their .NET API's are powered through unirest ( To get this to work I had to add a couple of DefaultRequestHeader paramters to match the documentation there. Still, rather straight forward to communicate with.

That is about it. While this does put some requirement to set up good REST endpoints for your mobile applications, it tends to be worth the effort. Even if you have legacy WCF systems or complicated back ends, I have found that companies that have made exposed REST front ends to facilitate the communication can help streamline the entire process and, as you see above, can really make consumption on the mobile side quite easy. Until next time!

Monday, May 16, 2016

Complete Mobile Dev Ops with Visual Studio Team Services and Xamarin Test Cloud

Wow it has been over six months. Sorry! As you can imagine, things have been busy in 2016. There has been an acquisition, Xamarin tools made available for free in Visual Studio, and then Xamarin Evolve. Now that things have settled down, and integration into Microsoft underway, I wanted to take this as an opportunity to get back to making semi-regular posts once more.

When I joined Xamarin in December of 2013, it was still largely a one product company. Xamarin enabled you to develop apps for Android, iOS, or Mac using C#. (OK, technically three products but to a degree you can look at them as different facets of the same tool).

Since that point Xamarin has grown to help assist in the full mobile development lifecycle. This included the launch of Xamarin University for training, Xamarin Test Cloud for better testing and Xamarin Inisghts for crash reporting, messaging and analytics. With Xamarin now under the Microsoft umbrella, a few new tools are available to even further complete that picture. The focus of this entry will be on how to leverage Visual Studio Team Services with Xamarin, both development and Xamarin Test Cloud, to create a full Dev-Test-Publish lifecycle.

Getting setup with Visual Studio Team Services
I won't spend a whole lot of time on this. The basic checklist can be found below.

1. Create your VSTS account
2. Create your Project
3. Connect to Visual Studio
4. Set up your repo and code

The main setup guide hub can be found here:

For my scenario, I ended up using git as my repository, which would also be my recommendation if you don't have a previous requirement or preference.

Integrating Xamarin Test Cloud
Now that you have your code integrated with VSTS, and uploaded, the next step is to create a build process that confirms your build and also calls to Xamarin Test Cloud for regression testing. That way, any time a developer on your team submits their code, you can confirm everything is still working. Please note, this will require having created a UITest project and at least one step to run. If you have not ever done this, you can find more details here:

Now, the final piece of this puzzle is to integrate this as part of your VSTS build chain. Microsoft actually made this process quite straight forward, once I had my head wrapped around the tooling. A full general doc, found after I got it sorted myself, can be found here:

This is what I wanted to break down and guide in more detail. First, select the Build tab in the VSTS portal and hit the green "+" button:

This will create a new dialog window. This is where you will select your build type. For our example we will use Xamarin.Android template. If you need iOS, you would match this process with iOS.

So many options
From here you can use the default settings, you want to select your Repository in question so that it uses this code for the build. If you notice in my example, I have "Continuous integration" selected. I recommend this if possible as it will allow you to run these tests whenever code is submitted to the branch.

Once you hit create, you are then resented with a dialog to configure the specific build settings. There are a three steps that require input:

But it can be boiled down to
1. Your license login (user name and password) information to activate\deactivate your Xamarin credentials
2. Xamarin Test Cloud API Key, Device ID, Test Cloud email

As a pro-tip for the password, the password field defaults to a plain text entry. What I would recommend is select the variables tab, and add your password as a variable, with the lock icon selected to flag it as "Secret".
MyPassword is the variable I have created.
Then in the password field you just use that variable with the syntax $(_VARNAME_). Much more secure than plain text usage.

For the "Test" step, you need to provide a few pieces of information.

First is your Test Cloud API Key, which is found under Teams and Organizations on your Test Cloud account. You can find details on obtaining that here:
If you are not currently using Xamarin Test Cloud, fear not! We have a free trial that you can try out. More details can be found here:

Again, you need to provide an email, this time the email of registered/added to the Test Cloud account. This may or may not differ from your Xamarin license details.

The devices ID you can acquire when you create an upload on Xamarin Test Cloud. The final step will give you a command line prompt that can be used for Windows or OSX and included is a --devices (#########) flag. This id is the final piece of information as it tells Test Cloud what devices the test needs to be run on, and can be reused from run to run. I would recommend recording these ID's as currently there is not another way to retrieve them to my knowledge.

Once you have entered all this information you have everything you need. At this point I would recommend selecting "Queue build" to do a test run with what you have uploaded, troubleshoot issues as needed. Ideally you should see this:
Green is good!
That's it! You have made your first step into a larger world of end to end mobile development and more efficient DevOps! Now, any time you submit code from git, this build step will be executed and you are on your way to writing higher quality code. Use this to make sure you are keeping your app at a high quality, and catch bugs and regressions before your users do!