Tuesday 14 April 2015

WinRt Relay Command with Parameter

If you start using the Out-of-The-Box RelayCommand in WinRt that in a phone project gets added to the Common folder and you start binding commands you quickly realize that even though there is an execute method that takes in a parameter:

/// <summary>
/// Executes the <see cref="RelayCommand"/> on the current command target.
/// </summary>
/// <param name="parameter">
/// Data used by the command. If the command does not require data to be passed,
/// this object can be set to null.
/// </param>
public void Execute(object parameter)
{
    _execute();
}

this method doesn't actually call the Action delegate "_execute()" with the Parameter, so why the hell is it there? seriously if someone knows please tell me.

What I did to get around this kerfuffle, is I added a private Action<object> delegate to store my command that expects a parameter.

private readonly Action<object> _executeWithParameter;

I then added added two constructors one that would accept my Action<object> delegate and a second that would accept both my Action<object> delegate and a func<bool> delegate for canExecute, much like the logic that is auto generated for you.

/// <summary>
/// Creates a new command that expects a parameter
/// </summary>
/// <param name="execute"></param>
public RelayCommand(Action<object> execute) : this(execute, null) { }


/// <summary>
/// Creates a new command that expects a parameter
/// </summary>
/// <param name="execute"></param>
/// <param name="canExecute"></param>
public RelayCommand(Action<object> execute, Func<bool> canExecute)
{
    if (execute == null)
        throw new ArgumentNullException("execute");
    _executeWithParameter = execute;
    _canExecute = canExecute;
}

now finally I modified the Execute Method to call the parameter-less _execute delegate if either the parameter or my _executeWithParameter delegate is null, otherwise I call my _executeWithParameter Delegate.

/// <summary>
/// Executes the <see cref="RelayCommand"/> on the current command target.
/// </summary>
/// <param name="parameter">
/// Data used by the command. If the command does not require data to be passed, this object can be set to null.
/// </param>
public void Execute(object parameter)
{
    if (parameter == null || _executeWithParameter == null)
        _execute();
    else
        _executeWithParameter(parameter);
}

Now I'm not 100% sure if this is the best way to skin this cat, but it's what I did and it's working, if someone has a better solution that doesn't involve installing a mvvm toolkit, I'm all ears. 

The Final class looks like the following:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Input;

namespace pc.activFitnes.phone81.Common
{
/// <summary>
/// A command whose sole purpose is to relay its functionality
/// to other objects by invoking delegates.
/// The default return value for the CanExecute method is 'true'.
/// <see cref="RaiseCanExecuteChanged"/> needs to be called whenever
/// <see cref="CanExecute"/> is expected to return a different value.
/// </summary>
public class RelayCommand : ICommand
{
private readonly Action _execute;
private readonly Action<object> _executeWithParameter;
private readonly Func<bool> _canExecute;

/// <summary>
/// Raised when RaiseCanExecuteChanged is called.
/// </summary>
public event EventHandler CanExecuteChanged;

/// <summary>
/// Creates a new command that can always execute.
/// </summary>
/// <param name="execute">The execution logic.</param>
public RelayCommand(Action execute) : this(execute, null) { }

/// <summary>
/// Creates a new command that expects a parameter
/// </summary>
/// <param name="execute"></param>
public RelayCommand(Action<object> execute) : this(execute, null) { }

/// <summary>
/// Creates a new command.
/// </summary>
/// <param name="execute">The execution logic.</param>
/// <param name="canExecute">The execution status logic.</param>
public RelayCommand(Action execute, Func<bool> canExecute)
{
    if (execute == null)
        throw new ArgumentNullException("execute");
    _execute = execute;
    _canExecute = canExecute;
}

/// <summary>
/// Creates a new command that expects a parameter
/// </summary>
/// <param name="execute"></param>
/// <param name="canExecute"></param>
public RelayCommand(Action<object> execute, Func<bool> canExecute)
{
    if (execute == null)
        throw new ArgumentNullException("execute");
    _executeWithParameter = execute;
    _canExecute = canExecute;
}

/// <summary>
/// Determines whether this <see cref="RelayCommand"/> can execute in its current state.
/// </summary>
/// <param name="parameter">
/// Data used by the command. If the command does not require data to be passed, 
/// this object can be set to null.
/// </param>
/// <returns>true if this command can be executed; otherwise, false.</returns>
public bool CanExecute(object parameter)
{
    return _canExecute == null ? true : _canExecute();
}

/// <summary>
/// Executes the <see cref="RelayCommand"/> on the current command target.
/// </summary>
/// <param name="parameter">
/// Data used by the command. If the command does not require data to be passed, 
/// this object can be set to null.
/// </param>
public void Execute(object parameter)
{
    if (parameter == null || _executeWithParameter == null)
        _execute();
    else
        _executeWithParameter(parameter);
}

/// <summary>
/// Method used to raise the <see cref="CanExecuteChanged"/> event
/// to indicate that the return value of the <see cref="CanExecute"/>
/// method has changed.
/// </summary>
public void RaiseCanExecuteChanged()
{
    var handler = CanExecuteChanged;
    if (handler != null)
    {
        handler(thisEventArgs.Empty);
    }
}
}
}

