Menu Sidebar
Menu

Alex Hardwicke

I'm the author of this blog. I'm a dad, husband and programmer, in roughly that order. Read more about me here.

Link: Exception.StackTraceEx

So, not long after I finally blog about Little Watson, Lucian Wischik releases a tool that could really help with it!

He’s created a fantastic tool called Exception.StackTraceEx. He explains it better than I could, but essentially it provides a way to have exceptions in async calls provide much more information, including filenames and line numbers. I’m definitely going to check if Little Watson already supports it if I use the .Log() call he’s provided.

Get it here: http://blogs.msdn.com/b/lucian/archive/2014/08/25/exception-stacktraceex-better-exception-stacktrace-for-async-code.aspx

Pattern Matching

Pattern matching is pretty great. Essentially, it lets us match stuff.

The verbose (although not very) syntax is:

let equalToTen x =
    match x with
    | 10 -> printfn "Equal to ten!"
    | _ -> printfn "Not equal to ten!"

Or, we can do this:

let equalToTen = function
    | 10 -> printfn "Equal to ten!"
    | _ -> printfn "Not equal to ten!"

If you hadn’t figured it out, _ is the wildcard. If you don’t have a wildcard and don’t get a match, you’ll have a MatchFailureException thrown.

We can also pattern match our own types of course.

type Language = { Name : string }

let checkLanguage x =
    match x with
    | { Name= "F#"} -> printfn "We've got a winner! F#!"
    | { Name= "C#"} -> printfn "We've got C#! Not bad."
    | _ -> printfn "Really? Try F# instead!"
 
do checkLanguage { Name = "F#"}
do checkLanguage { Name = "C#"}
do checkLanguage { Name = "Java"}

If we start working with tuples, we get access to a lovely range of pattern matching things. A quick aside first: tuples in F# are very simple. They are represented inside brackets and can have as many values as you want.

let tuple = (1, 2)
let child = ("Age", 5)
let vowels = ("A", "E", "I", "O", "U")
let singlePositiveIntegers = (0, 1, 2, 3, 4, 5, 6, 7, 8, 9)

So, back to pattern matching.

We can pattern match tuples based on a variety of things, such as checking a specific part of the tuple, or comparing the left hand side of a tuple of 2 with the right hand side.

let tupleCompare = function
    | (0, 0) -> printfn "Tuple of two zeroes"
    | (0, _) | (_, 0) -> printfn "Tuple of one zero"
    | (a, b) when a > b -> printfn "Tuple with a larger lhs"
    | (a, b) when a < b -> printfn "Tuple with a larger rhs"
    | (a, b) -> printfn "Tuple that's equal and non-zero"
    | _ -> printfn "Do you think it's possible to get here?"

tupleCompare (0, 0)
tupleCompare (0, 1)
tupleCompare (1, 0)
tupleCompare (2, 1)
tupleCompare (1, 2)
tupleCompare (2, 2)

You also hopefully noted there that you can use | as an or operator, to combine multiple matches, and that you can also use when to perform comparisons.

We can do this sort of matching with lists, discriminated unions and arrays, too. It’s really a very powerful way to work with your data.

Link: Mr Flakey

That genius Lucian Wischik at Microsoft has written a nice tool called Mr Flakey which you can use to fiddle with async calls.

He describes the use in detail in the link, but essentially Mr Flakey lets you simulate async calls failing (e.g. network errors) and test how your code responds to these errors. It works with both Windows 8.1 and Windows Phone 8.1, so it’s perfect for universal apps.

This is something I can already see being incredibly useful and I’m expecting it to be a useful tool for app development for quite some time.

Get it here: http://blogs.msdn.com/b/lucian/archive/2014/08/09/mr-flakey-helps-you-write-more-robust-async-code.aspx.

Little Watson

Dr Watson (the debugger included with Windows, not Sherlock Holmes’ Boswell) is obviously the inspiration of this name. I’m not sure where the term first originated, but for those not in the know, a Little Watson is a very simple bug reporter.

The flow is simple: catch all uncaught exceptions, save them to disk and then when the user re-opens the application, ask if they want to report the crash. If they do, you can either use your own network code, or just send the stacktrace in an e-mail.

There’s a Windows Phone 8 version that’s been around for a while, but it doesn’t work on Windows 8, and as such, Windows Phone 8.1. The problem is that saving to disk is an asynchronous call, and that when you await it, control returns to the UI thread and the app crashes (because there’s an uncaught exception). Normally the solution to this problem is to use a deferral but there’s no real way to get one here.

My solution is to use the settings storage, instead, as saving to that is not asynchronous. I’ve included the code below.

To use my Little Watson on Windows 8.1 or Windows Phone 8.1, you need to do the following:

