Stretchy UITableView Headers with Xamarin

The Yahoo News Digest app includes a couple of interesting user interface elements that I wanted to use within my own apps. The feature that I was most keen to recreate was the stretching UITableViewHeader. Its an effect seen in lots of iOS (sometimes referred to as a parallax header). As Beer Drinkin is going to support multi-tasking on iOS, I needed to ensure my implementation continues to support Storyboards and Auto Layout. Fortunately it proved very simple to get everything setup. In this blog post I’ll be sharing how I went about implementing it


Setting up the Storyboard

Adding a header view

To get started I opened my existing Storyboard and selected the UIViewController that requires the tableview header. In my case the scene (or view controller) isn’t a UITableViewController because I require a floating ‘Check in’ button to be visible at all times. Its worth noting that all the steps in the tutorial work with both UITableViewControllers and UIViewControllers.

Screen Shot 2016-02-01 at 11.36.06

Once I had the storyboard loaded, I dragged a UIView from the toolbox and made sure to insert it above the UITableViewCells as a the header view for the table. I then added a UIImageView to the new UIView and set its constraints to be 0,0,0,0. This way when the parent view (the UIView) resizes, the UIImageView will resize as well. I also made sure to set the UIImageView view mode property to Aspect Fit, which makes sure the image looks great no matter what size the view.

Screen Shot 2016-02-01 at 11.39.13

Adding some C#

Adding the resize code

If I were to have run this now, the table header would be displayed but wouldn’t resize with scroll events. To add scaling, I needed to add a code into my ViewController to setup the stretchy goodness that I wanted.

Because I use the header views height in a number of locations throughout the beer description view controller, I went ahead and created a variable rather than scattering magic numbers over my class.

private nfloat headerViewHeight = 200;

Managing the header view

To allow me to manage the table header, I needed to remove it from the UITableView and keep it as a variable for use later. To do this I created a variable in the beer description view controller.

private UIView headerView;

When we load the view controller, we’ll want to set our headerView variable and then set the UITableViews header property to null. This means the tableview has no header view to manage anymore, instead I’ve taken control of the view which allows me to ensure it resizes correctly as the table view scrolls.Despite having just removed the header view from the UITableView, I actually want to go ahead and add it to the table view hierarchy (but not as the header view property of the UITableView)

 headerView = tableView.TableHeaderView;
 tableView.TableHeaderView = null;
 tableView.AddSubview (headerView);
 tableView.ContentInset = new UIEdgeInsets (headerViewHeight, 0, 0, 0);
 tableView.BackgroundColor = UIColor.Clear;

Listening to TableViewDidScroll

In order to successfully respond to the DidScroll event of the UITableViewSource, I’ll need to create an event in the table views delegate. This is because of an issue with the UITableView DidScroll event not firing when a delegate has been set.

public override void Scrolled (UIScrollView scrollView)
    DidScroll ();

public event DidScrollEventHandler DidScroll;

We can now hook up the table DidScroll event with a small piece of logic for resizing the view.

//Update Tableview
tableView.Source = new BeerDescriptionDataSource(ref cells);
var deleg = new DescriptionDelegate (ref cells);
deleg.DidScroll += UpdateHeaderView;
tableView.Delegate = deleg;

tableView.ReloadData ();
View.SetNeedsDisplay ();
void UpdateHeaderView ()
    var headerRect = new CGRect (0, -headerViewHeight, tableView.Frame.Width, headerViewHeight);
    if (tableView.ContentOffset.Y < -headerViewHeight)
        headerRect.Location = new CGPoint (headerRect.Location.X, tableView.ContentOffset.Y);
        headerRect.Size = new CGSize (headerRect.Size.Width, -tableView.ContentOffset.Y);
    headerView.Frame = headerRect;


Its very easy to use this approach to add resizing animations to any number of controls within your UITableView. My favourite part of this solution is that it works perfectly across all iOS devices and doesn’t force me to drop support of Autolayout.

Creating a 5 star search experience

Search is a feature that can make or break your mobile app, but it can be incredibly difficult to get right. In this blog post, I’m going to share how I’m solving search with Beer Drinkin.

