Nick's .NET Travels

Continually looking for the yellow brick road so I can catch me a wizard....

Calculator App in 100 Lines

A bit of a challenge was set off over the last week which I think started after Don Syme tweeted about a Calculator sample app that had been done in 95 lines of code

image

Github repo at https://github.com/nosami/Elmish.Calculator and was based off a Xamarin sample https://github.com/xamarin/mobile-samples/tree/master/LivePlayer/BasicCalculator

As there was a bit of discussion as to the pros and cons of different mobile platforms, some of the community set out to see how many lines of code it would take them to build the same sample. Thomas tweeted about doing it in Flutter which originally came in a 93 lines of code (I question the choice of colours and definitely prefer the colours in the original sample)

Update: In my original post I didn’t link to the correct info. Thomas’ calculator came in at 90 lines of code and sticks with the original colour scheme

Github: https://github.com/escamoteur/flutter_calculator

There was an alternative colour scheme proposed which came in at 93 lines of code

image

Github repo: https://github.com/fmatosqg/flutter_calculator

I tweeted in jest that a XAML app wouldn’t get out of bed for less than 100 lines of code, and sure enough when I did a very quick attempt it came in at approximately 70 lines of XAML and the same again for codebehind, so ~140 lines all up. I think with a bit of optimising I could get it down to say 120 lines but the reality is that XAML is verbose and that there is a cost associated with splitting the code between XAML and codebehind. Of course, if I’d actually applied an MVVM pattern it’d probably jump up to say 150 lines of code.

One way I could optimise this to get a result closer to either the Elmish or Flutter examples would be to do all my layout in code. I mentioned in my post on using declarative C# that following Vincent’s example of using extension methods you can easily do your layout in C# and avoid any of the overhead of splitting out XAML, C# and ViewModel code.

The question I ask is what do we lose in defining layout in code. As Vincent points out in his example, the answer can be that we lose very little but my concern is that whilst defining layout in code works for seasoned developers, how will it go with more junior developers?

For those who have been building apps for long enough, you’ll remember how we despised building Windows Forms applications because all the layout was done in code – sure there was a design experience, but before long you were writing a lot of logic to manipulate the UI which resulted in mal-formed code that was a pain to debug/maintain. Is this where we’re going to end up with all these code-first approaches to defining layout? (and this question isn’t about which platform is better, it’s about declarative over coded UI).

By way of example, stop and take a look at the code Thomas put together in his Flutter example – very efficient but imagine it on a much more complex application. You can quite easily see how it’s going to become hard to understand/follow for a developer who has to maintain it.

Redux and the State of My XAML Application (part 3)

This is the final part in this series looking at using Redux in a XAML application. Previous parts:

- Part 1 - https://nicksnettravels.builttoroam.com/post/2018/05/15/Redux-and-the-State-of-My-XAML-Application-(part-1).aspx

- Part 2 - https://nicksnettravels.builttoroam.com/post/2018/05/16/Redux-and-the-State-of-My-XAML-Application-(part-2).aspx

At the end of Part 2 I left you wondering what magic I’m using to prevent the entire list being refreshed as items were being added/removed from the Family. In this post we’ll look at what’s going on behind the scenes.

Let’s start with the bolded text from the XAML in Part 2 – I’ve included it here so you don’t need to go back and look.

<Page.Resources>
   <converters:ImmutableDataConverter x:Key="ImmutableDataConverter"/>
</Page.Resources>
<Grid DataContext="{Binding Converter={StaticResource ImmutableDataConverter}}">

So the secret ingredient is the ImmutableDataConverter which takes the current DataContext (which will be an instance of the MainViewModel) and returns an object that will become the DataContext for the rest of the page. The question is, what is this object and what does it do?

If you recall the issue we saw when we didn’t use the ImmutableDataConverter is that when the Data property on the MainViewModel changes (ie raised the PropertyChanged event) every data bound element on the page is refreshed. What we want is that only the elements on the page where data has changed should be updated. To do this, we need to step through the Data object and only raise PropertyChanged for the parts that have actually changed. Based on this description, the ImmutableDataConverter has to have the smarts to a) prevent PropertyChanged causing the entire UI to refresh and b) be able to iterate over every object in the Data object graph and where appropriate raise the PropertyChanged event.

Behind the scenes the ImmutableDataConverter is super simple – all it does is create an instance of the ImmutableDataWrapper<T> class. It uses a small piece of reflection to determine what the generic parameter should be based on the implementation of the IHasImmutableData interface on the MainViewModel.

