Nico's digital footprint

I grew up in the nineties, that makes me awesome by default

HttpClient in mobile apps

by Nico

I’ve been seeing a lot of discussions lately on how to correctly use HttpClient in mobile apps, both UWP and / or Xamarin apps. In this post I’d like to share how I currently use HttpClient in my apps.

Read this first -> Disclaimer

This article discusses how I use the HttpClient class. If you use it in a different way or don’t agree with what I write here, feel free to start a constructive discussion in the comments. I’ll be happy to discuss your way of thinking vs mine and adjust the article where necessary.

To single-instance or to multi-instance

Back when I was getting into writing mobile apps (in the WP7 era) I started learning about REST services and how to call them from .NET code. I learned about HttpClient and quickly found out that it implemented IDisposable, so the logical step was the using keyword.

Turns out, not the best way to go at it. When you dispose an HttpClient instance, the connection to the server is closed.
When you do the next call to the server, with a new HttpClient instance, that connection is reopened. This causes delay in getting a response from the webservice. If a server really doesn’t want you to keep your connection open, it will inform us of that via a header and the HttpClient instance will quietly close the connection and reopen it the next time.

So, how do we create an easy to (re)use instance?

And to use this instance:

Use a base URL (and don’t even dare making it a magic string)

The HttpClient class has a base url property. As you might have figured out, that property is meant to contain the root url of your API. So if we modify our HttpClient a bit we get this

As for the magic strings remark, put all your  string values into a constants class (or whatever you want to name it, as long as they’re all together). If you don’t understand the reasoning behind this, just try writing applications with string values in the code, you’ll find out soon enough Smile

Use compression where possible

Since we’re mostly writing mobile applications we need to keep data usage in mind. We have no idea if our users will have an expensive data plan or unlimited data or if they’re on WIFI. This means that it’s our job as developers to keep the data usage as low as possible. The quickest win here is to compress the data from the server and decompress it on the device, this of course means that the server needs to support compression. If you yourself maintain the server, make sure that it is enabled (it’s enabled by default in Web API). Once that is enabled, we need to tell the HttpClient to enable decompression from either Deflate or Gzip formats. Enable decompression is done through an HttpClientHandler object that we can pass into the HttpClient constructor.


Another often overlooked way of limiting data usage is caching. You’d be surprised of the times users request the same data, if we cache the API result we can just fetch it from that cache again. Extra usability feature here is that we can actually show results when the device is offline. You can write your own caching framework if you want, or use one of the existing ones. I tend to switch between Q42 (they save cached data in JSON files) and Akavache (they save cached data in SQLite).

Security Tokens

We often need to make API calls to secured services. To do this we need to go through some form of authorization / authentication flow where we get an access token from (a bearer token for example). That token needs to be passed in with every API call we make. Since we’re now using a single instance for our HttpClient, it would be nice to specify the token once and be done with it. This an easily be done by using the default headers. HttpClient contains a collection of headers that it will use with every call it makes. This is how you add a Bearer token for example:

Use ConfigureAwait(false)

HttpClient is an async library. This means that we usually use this in a method that returns either Task or Task<T>. This also means that if you don’t use ConfigureAwait(false) that you’ll create quite a lot of context switching. When you await an async method, and don’t specify ConfigureAwait(false), the method will do it’s thing on the thread pool and switch back to the caller’s context when finished. This is exactly the behavior that you want when you request a webresult and immediately put the data into a property that is bound against, since binding happens on the UI thread. But this is not what we want when we’re executing code in a library or in a service class, so that’s where we’ll use ConfigureAwait(false).

Let’s say, for example, that we have a method to fetch all resources as a JSON string. The correct way of using ConfigureAwait(false) would be:

The FetchData method doesn’t use ConfigureAwait(false) because it needs to return to the caller context. The caller context here is the UI thread. The property that the returned value is being set to will trigger a change notification, so we need to be on the UI thread.

The FetchAllResources method has two calls that are awaited, by not returning to caller context in that method we prevent two context switches to occur.

(Xamarin only) use ModernHttpClient

Xamarin allows us to write iOS and Android applications in C#. We can use the HttpClient for that but we'd be using an abstraction of the lowest common denominator of both platforms. If you use ModernHttpClient on those platforms instead, you will get the full networking stack of the respective platforms. (thanks for reminding me @Depechie)


In this post I discussed some techniques with using HttpClient to fetch data in mobile applications that I’ve picked up over the years. As I’ve mentioned in the disclaimer, this is what I’m doing today and what feels right to me. Feel free to let me know if you do things another way, if you can convince me that your way is better, I will have learned something and will update the post accordingly Smile.


.Net | Xamarin

Xamarin Forms Bindable Wrappanel

by Nico

A wrappanel is something XAML developers are very familiar with. It’s a panel that orders its children either horizontally or vertically but when the children reach the border, the panel wraps to the next row or column.

