The Most Popular Articles of the Year

I suspect there may be a bunch of blog posts around the Internet that wrap up the year. Here are the most popular articles on my blog for the year:

React with ES6 and JSX

In fifth place, I did a series of articles on working with ECMAScript 2015 and React/Flux, working on getting a typical application working. I also poked into some stage0 proposals for ECMAScript7. I really enjoy working with React, but I’m torn between Custom Elements (and Polymer specifically) and React. Custom Elements are more standard – React is more popular. I’ll be revisiting this again next year (which is in 24 hours, but I’ll likely take longer than that).

Aurelia – a new framework for ES6

In fourth place, people were interested in how I would do my test tutorial with Aurelia. Aurelia is a really interesting framework and I prefer it over Ember and Angular. The learning curve is relatively small, although I will have to revisit the whole framework discussion as Angular 2 and Ember next-gen are coming out. This tutorial included using authentication with Auth0 and accessing remote resources.

ASP.NET MVC6 and Bootstrap

A one-off article on adding Bootstrap to ASP.NET MVC6 applications came in third place. There are other Bootstrap posts that are also interesting, including one that got made into a video.

Talking of ASP.NET MVC6

With the next revision of ASP.NET imminent, I took several strolls through the alpha and beta releases of that framework. There is a lot to like about it and a lot that is familiar. I’ve mostly switched over to a NodeJS environment now, so I’m not expecting to do much more in this area, but it is a much nicer environment that the old ASP.NET.

And finally, Visual Studio Tooling!

Fueled in large part by a link from the ASP.NET Community Articles page, the #1 page for the year was an article I wrote that described the Web Development extensions I used in Visual Studio. It also generated the most discussion with lots of people telling me about their favorite extensions. I’m using Visual Studio Code more these days – it’s lighter weight. I still love this list though.

Next Year

2015 was definitely the year that frameworks changed – In .NET land we got a look at the next revision of the ASP.NET framework, and in JavaScript land we got Aurelia, React, Flux, Relay, Angular-2, ES2015, Web Components, and several new versions of Node. I hope the framework releases calm down in 2016 so we can start sorting out the good from the bad and ugly. I’m going to take new looks at all this and work on my side projects. I hope you will continue the journey with me.

Authentication using Azure App Service with a Universal Windows App

Now that I have my offline task list app written (you can check it out on my GitHub Repository), it’s time to hook it up to some backend logic. I want to share my tasks everywhere and I want them tagged as mine so that other people can use the same app yet have different data. To do that, I need an identity. Microsoft Azure App Service Mobile Apps has three facilities that I am going to use – Authentication, Data Access and Offline Sync – and I’m going to implement them in that order.

To start, I can add a login button. I want the login button to be on the right. I also want the login button to turn into a Sync button once I’ve implemented the whole application. I changed the XAML in MainPage.xaml to support this:

        <AppBar Grid.Row="3" Background="LightGray">
            <Grid>
                <StackPanel Orientation="Horizontal">
                    <AppBarButton Label="Filter">
                        <AppBarButton.Icon>
                            <SymbolIcon Symbol="Filter"/>
                        </AppBarButton.Icon>
                        <AppBarButton.Flyout>
                            <Flyout>
                                <StackPanel>
                                    <CheckBox x:Name="IncludeCompletedCheckbox" IsChecked="True" Click="FilterCompletedTasks_Clicked">Completed</CheckBox>
                                </StackPanel>
                            </Flyout>
                        </AppBarButton.Flyout>
                    </AppBarButton>
                    <AppBarButton Label="Sort">
                        <AppBarButton.Icon>
                            <SymbolIcon Symbol="Sort"/>
                        </AppBarButton.Icon>
                        <AppBarButton.Flyout>
                            <Flyout>
                                <StackPanel Orientation="Vertical">
                                    <RadioButton x:Name="SortMethod_Unsorted" GroupName="SortOptions" IsChecked="True" Click="SortTasks_Clicked">Unsorted</RadioButton>
                                    <RadioButton x:Name="SortMethod_ByTitle" GroupName="SortOptions" Click="SortTasks_Clicked">By Title</RadioButton>
                                </StackPanel>
                            </Flyout>
                        </AppBarButton.Flyout>
                    </AppBarButton>
                </StackPanel>
                <StackPanel Orientation="Horizontal" HorizontalAlignment="Right">
                    <AppBarButton x:Name="loginSyncButton" Label="Login" Click="LoginSync_Clicked">
                        <AppBarButton.Icon>
                            <SymbolIcon Symbol="Sync"/>
                        </AppBarButton.Icon>
                    </AppBarButton>
                </StackPanel>
            </Grid>
        </AppBar>

Note that I’ve changed the internals of my AppBar. It’s now a grid with two stackpanels – the second stack panel is right justified. I’ve wired up an event handler called LoginSync_Clicked() that is implemented in the code-behind file:

        private async void LoginSync_Clicked(object sender, RoutedEventArgs e)
        {
            if (user == null)
            {

                try
                {
                    user = await App.MobileService.LoginAsync(MobileServiceAuthenticationProvider.MicrosoftAccount);
                    loginSyncButton.Label = "Sync";
                }
                catch (MobileServiceInvalidOperationException ex)
                {
                    System.Diagnostics.Debug.WriteLine(String.Format("Mobile Services Error: {0}", ex.Message));
                    user = null;
                    var dialog = new MessageDialog(ex.Message);
                    dialog.Commands.Add(new UICommand("OK"));
                    await dialog.ShowAsync();
                }
            }
            else
            {
                // Sync Action
                System.Diagnostics.Debug.WriteLine("MobileServices Sync");
            }
        }