// Put this BEFORE the call to this.InitializeComponent()
this.UnhandledException += (s, e) => LittleWatson.ReportException(e.Exception, "extra message goes here");

// Put this after this.InitializeComponent()
this.Loaded += async (s, e) => await LittleWatson.CheckForPreviousException();
rootFrame.NavigationFailed += (s, e) => LittleWatson.ReportException(e.Exception, "extra message goes here");
namespace YourApp
{
    using Windows.Storage;
    using Windows.UI.Popups;
    using System;
    using System.Collections.Generic;
    using System.Text;
    using System.Threading.Tasks;

    public class LittleWatson
    {
        private const string settingname = "LittleWatsonDetails";
        private const string email = "mailto:?to=you@example.com&subject=YourApp auto-generated problem report&body=";
        private const string extra = "extra", message = "message", stacktrace = "stacktrace";

        internal static void ReportException(Exception ex, string extraData)
        {
            ApplicationData.Current.LocalSettings.CreateContainer(settingname, Windows.Storage.ApplicationDataCreateDisposition.Always);
            var exceptionValues = ApplicationData.Current.LocalSettings.Containers[settingname].Values;

            exceptionValues[extra] = extraData;
            exceptionValues[message] = ex.Message;
            exceptionValues[stacktrace] = ex.StackTrace;
        }

        internal async static Task CheckForPreviousException()
        {
            var container = ApplicationData.Current.LocalSettings.Containers;
            try
            {
                var exceptionValues = container[settingname].Values;
                string extraData = exceptionValues[extra] as string;
                string messageData = exceptionValues[message] as string;
                string stacktraceData = exceptionValues[stacktrace] as string;

                var sb = new StringBuilder();
                sb.AppendLine(extraData);
                sb.AppendLine(messageData);
                sb.AppendLine(stacktraceData);

                string contents = sb.ToString();

                SafeDeleteLog();

                if (stacktraceData != null && stacktraceData.Length > 0)
                {
                    var dialog = new MessageDialog("A problem occured the last time you ran this application. Would you like to report it so that we can fix the error?", "Error Report")
                    {
                        CancelCommandIndex = 1,
                        DefaultCommandIndex = 0
                    };

                    dialog.Commands.Add(new UICommand("Send", async delegate
                    {
                        var mailToSend = email.ToString();
                        mailToSend += contents;
                        var mailto = new Uri(mailToSend);
                        await Windows.System.Launcher.LaunchUriAsync(mailto);
                    }));
                    dialog.Commands.Add(new UICommand("Cancel"));

                    await dialog.ShowAsync();
                }
            }
            catch (KeyNotFoundException)
            {
                // KeyNotFoundException will fire if we've not ever had crash data. No worries!
            }
        }

        private static void SafeDeleteLog()
        {
            ApplicationData.Current.LocalSettings.CreateContainer(settingname, Windows.Storage.ApplicationDataCreateDisposition.Always);
            var exceptionValues = ApplicationData.Current.LocalSettings.Containers[settingname].Values;

            exceptionValues[extra] = string.Empty;
            exceptionValues[message] = string.Empty;
            exceptionValues[stacktrace] = string.Empty;
        }
    }
}

Link: Raygun Error and Crash Reporting

I stumbled upon Raygun, an automated error and crash reporter. It looks very interesting: reasonable pricing (even affordable for some hobbyists), used by a lot of great companies, and supports every platform you can think of (yes, including all Microsoft platforms).

I currently use my own Little Watson implementation, but it relies on user interaction. Raygun not only reports in the background, but caches the crash data if there’s no internet connection until it can, which is great.

On top of that, it integrates with various places, including GitHub and Visual Studio Online.

I’m definitely going to give it a go, and you should too!

Find it here: https://raygun.io/.

WinRT Flyout Performance

I’ve been having problems with the files flyout in Surge for some time. The performance was pretty terrible: for normal torrents with at most hundreds of files, performance was almost acceptable on my desktop but terrible on my Surface RT. However, with torrents with thousands of files, even my desktop took more than thirty seconds to display the flyout.

This just isn’t acceptable, and frankly, shouldn’t happen. The list is virtualised and shouldn’t be giving me performance problems like this.

I finally got around to doing some testing, and it turned out that the inbuilt flyout class that Microsoft have provided was the problem. I’m not sure whether it was just breaking the virtualisation or if something else was going on, but I appeared to have found the problem.

To solve it, I wrote my own flyout class and performance is substantially better – up to 45 times faster with the larger lists – which is beyond what I expected.

I’ve included the XAML and C# code for the flyout itself inline below, and there’s a link to download a solution that demonstrates the use of the flyout. It’s a universal app, but the flyout is only for Windows 8, not for Windows Phone.