Wednesday 8 April 2015

Dependency Property

Before discussing what a dependency propriety it's good to go over what a regular property is; A property is an accessor to a field, that is the public property PropertyName {get; set;} is actually used to retrieve or set a private backing field, think of it as a gatekeeper; when all you see is:


public string Name { get; set; }

what it actually complies into is


private string _name;

public string Name
{
    get { return _name; }
    set { _name = value; }

}

Well at the c# level once it goes into msil then that's another story.

This paradigm allows you to do validation on the setting of the backing field or sanitation on the getting of the backing field.

Now there is a drawback to such properties, and that is that the take up memory, not a big deal right? well let's say you have a control that has 50 properties, each on of them takes up memory, so if you now have multiple instances of this control (let's say a button or a textbox) well then that's 50 times however many instances of that control you have on your form; as you can imagine these properties will chew through your memory. Worse yet how many of these properties do you change from their default values, 3? maybe 5?

In come Dependency Properties, you can think of dependency properties as static if they are left in their default state, that means for example: all buttons share the IsEnabled property if it's left in it's default value of true, only when the value is changed on a control is the dependency property stored.

Any class that wants to use a dependency property must inherit from DependencyObject, inside of this baseclass there exists the mechanism that stores all of the customized values in a key value dictionary, Internally when you call the GetValue(DependencyProperty) function on a dependency property first the dictionary is checked for a set local value, if one does not exist, the mechanism walks up the logical tree looking for an inherited value (ie something like font) then finally if it walks all the way up the logical tree it takes the default static value of the dependency property.

As mentioned Dependency Properties allow controls to use inheritance; often when you set properties such as font or color you want them to be inherited by the controls children, as mentioned if no defined local value exists for a Dependency Property it will next try to find the inherited value before defaulting to the static one.

Possibly the most advantageous benefit of Dependency Properties is Change Notification, when you declare a Dependency Property you pass in a callback that notifies you if the value is changed, this is utilized by DataBinding.

In Summary Dependency Properties bring Three Main advantages to the Table

  1. Change Notification: mainly used by animations to change values
  2. Reduced Memory Footprint: Static default values, allow you to share backing fields
  3. Value Inheritance: allow dependency Properties to inherit values from parent controls.

Let's take a deeper look,  now remember when I said that Dependency properties resolve to their local value, inherited value and then their default value? we'll I left 7 other things they could resolve to:
  1. Animation: the current animation that is being executed on your control. 
  2. Bound Value: the corresponding property bound to in a ViewModel 
  3. Local Value: a local value that is set in the xaml 
  4. Template Properties: values set in a control template 
  5. Custom Style Setter: a style that is specified in the resources of either your page or app 
  6. Default Style Trigger 
  7. Default Style Setter: A value that is defined at: "C:\Program Files (x86)\Windows Kits\8.1\Include\winrt\xaml\design" 
  8. Inherited Value: A value from a parent control that has the same Property 
  9. Default Value: the value specified when the Property is Registered
Now to declare a Dependency property look below