The code here is ripped directly from the QuickStart tutorial for Authentication in Azure App Service Mobile Apps. You will need to add WindowsAzure.MobileServices as a NuGet package and select 2.0.0-beta-2. To get that, ensure “Include prerelease” is checked:

11032015-1

The variable user is a private variable defined at the top of the class:

private MobileServiceUser user = null

Finally, There is a variable in that code – App.MobileService – that appears in App.xaml.cs like this:

        // Reference to the Mobile Service Client connection
        public static MobileServiceClient MobileService = new MobileServiceClient(
            "https://ahall-mobile-nodebackend.azurewebsites.net",
            "https://ahall-mobile-nodebackend-gateway.azurewebsite.net",
            ""
        );

There are two URIs here – the URI for your mobile backend and the URI for the Authentication Gateway. You get those from the Azure Portal.

Creating a Mobile Backend in Azure

I have a fairly simple mobile backend right now. You can find the code on my blog post or with the Azure blog announcement. It actually does not matter if you have the Mobile API implemented or not for authentication – you just need something. In my case, I’ve created a mobile backend called ahall-mobile-nodebackend – it gets a URI from the portal and I’ve put that into the first argument of the MobileServiceClient() constructor call.

To create the gateway, open up your web app in the Azure Portal, click on Settings and then Mobile Authentication:

11032015-2

This will pop up a request to create the gateway. Do that by clicking on Create. Note that the site will close and you will be sitting at the top level page again. Resist the urge to go do it again. THe process is in progress and you can monitor the creation using the notifications area. Only go back when you see it has finished. Mine took only 2 minutes, so it isn’t a long time (unless you are waiting for it). When you go back in, you will see the five valid authentication schemes – Microsoft Account, Google, Facebook, Twitter and Azure Active Directory. I’m using the Microsoft Account for my application.

You need to get a Client ID and Client Secret for each authentication mechanism you choose. When I was using Auth0, they had developer keys already implemented so I could bypass this step. I’m using the Microsoft Account since this is the quickest of the set. I’m already a developer, so I just need to create the keys. Each authentication provider within the Azure Portal has a “how to set this up” link.

First off, copy your Redirect URL – you will need it. The redirect URL is in the Identity provider:

11032015-3

There is a convenient copy button next to it. Now, go to the Microsoft Account Developer Portal to register an application. If this is your first app, you will be presented with the create an application screen directly. Otherwise you will have to click on “Create an application” to see it:

11032015-4