There are many options for us developers looking to implement search solutions into our projects. Some of us may decide to use Linq and Entity Framework to look through a table, and the more adventurous may opt to create an instance of Elastic Search, which requires a lot of work to set up and maintain. For Beer Drinkin, I’m using Microsoft’s Azure Search service as it has proved to be easy to configure and requires zero maintenance.

The reason that Beer Drinkin uses Azure Search is simple: the BreweryDB search functionality is too limited for my needs. One example of this is that the end point often returns zero results if the user misspells a search term. If I searched for “Duval” rather than “Duvel,” BreweryDB’s search would return zero beers. Even if I were to spell the search term correctly, BreweryDB would return all beers from the Duvel Moortgat brewery. Although this is minor, I would prefer that Maredsous 6 and Vedett Extra White not be returned as these do not have “Duvel” in the name.

Screen Shot 2015-12-21 at 15.36.14

Spelling Mistakes

Another issue with using the default search functionality of BreweryDB is its inability to deal with spelling mistakes or offer suggestions. Simple off-by-one-letter spelling mistakes yield no results, something that should be easy to resolve.

Screen Shot 2015-12-21 at 15.40.40

I’ve had sleepless nights worrying that on release, users fail to find results due to simple spelling mistakes. One way to address spelling mistakes is to utilize a spell checking service like

The issue with a service such as WebSpellChecker is that it has no context in which to make corrections when it comes to names of products and it also doesn’t support multiple languages.

Another way to minimize spelling mistakes is to provide a list of suggestions as the user types in a search query. You’re probably familiar with this in search engines like Google and Bing. This approach to searching is intuitive to users and significantly reduces the number of spelling mistakes.

Enter Azure Search

Azure Search aims to remove the complexity of providing advanced search functionality by offering a service that does the heavy lifting for implementing a modern and feature-rich search solution. Microsoft handles all the infrastructure required to scale as it gains more users and indexes more data. Not to mention that Azure Search supports 50 languages, which use technologies from multiple teams within Microsoft (such as Office and Bing). What this equates to is Azure Search understands the languages and words of the search requests.

Some of my favorite features

Fuzzy search – Find strings that match a pattern approximately.

Proximity search – Geospatial queries. Find search targets within a certain distance of a particular point.

Term boosting –  Boosting allows me to promote results based on rules I create. One example might be to boost old stock or discounted items.

Getting Started

The first step I took was to provision an Azure Search service within the Azure Portal. I had two options for setting up the service; I could have opted for a free tier or have paid for dedicated resources. The free tier offers up to 10,000 documents and 50MB storage, which is a little limited for what I need.

Because my index already contains over 50,000 beers, I had no option but to opt for the Standard S1 service, which comes at a cool $250 per month (for Europeans, that’s €211). With the fee comes a lot more power with the use of dedicated resources, and I’m able to store 25GB of data. When paying for Search, you’ll be able to scale out to 36 units, which provides plenty of room to grow.

Creating an index

Before I could take advantage of Azure Search, I needed to upload my data to be indexed. Fortunately, with the .NET SDK the Azure Search team provides, it’s exceptionally easy to interact with the service. Using the .NET library I wrote a few weeks ago, which calls BreweryDB, I was able to iterate quickly through each page of beer results and upload them in blocks to the search service.

Screen Shot 2016-01-04 at 10.18.02.png

Uploading documents