Xamarin Forms currently does not have a default implementation for something similar so I set out to find one online. To my surprise it took quite some time to find something (guess I’m spoiled by the awesome toolkits we have as Windows app devs), eventually I found the WrapLayout.

The WrapLayout works but had a disadvantage, it didn’t have an ItemsSource or DataTemplate property but I did have a solid foundation, so I went to expand the implementation.

I started by creating a bindable property for itemssource and one for item template. In MS XAML we would use Dependency properties, in Xamarin XAML it’s called BindableProperty.

   1: /// <summary>
   2: /// Backing Storage for the Spacing property
   3: /// </summary>
   4: public static readonly BindableProperty ItemTemplateProperty =
   5:     BindableProperty.Create<AwesomeWrappanel, DataTemplate>(w => w.ItemTemplate, null,
   6:         propertyChanged: (bindable, oldvalue, newvalue) => ((AwesomeWrappanel)bindable).OnSizeChanged());
   8: /// <summary>
   9: /// Spacing added between elements (both directions)
  10: /// </summary>
  11: /// <value>The spacing.</value>
  12: public DataTemplate ItemTemplate
  13: {
  14:     get { return (DataTemplate)GetValue(ItemTemplateProperty); }
  15:     set { SetValue(ItemTemplateProperty, value); }
  16: }
  18: /// <summary>
  19: /// Backing Storage for the Spacing property
  20: /// </summary>
  21: public static readonly BindableProperty ItemsSourceProperty =
  22:     BindableProperty.Create<AwesomeWrappanel, IEnumerable>(w => w.ItemsSource, null,
  23:         propertyChanged: ItemsSource_OnPropertyChanged);
  25: /// <summary>
  26: /// Spacing added between elements (both directions)
  27: /// </summary>
  28: /// <value>The spacing.</value>
  29: public IEnumerable ItemsSource
  30: {
  31:     get { return (IEnumerable)GetValue(ItemsSourceProperty); }
  32:     set { SetValue(ItemsSourceProperty, value); }
  33: }

ItemTemplate is a property of type DataTemplate, ItemSource is an IEnumerable (the non-generic version). So far so good, next up is adding some logic to add the itemsource items as children of the Layout. Since the wrappanel has Layout<T> as a base there is no itemsource from the underlying control.

   1: private void OnCollectionChanged(object sender, NotifyCollectionChangedEventArgs args)
   2: {
   3:     foreach (object item in args.NewItems)
   4:     {
   5:         var child = ItemTemplate.CreateContent() as View;
   6:         if (child == null)
   7:             return;
   9:         child.BindingContext = item;
  10:         Children.Add(child);
  11:     }
  12: }

We’re going to respond to collection changed events, hoping that whoever uses the control binds to a collection that implements INotifyCollectionChanged, like the infamous ObservableCollection<T>. We’re creating a View from the DataTemplate for every newly added item, set the BindingContext to the item itself and add it to the Children collection. The binding framework will take care of all the rest.

One step left, we need to add an event handler for the CollectionChanged event. We do this in the property changed callback of the ItemSource bindable property

   1: private static void ItemsSource_OnPropertyChanged(BindableObject bindable, IEnumerable oldvalue, IEnumerable newvalue)
   2: {
   3:     if (oldvalue != null)
   4:     {
   5:         var coll = (INotifyCollectionChanged)oldvalue;
   6:         // Unsubscribe from CollectionChanged on the old collection
   7:         coll.CollectionChanged -= ItemsSource_OnItemChanged;
   8:     }
  10:     if (newvalue != null)
  11:     {
  12:         var coll = (INotifyCollectionChanged)newvalue;
  13:         // Subscribe to CollectionChanged on the new collection
  14:         coll.CollectionChanged += ItemsSource_OnItemChanged;
  15:     }
  16: }

If there’s a previous instance we disconnect from its event, afterwards we try to cast the itemsource to INotifyCollectionChanged, if that succeeds we know there’s a collection changed event we can hook into. One problem here, this is all static but the properties we need to use in the event handler are not so we need to find a way to get from static to non-static code, events to the rescue!

I added a static event, cool thing about those is that the event handlers can be non-static.

   1: private static event EventHandler<NotifyCollectionChangedEventArgs> _collectionChanged;

Used the constructor to hook up the handler

   1: public AwesomeWrappanel()
   2: {
   3:     _collectionChanged += OnCollectionChanged;
   4: }

And that’s it! The handler method is the one we discussed a bit earlier, where the items in the itemsource are converted into Children elements.

Here’s how to use it in XAML

   1: <controls:AwesomeWrappanel ItemsSource="{Binding Persons}" Orientation="Horizontal">
   2:     <controls:AwesomeWrappanel.ItemTemplate>
   3:         <DataTemplate>
   4:             <StackLayout BackgroundColor="Red">
   5:                 <Label Text="{Binding Name}" />
   6:                 <Label Text="{Binding Age}" />
   7:             </StackLayout>
   8:         </DataTemplate>
   9:     </controls:AwesomeWrappanel.ItemTemplate>
  10: </controls:AwesomeWrappanel>