Enter a name (I called mine “Quickstarts.UWP” and click on I accept. On the next screen, click on API Settings. Set “Mobile or desktop client app” to Yes and fill in the Redirect URL (you copied it earlier, right?) then click on Save.

11032015-5

Now click on App Settings. You will see the Client ID and Client Secret. The Client Secret should be protected (don’t check it into code).

11032015-6

Cut and paste the Client ID and Client Secret into the Identity Settings page on the Azure Portal in the appropriate fields. Remember to click on Save to save those settings.

Wrap Up

This turned out to be a lot easier than I thought. I was primarily worried about how my application would present the login screen and registering an app for a client ID and secret – it turned into a non-event. The Azure App Service Mobile Apps code to authenticate is easy. Just make sure you are using the latest SDK (v2.0.0-beta-2 right now) and follow the QuickStart tutorial.

And as always, you can get the code on my GitHub Repository.

Filtering and Sorting a ListView in a UWP – Part 2 – The Code

I have to admit that after the ease of implementing the UX for filtering and sorting, I was expecting the implementation of filtering and sorting to be easy. After all, prior versions of the Windows SDK and XAML had a nice CollectionViewSource object that had Filter and SortDescriptions fields and I just hook into them, right? Well, it didn’t turn out to be that easy. How on earth do others do it?

Implementing a Filtered Store

After consulting with others, reading a whole bunch of StackOverflow, and delving into the documentation, I settled on an implementation. Obviously, CollectionViewSource was not going to do it, so I might as well roll my own wrapper. The ListView requires an object that implements IList (so that it can iterate over the list) and INotifyCollectionChanged (so it knows when to change asynchronously). These are easy to implement, so I created a Models/FilteredTaskStore.cs as follows:

using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;
using System.Threading.Tasks;

namespace QuickStart.UWP.Models
{
    /// <summary>
    /// A filtered version of the task store.
    /// </summary>
    class FilteredTaskStore : INotifyCollectionChanged, IList
    {
        private TaskStore _store;
        private List<TaskItem> _view;
        private bool _filterCompleted = true;
        private string _sortMethod = null;

        /// <summary>
        /// Create a new FilteredTaskStore based on an existing TaskStore
        /// </summary>
        /// <param name="store">The TaskStore to base this filter on</param>
        public FilteredTaskStore(TaskStore <span class="hiddenGrammarError" pre="">store)
        {
            _store</span> = store;
            _view = new List<TaskItem>(this._store);
        }

        public bool IncludeCompletedItems
        {
            get
            {
                return _filterCompleted;
            }
            set
            {
                _filterCompleted = value;
                RefreshView();
            }
        }

        public string SortMethod
        {
            get
            {
                return _sortMethod;
            }
            set
            {
                _sortMethod = value;
                RefreshView();
            }
        }

In order to implement a filter, I need to keep the original (the TaskStore in my implementation) and I need to handle a view of the original (called _view). I’ve got a property for the filter – do I include completed items or not? I’ve also got a SortMethod which will be null or the field to be filtered. Note that when I set either the filter or the sort method, I call RefreshView() – more on that method later.

Since I am using Visual Studio, I right-clicked on the IList interface and told it to implement the interface based on the _view. This allows me to utilize this class as if it is a list. When you access it via the list specification, you are iterating over the view. In the code, I’ve surrounded this code as a #region so I can hide it. I’ve not touched that code from the scaffolding though.

In addition, I want to call this code as if it was a TaskStore. That means implementing the TaskStore methods and using a pass-through:

        #region TaskStore interface
        /// <summary>
        /// Create a new Task asynchronously
        /// </summary>
        /// <param name="item"></param>
        /// <returns></returns>
        public async Task Create(TaskItem item)
        {
            await _store.Create(item);
            RefreshView();
        }

        /// <summary>
        /// Update a task asynchronously
        /// </summary>
        /// <param name="item"></param>
        /// <returns></returns>
        public async Task Update(TaskItem item)
        {
            await _store.Update(item);
            RefreshView();
        }

        /// <summary>
        /// Delete a task asynchronously
        /// </summary>
        /// <param name="item"></param>
        /// <returns></returns>
        public async Task Delete(TaskItem item)
        {
            await _store.Delete(item);
            RefreshView();
        }
        #endregion

Just like the setter in the filter and sort method, I’m calling RefreshView() in addition to calling the equivalent in the backend store. This allows me to update the view according to the new store values. That leaves me RefreshView() to write:

        /// <summary>
        /// Refresh the view, based on filters and sorting mechanisms.
        /// </summary>
        public void RefreshView()
        {
            var oldItems = _view.ToArray();

            var tasks = _store.Where<TaskItem>(task => IncludeCompletedItems || !task.Completed);

            _view.Clear();
            _view.AddRange(tasks);
            if (CollectionChanged != null)
            {
                // Call the event handler for the updated list.
                CollectionChanged(this, new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset));
            }

        }

This version only filters – it doesn’t sort yet (more on THAT later). The Where statement is dynamic LINQ. In this case, I’ve said “where either include completed items is on OR (includes completed items is off and the task is not complete)”. I then build the new view based on the filtered list. Finally, I emit a Reset event on the CollectionChanged event delegate channel. This tells the ListView that the whole list has been updated and it needs to re-render everything.

Wiring in the Filtered Store

The wiring for the filtered store is everywhere. Firstly, I need to initialize it. I do this in the constructor for the main page (in MainPage.xaml.cs):

        public MainPage()
        {
            store = new FilteredTaskStore(new TaskStore());
            this.InitializeComponent();

            SizeChanged += MainPage_SizeChanged;
            tasksListView.ItemsSource = store;

            // Set up the defaults for filtering by the store definition
            IncludeCompletedCheckbox.IsChecked = store.IncludeCompletedItems;
        }

One of the things I discovered while doing this was that you can only set the ItemsSource once. As a result, you want to set it in the constructor and then leave it alone. I want to refresh the view of the filtered source when I navigate to the main page:

        /// <summary>
        /// Refresh the contents of the list when the page is loaded
        /// </summary>
        /// <param name="e"></param>
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            store.RefreshView();
        }

I also want to wire up the Filter option:

        private void FilterCompletedTasks_Clicked(object sender, RoutedEventArgs e)
        {
            var includeCompleted = (bool)((CheckBox)sender).IsChecked;
            store.IncludeCompletedItems = includeCompleted;
        }

The FilteredTaskStore object takes care of most of the refresh activities for me. Full disclosure – I also adjusted the XAML for the filter checkbox as follows:

                <AppBarButton Label="Filter">
                    <AppBarButton.Icon>
                        <SymbolIcon Symbol="Filter"/>
                    </AppBarButton.Icon>
                    <AppBarButton.Flyout>
                        <Flyout>
                            <StackPanel>
                                <CheckBox x:Name="IncludeCompletedCheckbox" IsChecked="True" Click="FilterCompletedTasks_Clicked">Completed</CheckBox>
                            </StackPanel>
                        </Flyout>
                    </AppBarButton.Flyout>
                </AppBarButton>

At this point you can run the code and see the filtering working. Pop open the filter box, uncheck the Include Completed checkbox, then check an item and watch it disappear. I did see a couple of visual bugs, but I’ll sort those out later.

Implementing Sorting

Sorting was now a case of wiring up the AppBarButton code to set the SortMethod and then implementing sorting in the RefreshView() method inside the FilteredTaskStore. To wire up the AppBarButton, I added a Click event handler to each RadioButton to call the same method:

                <AppBarButton Label="Sort">
                    <AppBarButton.Icon>
                        <SymbolIcon Symbol="Sort"/>
                    </AppBarButton.Icon>
                    <AppBarButton.Flyout>
                        <Flyout>
                            <StackPanel Orientation="Vertical">
                                <RadioButton x:Name="SortMethod_Unsorted" GroupName="SortOptions" IsChecked="True" Click="SortTasks_Clicked">Unsorted</RadioButton>
                                <RadioButton x:Name="SortMethod_ByTitle" GroupName="SortOptions" Click="SortTasks_Clicked">By Title</RadioButton>
                            </StackPanel>
                        </Flyout>
                    </AppBarButton.Flyout>
                </AppBarButton>

I need to implement the event handler in the MainPage.xaml.cs:

        private void SortTasks_Clicked(object sender, RoutedEventArgs e)
        {
            var b = ((RadioButton)sender).Name.Replace("SortMethod_","");
            store.SortMethod = (b.Equals("Unsorted")) ? null : b;
        }

Most of the interesting code is in the RefreshView() where I need to order the values:

        public void RefreshView()
        {
            var oldItems = _view.ToArray();

            var tasks = _store.Where(task => IncludeCompletedItems || !task.Completed);
            if (SortMethod != null)
            {
                if (SortMethod.Equals("ByTitle"))
                {
                    tasks = tasks.OrderBy(t => t.Title);
                }
            }

            _view.Clear();
            _view.AddRange(tasks);
            if (CollectionChanged != null)
            {
                // Call the event handler for the updated list.
                CollectionChanged(this, new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset));
            }
        }