Parallel.For(1, totalPageCount, new ParallelOptions {MaxDegreeOfParallelism = 25}, index =>
    var response = client.Beers.GetAll(index).Result;
    var beersToAdd = new List();
    foreach (var beer in response.Data)
        var indexedBeer = new IndexedBeer
            Id = beer.Id,
            Name = beer.Name,
            Description = beer.Description,
            BreweryDbId = beer.Id,
            BreweryId = beer?.Breweries?.FirstOrDefault()?.Id,
            BreweryName = beer?.Breweries?.FirstOrDefault()?.Name,
            AvailableId = beer.AvailableId.ToString(),
            GlassId = beer.GlasswareId.ToString(),
            Abv = beer.Abv

         if (beer.Labels != null)
            indexedBeer.Images = new[] {beer.Labels.Icon, beer.Labels.Medium, beer.Labels.Large};

    Console.Write( $"\rAdded {beersToAdd.Count} beers to Index | Page {processedPageCount} of {totalPageCount}");

Other data import methods

Azure Search also supports the ability to index data stored in Azure SQL or DocumentDB, which enables you to point a crawler to your SQL table and ensures it is always up to date rather than requiring you to manually manage the document index yourself. There are a few reasons you may not want to use a crawler. The best reason for not using a crawler is that it introduces the possibility of a delay between your DB changing and your search index reflecting the changes. The crawler will only crawl on a schedule, which results in an out-of-data index.

If you opt for the self-managed approach, you can add, remove, and edit your indexed documents yourself as the changes happen in your back end. This provides you with live search results as you know the data is always up to date. Using the crawler is an excellent way to get started with search and quickly get some data in place, but I wouldn’t consider it a good strategy for long-term use.

I mentioned earlier that the free tier is limited to 10,000 documents, which translates to 10,000 rows in a table. If your table has more than 10,000 rows, then you’ll need to purchase the Standard S1 tier.


Before we can use suggestions, we’ll need to ensure that we’ve created a suggester within Azure.

Screen Shot 2016-01-04 at 10.27.15.png

In the current service release, there is support for limited index schema updates. Any schema updates that would require re-indexing, such as changing field types, are not currently supported. Although existing fields cannot be modified or deleted, new fields can be added to an existing index at any time.

If you’ve not checked the suggester checkbox at the time of creating a field, then you’ll need to create a secondary field as Azure Search doesn’t currently support editing the fields. The Azure Search team recommends that you create new fields if you require a change in functionality.

The simplest way to get suggestions would use the following API.

var response = await indexClient.Documents.SuggestAsync(searchBar.Text, "nameSuggester");
foreach(var r in response)

Having fun with the suggestion API

The API suggestion provides properties for enabling fuzzing matching and hit highlighting. Let’s see how we might enable that functionality within our app.

var suggestParameters = new SuggestParameters();
suggestParameters.UseFuzzyMatching = true;
suggestParameters.Top = 25;
suggestParameters.HighlightPreTag = "[";
suggestParameters.HighlightPostTag = "]";
suggestParameters.MinimumCoverage = 100;

What do the properties do?

UseFuzzyMatching – The query will find suggestions even if there’s a substituted or missing character in the search text. While this provides a better search experiance, it comes at the cost of slower operations and consumes more resources.

Top – Number of suggestions to retreive. It must be a number between 1 and 100, with its default to to 5.

HightlightPreTag – Gets or sets the tag that is prepended to hit highlights. It MUST be set with a post tag.

HightlightPostTag – Gets or sets the tag that is prepended to hit highlights. It MUST be set with a pre tag.

MinimumCoverage – Represents the precentage of the index that must be covered by a suggestion query in order for the query to be reported a sucess. The default is 80%.

How do the results look?

Simulator Screen Shot 4 Jan 2016, 10.39.25.png


The Search API itself is even easier (assuming we don’t use filtering, which is a topic for another day).

var searchParameters = new SearchParameters() { SearchMode = SearchMode.All };

indexClient.Documents.SearchAsync(searchBar.Text, searchParameters);

Special Thanks

I’d like to take a moment to thank Janusz Lembicz for helping me get started with Azure Search suggestions by answering all my questions. I  appreciate your support (especially given it was on a weekend!).

Updated BreweryDB .NET client



Over the weekend I decided to look at a project which hasn’t recieved much love since I orginally wrote it earlier in the year. That project is PCL for interacting with the awesome beer database that is BreweryDB.

My orginal implementation was very simplistic in its design, only exposed a handful of the endpoint, lacked any error checking and also had a few too little unit tests. With BeerDrinkin’s development coming along nicey, I thought it time to take a look at some of its dependencies and see how I could improve them. First up was BreweryDB and so I set about improving the PCL to hopefully make it useful for other .NET developers.

Supported enpoints

This new version of BreweryDB includes many more supported endpoints. Its now possible to query almost all of BreweryDB using .NET.

  • Adjuncts
  • Beers
  • Breweries
  • Categories
  • Events
  • Features
  • Fermentables
  • FluidSizes
  • Guilds
  • SocialSites
  • Yeasts


Getting Started


  • GET/beers
  • GET/beer/beerId
  • GET/search/

Get all

This returns a list of all beers but will be paginated with 50 beers per page.

//Will return the first page
var response = await client.Beers.GetAll();

//Will return the fourth page
var response = await client.Beers.GetAll(4);

Get by id

This returns a single beer

var response = awaitclient.Beers.Get("cBLTUw");

Using request parameters

This returns a  list of beers

var parameters = new NameValueCollection {{BeerRequestParameters.Name, "duvel single"}};
var response = await client.Beers.Get(parameters);

Search by name

This returns a  list of beers

var response = await client.Beers.Search("duvel");


  • GET/breweries
  • GET/brewery/breweryId
  • GET/search/

Get all

This returns a list of all breweries but will be paginated with 50 breweries per page.

//Will return the first page
var response = await client.Breweries.GetAll();

//Will return the forth page
var response = await client.Breweries.GetAll(4);

Get by Id

This returns a single Brewery

var response = await client.Breweries.Get("YXDiJk");

Search by name

This returns a  list of breweries

var response = await client.Breweries.Search("duvel");

Naturally its open source

As always, I’ve made this avaiaible on GitHub and Nuget for you to use in your own apps.

Auto Layout 101 with Xamarin

Until recently I’d done an amazing job of avoiding Auto Layouts on anything other than demo apps, instead opting to create my layouts with springs and structs. All my apps within the App Store use the old approach, which although being exceptionally easy to create, its limited when running across all the different form factors that iOS runs on.

With multitasking on the iPad requiring Auto Layouts, I thought its probably about time that I took the time to learn to love the contraversal layout engine.

What is Auto Layout?

Auto Layout is a constraints based layout system for iOS, tvOS and OS X. It allows me to create adaptive user interaces that respond appropriatly to changes in screen size and orientation.

Auto Layouts is supported in both Xamarin Studio and Visual Studio when using Xamarin.iOS but will not be applicable to Xamarin.Forms developers. Xamarin.Forms developers dont need to worry as Forms apps already work fantasticlly on iPad with multitasking!

Layout contraints

Contraints are a mathematical representation of the relationship between views. The NSLayoutContraint class is used to create contraints on both iOS and OS X but for the most part, you’ll want to create contraints using our iOS Designer rather than programatically as its much easier.

Auto Layout has a number of constraints which include size, alignment and spacing. By providing each view within a scene with constraints, Auto Layout will determine the frame of each view at runtime.

One really important tip which will help you solve Auto Layout issues is to remember: Most controls will require constraints that define its height, width, x position and y position. 

Getting Started

To get started, I want to center a UIView within my scene. I want to remain in the center of the scene no matter what size of device its running on.

Screen Shot 2015-11-25 at 15.13.13

Above you can see that I’ve added a UIView to my scene and set its background colour to blue. Although it looks like its center to my scene, no iOS device actually has this form factor. We can use the View As drop down to simulate the different size. Lets see how this would look on a 5s with no constraints.

Screen Shot 2015-11-25 at 15.13.41

We can see that my UIView isn’t position correctly! To resolve this, lets go ahead and add some contraints.

I’m going to lock its height and width. To do this, I’ll click the handle bar button.


This has now locked the width and height of my view so that no matter what device I’m running on, the box will always remain the same dimentions. You’ll note that the lines are currently orange. This means that the control contains some errors with its contraints.

If you recall back to my pro tip, you’ll know that we’re only 50% of the way to completing the contraints for this view. We have yet to provide Auto Layouts with any information on where to position this view.

To do this, I clicked on the orange button in the middle of the view and connect it to the verticle line running through the scene. I repeat this for the horizontal line. This is telling Auto Layout that I want this views X and Y to be centered on the center of the super view.


When the view has 4 contraints (width, height, x and y), you’ll see the lines now turn to blue. This marks a valid set of contraints for the view and lets us know everything is valid. If you see orange lines, its Auto Layouts telling you that somethings gone wrong. Dont worry if you see orange whilst your still editing, its perfectly normal.

Screen Shot 2015-11-25 at 15.18.44

Wrapping up

This is a crazy simple demo of Auto Layouts but provides you with the basic you need to get started.

Come back in a few weeks to see more Auto Layout goodness as I convert an existing login screen to use Auto Layout.



iOS Awesomizer

A couple of weeks ago I started writing a library to speed up the development of iOS app. My aim was to make creating beautiful iOS apps even easier and share more code accross my iOS projects.

The main requirment of iOS development that I found consitant across all my apps is the need for animations. Since the orginal iPhone, iOS has had beautiful animations that create compelling user experiances which is why I feel its essential to have animations in my apps. Thankfully, creating animations for iOS is pretty simple but it still remains repetitive.

Its for this reason that I created iOS Awesomizer. Awesomizer allows me to animate any class that inherhits from UIView (thats most of the UI controls you’ll be using) with an extension method.

Whats supported?










Horizontal and verticle shake













How to use

Because the animations are UIView extensions, its incredibly easy to add animations to existing controls. Let say I wanted to add a shake animation to a UIImageView, I’d simply do the following:

using Awesomizer;

//More code here which we don't care about

Naturally, its open source

You can find the code for iOS Awesomizer on GitHub. I’m happy to accept any pull requests!

Facebook Authentication with Azure

Important Note

Microsoft have recently released Azure App Services which aims to replace Mobile Services. I will be writing an updated guide shortly.


Azure Mobile Services (AMS) is a great platform for .NET developers to build complex apps that require a backend in almost no time and at very competitive prices. I’ve been using it for about 6 months to develop a beer tracking app called BeerDrinkin.

One of the requirements of BeerDrinkin was its ability to sync account data accross all the users devices and AMS makes this incredibly easy with offline sync.

I couldn’t help but feel that if I’m going to be storing data in Azure, showing what beers people love and hate, then I really should be doing something more interesting than simply syncing to a handful of devices. This is why I decided to try and build a beer recommendation engine into BeerDrinkins backend. The aim is to make use of Azure Machine Learning to make suggestions about what beers you might like based on your constumption history and those of your peers.

In order to build a users profile to feed into machine learning, I needed more information than the simple GUID that AMS returns when calling the FacebookLoginProvier within the ConfigOptions of a Mobile Service WebApiConfig class.

The information that I wanted to have about the user:

  • Email Address
  • First Name
  • Last Name
  • Gender
  • Date of Birth

I will be adding additional data about users at various points during the users interaction with the app. One example is location data and I even plan on recroding local weather conditions for each beer the user checks in. With this, I can use machine learning to predict beers based on current weather conditions. This is important as on a warm day, most people will likely want a lager rather than a thick, blood warming Belgian double.

Creating a custom LoginProvider

To fetch the extra information, I needed to do a couple of things. First things first, I needed to remove the default FacebookLoginProvider from my ConfigOptions. To do this I called the following:


I then went ahead and created a new class which I named CustomFacebookLoginProvider which importantly overrides the CreateCentials method.

public class CustomFacebookLoginProvider : FacebookLoginProvider
public CustomFacebookLoginProvider(HttpConfiguration config, IServiceTokenHandler tokenHandler)
: base(config, tokenHandler)

public override ProviderCredentials CreateCredentials(ClaimsIdentity claimsIdentity)
var accessToken = string.Empty;
var emailAddress = string.Empty;
foreach (var claim in claimsIdentity.Claims)
if (claim.Type == "Zumo:ProviderAccessToken")
accessToken = claim.Value;

if (claim.Type == "")
emailAddress = claim.Value;

I now had some basic information regarding the user, such as their Facebook token (which is essential for gathering more information) and their email address. I then use a 3rd party Nuget package to query Facebook’s opengraph for more information regarding the user.

The entire method in BeerDrinkin’s Azure backend looks something like this:

public class CustomFacebookLoginProvider : FacebookLoginProvider
public CustomFacebookLoginProvider(HttpConfiguration config, IServiceTokenHandler tokenHandler)
: base(config, tokenHandler)

public override ProviderCredentials CreateCredentials(ClaimsIdentity claimsIdentity)
var accessToken = string.Empty;
var emailAddress = string.Empty;
foreach (var claim in claimsIdentity.Claims)
if (claim.Type == "Zumo:ProviderAccessToken")
accessToken = claim.Value;

if (claim.Type == "")
emailAddress = claim.Value;

if (string.IsNullOrEmpty(accessToken))
return null;

var client = new FacebookClient(accessToken);
dynamic user = client.Get("me");

DateTime dateOfBirth;
DateTime.TryParse(user.birthday, out dateOfBirth);

//Keeping userItem for the moment but may well kill it. I was going to seperate userItem into public info and accountItem into public
var userItem = new UserItem
Id =,

var accountItem = new AccountItem
Id = userItem.Id,
Email = emailAddress,
FirstName = user.first_name,
LastName = user.last_name,
IsMale = user.gender == "male",
DateOfBirth = dateOfBirth,
AvatarUrl = $"{userItem.Id}/picture?type=large"

var context = new BeerDrinkinContext();
if (context.UserItems.FirstOrDefault(x => x.Id == userItem.Id) != null)
return base.CreateCredentials(claimsIdentity);


return base.CreateCredentials(claimsIdentity);

Using the CustomFacebookLoginProvider

In order to use my implementation of the login provider, I needed to go ahead and add it to the ConfigOptions.



One thing I forgot when I first implemented this approach was ensuring that I updated my scopes. By default, Facebook wont provide me with the information I require. In order to have Azure Mobile Service pass the correct request to Facebook, I needed to log into my Azure management portal and add MS_FacebookScope to my App Settings. The exact scope I’m requesting is email user_birthday user_friends.


BeerDrinkin (espically the backend) is worked on mostly whilst ‘testing’ the app (drinking beer). Some of the code is horrible and need to be refactored. The above code could 100% do with a tidy up but works so I’ve left it as is. The project is on please do contribute if you can.

Find your users gender without asking

The app I’m working on in my spare time (BeerDrinkin) requires a modest amount of user data to in the future provide the best possible suggestions for new beers the user might like to try. Part of building a great model of my users is knowing thier gender.

When a user authenticates within BeerDrinkin using Facebook, I can simply parse the returned information and add the users gender to my database. Unfortunately, not all social authentication providers were born equal. With the recent addition of Google Auth, which I added to allow my father (who isn’t even sure what Facebook is) to use my app, I was unable to get the users gender.

Its for this reason that I’ve created a library that allows me to query Genderize. Genderize is a restful service which allows me to determine the gender of a user based on only a first name. It offers a free tier which includes the ability to query 1000 names a day which is more than enough for my requirements. If I find myself hitting the limit I’ll firstly buy a bottle of champagne to celebrate high user adoption and to drink away the thoughts of my Azure bill. On a serious note, Genderize provide the option to upgrade the account plan for a nominal fee to 100,000 users a month.

Given that BeerDrinkin does some sneaky UX to make a Facebook auth more likely (I delay showing the Google sign-in button for a few seconds so the user intially is confronted with only 1 option. Its very subtle but seems to help push Facebook as the prefered option), the free teir should be perfect for me.

Creating a PCL to interact with Genderize

To get started I headed over to the Genderize’s documentation to see what response I should expect back when querying the service. It’s actually increbily easy to use this service so much so that the entire PCL consists of no more than 100 lines of code.

Sample JSON response


Corresponding C# model

public class Response
    private string gender { get; set; }

    public string Name { get; set; }

    public Gender Gender { get; set; }

    public string Probability { get; set; }

    public int Count { get; set; }

public enum Gender

One thing to note is that I’m using Json.NET’s JsonConverter to deal with converting from a string gender to an enum. This is just one of the many featuress of Json.NET that make it a pleasure to use.

Genderize Client Code

public class Client
    public Client()

    public async Task GenderizeSingleName(string name)
        if (_client == null)
            _client = new HttpClient();

        Response model;

        var url = string.Format("{0}", name);
        var response = await _client.GetAsync(url);

        var jsonString = response.Content.ReadAsStringAsync();
        model = JsonConvert.DeserializeObject(jsonString.Result);

        return model;

    HttpClient _client;

As always, its open source

If you want to use the library, you can go ahead and grab a copy from my GitHub page. Once I get home from Australia I’ll add more features and publish to Nuget.


Adding Parse to your Xamarin.Forms solution

I’ve recently been developing a Xamarin.Forms app which required a cloud service for data persistence and syncing across multiple devices and platforms. Normally when I’m developing Xamarin.Forms apps, it tends to be because I’m either writing a proof of concept or a tech demo. Both these types of projects focus of speed of development and code reuse rather than crafting delightful user experiences (it’s 100% possible to create delightful experiences in forms, its just not the primary objective of a Xamarin.Forms app in most situations).

The app I’m developing requires both user signup and the ability of the user to sign in, which is where the Parse .NET client API shines. Although Parse may be one of the more unknown cloud service providers (especially in .NET circles), it’s my favourite for a number of reasons. It’s incredibly easy to get started with, the API is concise, and the documentation is fantastic. Not to mention a generous free plan makes it a no brainer for apps I want to deploy quickly, while being unsure how much traffic they’ll bring. My only complaint when using Parse is the lack of PCL for Xamarin.Forms. I have spoken with Parse about this and they assure me this issue will be resolved.

Adding Parse to your Forms app

Because of the PCL issue for Xamarin.Forms, you’re going to need to select a Shared Code solution, rather than a PCL backed solution. Once you’ve done this, you’ll need to add the Parse Nuget package to the individual platform projects. This means, firing up the package manager and adding Parse to the iOS, Android, and Windows Phone projects.

Initialising Parse

Before getting started with Parse, you’re going to need to ensure it’s initialised. I tend to create a class called Keys in my forms solution, which is where I store all the keys to services such as Parse and Xamarin.Insights. Below is an example keys class which you can reuse in your Xamarin.Forms apps.

public class Keys
    public static readonly string XamarinInsightsKey = "0000";

    public static readonly string ParseAppKey = "0000";
    public static readonly string ParseDotNetKey = "0000";

You can then call the ParseClient.Initialize API.

public App()
    ParseClient.Initialize(Helpers.Keys.ParseAppKey,   Helpers.Keys.ParseDotNetKey);

    // The root page of your application
    MainPage = new ContentPage{BackgroundColor = Color.Red};

Signing up a user

Now that Parse is ready to use, lets go ahead and create a new user. The API for creating a user couldn’t be any simpler, it’s one of the reasons why I’ve fallen in love with using Parse.

private async Task ExecuteSignUpUserCommand ()
    if (IsBusy)
    IsBusy = true;

        var user = new ParseUser()
            Username = username,
            Password = password,
            Email = email

        user["firstName"] = firstName;
        user["lastName"] = lastName;

        var connected = CrossConnectivity.Current.IsConnected;
        if (connected)
            UserDialogs.Instance.ShowLoading ("Creating Account");

            //The code that actually signs a user up!
            await user.SignUpAsync();

            //More UI stuff..
            UserDialogs.Instance.HideLoading ();
            await NavigateToMainUI ();
        } else {
            UserDialogs.Instance.ShowError ("No Internet Connection");
    catch (Exception ex)
        UserDialogs.Instance.ShowError(ex.Message, 3);
        Xamarin.Insights.Report (ex);
    IsBusy = false;

Lets save some data

The not so pretty way
We have two options for saving data with Parse. We can use the dictionary-initialization syntax or we can subclass from ParseObject. I much prefer to subclass the ParseObject as this allows for type-safety and IntelliSense (which are two of the many reasons I use C#). Below we will save an object to Parse using both approaches.


var sampleData = new ParseObject("Planet");
sampleData["name"] = "Earth";
sampleData["distanceFromSun"] = 100;
await sampleData.SaveAsync();

Subclassing ParseObject

// Planet.cs
using Parse;

public class Planet : ParseObject
    public string Name
        get { return GetProperty(); }
        set { SetProperty(value); }

    public int DistanceFromSun
        get { return GetProperty(); }
        set { SetProperty(value); }

Registering Subclasses objects

You’ll need to call ParseObject.RegisterSubclass() in your apps initialisation before calling ParseClient.Initialize(). If you don’t don’t do this, your app will crash!


The final initialisation method

public App()
    ParseClient.Initialize(Helpers.Keys.ParseAppKey,         Helpers.Keys.ParseDotNetKey);

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

Using our subclasses ParseObject

var planet = new Models.Planet()
    Name = "Mars",
    DistanceFromSun = 227900000
await planet.SaveAsync();


You can download a sample project from GitHub which demonstrates how to sign up, sign in, save and most importantly, retrieve data.

If you’ve any questions then please feel free to comment or get in touch via Twitter

Watch out, we support WatchKit!


Xamarin have just announced preview support for Apple Watch and I can’t express how excited I was over the weekend playing with our internal preview build. At this moment time, getting started with Apple Watch can be little confusing, what with the need for 3 different project types to get a hello world sample running! You can see this in the below screenshot of Xamarin Studio. This complexity increases the learning curve so I’ve done my best to try and help.

I’ve created a simple Hello World Apple Watch sample solution which you can download from my GitHub.

One Solution – Three Projects – One Watch App!

Even a basic Apple Watch app requires 1 part App Extension, 1 part Watch App and finally 1 part Unified iOS App. When combined with the correct Bundle Identifiers, you’ve got yourself the beginnings of Apple Watch support. At this moment in time, you’ll need to be editing your storyboard in Xcode rather than Xamarin Studio or Visual Studio. I believe our engineers are hard at work on integrating Apple Watch UI storyboard support in VS and XS much like we have for iPhone and iPad.


 Learn more with some awesome documentation!

Xamarin has some excellent documentation on Apple Watch which I highly recommend you thoroughly read.

Cross-Platform Desktop UIs with C#


I’ve spent the last 4 weeks traveling Europe for the Xamarin European roadshow, and have had the opportunity to meet a few thousand C# developers who share a passion for cross-platform development.

In almost every city, I’ve been asked to recommend a Xamarin.Forms style library for developing desktop applications. In this blog post I’m going to give an overview of the different options available to desktop developers who wish to target Windows, Mac and Linux.

Traditional Approach

The first approach is what we’ve named at Xamarin the ‘traditional’ approach. You’ve probably seen this approach, but for mobile. The general idea is that you should implement your user interface uniquely for each platform you wish to target. This means on Mac, you would use Cocoa (Xamarin.Mac), Windows would use WPF and Linux would use Gtk (Gtk#). This approach will guarantee that your desktop application looks and behaves as the platform users expect. It also means that your application looks great if Apple, Microsoft or the OpenSource community decide to update the look and feel of the underlying OS. It’s also worth noting that with this approach you gain 100% access to every UI control and API available in the UI libraries, and won’t be limited in your ability to create beautiful experiences for your users.

In case you’re in any doubt, this is the approach I recommend you take when developing your apps. This is actually the approach Xamarin has started to use for our new products. You can see this in action with our Profiler and Android Simulator; both of these use WPF on Windows, and Xamarin.Mac (Cocoa) on OS X.


Much like Xamarin.Forms, Xwt allows you to use one API that maps to the native widgets of the platform. This means your application when running on Windows will be using WPF widgets, on Mac its Cocoa, and Linux is Gtk. This results in a 100% native user interface on three platforms from one codebase. Much like Xamarin.Forms, because its aim is to create a unified API for all desktop platforms, it only maps to a subset of widgets and properties. It’s worth noting that with Xwt you still have the ability to implement a native widget which isn’t mapped as part of the API.

For all platforms you can use the native engine, or the Gtk engine. If you’re wondering what a Gtk app looks like on Windows and Mac, then I recommend downloading Xamarin Studio. This is primarily built using Gtk, and in areas actually uses Xwt. On Windows the native engine is WPF, on OS X its Cocoa, and on Linux it remains Gtk (using Gtk#).


One other option you might want to consider, is using a WebView for your user interface whilst maintaining a C# backend. This is the approach that Rdio has taken for their OS X client, and to a novice it’s difficult to spot that it’s not a native app. This approach can produce some great looking applications which can even run in the Cloud, but it would be difficult to claim you’ve created an application when the reality is you’ve packaged up a website.


Although this approach is not yet ready for consumption, I thought I would mention it as it’s a project on GitHub that excites me. Much like Xamarin.Mac is a binding to the Cocoa framework, a group of enterprising .Net developers are aiming to create a .Net binding to the Qt library. Having used Qt in a previous life, I can confirm that the UIs can often be a little hit or miss (because it’s a lowest common denominator approach). That said, if you’re developing an internal application, or willing to take the time to craft the UI for each platform (different layouts for each platform) then it can work really well.

The project is still in its infancy, and many developers have tried and failed at this approach. Its not ready for production as yet (it doesn’t appear to even be close) but its a great start. My fingers are crossed that the developers continue to invest their time in the project, and the .Net community gains access to one of the most widely used cross-platform user interfaces frameworks in existence.