A quick screenshot of the result:

A demo project can be found on my OneDrive or see this GitHub Gist for the Wrappanel class.

Happy coding!


.Net | Xamarin | XAML | WinRT

Grid column behavior–Xamarin XAML vs MS XAML

by Nico

There’s a small detail difference in how rows and columns in a Grid behave in Xamarin Forms vs Microsoft XAML. A small difference but with quite a big impact. Look at the following XAML snippet (Microsoft XAML)

Code Snippet
  1. <Grid Background="Red">
  2.     <Grid.RowDefinitions>
  3.         <RowDefinition Height="50" />
  4.         <RowDefinition Height="*" />
  5.     </Grid.RowDefinitions>
  7.     <Grid Grid.Row="1" Background="Blue">
  8.         <Grid.RowDefinitions>
  9.             <RowDefinition Height="Auto" />
  10.             <RowDefinition Height="300" />
  11.         </Grid.RowDefinitions>
  12.     </Grid>
  13. </Grid>

At runtime this looks like:

Exactly what we as seasoned XAML developers would expect.

Converted to Xamarin Forms XAML this turns into:

Code Snippet
  1. <Grid BackgroundColor="Red">
  2.   <Grid.RowDefinitions>
  3.     <RowDefinition Height="50" />
  4.     <RowDefinition Height="*" />
  5.   </Grid.RowDefinitions>
  7.   <Grid Grid.Row="1" BackgroundColor="Blue">
  8.     <Grid.RowDefinitions>
  9.       <RowDefinition Height="Auto" />
  10.       <RowDefinition Height="300" />
  11.     </Grid.RowDefinitions>
  12.   </Grid>
  13. </Grid>

Only difference is the property name to set the background color. However, if we look at this at runtime we see a completely different story.

It looks like the inner Grid isn’t rendered at all. But let’s try to add a Label to the inner Grid.

Code Snippet
  1. <Grid BackgroundColor="Red">
  2.   <Grid.RowDefinitions>
  3.     <RowDefinition Height="50" />
  4.     <RowDefinition Height="*" />
  5.   </Grid.RowDefinitions>
  7.   <Grid Grid.Row="1" BackgroundColor="Blue">
  8.     <Grid.RowDefinitions>
  9.       <RowDefinition Height="Auto" />
  10.       <RowDefinition Height="300" />
  11.     </Grid.RowDefinitions>
  12.     <Label Text="Hello Xamarin!" />
  13.   </Grid>
  14. </Grid>

So what exactly is going on here? The inner Grid (the blue one) doesn’t specify any columns, that means that by default there’s only one column available. In Microsoft XAML the width of that default column is set to “*” so it takes up all available space. In Xamarin Forms that width is set to “Auto” so it only takes up the space it needs. A subtle difference with a big impact.

To fix this, add a column with “*” as width

Code Snippet
  1. <Grid BackgroundColor="Red">
  2.   <Grid.RowDefinitions>
  3.     <RowDefinition Height="50" />
  4.     <RowDefinition Height="*" />
  5.   </Grid.RowDefinitions>
  6.   <Grid.ColumnDefinitions>
  7.     <ColumnDefinition Width="*" />
  8.   </Grid.ColumnDefinitions>
  10.   <Grid Grid.Row="1" BackgroundColor="Blue">
  11.     <Grid.RowDefinitions>
  12.       <RowDefinition Height="Auto" />
  13.       <RowDefinition Height="300" />
  14.     </Grid.RowDefinitions>
  16.   </Grid>
  17. </Grid>



In this post I’ve shown a difference in implementation between Xamarin Forms XAML and Microsoft XAML and how to fix it.

Note that this sample is based on Xamarin Forms 1.2. Xamarin has stated that they will change the implementation in Forms 1.3 to reflect the Microsoft implementation.


XAML | WinRT | WP8 | WPF | Xamarin

  Log in

About the author


My name is Nico, I’m an MVP Windows Platform Development living in Belgium.
I’m currently employed as a .NET consultant at RealDolmen, one of Belgium’s leading IT single source providers.

I'm also founding member and board member of the Belgian Metro App Developer Network, a user group focussed on Windows 8 and Windows Phone development. If you're in Belgium feel free to drop by if we're doing an event.

Since June 2012 I'm a proud member of Microsoft's Extended Experts Team Belgium. And in February 2013 I became a member of DZone's Most Valuable Bloggers family.

In 2013 I became a book author and wrote "Windows 8 app projects, XAML & C# edition".

In 2014 I received the MVP award for the very first time.

I hope to get feedback from my readers either through comments, mail (, twitter, facebook, …












Month List