Note that I’ve removed the specific model I’m using in the Where. There is no problem in the Where() clause but if you do that with the OrderBy, you’ll get an error that the method does not exist.

Wrap-up

Firstly, why did the folks who write this remove the filter and sort from the CollectionViewSource? That functionality would have made this so much easier! In that absence, there are definitely things I would implement in the FilteredTaskStore to make the UI look better. Most notably, I’d emit Add and Remove elements when I change the filtering mechanisms or add/remove an element. I’d also add an INotifyPropertyChanged interface when I update rather than updating the entire list.

So there are definitely things I can do to improve things, but as an example, this is great!

As always, you can find my code on my GitHub Repository.

Filtering and Sorting a ListView in a UWP – Part 1 – The UX

In my last article, I got the ListView that is driving my task list hooked up to my Task Store by making my Task Store an ObservableCollection. Today I am starting work on the UX for implementing filtering. I want two activities: I want to filter the tasks based on their completed status and I want to be able to sort tasks on something – title, since that’s the only thing I have.

To do this, I need an application bar. Right now, I have a placeholder piece of XML in there. It’s the fourth segment of my UI. Starting from the top, I have the title, the new task box, the list of tasks and finally the app bar. Appbars are relatively easy to produce:

        <AppBar Grid.Row="3" Background="LightGray">
            <StackPanel Orientation="Horizontal">
                <AppBarButton Label="Filter">
                    <AppBarButton.Icon>
                        <SymbolIcon Symbol="Filter"/>
                    </AppBarButton.Icon>
                </AppBarButton>
                <AppBarButton Label="Sort">
                    <AppBarButton.Icon>
                        <SymbolIcon Symbol="Sort"/>
                    </AppBarButton.Icon>
                </AppBarButton>
            </StackPanel>
        </AppBar>

One of the things I try to do is to expand the XAML out. It can always be consolidated later, but breaking it out when you need to is sometimes hard. As a result, this is a longer form than I normally do. If you run this, you will get a light gray bottom panel with an ellipsis on it. Pressing the ellipsis will expand the app bar and show two items on the left – a sort and filter icon. Since I’m using the symbol font, the standard icons are being used.

When I press these icons, I want a menu, but let me think about the menu for a moment. There are two types of menu – a standard flyout allows you to construct the menu yourself with a stack panel and any valid XAML. There is also a MenuFlyout for handling menus. There are MenuFlyoutItem types (a standard one, a separator and a toggle) that can be used to construct the menu. The difference is what happens when a menu item is selected. In the standard flyout, the menu remains open. In the MenuFlyout, the menu closes. If you want the menu to remain open, you must produce your own XAML code. If you are ok with it being closed automatically, then you can use a MenuFlyout. A MenuFlyout would look like this:

                <AppBarButton Label="Filter">
                    <AppBarButton.Icon>
                        <SymbolIcon Symbol="Filter"/>
                    </AppBarButton.Icon>
                    <AppBarButton.Flyout>
                        <MenuFlyout>
                            <ToggleMenuFlyoutItem x:Name="IncludeCompletedCheckbox" IsChecked="False">Completed</ToggleMenuFlyoutItem>
                        </MenuFlyout>
                    </AppBarButton.Flyout>
                </AppBarButton>