public int MyProp
{
    get { return (int)GetValue(MyPropProperty); }
    set { SetValue(MyPropProperty, value); }
}

// Using a DependencyProperty as the backing store for MyProp.  This enables animation, styling, binding, etc...
public static readonly DependencyProperty MyPropProperty =
DependencyProperty.Register("MyProp"typeof(int), typeof(Exercise),new PropertyMetadata(0));

Visual studio has a propdb snippet to save you the trouble of memorizing this.

  1. The first parameter is the key associated with the dependency property it has to match the accessor Property name, 
  2. the second is the type that the property represents, 
  3. the third is the class that the dependency property is in, 

The third property is where the action happens, it has 5 constructors PropertyMetadata basically it has three potential parameters:

  1. Object: a default value for the Dependency property 
  2. PropertyChangedCallback: a delegate that get's called every time the property is changed. 
  3. CoerceValueCallback: allows you to set a boundary of values for your dependency properties

Finally you can also mark your dependency property as read-only, these are used to notify of things such as mouse over.

Wednesday 1 April 2015

Async Exceptions

In synchronous code exceptions travel up the call stack until they're handled or your application crashes. however not the case with asynchronous calls, lets take a look at the following

and the xaml

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

    <Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
        <Grid.RowDefinitions>
            <RowDefinition Height="100"/>
            <RowDefinition Height="*"/>
        </Grid.RowDefinitions>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="100"/>
            <ColumnDefinition Width="*"/>
        </Grid.ColumnDefinitions>
        <TextBlock Grid.Column="1" Text="Async Exception Example"
                   Style="{ThemeResource HeaderTextBlockStyle}"
                   VerticalAlignment="Center" />
        <StackPanel Grid.Column="1" Grid.Row="1">
            <StackPanel Orientation="Horizontal">
                <TextBox x:Name="Numerator_TXT" Header="Numerator"
                   Text="0"/>
                <TextBlock Text="/" VerticalAlignment="Bottom"
                           FontSize="42" Margin="10 0" />
                <TextBox x:Name="Denominator_TXT" Header="Denominator" 
                         Text="0"/>
                <TextBlock Text="=" VerticalAlignment="Bottom"
                           FontSize="42" Margin="10 0" />
                <TextBox x:Name="Result_TXT" Header="Result" 
                         Text="0"/>
            </StackPanel>
            <Button x:Name="Synchronous_BTN" Content="Synchronous"/>
            <Button x:Name="Asynchronous_BTN" Content="Asynchronous"/>
           
            <Button x:Name="Task1_BTN" Content="Task 1"/>
            <Button x:Name="Task2_BTN" Content="Task 2"/>
           
            <Button x:Name="Void_BTN" Content="Void"/>
            <Button x:Name="AsyncTask_BTN" Content="Async Task"/>
        </StackPanel>
    </Grid>
</Page>


and the codebhind