The ImmutableDataWrapper<T> exposes a single property Data, of type T (and it’s no coincidence that this is the same as the IHasImmutableData<T> interface which also exposes a property Data, of type T – thereby making it simple to add the ImmutableDataConverter without changing any other lines of XAML). It also listens to the PropertyChanged event on the source entity, which in this case is the MainViewModel. Now instead of the PropertyChanged event on the MainViewModel being picked up by the MainPage, it is instead picked up by the ImmutableDataWrapper and used to invoke the ChangeData method where all the work happens.

The ChangeData method is used to compare the old Data object with the new Data object (ie the value that is set on the MainViewModel when the PropertyChanged event is triggered). It does this by using reflection to step through each property on the Data object:

- Properties that are of value type, or string, are updated on the old Data object if the value on the new Data object is different – the PropertyChanged event is raised for just that property.

- For properties that return a non-value type (or string) reflection is used to interrogate the nested entity and work out which properties need to be updated.

- For ObservableCollections some basic list change detection is used to trigger add/remove events on the collection on the old Data object – we can probably improve the logic here to be more efficient but for the moment it does the job.

As you can imagine there’s quite a bit of reflection that has to go on each time the Data object changes. Assuming that the Data object could change quite a bit, we don’t want to be doing reflection every time, which is where the TypeHelper class comes it. The TypeHelper class has some smarts of assisting with both checking to see if an entity has change, and for updating entities. Based on the type of entity, it caches methods that are used for comparison and updating entities. You can check out the TypeHelper class if you want to see more of the details

So lastly, let’s look at the requirements for the ViewModel and your Data entity:

- ViewModel needs to implement IHasImmutableData

- Data entity (and any nested entities) needs to implement INotifyPropertyChanged but also IRaisePropertyChanged – this is required so that the ChangeData method can raise the PropertyChanged on behalf of a data entity

- Properties on the Data entity (and any nested entities) should not raise PropertyChanged – otherwise there will be multiple PropertyChanged events raised

- Any collections within the Data entity hierarchy should use ObservableCollection<T>

A couple of final pointers:

- Currently this is only available for UWP – I need to implement the appropriate converter for Xamarin.Forms (and I guess WPF if anyone cares?)

- Currently this is not thread safe – make sure you update the Data property on the ViewModel on the UI thread.

Redux and the State of My XAML Application (part 2)

In part 1 I talked a bit about the challenge that XAML based applications face when trying to use a pattern such as Redux. In this post I’m going to jump in and use Redux.NET to demonstrate the issue, and the show how we can make a small adaption to the XAML to fix this issue.

We’ll start with the basic – our application state is a Person entity, with a Name property and a Family property. The Family property is an ObservableCollection of Person:

public class Person : NotifyBase
{
     public string Name { get; set; }

    public ObservableCollection<Person> Family { get; set; } = new ObservableCollection<Person>();
}

In this case NotifyBase comes from the BuildIt.General library and implements INotifyPropertyChanged. It also implements IRaisePropertyChanged which exposes a RaisePropertyChanged method which can be called in order to raise a PropertyChanged event on the object – we’ll come to why this is important later.

Implementing the Redux pattern starts with the Store, and in this case I’m just going to expose this as a static property off the App class. In reality you’d probably register this with your IoC container and have it injected into your ViewModel but to keep things simple I’m just creating it as a static property.

sealed partial class App : Application
{
     public static IStore<Person> PersonStore { get; private set; } = new Store<Person>(reducer: PersonReducer.Execute, initialState: new Person { Name = "Fred" });

The Store of course requires a Reducer, which in this case will be the PersonReducer class

public static class PersonReducer
{
     private static Random rnd = new Random();
     public static Person Execute(Person state, IAction action)
     {
         if (action is AddAction addAction)
         {
             var newPerson = new Person { Name = addAction.NameOfNewFamilyMember };

            return new Person
             {
                 Name = state.Name,
                 Family = state.Family.DeepClone().AddItem(newPerson)
             };
         }

        if (action is RemoveAction)
         {
             var idxToRemove = rnd.Next(0, 1000) % state.Family.Count;
             return new Person
             {
                 Name = state.Name,
                 Family = state.Family.DeepClone().RemoveItemAt(idxToRemove)
             };
         }

        return state;
     }
}

As you can see from the code the PersonReducer implements two actions: AddAction and RemoveAction. We’ll create these as classes

public class AddAction : IAction
{
     public string NameOfNewFamilyMember { get; set; }
}

public class RemoveAction : IAction { }

The other thing to note about the PersonReducer is that both actions return entirely new Person entities. It also makes use of a couple of helper methods:

public static class ReduxHelpers
{

    public static ObservableCollection<T> DeepClone<T>(this ObservableCollection<T> source) where T : new()
     {
         var collection = new ObservableCollection<T>();
         var helper = TypeHelper.RetrieveHelperForType(typeof(T));
         foreach (var item in source)
         {
             var newItem = new T();
             helper.DeepUpdater(newItem, item);
             collection.Add(newItem);
         }
         return collection;
     }