This menu contains one item. If I click on the Completed icon, it gets a check mark next to it and the menu is closed. This is great for menus that select new pages, but it is really a bad experience for menus that set or clear settings. I want a standard flyout here. Here is my XAML code that includes the flyout:

        <AppBar Grid.Row="3" Background="LightGray">
            <StackPanel Orientation="Horizontal">
                <AppBarButton Label="Filter">
                    <AppBarButton.Icon>
                        <SymbolIcon Symbol="Filter"/>
                    </AppBarButton.Icon>
                    <AppBarButton.Flyout>
                        <Flyout>
                            <StackPanel>
                                <CheckBox x:Name="IncludeCompletedCheckbox" IsChecked="False" Click="IncludeCompletedCheckbox_Changed">Completed</CheckBox>
                            </StackPanel>
                        </Flyout>
                    </AppBarButton.Flyout>
                </AppBarButton>
                <AppBarButton Label="Sort">
                    <AppBarButton.Icon>
                        <SymbolIcon Symbol="Sort"/>
                    </AppBarButton.Icon>
                    <AppBarButton.Flyout>
                        <Flyout>
                            <StackPanel Orientation="Vertical">
                                <RadioButton x:Name="SortMethod_Unsorted" GroupName="SortOptions" IsChecked="True" Checked="SortMethod_Changed">Unsorted</RadioButton>
                                <RadioButton x:Name="SortMethod_ByTitle" GroupName="SortOptions" Checked="SortMethod_Changed">By Title</RadioButton>
                            </StackPanel>
                        </Flyout>
                    </AppBarButton.Flyout>
                </AppBarButton>
            </StackPanel>
        </AppBar>

Clicking anywhere outside the menu will close the menu in both cases. It’s just a case of the action when a menu option is chosen. In this case, I’ve got a checkbox for the filter and I’ve got a radio button group for the sort mechanism. I’m using the standard styling here (I’ll do another blog post on styling when I work out how to do it), so the controls are clearly form controls.

Now for the code. In MainPage.xaml.cs – the code behind file for the XAML – I’ve defined an enum for the SortMethod:

    enum SortMethod
    {
        Unsorted,
        ByTitle
    }

I’ve also defined two private variables in the MainPage partial class. The default values reflect the default values in the XAML:

    public sealed partial class MainPage : Page
    {
        private TaskStore store;
        private bool includeCompleted = false;
        private SortMethod sortMethod = SortMethod.Unsorted;

The XAML defines two event handlers I need – one for the checkbox and one for the sort method. In both cases, they set the private variables so that the two values are in sync:

        private void IncludeCompletedCheckbox_Changed(object sender, RoutedEventArgs e)
        {
            this.includeCompleted = (bool)((CheckBox)sender).IsChecked;
            System.Diagnostics.Debug.WriteLine(string.Format("Include Completed = {0}", this.includeCompleted));
        }

        private void SortMethod_Changed(object sender, RoutedEventArgs e)
        {
            var item = (RadioButton)sender;
            if (item.Name.Equals("SortMethod_Unsorted"))
            {
                this.sortMethod = SortMethod.Unsorted;
            }
            else if (item.Name.Equals("SortMethod_ByTitle"))
            {
                this.sortMethod = SortMethod.ByTitle;
            }
            System.Diagnostics.Debug.WriteLine(string.Format("Sort Method = {0}", this.sortMethod));
        }

I could easily have a property that just returns these from the UI, but I think it’s more obvious when reading the code what is happening when I use a private variable intermediary. Right now, all I am doing is to change the private variables. These will be used by the filtered list, but that’s my next blog post. Until then, you can find this code in my GitHub Repository.

ListViews and The Task Store in a Universal Windows App

In my prior articles, I’ve gone through data binding and responsive design techniques for Universal Windows Apps. I bumped into a bug and it bit me badly. Here is the short version. I have a nice new task workflow – I enter some text in the new task area and click on Save and a new task is created. The actual code for this is fairly simple – it’s mostly in the backing file MainPage.xaml.cs:

        private async void SaveTaskButton_Click(object sender, RoutedEventArgs e)
        {
            await store.Create(new TaskItem { Title = NewTaskContent.Text.Trim() });
            NewTaskContent.Text = "";
        }

        private void NewTaskContent_TextChanged(object sender, TextChangedEventArgs e)
        {
            TextBox box = (TextBox)sender;
            SaveTaskButton.IsEnabled = (box.Text.Trim().Length > 0);
        }

I’ve wired this up in the XAML code like this:

        <Grid x:Name="NewTaskPanel" Grid.Row="1" Background="#00abec">
            <Grid.ColumnDefinitions>
                <ColumnDefinition Width="*"/>
                <ColumnDefinition Width="Auto"/>
            </Grid.ColumnDefinitions>

            <TextBox x:Name="NewTaskContent" Grid.Column="0" Margin="10,4,10,4" PlaceholderText="Enter a new task..." TextChanged="NewTaskContent_TextChanged"/>
            <Button x:Name="SaveTaskButton" Grid.Column="1" Margin="10,4,10,4" IsEnabled="False" Click="SaveTaskButton_Click">Save</Button>
        </Grid>

However, when I ran this code and added a new task, nothing happened. The new task box cleared, but the new task was not added to the list of tasks as I was expecting. My list, if you will remember, is just a standard List and that is bound to a ListView object using the ItemsSource property. A little bit of investigation – primarily by setting a breakpoint on the Create method in the TaskStore – showed that the task was actually being added to the store. The UI was not being updated.

So what is going wrong?

It turns out that it was a fairly simple problem, and one that seems to bite a lot of people. Stack Overflow to the rescue! The problem is that the ListView expects to be able to observe by registering a notify event handler on the object. My object did not implement that pattern. Fortunately, there is an ObservableCollection – I can make my store a version of the ObservableCollection and then assign the ItemsSource to the TaskStore directly.

First the Models/TaskStore.cs file:

using System;
using System.Collections.ObjectModel;
using System.Threading.Tasks;

// This file includes non-await code for an async interface
// it will execute synchronously - we are ok with that right
// now as the whole system will be replaced with an async
// version later on
#pragma warning disable 1998
namespace QuickStart.UWP.Models
{
    /// <summary>
    /// Implementation of the TaskStore - this is a basic
    /// CRUD type store.
    /// </summary>
    class TaskStore : ObservableCollection<TaskItem>
    {
        public TaskStore()
        {
            Add(new TaskItem { Id = Guid.NewGuid().ToString(), Title = "Task 1" });
            Add(new TaskItem { Id = Guid.NewGuid().ToString(), Title = "Task 2" });
        }

        public async Task Create(TaskItem item)
        {
            item.Id = Guid.NewGuid().ToString();
            this.Add(item);
        }

        public async Task Update(TaskItem item)
        {
            for (var idx = 0; idx < this.Count; idx++)
            {
                if (this.Items[idx].Id.Equals(item.Id))
                {
                    this.Items[idx] = item;
                }
            }
        }

        public async Task Delete(TaskItem item)
        {
            this.Remove(item);
        }

    }
}

Since my new code is an extension of an ObservableCollection, I don’t need to handle the retrieve or the retrieveAll methods – there are methods and properties already defined for this. I did want to create a couple of default tasks and handle Create, Update and Delete explicitly. Delete is just an async version of Remove; Create adds a Guid and Update has to find the right record before updating it.

With this new class, I can update the MainPage.xaml.cs as follows. Firstly, I removed the RefreshItems() method – it is no longer required. As long as I use the ObservableCollection, I can rely on the refresh. In the OnNavigatedTo() method, I just need to assign the TaskStore to the ItemsSource:

        /// <summary>
        /// Refresh the contents of the list when the page is loaded
        /// </summary>
        /// <param name="e"></param>
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            ListItems.ItemsSource = store;
        }