using System;
using System.Threading.Tasks;
using Windows.UI.Core;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;

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

            this.Synchronous_BTN.Click += Synchronous_BTN_Click;
            this.Asynchronous_BTN.Click += Asynchronous_BTN_Click;
            this.Task1_BTN.Click += Task_BTN_Click;
            this.Task2_BTN.Click += Task2_BTN_Click;
            this.Void_BTN.Click += Void_BTN_Click;
            this.AsyncTask_BTN.Click += AsyncTask_BTN_Click;
        }

        void Synchronous_BTN_Click(object sender, RoutedEventArgs e)
        {
            var n = Convert.ToInt32(this.Numerator_TXT.Text);
            var d = Convert.ToInt32(this.Denominator_TXT.Text);

            try
            {
                this.Result_TXT.Text = (n / d).ToString();
            }
            catch (DivideByZeroException ex)
            {
                this.Result_TXT.Text = "Sync undefined";
            }
        }

        async void Asynchronous_BTN_Click(object sender, RoutedEventArgs e)
        {
            var n = Convert.ToInt32(this.Numerator_TXT.Text);
            var d = Convert.ToInt32(this.Denominator_TXT.Text);

            try
            {
                this.Result_TXT.Text = await Task.Run(() => (n / d).ToString());
            }
            catch (DivideByZeroException ex)
            {
                this.Result_TXT.Text = "Async undefined";
            }
        }

        void Task_BTN_Click(object sender, RoutedEventArgs e)
        {
            var n = Convert.ToInt32(this.Numerator_TXT.Text);
            var d = Convert.ToInt32(this.Denominator_TXT.Text);

            try
            {
                //Silently fails
                Task.Factory.StartNew(async () => await this.Dispatcher
                    .RunAsync(CoreDispatcherPriority.Normal, () =>
                        this.Result_TXT.Text = (n / d).ToString()));
            }
            catch (DivideByZeroException ex)
            {
                this.Result_TXT.Text = "Task 1 undefined";
            }
        }

        void Task2_BTN_Click(object sender, RoutedEventArgs e)
        {
            var n = Convert.ToInt32(this.Numerator_TXT.Text);
            var d = Convert.ToInt32(this.Denominator_TXT.Text);

            try
            {
                this.Result_TXT.Text = Task.Factory.StartNew(() => (n / d).ToString()).Result;
            }
            catch (DivideByZeroException ex)
            {
                this.Result_TXT.Text = "Task 2 undefined";
            }
            catch (AggregateException ex)
            {
                this.Result_TXT.Text = "aggregate undefined";
            }
        }

        #region Call Async Method that return void
        void Void_BTN_Click(object sender, RoutedEventArgs e)
        {
            var n = Convert.ToInt32(this.Numerator_TXT.Text);
            var d = Convert.ToInt32(this.Denominator_TXT.Text);

            try
            {
                //Cant await
                CalculateAsync1(n, d);
            }
            catch (DivideByZeroException ex)
            {
                this.Result_TXT.Text = "Void undefined";
            }
        }

        async void CalculateAsync1(int n, int d)
        {
            this.Result_TXT.Text = (n / d).ToString();
        }
        #endregion

        #region Call Async Function that returns Task
        async void AsyncTask_BTN_Click(object Sender, RoutedEventArgs e)
        {
            var n = Convert.ToInt32(this.Numerator_TXT.Text);
            var d = Convert.ToInt32(this.Denominator_TXT.Text);

            try
            {
                //Can await
                await CalculateAsync2(n, d);
            }
            catch (DivideByZeroException ex)
            {
                this.Result_TXT.Text = "Async Task undefined";
            }
        }

        async Task CalculateAsync2(int n, int d)
        {
            this.Result_TXT.Text = await Task.Factory.StartNew(() => (n / d).ToString());
        }
        #endregion
    }
}



OK now let's look at the different attempts individually, let's start with the regular synchronous approach.

void Synchronous_BTN_Click(object sender, RoutedEventArgs e)
{
    var n = Convert.ToInt32(this.Numerator_TXT.Text);
    var d = Convert.ToInt32(this.Denominator_TXT.Text);

    try
    {
        this.Result_TXT.Text = (n / d).ToString();
    }
    catch (DivideByZeroException ex)
    {
        this.Result_TXT.Text = "Sync undefined";
    }

}

straight forward there's a try catch when we try to divide by zero the exception is caught and the corresponding text is set to the result textbox.

Next let's take a look at utilizing the async and await keywords.

async void Asynchronous_BTN_Click(object sender, RoutedEventArgs e)
{
    var n = Convert.ToInt32(this.Numerator_TXT.Text);
    var d = Convert.ToInt32(this.Denominator_TXT.Text);

    try
    {
        this.Result_TXT.Text = await Task.Run(() => (n / d).ToString());
    }
    catch (DivideByZeroException ex)
    {
        this.Result_TXT.Text = "Async undefined";
    }

}

also works like a charm, the exception happens when the task return via the await key word our exception is caught and just as before the corresponding text is set to the restul textbox.

Thirdly lets look at the isolated task method, that is everything is done in a separate task which updates the UI via the dispatcher, this allows us to update the UI Thread

