Xamarin Forms Threading Fun

I’ve been trying out the async/await model in Xamarin Forms, and have had trouble getting it to work. It turns out there is great challenge in ensuring everything runs on the same thread. In this I learned a few lessons:

1) Make sure that once you start an operation asynchronously, make sure everything is also called in an async fashion. For instance, I had the following call hierarchy:

async LoginButton_Click
async HandleSignInCompleted(..);
async loginService.Login(..);
async HttpClient.PostAsync(..);

It’s important to make sure everything uses the async model, rather than calling the method directly. For instance, an async method can be called directly, or the results invoked directly with the .Result property on the Task. But don’t do it! Be consistent with the async/await setup.

2) Use ConfigureAwait(false)

The Task object has a ConfigureAwait method. I had success using it by applying it EVERYWHERE, on every async operation. In my above stack trace, this looked like:

async void LoginButton_Click //Since a button callback, can't define here
    async HandleSignInCompleted(..).ConfigureAwait(false);
       async loginService.Login(..).ConfigureAwait(false);
          async HttpClient.PostAsync(..).ConfigureAwait(false);

3) UI Synchronization

In my call stack, in the HandleSignInCompleted, there was a call to:

var page = new DashboardPage();
await this.Navigation.PushAsync(newPage);

This failed with an Android error (tested on an Android device) stating that the view was modified on a different thread that the original, which makes sense since we are in the async thread. The solution to that was to wrap the call in a Device.BeginInvokeOnMainThread method call. This built up the UI for the Dashboard page in the main UI thread instead.