With this code, I can now add records to my in-memory data store and I can mark them as completed. Now I can get back to the filtering question I was handling for this! In the mean time, here is the code on my GitHub Repository.

Data Binding in Universal Windows Apps

I’m currently writing a simple task list as a Universal Windows App as part of my study to onboard onto my new job in Microsoft Azure. In the last article I explorer responsive design techniques for universal apps. Today was all about data binding. Explicitly, I wanted to create a simple task list and show it off in a scrollable list view. I figured I was going to need some sort of task store, so I also wanted to implement a simple CRUD store for holding my tasks.

Let’s go to the code. My model is called TaskItem – I’m placing both the model and the store in their own namespace. That way I can put them into their own project down the road if I need to share models between the UWP and, say, a web site. The Models/TaskItem.cs is fairly simple:

namespace QuickStart.UWP.Models
{
    class TaskItem
    {
        public string Id { get; set; }

        public string Title { get; set; }

        public bool Completed { get; set; }
    }
}

I know that my backend is likely to need a string as the Id, although I could choose anything and get the backend to convert it. Then I have the two fields I actually want to show off. These could be anything. I’m creating a task list, so I have the title and the completed flag. To go along with this, I have a simple store in Models/TaskStore.cs:

using System;
using System.Collections.Generic;
using System.Threading.Tasks;

// This file includes non-await code for an async interface
// it will execute synchronously - we are ok with that right
// now as the whole system will be replaced with an async
// version later on
#pragma warning disable 1998
namespace QuickStart.UWP.Models
{
    /// <summary>
    /// Implementation of the TaskStore - this is a basic
    /// CRUD type store.
    /// </summary>
    class TaskStore
    {
        private List<TaskItem> _items;

        public TaskStore()
        {
            _items = new List<TaskItem>();

            _items.Add(new TaskItem { Id = "0", Title = "Task 1" });
            _items.Add(new TaskItem { Id = "1", Title = "Task 2" });
        }

        public async Task CreateTaskItem(TaskItem item)
        {
            item.Id = Guid.NewGuid().ToString();
            _items.Add(item);
        }

        public async Task<TaskItem> RetrieveTaskItem(string itemID)
        {
            return _items.Find(t => t.Id.Equals(itemID));
        }

        public async Task UpdateTaskItem(TaskItem item)
        {
            var idx = _items.FindIndex(t => t.Id.Equals(item.Id));
            if (idx >= 0)
            {
                _items[idx] = item;
            }
        }

        public async Task DeleteTaskItem(TaskItem item)
        {
            var idx = _items.FindIndex(t => t.Id.Equals(item.Id));
            if (idx >= 0)
            {
                _items.RemoveAt(idx);
            }
        }