The XAML for the flyout references a button style for the app bar back button. This is included in the download, in Styles.xaml.

Using the control is very simple:
flyout.Show() shows the flyout. It’s async, so await it.
flyout.Hide() hides the flyout.
flyout.Reposition() moves the flyout. If you add a call to this to your page’s LayoutUpdated event then the flyout will stay open if the user snaps the app.

Download the Flyout Solution Demo here.

<UserControl
    x:Class="xxx.FlyOut"
    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"
    mc:Ignorable="d"
    d:DesignHeight="768"
    d:DesignWidth="500"
    Width="500"
    x:Name="flyoutRoot" >

    <Popup x:Name="uxFlyout"
           Closed="OnPopupClosed"
           IsLightDismissEnabled="False">
        <Border x:Name="uxBorder"
                BorderThickness="1,0,0,0"
                Background="#0193E8">
            <Border.Transitions>
                <TransitionCollection>
                    <EntranceThemeTransition FromHorizontalOffset="120" />
                </TransitionCollection>
            </Border.Transitions>

            <StackPanel Orientation="Vertical"
                        Background="#FFFFFF"
                        Margin="1,0,0,0">
                <StackPanel Width="{Binding ElementName=uxFlyout, Path=Width}"
                            Background="{Binding ElementName=uxBorder, Path=Background}"
                            Orientation="Horizontal"
                            HorizontalAlignment="Left"
                            VerticalAlignment="Top"
                            Height="80">
                    <Button Click="BackButton_Click"
                        Content="&#xE112;"
                        Style="{ThemeResource AppBarButtonStyle}" />
                    <TextBlock FontFamily="{StaticResource ContentControlThemeFontFamily}"
                               FontSize="28"
                               FontWeight="SemiLight"
                               Foreground="#FFFFFF"
                               HorizontalAlignment="Center"
                               LineHeight="28"
                               Margin="-26, 31, 0, 0"
                               Text="My Fly-out"
                               TextAlignment="Center"
                               VerticalAlignment="Top" />
                </StackPanel>

                <!-- Put your content here -->

            </StackPanel>
        </Border>
    </Popup>
</UserControl>
namespace xxx
{
    using System.Threading.Tasks;
    using Windows.UI.Xaml;
    using Windows.UI.Xaml.Controls;

    public sealed partial class FlyOut
    {
        /// <summary>
        /// Initialises a new instance of the <see cref="FlyOut"/> class.
        /// </summary>
        public FlyOut()
        {
            this.InitializeComponent();
        }

        /// <summary>
        /// Display the fly-out and start the slide-in animation
        /// </summary>
        public async Task Show()
        {
            await Task.Delay(50); // This is a fairly hideous hack, but adding a 50ms delay seems to make WinRT animations MUCH more reliable.

            this.uxFlyout.IsOpen = true;

            this.Reposition();
        }

        /// <summary>
        /// Run when the fly-out is shown or when the size of the application has changed (snapping/resizing).
        /// </summary>
        public void Reposition()
        {
            if (uxFlyout.IsOpen == false)
            {
                return;
            }

            double screenWidth = Window.Current.Bounds.Width;

            // If the screen is smaller than 500, cap the width at screen width
            var chosenWidth = screenWidth > 500 ? 500 : screenWidth;

            this.uxFlyout.Width = chosenWidth;
            this.uxBorder.Width = chosenWidth;
            this.uxBorder.Height = Window.Current.Bounds.Height;

            Canvas.SetLeft(this.uxFlyout, screenWidth - chosenWidth);
        }

        /// <summary>
        /// Hide the fly-out
        /// </summary>
        public void Hide()
        {
            this.OnClosingEvent(this);
            this.uxFlyout.IsOpen = false;
        }

        /// <summary>
        /// Run when the fly-out is closing.
        /// </summary>
        /// <param name="sender">The argument is not used.</param>
        public void OnClosingEvent(object sender)
        {
            this.uxFlyout.IsOpen = false;
            Canvas.SetLeft(this.uxFlyout, Window.Current.Bounds.Width + 10);
        }

        /// <summary>
        /// Run when the pop-up is being closed - hides the fly-out.
        /// </summary>
        /// <param name="sender">The argument is not used.</param>
        /// <param name="e">The argument is not used.</param>
        private void OnPopupClosed(object sender, object e)
        {
            this.Hide();
        }

        /// <summary>
        /// Run when the back button is clicked - hides the fly-out.
        /// </summary>
        /// <param name="sender">The argument is not used.</param>
        /// <param name="e">The argument is not used.</param>
        private void BackButton_Click(object sender, RoutedEventArgs e)
        {
            this.Hide();
        }
    }
}