Device.BeginInvokeOnMainThread(() => {
var page = new DashboardPage();
await this.Navigation.PushAsync(newPage);

Read more about BeginInvokeOnMainThread to understand the specifics, and why it may work in some situations and not others. So far that has been the tale of my adventures in asynchronous operations in Xamarin Forms. Hopefully this might help you as you use Xamarin Forms.


Xamarin Forms Async Loading of Data

Xamarin supports the async/await model of the .NET framework, which is an awesome capability. Because async/await is supported, it’s possible to use this to load the data in your application on demand. For instance, suppose we had a page with two listviews, such as the following sample page:



Let’s take a second to look at the ListView markup. The ListView renders a custom ViewCell for each item in the list. We can use ViewCell to create a custom UI for each list item, which is provided by the inner StackLayout. The ListView is bound in code (though could be easily bound in the markup) as shown below, each delaying a specific period of time (for the purposes of simulating a network request).

public class Game
	public string Name { get; set; }
	public int Score { get; set; }
	public string PlayerImageUrl { get; set; }
public class HighScore
	public string Name { get; set; }
	public string Level { get; set; }
	public int Score { get; set; }

private async void LoadGames()
	await Task.Delay (3000);

	//All zeros is used for demoing purposes.
	this.GamesList.ItemsSource = new List {
		new Game { Name = "Paul J.", Score = 5350, PlayerImageUrl = "http://www.gravatar.com/avatar/00000000000000000000000000000000?s=40" },
		new Game { Name = "Peter K.", Score = 3410, PlayerImageUrl = "http://www.gravatar.com/avatar/00000000000000000000000000000000?s=40" },
		new Game { Name = "Bill C.", Score = 960, PlayerImageUrl = "http://www.gravatar.com/avatar/00000000000000000000000000000000?s=40" },
		new Game { Name = "Bobby B.", Score = 3190, PlayerImageUrl = "http://www.gravatar.com/avatar/00000000000000000000000000000000?s=40" },
		new Game { Name = "Amy S.", Score = 5950, PlayerImageUrl = "http://www.gravatar.com/avatar/00000000000000000000000000000000?s=40" }

private async void LoadHighScores()
	await Task.Delay (5000);

	this.HighScoresList.ItemsSource = new List {
		new HighScore { Name = "Robby10210.", Score = 907409, Level = "Lv. 42" },
		new HighScore { Name = "Peter K.", Score = 891399, Level = "Lv. 41" },
		new HighScore { Name = "Bill C.", Score = 801222, Level = "Lv. 39" },
		new HighScore { Name = "Bobby B.", Score = 681202, Level = "Lv. 34" },
		new HighScore { Name = "Amy S.", Score = 660198, Level = "Lv. 33" }

This loads data into the lists after a delay without interruption to the user. A quick demo of the app is illustrated below for your viewing pleasure on Youtube at the URL, taken with Camtasia – a great screen recording tool: http://www.youtube.com/watch?v=3l2B9v2b0gw.

Single Page Binding with Kendo UI ListView

If you’ve looked at the demos on the Kendo UI site, you’ll notice the ListView and DataSource combination are a pretty capable combination. The ListView gives you full control over the user interface, while supporting common functionality like paging, sorting, and more. The DataSource provides read and update functionality to a local or remote data source, even giving you full control over these processes (for instance, you can use JQuery directly for AJAX communication). The pager natively pages through the contents of the listview automatically for you. The three widgets offer great functionality for the developer.

While the combination works well, I personally ran into a snag using the Kendo UI core version (open source). With the pager component natively paging the content, the data source required a complete dataset downloaded from the server. If your ListView will be presenting 30 records, all 30 must be retrieved from the server; if 3,000, all 3,000 must be retrieved from the server. Now natively the data source control supports server paging, most examples illustrated using the Telerik MVC wrappers for handling the server-side processing, and as such, I wasn’t sure whether it was supported. If it works, I would recommend using the kendo pager as it offers the smoothest navigation; but if not, this workaround worked just as well, with some added effort. In order to get around this, I ended up using the Bootstrap Paginator plugin.

The bootstrap paginator allows you control over the number of pages to show, and provide delegation on user interaction, with the example below.

            currentPage: 1,
            totalPages: 10,
            onPageClicked: function(e, evt, type, page){
                //Reload the listview - listview uses custom AJAX option

The currentPage option sets the current page in the list, within the range of total pages. It’s possible to preload these from an MVC model, especially when you factor in postbacks (the pager needs reinitialized on postbacks), as in the following:

   currentPage: @Model.CurrentPage,
   totalPages: @Model.TotalPages

When the user clicks on a page, it fires the onPageClicked callback handler, which subsequently triggers an AJAX action back to the server. We’ll need the new page index from the event handler; we can get it directly from the plugin, or store the current index in a hidden variable. Either way, this piece of information needs passed back to the server.
If you looked in the example online, it has a custom AJAX action as shown below.

    dataSource: {
       transport: {
           read: function(o) {
              var index = // Get index from hidden variable or wherever

                  type: "post",
                  url: "@Url.Action("Action", "Controller"),
                  data: { index: index, otherParams: "OTHER PARAMS" },
                  success: function(d) { o.success(d); },
                  error: function(d) { o.error(d); }

Here we trigger the postback to the server, and pass in the list of form data values, as well as the currently selected page index. Since the items per page is hard-coded in this scenario (at say 10, for example), we can quickly calculate the starting index and ending index of the current page.

There are many ways to implement this solution; this is one quick, simple way to introduce paging with large lists of data, where each page is dynamically loaded at paging time.

Using JQuery FullCalendar with ASP.NET MVC and Entity Framework

I had a need to use a calendar component in my application. Calendars are hard to come by, that also act as a scheduling component. In comes JQuery FullCalendar, a plugin that renders a calendar with event components.

To set this up

1. Create an Entity Framework model with all of the AdventureWorks entities.  Choose whatever template you like. Leave the context name as the default “AdventureWorksEntities”.

2. Create a new MVC project. Add a new controller named OrderHistoryController. The OrderHistoryController that I used is defined as the following:

public class OrderHistoryController : Controller
// GET: /OrderHistory/
public ActionResult Index()
return View();

public ActionResult List(long start, long end)
var epoch = new DateTime(1970, 1, 1);
var startDate = epoch.AddMilliseconds(start);
var endDate = epoch.AddMilliseconds(end);

var ctx = new AdventureWorksEntities();
var data = ctx.SalesOrderHeaders
.Where(i => startDate <= i.OrderDate && i.OrderDate <= endDate)
.GroupBy(i => i.OrderDate)
.Select(i => new { OrderDate = i.Key, Sales = i.FirstOrDefault()}).Take(20).ToList();

return Json(data.Select(i => new
title = (i.Sales.Customer != null) ? i.Sales.Customer.AccountNumber : “Untitled”,
start = i.OrderDate.ToShortDateString(),
allDay = true


The Index action serves up the view.  Once the view is loaded, an AJAX request is made back to the server, looking for any orders.  Using LINQ, we load up some of those records.  I used a GroupBy statement so that I could get one record back per date for a given month, as a way to test with a single record per day.

JSON is the preferred mechanism to return to the client.  We’ll need to massage the data a little bit in order to work with the full calendar.   For instance, we’ll have to convert the date appropriately.  For simplicity, I used ToShortDateString to get the date and parse it in JavaScript.  However, it would have been more appropriate to convert the date to Epoch time (time since 1/1/197o).

3.  Download JQuery FullCalendar from the following URL: http://arshaw.com/fullcalendar/download/.  Copy the JS and CSS files to your project, in the Content and Scripts folder (or whatever folder structure you are using).  The files includes are:

  • fullcalendar.css – the core CSS file
  • fullcalendar.print.css – the CSS stylesheet for printing a calendar
  • fullcalendar.js – the core JS file
  • fullcalendar.min.js – the minified JS file
  • gcal.js – Google calendar integration

4.  Add scripts to your page

Rather than adding all the scripts to every page, I added the scripts to the OrderHistory view.  To do this, I started by creating a bundle.  Open up Bundle.config and add the following:

bundles.Add(new ScriptBundle(“~/bundles/calendar”).Include(






));bundles.Add(new StyleBundle(“~/Content/calendar”).Include(




We use these bundles within the view. To setup the calendar, all that we need to do is add a DIV to a page with an ID, like <div id=”container”></div>. The FullCalendar plugin simply attaches to

    header: {
        left: ‘prev,next today’,
        center: ‘title’,
        right: ‘month,agendaWeek,agendaDay’
    editable: true,
    eventClick: function(i, evt, view) {
    events: function (start, end, callback) {
            type: “post”,
            url: ‘@Url.Action(“List”, “OrderHistory”)?start=’ + start.getTime().toString() + “&end=” + end.getTime().toString(),
            success: function (d) {
                var list = [];
                for (var i = 0, len = d.length; i < len; i++) {
                    var item = d[i];
                    item.start = new Date(item.start);


            error: function (e) {


The plugin supports a variety of members defined in the documentation that can be specified at initialization time. The key is the events property, which defines the source of the events. The source can be a static list, a pointer to a page or web service, or even a function callback. The latter option gives you the most flexibility, and I’ve demonstrated it’s usage in this example. The callback gets a start and end parameter. These parameters are dates, converted to epoch time (in milliseconds) as they are sent to the server. JQuery is used to make the call to the server, and as the results come back, the process does some massaging first. For instance, a date is coming back to the client in string form, and converts the date back to a date form.

Once our final list is complete, and to load them into the calendar, they are passed to the callback. The plugin handles all of the loading of data into the calendar. Remember from the MVC controller, it returned a title, start (date), and an allDay indicator. Using this data is what the FullCalendar plugin uses as the data source. More parameters

Knockout and Binding Lists

I have been using Knockout in an MVC project where I have been binding list-oriented data in the user interface.  I’ve been trying to use a more efficient approach to loading the UI by pushing the view with no data bound from the server, then following up with a subsequent request to serve up JSON, which populates the list.  This is the technique I’m focusing on in this article.  This means that the page builds an empty document model, then populates the model on document ready.  In my page, I build an empty view model:

function viewModel() {
var self = this;

self.listData = ko.observableArray([]);

Initially we start with an empty list.  At this point, on initial load, it’s beneficial to show something to the user that we have no data.  In order to do this, I found adding some computed properties for determining status was helpful.  These properties also existed in the model:

self.hasLoadedListData = ko.observable(false);
self.emptyListData = ko.computed(function() { return self.listData.length > 0; });

Here we have two properties, one for determining if we bound any data to the UI at all, and the second for determining whether the list is empty.  The difference between the two is that we may not want to show the list if there isn’t any data to bind; however, once we bound, we may want to instead show a “no records found” message, which the emptyListData property is used for.  Additionally, if we have no data to bind, and the observable points to a null value, we can get an exception too.  However, I’m going to shortly circumvent that by using the “if” binding.  In the user interface, we can setup the view to use these properties as so:

<div data-bind=”if:hasLoadedListData”>
<div data-bind=”if:emptyListData”>
No records found.
<div data-bind=”ifnot:emptyListData”>
<!– data template –>

Now it’s time to load the data.  Once data is passed to the model, it loads the view with the data at the time it’s populated.  I’m not going to get into the aspects of where the data comes from. Assuming we can get JSON from some data store, the JSON we would use, requested from JQuery, can then be passed to the view model, as in the following:

type: “post”,
url: “…”,
data: { .. },
success: function(d) {
viewModel.itemData(d.Data); //array data in Data property

Here we get the data in JSON form, grab the array data from the Data property (as it’s recommended to return an object as the root object, not an array, for security purposes), and push it to the model.  There is an interesting point here; when we push the data in, the data in the array is not observable by its nature.  While this data would load into the user interface, any changes made to the values of the individual objects themselves are not observable and do not participate in two-way binding.  You could do a conversion like:

from (var i = 0, len = d.Data.length; i < len; i++)
viewModel.itemData.push({ firstName: ko.observable(d.Data[i].firstName), .. });

Through this conversion, each object is observable and participates in two-way binding.

Now that we have our data, it loads into the user interface, either through the observable templates as I blogged about before, or through an inline template.