void Task_BTN_Click(object sender, RoutedEventArgs e)
{
    var n = Convert.ToInt32(this.Numerator_TXT.Text);
    var d = Convert.ToInt32(this.Denominator_TXT.Text);

    try
    {
        Task.Factory.StartNew(async () => await this.Dispatcher
            .RunAsync(CoreDispatcherPriority.Normal, () =>
                this.Result_TXT.Text = (n / d).ToString()));
    }
    catch (DivideByZeroException ex)
    {
        this.Result_TXT.Text = "Task 1 undefined";
    }

}

this is where we fall into problems, the exception fires inside the task, however our code never hears of it so we don't update the result textbox, the app just continues on as if nothing happend.

and now lets look at a better way to utilize the TPL

void Task2_BTN_Click(object sender, RoutedEventArgs e)
{
    var n = Convert.ToInt32(this.Numerator_TXT.Text);
    var d = Convert.ToInt32(this.Denominator_TXT.Text);

    try
    {
        this.Result_TXT.Text = Task.Factory.StartNew(() => (n / d).ToString()).Result;
    }
    catch (DivideByZeroException ex)
    {
        this.Result_TXT.Text = "Task 2 undefined";
    }
    catch(AggregateException ex)
    {
        this.Result_TXT.Text = "aggregate undefined";
    }

}

above we use the task.factory, however this time because we ask for the result and don't update the UI from within our task we catch our exception, but not the one we may have been expecting. instead we catch the aggregate exception and our divide by zero is actually the inner exception; still better then not catching it at all.

Now we could potentially end up with various nested InnerExceptions, luckily there's a flatten function

void Task2_BTN_Click(object sender, RoutedEventArgs e)
{
    var n = Convert.ToInt32(this.Numerator_TXT.Text);
    var d = Convert.ToInt32(this.Denominator_TXT.Text);

    try
    {
        this.Result_TXT.Text = Task.Factory.StartNew(() => (n / d).ToString()).Result;
    }
    catch (DivideByZeroException ex)
    {
        this.Result_TXT.Text = "Task 2 undefined";
    }
    catch (AggregateException ex)
    {
        this.Result_TXT.Text = "aggregate undefined";

        foreach(var Ex in ex.Flatten().InnerExceptions)
        {
            //log the exceptions
        }
    }

}

now lets take a look at calling the an async function that returns void

#region Call Async Method that return void
void Void_BTN_Click(object sender, RoutedEventArgs e)
{
    var n = Convert.ToInt32(this.Numerator_TXT.Text);
    var d = Convert.ToInt32(this.Denominator_TXT.Text);

    try
    {
        //Cant await
        CalculateAsync1(n, d);
    }
    catch (DivideByZeroException ex)
    {
        this.Result_TXT.Text = "Void undefined";
    }
}

async void CalculateAsync1(int n, int d)
{
    this.Result_TXT.Text = (n / d).ToString();
}

#endregion

because our asynchronous void method cannot be awaited its exceptions cannot be caught however they don't just continue silently they crash our application, hence it's probably best that our asynchronous functions return tasks.

now let's look at a asynchronous function that instead returns a task

#region Call Async Function that returns Task
async void AsyncTask_BTN_Click(object Sender, RoutedEventArgs e)
{
    var n = Convert.ToInt32(this.Numerator_TXT.Text);
    var d = Convert.ToInt32(this.Denominator_TXT.Text);

    try
    {
        //Can await
        await CalculateAsync2(n, d);
    }
    catch (DivideByZeroException ex)
    {
        this.Result_TXT.Text = "Async Task undefined";
    }
}

async Task CalculateAsync2(int n, int d)
{
    this.Result_TXT.Text = await Task.Factory.StartNew(() => (n / d).ToString());
}

#endregion

here since our calculateAsync2 function returns a task instead of being a void method the exception can be caught and handled in our event.

one thing to note is that when you fire a task without using the await keyword, or without somehow waiting for the result and an exception occurs inside that task, it happens inside an anonymous task and thus is not observed hence the term unobserved exception, this can be a real drag because let's say that you have an anonymous task that saves data to a web service well your application has no way of knowing that something went wrong potentially creating a poor user experience. Imagine saving thinking everything went great, only to find out next time your run your app that you lost all your work.