        public async Task<ICollection<TaskItem>> RetrieveTaskItems()
        {
            return _items;
        }
    }
}

This is a fairly simple CRUD implementation. In fact, I’ve named the methods after the CRUD operations. Note line 9. My current implementation is synchronous, but I want it to ACT like an async store. The pragma will squelch the warning about using async in synchronous methods. When I implement a backend store (for example, SQLite or Azure App Service Mobile Apps), then this will become async and I will remove the pragma.

Now to the main feature – the XAML code. From my prior code, I’ve got a MainPage.xaml with a scroll viewer in it. Within that, I’m going to implement a list view that does the 2-way data binding:

<ScrollViewer Grid.Row="2" HorizontalScrollBarVisibility="Hidden" VerticalScrollBarVisibility="Auto">
    <ListView x:Name="ListItems" Margin="5,5,0,0">
        <ListView.ItemTemplate>
            <DataTemplate>
                <StackPanel Orientation="Horizontal">
                    <CheckBox Name="CheckBoxComplete" IsChecked="{Binding Completed, Mode=TwoWay}" Margin="10,5" VerticalAlignment="Center" Content="{Binding Title}"/>
                </StackPanel>
            </DataTemplate>
        </ListView.ItemTemplate>
    </ListView>
</ScrollViewer>

The ScrollViewer puts scroll bars on whatever is inside it. I’ve hidden the horizontal scroll bar and made the vertical scroll bar pop up when the need arises. The contents is the ListView – a control that just repeats template across a bound entity. I’ve named this – more on why later. The template is a data template. The main thing to note here is the {Binding} elements. You can make the binding one way (the default) or two way. Each one has a property name and that is matched on the bound entity. My entity is going to be a list of TaskItems – each TaskItem has a title and a completed flag.

This doesn’t do anything without having something to iterate over. On the ListView, that’s the ItemsSource property, which takes – well – a list. You could have probably guessed that.

To set up the ItemsSource, I need to load it from the TaskStore. This is done in the MainPage.xaml.cs backing code file. First up, I have to create a TaskStore:

        private TaskStore store;

        public MainPage()
        {
            store = new TaskStore();
            this.InitializeComponent();
            SizeChanged += MainPage_SizeChanged;
        }

Since UWP applications only have one Main Page, this is safe. If it was less safe, I would ensure that the TaskStore is a singleton pattern and use TaskStore.Instance() instead. Next, I need to have a method that refreshes the items in the ItemsList control:

        /// <summary>
        /// Refresh the items in the list.
        /// </summary>
        private async void RefreshItems()
        {
            try
            {
                ListItems.ItemsSource = (List<TaskItem>)(await store.RetrieveTaskItems());
            }
            catch (Exception ex)
            {
                await new MessageDialog(ex.Message, "Error loading tasks").ShowAsync();
            }
        }

I’ve defined our TaskStore with an async interface with the expectation that it will be async in the future. That means I need to await for the results.

Finally, when the Main Page is brought up, I want to refresh the items. There is a special navigation event handler that I can use to do this:

        /// <summary>
        /// Refresh the contents of the list when the page is loaded
        /// </summary>
        /// <param name="e"></param>
        protected override async void OnNavigatedTo(NavigationEventArgs e)
        {
            RefreshItems();
        }

I don’t need to wire this up – this is a special event handler that is called no matter what happens. It’s defined by default in the Page object, so you have to override it to use it.

One of the things to note is that this is a two-way binding. That means the model is updated when the UI updates it. For instance, I created a CheckBoxComplete_Checked event handler to handle the case when a checkbox was checked. I put a debug line in there and set a breakpoint on the debug line so I could inspect the state. Taking a look at the store that I created in the main page, I saw this:

09202015-1

Note that the Completed flag is true. This reflects the state of the checkbox. This can be very useful when doing automatic saves, background loading or filtering. If you change the list, your UI updates automatically. However, I want to moderate all access through my store. This will make saving and such like easier later. As a result, I dropped the Mode=Twoway from the XAML declaration. Now I want to call store.UpdateTaskItem() in my event handler:

        /// <summary>
        /// Event handler that is called when a checkbox is set or cleared
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void CheckBoxComplete_Checked(object sender, RoutedEventArgs e)
        {
            CheckBox checkbox = (CheckBox)sender;
            TaskItem item = checkbox.DataContext as TaskItem;
            item.Completed = (bool)checkbox.IsChecked;
            await store.UpdateTaskItem(item);
            await RefreshItems();
        }

My XAML becomes this:

<CheckBox Name="CheckBoxComplete" 
    IsChecked="{Binding Completed}" 
    Margin="10,5" 
    VerticalAlignment="Center" 
    Content="{Binding Title}" 
    Checked="CheckBoxComplete_Checked" 
    Unchecked="CheckBoxComplete_Checked"/>

Now I have the one-way binding that I want. When I click on a checkbox, the event handler changes the value in the TaskItem and updates the store. It then refreshes the data binding from the store, which will update the task list.

Talking of filtering, that’s my next task, and I’ll tackle that in my next blog post. In the mean time, keep up with the sameple code I am writing by checkout out my GitHub repository.