    public static ObservableCollection<T> AddItem<T>(this ObservableCollection<T> source, T itemToAdd)
     {
         source.Add(itemToAdd);
         return source;
     }

    public static ObservableCollection<T> RemoveItemAt<T>(this ObservableCollection<T> source, int index)
     {
         if (index < 0 || index >= source.Count) return source;
         source.RemoveAt(index);
         return source;
     }
}

Note: These extension methods will be added to BuildIt.General in the coming days and they rely on other types/methods (such as the TypeHelper class) that are already part of the BuildIt.General library.

With the Store and Reducer defined, we can define our MainViewModel

public class MainViewModel : NotifyBase, IHasImmutableData<Person>
{
     private Person data;
     public Person Data
     {
         get => data;
         set => SetProperty(ref data, value);
     }

    public MainViewModel()
     {
         App.PersonStore.Subscribe(newData => Data = newData);
     }
}

As this code shows, when the state in the Store changes, we’re just updating the Data property on the MainViewModel, this will in turn raise the PropertyChanged event causing the UI to be re-bound. Let’s take a look at the XAML for the MainPage.xaml:

<Page
     x:Class="reduxsample.MainPage"
     xmlns="
http://schemas.microsoft.com/winfx/2006/xaml/presentation"
     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
     xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
     xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
     xmlns:converters="using:BuildIt.UI.Converters"
     mc:Ignorable="d"
     Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
     <Page.Resources>
         <converters:ImmutableDataConverter x:Key="ImmutableDataConverter"/>
     </Page.Resources>

     <Grid DataContext="{Binding Converter={StaticResource ImmutableDataConverter}}">
         <Grid DataContext="{Binding Data}">
             <Grid.RowDefinitions>
                 <RowDefinition Height="Auto"/>
                 <RowDefinition />
             </Grid.RowDefinitions>
             <StackPanel Grid.Row="0">
                 <TextBlock Text="Name"/>
                 <TextBlock Text="{Binding Name}"/>
                 <TextBlock Text="Family member to add"/>
                 <TextBox x:Name="NewFamilyMemberName"/>
                 <Button Content="Add" Click="AddFamilyClick"/>
                 <Button Content="Remove" Click="RemoveFamilyClick"/>
             </StackPanel>
             <ListView Grid.Row="1" ItemsSource="{Binding Family}">
                 <ListView.ItemTemplate>
                     <DataTemplate>
                         <Border
                             BorderBrush="Azure"
                             BorderThickness="0,0,0,1">
                             <TextBlock Text="{Binding Name}"/>
                         </Border>
                     </DataTemplate>
                 </ListView.ItemTemplate>
             </ListView>
         </Grid>
     </Grid>
</Page>

This is all stock XAML with the exception of the Bold text (which we’ll come to in a minute). First, let’s add the methods for adding and removing family members

public sealed partial class MainPage : Page
{
     public MainPage()
     {
         this.InitializeComponent();

        DataContext = new MainViewModel();
     }
     private void AddFamilyClick(object sender, RoutedEventArgs e)
     {
         App.PersonStore.Dispatch(new AddAction { NameOfNewFamilyMember = NewFamilyMemberName.Text });
     }
     private void RemoveFamilyClick(object sender, RoutedEventArgs e)
     {
         App.PersonStore.Dispatch(new RemoveAction());
     }
}

Ok, now for a minute, let’s go back to the XAML and for a minute imagine that the bold text isn’t there. Now when we run the app and click the Add or Remove button, the Data property on the MainViewModel will get repopulated – the implication on the UI is that the ListView which binds to the Family property will refresh entirely. This will cause a flicker, and will drop any selected state and/or scroll position on the list – generally a really bad user experience.

With the bold text left in the XAML, when we run the app and click the Add or Remove button, only the properties that have changed are refreshed – there is no flicker on the ListView and any selection/scroll position is maintained….. so what’s going on…. can you work out why IRaisePropertyChanged is important…. more to come in my next post.

Redux and the State of My XAML Application (part 1)

Recently there has been quite a bit of noise about new tools and technologies (eg Flutter) and how they’re going to reshape how we build mobile applications. Various developers have blown a lot of smoke into the ecosystem as they’ve thrown in the towel with one technology and jumped headlong into the unknown. In this post I wanted to explore one of the key architectural differences that has developers up in arms about.

Let’s firstly step back a few, or more, years back to the dark ages of building Windows Forms (WinForms) applications where everything was done via imperative code. Visual Studio provided some basic abstraction from designer generated code v’s developer code but other than that everything was done manually. Whilst WinForms did have a form of data binding, it was so hard to get it to work well, most apps ended up resorting to writing logic to set properties on the UI elements directly.

A little further along the timeline we see the introduction of XAML (WPF, Silverlight etc) where data binding was a first class citizen. Enter the age of the MVVM pattern which was widely adopted as it offered a great separation of concerns between the view (ie the XAML) and the logic of the app. Personally I’ve never seen MVVM as much more than just the use of data binding. Recently I’ve heard of all sorts of reasons why developers thought that MVVM was being used, such as allowing the reuse of ViewModels and/or Models across different apps – I’m not sure where this concept came from but the reality is that it never happens. I think MVVM is still just about making it easier to test the logic of the application without having to spin up the UI.

Databinding works well, allowing the UI to be declaratively defined (either in XAML or code) but it doesn’t prescribe how an application should be architected behind the scenes. There are some frameworks, such as MvvmCross that help with a lot of the boilerplate logic (app start up, DI framework, navigation etc), but that’s where the guidance ends. For simple applications this isn’t an issue, and for a lot of application complexity is kept quite low, which means that keeping business logic, and state, on a page by page basis isn’t an issue. However, over time applications grow, and the complexity increases. This was identified by Facebook as the complexity of their website grew and they needed a more effective way to manage state. At this point I’m going to skip ahead to Redux (there’s more background at redux.js.org) which aims to solve the issue of state management within an application using a mono-direction flow to ensure consistency of state. I’m also not going to proclaim to be a guru on Redux, I just want to point to how it supports a new wave of React style development. The essential concept is that app state is immutable and that any changes result in a new state.

If you take a look at the way that Flutter builds their UI, the layout is made up of a sequence of widgets generated each time the build method is invoked. As the state of the application changes, a call to setState will trigger the build method to be run, yielding a completely new set of widgets that will be painted in the next pass to the screen. It’s pretty obvious that if the app state is being regenerated on each change (ie Redux pattern), this plays nicely with the setState/build flow that’s core to Flutter.

So, the question is – if we want to take advantage of Redux, do we have to abandon ship and start building Flutter apps? Well if you want to give up on all the years of experience you have, the mature ecosystem, and all the platforms that Flutter doesn’t support, sure, why not, but I do feel that in the absence of other reasons, that this is a bit like throwing the baby out with the bathwater.

To rephrase the question – in a XAML application, how do we take advantage of Redux? Well the good news is that half the work is already done – Redux.NET. However, I would caution you not to follow the rather simplistic examples given on the project website which essentially disposes of the use of data binding – if you’re going to do that, just go build your app using a different technology. Instead, we need to think a bit more about how we can marry the concept of immutable state with data binding.

The naïve approach is to expose the state of the application as a property and then every time the state changes, we update the property with the new value. For example the following ViewModel exposes a Person object which represents the current state of this simple application.

public class MainViewModel : INotifyPropertyChanged
{
     private Person data;