This code is based on code I used when Windows 8 was in pre-release. That code was in turn based on a flyout example I stumbled on at the time. I can’t find it now, but if anybody recognises it, please let me know so I can give credit where it’s due.

Link: Visual Studio Image Library

I recently discovered the Visual Studio Image Library. Microsoft has made over 1,000 icons used in Office, Windows, Visual Studio and other software available so that your desktop software can have a consistent look with modern Microsoft applications.

I can definitely see myself using some of these in the future, and using some as base images to modify and use in Metro software.

Get it here: http://go.microsoft.com/fwlink/p/?LinkId=275090.

Units of Measure in F#

So, F# has units of measure built in. They’re pretty cool.

Essentially, you can declare units of measure, like this:

[<Measure>] type kg
[<Measure>] type m
[<Measure>] type s

Once you’ve done that, you can then associate these units of measure with numeric types.

let distance = 5.0<m>
let time = 30<s>
let weight = 50<kg>

You can combine measures, either with new values, or by multiplying or dividing already existing identifiers with units.

let speed = distance / (float time);
let force = 5.0<kg m/s^2>

Finally, you can declare units of measure based on existing units of measure.

[<Measure>] type N = kg m/s^2
let forceNewton = 5.0<N>
let equal = forceNewton = force

From that, we’ll get the output:

val equal : bool = true

If the numbers are different, the bool is false, and if the types are wrong, it fails with a type mismatch.

So, that’s a quick demonstration of Units of Measure in F#. They’re fantastic.

Functional Programming

Since around Christmas, I’ve been slowly falling in love with F#. The more I look at it, read about it and try it, the more I appreciate functional programming in general, and particularly F#.

One of the joys is that the list is so core to the entire experience. As I’ve learnt more as a programmer, I’ve realised that so much of what we do is working with lists, and although C# is getting better with things like LINQ, it’s still so far behind.

F# also has the advantage that it’s a .NET language and is not only fully functional, but also fully object oriented. It’s a superset of C#, so you get the joys of C#, along with being able to program functionally.

A few quick examples to demonstrate some F#:

let square x = x * x

let sumOfSquares n =
    [1..n] |> List.map square |> List.sum
let sumOfOddSquares n = 
    [1..2..n] |> List.map square |> List.sum

printfn "Sum of Squares 1..100: %i" (sumOfSquares 100)
printfn "Sum of odd Squares 1..100: %i" (sumOfOddSquares 100)

The equivalent C# code:

public class Program
{
    public static int Square(int x)
    {
        return x*x;
    }

    public static int SumOfSquares(int n)
    {
        int sum = 0;
        for (int i = 0; i < n; ++i)
        {
            sum += Square(i);
        }

        return sum;
    }

    public static int SumOfOddSquares(int n)
    {
        int sum = 0;
        for (int i = 1; i < n; i+=2)
        {
            sum += Square(i);
        }

        return sum;
    }

    static void Main(string[] args)
    {
        Console.WriteLine("Sum of Squares 1..100: {0}", SumOfSquares(100));
        Console.WriteLine("Sum of odd Squares 1..100: {0}", SumOfOddSquares(100));
    }
}

And the C# code using modern techniques like LINQ:

public class Program
{
    public static int Square(int x)
    {
        return x*x;
    }

    public static int SumOfSquares(int n)
    {
        return Enumerable.Range(1, n)
                         .Select(i => Square(i))
                         .Sum();
    }

    public static int SumOfOddSquares(int n)
    {
        return Enumerable.Range(1, n)
                         .Where(i => i % 2 != 0)
                         .Select(i => Square(i))
                         .Sum();
    }

    static void Main(string[] args)
    {
        Console.WriteLine("Sum of Squares 1..100: {0}", SumOfSquares(100));
        Console.WriteLine("Sum of odd Squares 1..100: {0}", SumOfOddSquares(100));
    }
}

The LINQ code is clearly nicer than the old style C# code, but F# is just so much more concise and easier to understand. The benefits of easier comprehension along with the benefits of first-class lists are just fantastic.

Learning about F# is the most I’ve been interested in programming since discovering mobile development so many years ago. It should be very exciting to carry on with F# and see what the future brings.

Well, here we go

Now that many more interesting things are going on, what with fatherhood, employment, graduation and exciting new things going on in the world of programming, it’s time I have a proper blog and homepage.

I’ll be updating this blog at least once a week, with a programming or tech related post every Sunday and posts on other days when I have the time and something to post about.

For now I’m going to write about my experiences developing for Microsoft’s mobile platforms as well as interesting things I discover in F# as I learn the language.

Newer Posts

Alex Hardwicke

A programming blog, focused on Xamarin & F#.