Responsive Design in Universal Windows Apps

I’ve been working a little bit in Universal Windows apps recently as part of my onboarding of mobile apps at Microsoft Azure. It’s been a fun time. One of the things I found hard was to handle responsive design. How does one design for both a tablet and a phone, plus the various orientations of the devices? After all, the layout doesn’t just change. In HTML land, you have media queries – you can use CSS3 to control the visibility of the various pieces.

It turns out that there are two pieces you need to understand. The first is a XAML piece – defining a visual state manager that does the same thing as the content of the media queries. It alters the style of the components of the page. The second is a piece of code that sets the appropriate visual state. This can be considered the definition of the media query.

To start with, I created a Universal Windows App. I opened the MainPage.xaml file and put in the following XAML:

<Page
    x:Class="QuickStart.UWP.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:QuickStart.UWP"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d">

    <Grid x:Name="LayoutRoot" Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="*"/>
            <RowDefinition Height="26"/>
        </Grid.RowDefinitions>

        <StackPanel x:Name="TitlePanel" Grid.Row="0" Background="#00abec">
            <TextBlock x:Name="TopBrandName" Margin="10,4,10,0" FontSize="28" Foreground="LightGray">Azure App Service Mobile Apps</TextBlock>
            <TextBlock x:Name="TopProductName" Margin="10,0,10,0" FontSize="45" Foreground="White">Task List</TextBlock>
        </StackPanel>

        <Grid x:Name="NewTaskPanel" Grid.Row="1" Background="#00abec">
            <Grid.ColumnDefinitions>
                <ColumnDefinition Width="*"/>
                <ColumnDefinition Width="Auto"/>
            </Grid.ColumnDefinitions>

            <TextBox x:Name="NewTaskContent" Grid.Column="0" Margin="10,4,10,4" PlaceholderText="Enter a new task..."/>
            <Button x:Name="SaveTaskButton" Grid.Column="1" Margin="10,4,10,4">Save</Button>
        </Grid>

        <ScrollViewer Grid.Row="2">

        </ScrollViewer>

        <AppBar Grid.Row="3">

        </AppBar>
    </Grid>
</Page>

This looks really good – I’ve got a brand title and a product title, my “enter a task” box with a save button and a couple of other areas that I haven’t filled in yet. The problem is in running this. If you go to a narrow screen, the title gets cut off, which is not a good experience. In addition, if I turn the device into a landscape mode, the title take a good chunk of real estate. I’ve decided I want to turn off the brand title when I’m on a smaller screen.

The first step is to define two visual states. I’ll have a Normal state and a Narrow state, defined like this:

        <VisualStateManager.VisualStateGroups>
            <VisualStateGroup x:Name="VisualStateGroup">
                <VisualState x:Name="Narrow">
                    <Storyboard>
                        <!-- List my changes to the normal here -->
                    </Storyboard>
                </VisualState>
                <VisualState x:Name="Normal"/>
            </VisualStateGroup>
        </VisualStateManager.VisualStateGroups>

My existing layout is my “normal” layout. I’m going to make some changes inside the storyboard section for the narrow layout. In my case, I’m going to make the visibility of the title block “collapsed” which will turn it off:

<ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="(UIElement.Visibility)" Storyboard.TargetName="TopBrandName">
    <DiscreteObjectKeyFrame KeyTime="0">
        <DiscreteObjectKeyFrame.Value>
            <Visibility>Collapsed</Visibility>
        </DiscreteObjectKeyFrame.Value>
    </DiscreteObjectKeyFrame>
</ObjectAnimationUsingKeyFrames>

This may seem like ludicrous amounts of code to turn something off – it allows you to do animations when a device goes from one state to another, which may result in a more pleasing effect. For my purposes, this isn’t a tutorial on animations, so I can just turn the visibility to collapsed. I can turn different properties to different things.

I don’t have to have a story board for the normal layout – I’ve already defined it.

Now for the code. In the MainPage.xaml.cs code behind file, I need to add an event handler for when the device size changes:

        public MainPage()
        {
            this.InitializeComponent();
            SizeChanged += MainPage_SizeChanged;
        }

This, of course, means I have to define a Size Changed function as well.

        private void MainPage_SizeChanged(object sender, SizeChangedEventArgs e) {
          var state = "Normal";
            if (e.NewSize.Width < 600 || e.NewSize.Height < 600)
            {
                state = "Narrow";
            }
            VisualStateManager.GoToState(this, state, true);
        }

I’ve named the visual states in the XAML code (check out the x:Name properties in the VisualState tag). I have to tell the VisualStateManager to change to that state. It will then apply the changes to the layout for me. My default state is “Normal”. I set the state explicitly to “Narrow” if I want the narrow styling to be applied – in this case, if the width or height of the new window is too small.

Run this project and resize the window – as it gets smaller, you will note the title at the top removed, but it is put back again when the display is widened.

You can have as many visual states as you want and adjust everything about the layout that you need. Visual Studio is also distributed with another tool called Blend that makes visual state editing easy to do. If you are more of a visual editor, check it out. There are plenty of tutorials out of the web now you know what the feature is called.