    public Person Data
     {
         get => data;
         set => SetProperty(ref data, value);
     }

This approach will work and as the Data property is updated with new Person entities, the data bound UI will update accordingly. However, if the Person object is moderately complex, with nested data bound properties, when you update the Data property there will be some nasty UI artefacts – this is because triggering PropertyChanged on the Data property will force every data binding that starts with Data to be re-evaluated. Imagine that the Person entity has a property Family, which is a list of Person entities, and that property is data bound to a ListView. If the Data property changes, the entire ListView will be repopulated, losing any selection or scroll position, not to mention other visual artefacts such as a flicker as it redraws. Clearly this isn’t what we want to happen.

This leads us to the question of how change is managed within our application. Let’s go back over our history lesson:

- With WinForms we were required to do everything. Every change within our application we needed to evaluate whether something needed to change on the UI, and then we’d explicitly set the appropriate property on the control.

- With XAML based applications we updated properties that were data bound. We still needed to work out what changed, because we didn’t want to raise the PropertyChanged event more than was absolutely necessary.

- With React style applications we no longer need to track what’s changed, we just use the latest state to build the UI.

The latter sounds great, except for the reality is that there is going to be some change tracking going on, we just don’t need to code for it. Let’s look at an example – say we have a list of items on the screen and the user has scrolled half way down the list. If the UI was to just be rebuilt, that scroll position would be lost. The same applies to text entered into a text field etc.

Perhaps what we need to do is to abstract away the need to work out what’s changed and invoke PropertyChanged only for the properties that have actually changed – if we can do that, then updating our Data property can be done as much as it needed without worrying about weird UI artefacts……

Part 2 will show an example of how changing state can be handled in a XAML application along with using Redux to keep our state immutable