<?xml version="1.0" encoding="UTF-8"?>
<rss xmlns:dc="http://purl.org/dc/elements/1.1/" version="2.0"><channel><atom:link rel="hub" href="http://tumblr.superfeedr.com/" xmlns:atom="http://www.w3.org/2005/Atom"/><description>The home of Frank Krueger.</description><title>præclarum</title><generator>Tumblr (3.0; @praeclarum)</generator><link>http://praeclarum.org/</link><item><title>Asynchronous Talk Proposal for MonkeySpace 2013</title><description>&lt;p&gt;Here is the abstract of a talk I hope to give at &lt;a href="http://monkeyspace.org" title="MonkeySpace 2013"&gt;MonkeySpace&lt;/a&gt; in July - submitted a mere one week after the deadline. Let&amp;#8217;s hope the organizers like the idea!&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Asynchronous Application Patterns in C#&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;Now that Mono 3.0 supports the await keyword in C# we finally have an excuse to go back and rewrite all our networking code. Wait, no, nevermind, don&amp;#8217;t do that.&lt;/p&gt;
&lt;p&gt;Instead, let&amp;#8217;s explore ways to write new code that takes advantage of this new syntax. We will look at common mobile app user experiences and see how we can use await and async code to create them. And maybe, just maybe, we&amp;#8217;ll write some networking code along the way.&lt;/p&gt;
&lt;p&gt;After we&amp;#8217;re all bored with the practical uses of await, let&amp;#8217;s take a quick glance at some more advanced - exotic - ridiculus? - uses of the syntax to enable new experiences.&lt;/p&gt;</description><link>http://praeclarum.org/post/48787944305</link><guid>http://praeclarum.org/post/48787944305</guid><pubDate>Wed, 24 Apr 2013 11:40:00 -0700</pubDate></item><item><title>Easy Layout - a DSL for NSLayoutConstraint</title><description>&lt;p&gt;&lt;img alt="image" src="http://media.tumblr.com/f0aeb31cc97efeaa9c91d3d7c91c77bd/tumblr_inline_mjvfrxd0Ai1qz4rgp.png"/&gt;&lt;/p&gt;

&lt;p&gt;Layout has changed in iOS 6. We no longer are supposed to calculate &lt;code&gt;RectangleF&lt;/code&gt;s and set springs and struts (&lt;code&gt;AutoresizingMask&lt;/code&gt;), we are to use this very advanced constraint solving system.&lt;/p&gt;
&lt;p&gt;That’s wonderful! Springs and struts, for those unfamiliar, is a lot like Anchors in Win Forms programming. It’s a really great model while you’re using an interactive design tool for layout, but if you want to do all your UI construction in code, then it’s a bit of work and relies on a lot of assumptions.&lt;/p&gt;
&lt;p&gt;For example, here is the code to layout a simple screen with a text box and a button:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;void LayoutWithSpringsAndStruts ()
{
    var b = View.Bounds;

    button.Frame = new RectangleF (
        b.Width - HPadding - ButtonWidth,
        VPadding,
        ButtonWidth,
        44);
    button.AutoresizingMask =
        UIViewAutoresizing.FlexibleLeftMargin |
        UIViewAutoresizing.FlexibleBottomMargin;

    text.Frame = new RectangleF (
        HPadding,
        VPadding,
        b.Width - ButtonWidth - 3 * HPadding,
        text.Font.PointSize + 14);
    text.AutoresizingMask =
        UIViewAutoresizing.FlexibleWidth |
        UIViewAutoresizing.FlexibleBottomMargin;
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;This code is easy to write. You just imagine the UI in your head and write this function down as fast as possible. Why fast? Because this code is read-only. It defies modification. Imagine if there were 10 different views each with their own obnoxious RectangleF math.&lt;/p&gt;
&lt;p&gt;There are also a lot of assumptions in the code. How tall should a button be? I don’t know so I just put in the constant 44. Likewise, how tall should the text field be? Who knows, but I found some math involving fonts that works decently well.&lt;/p&gt;
&lt;h3 id="abetterway"&gt;A better way&lt;/h3&gt;
&lt;p&gt;Apple must have gotten tired of writing this kind of code because they developed a wholy new layout system based on mathematical constraints.&lt;/p&gt;
&lt;p&gt;In this new system you layout views &lt;em&gt;relative&lt;/em&gt; to one another instead of using absolute coordinates, and you specify those relations using equations and inequalities:&lt;/p&gt;
&lt;p&gt;View1&lt;code&gt;.&lt;/code&gt;Property1 (= | &amp;lt;= | &amp;gt;=) View2&lt;code&gt;.&lt;/code&gt;Property2&amp;#160;&lt;code&gt;*&lt;/code&gt; mul &lt;code&gt;+&lt;/code&gt; constant&lt;/p&gt;
&lt;p&gt;That is to say, any layout property of a view can be constrained to be dependent on another property of another view. The power (and trouble) with this system derives from this generality.&lt;/p&gt;
&lt;p&gt;Instead of positioning the text field using a RectangleF, I create a bunch of constraints:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;button.Width = ButtonWidth
button.Right = View.Right - HPadding
button.Top = View.Top + VPadding

text.Left = View.Left + HPadding
text.Right = button.Left - HPadding
text.Top = button.Top
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;These 6 constraints lay out the UI in the same way as the springs and struts code above. But it is superior in a lot of way:&lt;/p&gt;
&lt;ol&gt;&lt;li&gt;
&lt;p&gt;It makes no assumptions about sizes. When using the new layout systems, Views can control their minimum size. This means that I don’t have to guess at the two heights anymore.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;There is no math involved. As much as I like measuring pixels and flexing my algebra skills, I am relieved to not have to do RectangleF math.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;It’s easy enough to read this code that I would even feel confident editing it over time. That is to say, it’s not read-only code. While it’s still not easy to get a picture of the UI from these constraints, they are much easier &lt;em&gt;to reason about&lt;/em&gt; than the prior pixel math.&lt;/p&gt;
&lt;/li&gt;
&lt;/ol&gt;&lt;p&gt;But there’s an issue. I haven’t actually shown you the code you need to write to implement these constraints. Without further ado:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;void LayoutWithConstraints ()
{
    // Set button width
    View.AddConstraint (NSLayoutConstraint.Create (
        button, NSLayoutAttribute.Width,
        NSLayoutRelation.Equal,
        null, NSLayoutAttribute.NoAttribute,
        0, ButtonWidth));

    // Set button top
    View.AddConstraint (NSLayoutConstraint.Create (
        button, NSLayoutAttribute.Top,
        NSLayoutRelation.Equal,
        View, NSLayoutAttribute.Top,
        1, VPadding));

    // Set button right
    View.AddConstraint (NSLayoutConstraint.Create (
        button, NSLayoutAttribute.Right,
        NSLayoutRelation.Equal,
        View, NSLayoutAttribute.Right,
        1, -HPadding));

    // Set text left
    View.AddConstraint (NSLayoutConstraint.Create (
        text, NSLayoutAttribute.Left,
        NSLayoutRelation.Equal,
        View, NSLayoutAttribute.Left,
        1, HPadding));

    // Set text right
    View.AddConstraint (NSLayoutConstraint.Create (
        text, NSLayoutAttribute.Right,
        NSLayoutRelation.Equal,
        button, NSLayoutAttribute.Left,
        1, -HPadding));

    // Set text top
    View.AddConstraint (NSLayoutConstraint.Create (
        text, NSLayoutAttribute.Top,
        NSLayoutRelation.Equal,
        button, NSLayoutAttribute.Top,
        1, 0));
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Our 6 constraints have inflated to 30 lines of code. Frown face. You can imagine how beautiful this code is in Objective-C where you’re forced to name every argument…&lt;/p&gt;
&lt;p&gt;Apple likes verbose APIs, but even they had to admit that this code is a bit ridiculous. So much so that they invented this &lt;a href="https://developer.apple.com/library/ios/#documentation/UserExperience/Conceptual/AutolayoutPG/Articles/formatLanguage.html#//apple_ref/doc/uid/TP40010853-CH3-SW1"&gt;THC-induced ASCII art way to establish these constraints&lt;/a&gt;. We will avoid this topic.&lt;/p&gt;
&lt;p&gt;So we’re stuck in an awkward place:&lt;/p&gt;
&lt;ol&gt;&lt;li&gt;We can keep using springs and struts and pretend that the world hasn’t moved on.&lt;/li&gt;
&lt;li&gt;We can write constraints using ridiculous amounts of code.&lt;/li&gt;
&lt;li&gt;We can draw ASCII art and &lt;a href="http://en.wikipedia.org/wiki/Sublime_(band)"&gt;songs about California&lt;/a&gt; while we’re at it.&lt;/li&gt;
&lt;/ol&gt;&lt;h3 id="challengeaccepted"&gt;Challenge Accepted&lt;/h3&gt;
&lt;p&gt;The world can always be improved. There is no reason to be stuck with these 3 bad options when we use a fantastically powerful language (dearest C# 5, this is a love letter) with a runtime that will keep us safe during our adventures.&lt;/p&gt;
&lt;p&gt;We are actually going to take our queue from Apple’s THC language, but let’s develop a DSL that’s easier to understand and aligns better with the actual constraints themselves.&lt;/p&gt;
&lt;p&gt;Here is what I came up with:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;void LayoutWithEase ()
{
    View.ConstrainLayout (() =&amp;gt; 
        button.Frame.Width == ButtonWidth &amp;amp;&amp;amp;
        button.Frame.Right == View.Frame.Right - HPadding &amp;amp;&amp;amp;
        button.Frame.Top == View.Frame.Top + VPadding &amp;amp;&amp;amp;

        text.Frame.Left == View.Frame.Left + HPadding &amp;amp;&amp;amp;
        text.Frame.Right == button.Frame.Left - HPadding &amp;amp;&amp;amp;
        text.Frame.Top == button.Frame.Top
    );
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;If you squint, this code is identical to the 6 constraint equations written earlier. I had to swap &lt;code&gt;==&lt;/code&gt; in place of &lt;code&gt;=&lt;/code&gt; and I had to put &lt;code&gt;.Frame&lt;/code&gt; everywhere because this code needs to compile. But, overall, this DSL quite perfectly matches the constraint system itself.&lt;/p&gt;
&lt;p&gt;When this code finishes, the View will have 6 new constraints added to to it. Let’s take a look at them using &lt;code&gt;View.Constraints&lt;/code&gt;:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;&amp;lt;NSLayoutConstraint:0xc55c9f0 H:[UIRoundedRectButton:0xc524180(88)]&amp;gt;
&amp;lt;NSLayoutConstraint:0xb4b2830 UIRoundedRectButton:0xc524180.right == UIView:0xc52c4e0.right - 22&amp;gt;
&amp;lt;NSLayoutConstraint:0xb4b0e70 V:|-(44)-[UIRoundedRectButton:0xc524180] (Names: '|':UIView:0xc52c4e0 )&amp;gt;
&amp;lt;NSLayoutConstraint:0xb4b2110 H:|-(22)-[UITextField:0xc52a710](LTR) (Names: '|':UIView:0xc52c4e0 )&amp;gt;
&amp;lt;NSLayoutConstraint:0xb4b20a0 UITextField:0xc52a710.right == UIRoundedRectButton:0xc524180.left - 22&amp;gt;
&amp;lt;NSLayoutConstraint:0xb4b2200 UITextField:0xc52a710.top == UIRoundedRectButton:0xc524180.top&amp;gt;
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;If you are one with the Visual Format Language, then you can see that our constraint equations turned into NSLayoutConstraints appropriately.&lt;/p&gt;
&lt;p&gt;So there you go, Option #4: Easy layout. This code is shorter than springs and struts, has all the power of auto layout, and is a lot easier to read and write than both.&lt;/p&gt;
&lt;h3 id="howitworks"&gt;How it Works&lt;/h3&gt;
&lt;p&gt;In order to provide this layout DSL, I took advantage of Linq expressions:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;public static void ConstrainLayout (this UIView view, Expression&amp;lt;Func&amp;lt;bool&amp;gt;&amp;gt; constraints)
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;When we pass code of the form &lt;code&gt;() =&amp;gt; button.Frame.Width == ButtonWidth&lt;/code&gt; to &lt;code&gt;ConstrainLayout&lt;/code&gt;, the compiler does two things:&lt;/p&gt;
&lt;ol&gt;&lt;li&gt;It compiles the code and statically checks types just as you would expect.&lt;/li&gt;
&lt;li&gt;The compiler does not execute the function, nor does it pass it to &lt;code&gt;ConstrainLayout&lt;/code&gt;; instead, it gives you the abstract syntax tree of the function represented using the &lt;code&gt;Expression&lt;/code&gt; hierarchy.&lt;/li&gt;
&lt;/ol&gt;&lt;p&gt;What we do with those expressions after compilation is up to us. This is the true power of Linq. While &lt;code&gt;from x in xs&lt;/code&gt; syntax is cool, I think this ability to do metaprogramming is 1,618 times more cool.&lt;/p&gt;
&lt;p&gt;Since we can do anything with expressions, let’s turn them into NSLayoutConstraints! Here’s the driver:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;    public static void ConstrainLayout (this UIView view, Expression&amp;lt;Func&amp;lt;bool&amp;gt;&amp;gt; constraints)
    {
        var exprs = new List&amp;lt;BinaryExpression&amp;gt; ();
        FindConstraints (((LambdaExpression)constraints).Body, exprs);

        view.AddConstraints (exprs.Select (CompileConstraint).ToArray ());
    }
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;This code takes expressions of the form &lt;code&gt;a &amp;amp;&amp;amp; b &amp;amp;&amp;amp; c&lt;/code&gt; and turns them into a list of expressions &lt;code&gt;[a, b, c]&lt;/code&gt;. It then compiles each of those expressions into an NSLayoutConstraint and adds those constraints to the view. Easy.&lt;/p&gt;
&lt;p&gt;A little more work is required to actually compile:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;static NSLayoutConstraint CompileConstraint (BinaryExpression expr)
{
    var rel = NSLayoutRelation.Equal;
    switch (expr.NodeType) {
    case ExpressionType.Equal:
        rel = NSLayoutRelation.Equal;
        break;
    case ExpressionType.LessThanOrEqual:
        rel = NSLayoutRelation.LessThanOrEqual;
        break;
    case ExpressionType.GreaterThanOrEqual:
        rel = NSLayoutRelation.GreaterThanOrEqual;
        break;
    default:
        throw new NotSupportedException ("Not a valid relationship for a constrain.");
    }

    var left = GetViewAndAttribute (expr.Left);
    left.Item1.TranslatesAutoresizingMaskIntoConstraints = false;

    var right = GetRight (expr.Right);
    if (right.Item1 != null) {
        right.Item1.TranslatesAutoresizingMaskIntoConstraints = false;
    }

    return NSLayoutConstraint.Create (
        left.Item1, left.Item2,
        rel,
        right.Item1, right.Item2,
        right.Item3, right.Item4);
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;This code implements all possible ways to specify constraints. Specifically, it can handle expressions of the form:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;text.Frame.Width &amp;gt;= button.Frame.Width * 0.5f + 5;
text.Frame.Width &amp;lt;= View.Frame.Width;
button.Frame.Height == button.Height - 10;
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;And so on. In total, it takes &lt;a href="https://gist.github.com/praeclarum/5175100"&gt;200loc to implement the layout DSL&lt;/a&gt;. You can see it on &lt;a href="https://gist.github.com/praeclarum/5175100"&gt;github&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;These 200 lines of code will save me from writing 4 boilerplate lines of code per constraint. This is a real win. That’s 80% less code to write. #winning&lt;/p&gt;
&lt;p&gt;Thanks as always to C# for making my life more pleasant, and the folks at &lt;a href="http://xamarin.com/ios"&gt;Xamarin who let me use my favorite language on my favorite platform&lt;/a&gt;.&lt;/p&gt;</description><link>http://praeclarum.org/post/45690317491</link><guid>http://praeclarum.org/post/45690317491</guid><pubDate>Mon, 18 Mar 2013 12:36:00 -0700</pubDate></item><item><title>Await in the Land of iOS - Scripting Users</title><description>&lt;h3 id="help"&gt;Help!&lt;/h3&gt;
&lt;p&gt;We all know our UIs are intuitive and that our icons are perfectly chosen, but why leave learning the UI to chance?&lt;/p&gt;
&lt;p&gt;The traditional solution to this problem is to provide help files. These are great, except no one reads them (at first!). If they get frustrated with your UI, they instead press the Home button and look at Twitter.&lt;/p&gt;
&lt;p&gt;An alternative help system, one that I think is superior, integrates with the UI of the application. Think “tooltips on steroids”.&lt;/p&gt;
&lt;p&gt;Check out the help system in Apple’s iPhoto app:&lt;/p&gt;
&lt;p&gt;&lt;img alt="image" src="http://media.tumblr.com/130c48f6005e9ad76f3a026901b8c33b/tumblr_inline_mjm0rrm53m1qz4rgp.png"/&gt;&lt;/p&gt;

&lt;p&gt;We have attractive tooltips describing the actions of the various toolbar items.&lt;/p&gt;
&lt;p&gt;This is nice, but what about accomplishing &lt;em&gt;tasks&lt;/em&gt;? Tasks often take multiple steps to accomplish use different parts of the UI. We write out tasks in our help files:&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;To search for pictures of cats:&lt;/p&gt;
&lt;ol&gt;&lt;li&gt;Enter the term “cats” in the search box.&lt;/li&gt;
&lt;li&gt;Tap the “Search” button.&lt;/li&gt;
&lt;/ol&gt;&lt;/blockquote&gt;
&lt;p&gt;This has the failing that the user has to swap between the app and the help file.&lt;/p&gt;
&lt;p&gt;I want a help system that walks a user through a specific task. And I want it to do it in a way that doesn’t force the user to search for “cats” (100% automated) but let’s them accomplish the task with their own input and decisions. Such a system could also be used to give introductory tutorials - the “getting to know the app” task.&lt;/p&gt;
&lt;p&gt;Ambitious? yes.&lt;/p&gt;
&lt;h3 id="await"&gt;Await&lt;/h3&gt;
&lt;p&gt;But I don’t know how to write it (frown face). Well, I don’t know how to write it without making a mess out of all my UI code that is already, well, messy. Instrumenting messy code with help file info sounds more than scary.&lt;/p&gt;
&lt;p&gt;It be nice (understatement) if I could just take those help file directions and turn them into code.&lt;/p&gt;
&lt;p&gt;Await has helped me see a nice way to implement it.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;async Task ShowTheUserHowToSearch ()
{
    await Tutorial.EnterText (searchField, minLength: 3);
    await Tutorial.Tap (searchButton);
    await Tutorial.Congratulate ("Now you know how to search.");
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;This is an async function that uses a library I call &lt;a href="#tutorial"&gt;Tutorial&lt;/a&gt; to execute help file instructions. I tend to call these things “scripts”.&lt;/p&gt;
&lt;p&gt;The method first asks the user to enter some text, then to tap a button. If they take those two tough steps, then you congratulate them!&lt;/p&gt;
&lt;p&gt;The system automatically highlights the control with some text while waiting for them to take a step to egg them on.&lt;/p&gt;
&lt;p&gt;This is my programmer art aspiring to be Apple’s beautiful UI in iPhoto:&lt;/p&gt;
&lt;p&gt;&lt;iframe frameborder="0" height="315" src="http://www.youtube.com/embed/TmAOeGToFeE?rel=0" width="420"&gt;&lt;/iframe&gt;&lt;/p&gt;
&lt;h3 id="tutorial"&gt;Tutorial&lt;/h3&gt;
&lt;p&gt;Thanks to the await keyword and async methods, it was shockingly easy to implement the Tutorial class. It comes out at a measly 40 lines of code if you ignore my ugly programmer art (100 lines otherwise).&lt;/p&gt;
&lt;p&gt;Let’s look at directing users to tap a button:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;public static class Tutorial
{
    public static async Task Tap (UIButton view)
    {
        Highlight (view, "Tap");
        await view.GetEventAsync ("TouchUpInside");
        Unhighlight (view);
    }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The first line highlights the button. We then wait for a &lt;code&gt;TouchUpInside&lt;/code&gt; event to fire. Once it has, we simply remove the highlight from the button. (&lt;code&gt;GetEventAsync&lt;/code&gt; is from the &lt;a href="http://praeclarum.org/post/45231096776/await-in-the-land-of-ios-drag-n-drop"&gt;previous post&lt;/a&gt;.)&lt;/p&gt;
&lt;p&gt;This code is quite straight-forward. Surprisingly straight-forward given the amount of work that it’s doing for us. It’s keeping track of state, UI elements, waiting for events. All in 3 lines of simple code.&lt;/p&gt;
&lt;p&gt;Let’s cover the rest before I get too choked up…&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;public static async Task EnterText (UITextField view, int minLength = 1)
{
    Func&amp;lt;bool&amp;gt; ok = () =&amp;gt;
        view.Text != null &amp;amp;&amp;amp; view.Text.Length &amp;gt;= minLength;
    if (ok ())
        return;

    Highlight (view, "Enter Text");
    view.BecomeFirstResponder ();

    for (;;) {
        await view.GetEventAsync ("AllEditingEvents");
        if (ok ()) {
            Unhighlight (view);
            return;
        }
    }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Entering text is just as easy but contains a bit more logic. We want to watch the UITextField every time the text changes. To accomplish this, we just keep checking the &lt;code&gt;Text&lt;/code&gt; property whenever an editing event has occurred.&lt;/p&gt;
&lt;p&gt;We also skip this step if there is already valid text. Whether this is a good idea or whether the library should force them to edit the text anyway is up for debate.&lt;/p&gt;
&lt;p&gt;If you read my &lt;a href="http://praeclarum.org/post/45231096776/await-in-the-land-of-ios-drag-n-drop"&gt;earlier blog post on await&lt;/a&gt; then you will notice this pattern emerging of infinite loops used to wait for potentially long periods of time. Please keep in mind that this isn’t polling - it just &lt;em&gt;looks like polling&lt;/em&gt;. We are still event based and there will be 0 CPU usage due to this infinite loop. Ahh, magic. As this is only my second day of experimentation, I don’t know if this is a good pattern or not. But for now, it works well and is pretty readable.&lt;/p&gt;
&lt;p&gt;Congratulating the user is also simple:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;public static async Task Congratulate (string message)
{
    var a = new UIAlertView ("Congratulations!", message, null, "OK");
    var clicked = a.GetEventAsync&amp;lt;UIButtonEventArgs&amp;gt; ("Clicked");
    a.Show ();
    await clicked;
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;We simply display an alert with a nice message and wait for the user to dismiss it.&lt;/p&gt;
&lt;p&gt;We can build upon &lt;code&gt;Congratulate&lt;/code&gt; to ask the user a question:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;public static async Task&amp;lt;int&amp;gt; Ask (string question, params string[] responses)
{
    var a = new UIAlertView (
        "", question, null,
        responses.First (), responses.Skip (1).ToArray ());
    var clicked = a.GetEventAsync&amp;lt;UIButtonEventArgs&amp;gt; ("Clicked");
    a.Show ();
    return (await clicked).ButtonIndex;
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Using &lt;code&gt;Ask&lt;/code&gt;, we can have a nice dialog with the user:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;async Task ShowTheUserHowToSearchWhileBeingAnnoying ()
{
    var r = await Tutorial.Ask (
        "Do you want to search for cats?",
        "No", "Yes, cats!");
    if (r == 1)
        searchField.Text = "cats";

    for (;;) {
        await ShowTheUserHowToSearch ();

        r = await Tutorial.Ask (
            "Do you want to play again?",
            "No", "Search!");
        if (r == 0)
            break;

        searchField.Text = "";
    }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;This script demonstrates that we can:&lt;/p&gt;
&lt;ul&gt;&lt;li&gt;Compose help tasks together easily&lt;/li&gt;
&lt;li&gt;Use all of C#’s control flow structures while disregarding time&lt;/li&gt;
&lt;li&gt;Interact with the user contextually without managing state variables&lt;/li&gt;
&lt;/ul&gt;&lt;p&gt;It’s a lot like scripting an application UI for testing. Except, now, we’re scripting the user and reacting to them.&lt;/p&gt;
&lt;p&gt;And it’s all possible thanks to await. Try writing that code using event handlers. I’ll wait…&lt;/p&gt;
&lt;p&gt;&lt;iframe frameborder="0" height="315" src="http://www.youtube.com/embed/yTD-pKe9vRw?rel=0" width="420"&gt;&lt;/iframe&gt;&lt;/p&gt;
&lt;h3 id="thanks"&gt;Thanks&lt;/h3&gt;
&lt;p&gt;My thanks go out to everyone who worked on async both at Microsoft and on the Mono project for building such a useful and versatile language feature.&lt;/p&gt;
&lt;p&gt;I want to re-iterate that I don’t know how, or couldn’t implement this kind of help system without async. Managing the state of many possible interactions (imagine two of these help tasks running simultaneously) without async hurts my head. Not only does async provide a solution to the state management problem, but it does so in a way that is simple and doesn’t touch your UI code.&lt;/p&gt;</description><link>http://praeclarum.org/post/45277337108</link><guid>http://praeclarum.org/post/45277337108</guid><pubDate>Wed, 13 Mar 2013 10:47:55 -0700</pubDate></item><item><title>Await in the Land of iOS - Drag-n-drop</title><description>&lt;p&gt;Today is a big day, &lt;a href="http://blog.xamarin.com/brave-new-async-mobile-world/"&gt;Xamarin has released&lt;/a&gt; (in alpha) support for the &lt;a href="http://msdn.microsoft.com/en-us/library/vstudio/hh156528.aspx"&gt;await keyword&lt;/a&gt; in C#.&lt;/p&gt;
&lt;p&gt;To celebrate, I thought I would write a few articles describing the ways I plan (and now am) taking advantage of that support.&lt;/p&gt;
&lt;h3 id="asynccodewithoutawaitiscodewritteninsideout"&gt;Async code without await is code written inside out&lt;/h3&gt;
&lt;p&gt;Asynchronous programming has taken over our lives. We allowed it to because it benefits software ranging from high performance servers all the way down to responsive UIs on phones. That is to say, it’s good for machines and users.&lt;/p&gt;
&lt;p&gt;But async programming comes at a cost for us programmers. It often asks us to mangle our beautiful procedural code into state machines or continuation passing style. We can’t just say “Do A, then B, then C”:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;DoA ();
DoB ();
DoC ();
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Instead, we have to write the code using callbacks:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;DoA (errA =&amp;gt;
    if (errA != null) HandleError (errA)
    else DoB (errB =&amp;gt;
        if (errB != null) HandleError (errB)
        else DoC ()));
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;That code is pretty horrendous compared to the procedural code. It’s too long. It turns our error handling from exception-based to return code-based. The error handling also hides the control flow. It is, quite simply, a mess.&lt;/p&gt;
&lt;p&gt;The C# await keyword allows us to write asynchronous procedural code in our preferred style so long we don’t mind a few keywords:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;await DoA ();
await DoB ();
await DoC ();
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;What a breath of fresh air!&lt;/p&gt;
&lt;h3 id="whatelseisinsideout"&gt;What else is inside out?&lt;/h3&gt;
&lt;p&gt;Await has paid for itself by greatly simplifying our async code. But it made me wonder, what other bits of code am I writing inside out? In other words, what other APIs do I often interact with that are async - that happen in user time, not CPU time?&lt;/p&gt;
&lt;p&gt;Event handlers for touch events sprung immediately to mind.&lt;/p&gt;
&lt;p&gt;I wondered about an old friend of mine, the drag-n-drop procedure. Dragging objects on the screen is simple:&lt;/p&gt;
&lt;ol&gt;&lt;li&gt;When a touch begins, look to see if it touches any subviews&lt;/li&gt;
&lt;li&gt;If it does, then move that view whenever the touch moves until the touch ends&lt;/li&gt;
&lt;/ol&gt;&lt;p&gt;Below is code that I have written 1,268 times (I checked) to implement that procedure in iOS:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;class DragInfo
{
    public UITouch Touch;
    public UIView View;
}

readonly Dictionary&amp;lt;UITouch, DragInfo&amp;gt; drags =
    new Dictionary&amp;lt;UITouch, DragInfo&amp;gt; ();

public override void TouchesBegan (NSSet touches, UIEvent evt)
{
    foreach (var touch in touches.ToArray&amp;lt;UITouch&amp;gt; ()) {
        var loc = touch.LocationInView (this);
        var view = Subviews.FirstOrDefault (x =&amp;gt; x.Frame.Contains (loc));

        if (view != null)
            drags[touch] = new DragInfo {
                Touch = touch,
                View = view,
            };
    }
}

public override void TouchesMoved (NSSet touches, UIEvent evt)
{
    foreach (var touch in touches.ToArray&amp;lt;UITouch&amp;gt; ()) {
        DragInfo drag;
        if (!drags.TryGetValue (touch, out drag))
            continue;

        var loc = touch.LocationInView (this);
        var ploc = touch.PreviousLocationInView (this);

        var fr = drag.View.Frame;
        fr.X += (loc.X - ploc.X);
        fr.Y += (loc.Y - ploc.Y);
        drag.View.Frame = fr;
    }
}

public override void TouchesEnded (NSSet touches, UIEvent evt)
{
    foreach (var touch in touches.ToArray&amp;lt;UITouch&amp;gt; ()) {
        DragInfo drag;
        if (drags.TryGetValue (touch, out drag))
            drags.Remove (touch);
    }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;It implements multi-touch dragging of views by using some fields to store state between touch events.&lt;/p&gt;
&lt;p&gt;How well does this code align with my dragging procedure above? I wrote the code as well as I ever have (i.e. my style hasn’t changed since programming Windows 3.1). But it still has very little resemblance.&lt;/p&gt;
&lt;p&gt;The events become the main focus of the code instead of the procedure. I had to introduce a data structure and some mutable, essentially global, data that 3 different functions work with in a coordinated way. Since async methods can be called any time, I just have to hope that I worked out all the possible interleaves in my head (I probably didn’t).&lt;/p&gt;
&lt;p&gt;Can we do better? I rewrote that code using &lt;code&gt;await&lt;/code&gt; to find out.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;// Step 1: Watch for dragging starts
async void WatchForDrags ()
{
    for (;;) {
        var began = await this.GetEventAsync&amp;lt;TouchEventArgs&amp;gt; ("TouchBegan");

        foreach (var t in began.Touches) {
            var loc = t.LocationInView (this);
            var view = Subviews.FirstOrDefault (x =&amp;gt; x.Frame.Contains (loc));

            if (view != null)
                DragView (t, view);
        }
    }
}

// Step 2: Carry-through with the drag until it's over
async void DragView (UITouch touch, UIView view)
{
    for (;;) {
        var moved = this.GetEventAsync&amp;lt;TouchEventArgs&amp;gt; ("TouchMoved");
        var ended = this.GetEventAsync&amp;lt;TouchEventArgs&amp;gt; ("TouchEnded");

        var ev = await Task.WhenAny (ended, moved);

        if (!ev.Result.Touches.Contains (touch))
            continue;

        if (ev == ended)
            return;

        var loc = touch.LocationInView (this);
        var ploc = touch.PreviousLocationInView (this);

        var fr = view.Frame;
        fr.X += (loc.X - ploc.X);
        fr.Y += (loc.Y - ploc.Y);
        view.Frame = fr;
    }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Using a little trick function, I was able to turn normal .NET events into tasks. The idea is simply to subscribe to the event long enough for it to fire once and only once. That one little trick allowed me to increase the readability of the code.&lt;/p&gt;
&lt;p&gt;What was 3 functions, 1 data structure, and 1 chunk of memory has been turned into two procedures that align very well to the English procedure above.&lt;/p&gt;
&lt;p&gt;I love that this code doesn’t leak its state out into the class containing it. &lt;code&gt;DragInfo&lt;/code&gt; is a failure of encapsulation - the data required by the events Began, Moved, Ended was available to all other methods in the class. Now, there is no leaked state. Instead, the state is held in a clojure created when DragView is called by WatchForDrag.&lt;/p&gt;
&lt;p&gt;I love that the new code is procedural - lines higher up on the screen happen earlier in time. I love that it processes events in the order that it cares about - no other order.&lt;/p&gt;
&lt;p&gt;This is straight procedural code that executes asynchronously in response to user interactions. The machine is happy because I’m not spawning threads, the user is happy because the UI is responsive, and I am happy because I can write code the way I think, not the way I’m required to just to satisfy those other two conditions.&lt;/p&gt;
&lt;p&gt;I hope you found this a little interesting. I have a lot more ideas on how to take advantage of &lt;code&gt;await&lt;/code&gt; so I hope you’ll stay tuned.&lt;/p&gt;
&lt;h3 id="alittletrickfunction"&gt;A little trick function&lt;/h3&gt;
&lt;p&gt;The GetEventAsync is the magic that allows me to await events. Here is a rough implementation of it.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;public static Task&amp;lt;T&amp;gt; GetEventAsync&amp;lt;T&amp;gt; (this object eventSource, string eventName)
    where T : EventArgs
{
    var tcs = new TaskCompletionSource&amp;lt;T&amp;gt;();

    var type = eventSource.GetType ();
    var ev = type.GetEvent (eventName);

    EventHandler handler;

    handler = delegate (object sender, EventArgs e) {
        ev.RemoveEventHandler (eventSource, handler);
        tcs.SetResult ((T)e);
    };  

    ev.AddEventHandler (eventSource, handler);
    return tcs.Task;
}
&lt;/code&gt;&lt;/pre&gt;</description><link>http://praeclarum.org/post/45231096776</link><guid>http://praeclarum.org/post/45231096776</guid><pubDate>Tue, 12 Mar 2013 17:54:00 -0700</pubDate></item><item><title>iCircuit Code Reuse, Part Cinq</title><description>&lt;p&gt;I have toiled away with the new Windows 8 OS, the new Visual Studio 2012, and the new Office 13/365 to present you, dear reader, with this fine set of charts:&lt;/p&gt;
&lt;p&gt;&lt;img alt="image" src="http://media.tumblr.com/566335601c4ad71a29602f119afe2510/tumblr_inline_mhrlp1np9s1qbzjil.png"/&gt;&lt;/p&gt;
&lt;p&gt;(This post is the 5th in a series where I describe the code reuse of &lt;a href="http://icircuitapp.com"&gt;iCircuit&lt;/a&gt; while porting it from platform to platform. Check out the &lt;a href="http://praeclarum.org/post/15789866032/icircuit-code-reuse-part-trois"&gt;previous&lt;/a&gt; &lt;a href="http://praeclarum.org/post/31799384896/icircuit-code-reuse-the-fourth-edition"&gt;posts&lt;/a&gt;.)&lt;/p&gt;
&lt;p&gt;Yesterday I completed the Metro, I mean Windows Store Modern App, version of iCircuit and achieved 85% code reuse from my other platforms! You should check it out, it&amp;#8217;s amazing to see Windows 8 actually do something useful! ;-)&lt;/p&gt;
&lt;p&gt;&lt;a href="http://apps.microsoft.com/windows/en-US/app/icircuit/4041b312-408b-4bea-9c16-c49529230173" title="iCircuit on the Windows 8 Store"&gt;iCircuit for Windows 8&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;To build this version, I used the work from the Windows Phone 7 port to get the basic app working in a XAML/C# solution. From there I &amp;#8220;just&amp;#8221; had to build up a modern desktop/tablet UI for the app. The initial port took about 1 day. Then I spent about 2 months refining the UI to feel good.&lt;/p&gt;
&lt;p&gt;Thanks to the amazing .NET/Mono platform I was able to &lt;strong&gt;reuse 39,000&lt;/strong&gt; lines of code and had to &lt;strong&gt;write 6,700 lines of platform dependent code&lt;/strong&gt;. These figures represent a &lt;strong&gt;code reuse of 85%&lt;/strong&gt;. This is on-par with all my other ports, and so I deem it a success.&lt;/p&gt;
&lt;p&gt;That said, I&amp;#8217;m a little disappointed that I had to write 6,700 lines. I was hoping for code reuse more inline with the OS X port of the app where I only had to write 4,000 loc. I blame WinRT&amp;#8217;s immaturity. You would be shocked to see some of the crazy bits of code I had to put in because the Win8 platform, while very rich, is also very generic and doesn&amp;#8217;t help you at all to build standard apps (document based, tools, etc.) That is to say, Cocoa is a very mature platform designed to make apps feature-rich and consistent while also making the developer&amp;#8217;s life easy. WinRT on the other hand gives you rectangles and a blog post that says &amp;#8220;good luck&amp;#8221;.&lt;/p&gt;
&lt;p&gt;Post Mortem&lt;/p&gt;
&lt;ul&gt;&lt;li&gt;&lt;strong&gt;Microsoft did a great job of porting XAML graphics&lt;/strong&gt; over to this new brave DirectX world. All my Silverlight code worked out of the gate and had decent performance.&lt;/li&gt;
&lt;li&gt;The &lt;strong&gt;XAML implementation is slow&lt;/strong&gt; as a snail slithering up a mountain during a rainstorm &lt;strong&gt;when it comes to changing the scale of render transforms&lt;/strong&gt;. I can pan around with high FPS but the moment you zoom in or out, the app feels like we&amp;#8217;re back in the 80s. Now, this is probably not Microsoft&amp;#8217;s fault since the perf profiler says that I spend all that stalled time in video card drivers (Intel 3000 on my dev machine), but Microsoft should lay some tough love on these hardware peeps.&lt;/li&gt;
&lt;li&gt;WinRT introduces&lt;strong&gt; yet another way to track multi-touch&lt;/strong&gt;. Now we have to wire up 5 Pointer events instead of a single Touch event from Silverlight. Check out &lt;a href="https://github.com/praeclarum/CrossGraphics/blob/master/src/XamlCanvas.cs#L345"&gt;my implementation in CrossGraphics&lt;/a&gt; to see the horror unfold. CocoaTouch nailed multi-touch on their first go. This is Microsoft&amp;#8217;s 3rd attempt. Let&amp;#8217;s hope they&amp;#8217;re happy this time.&lt;/li&gt;
&lt;li&gt;Just when I thought I had completed the port, I realized that the app isn&amp;#8217;t functional on non-touch devices - there was a whole list of actions you just couldn&amp;#8217;t do. So I had to write keyboard and mouse code to make that all happen. Coming from iOS, this felt crazy indeed. Why am I putting keyboard shortcuts into a tablet app? Because &lt;strong&gt;WinRT apps have to be just at home on the desktop as they need to be on tablets&lt;/strong&gt;.&lt;/li&gt;
&lt;li&gt;The &lt;strong&gt;WinRT XAML implementation isn&amp;#8217;t able to render the visual tree to bitmaps&lt;/strong&gt; (WriteableBitmap does not have the Render method). Let me just add my voice to the 1,000,000s of other devs as we cry &amp;#8220;Why Microsoft, why???&amp;#8221; To export PNGs, I had to resort to deep dark black magic of DirectX and Direct2D. Simple question to all the devs on the XAML team: if I can write code to render a visual tree using DirectX that gets dumped into a WIC bitmap, why the hell can&amp;#8217;t you?&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Testing the Share Charm is a real pita&lt;/strong&gt;. One little mistake and you will have to reboot Windows (yes, I said reboot Windows) to make sharing work again.&lt;/li&gt;
&lt;li&gt;The &lt;strong&gt;Visual Studio performance analysis tools are wonderful&lt;/strong&gt;. They give nicely detailed reports in a UI that makes&amp;#8230; well, some sense. It&amp;#8217;s still lightyears behind Instruments, but it&amp;#8217;s functional and enabled me to fix some hot spots in the code.&lt;/li&gt;
&lt;li&gt;The&lt;strong&gt; file system security model is ludicrous and stupid&lt;/strong&gt; and dumb and confusing and stupid and annoying and a pain to use. I had to disable one of my favorite features of iCircuit (subcircuits) because I couldn&amp;#8217;t find a way to open a StorageFile using just a path. &amp;#8220;Access Denied&amp;#8221; all over the place.&lt;/li&gt;
&lt;li&gt;The&lt;strong&gt; media system is a piece of crap compared to what we had in Silverlight&lt;/strong&gt; and WP7. I, again, had to disable major chunks of the app (microphone, speakers, and buzzer elements) because WInRT doesn&amp;#8217;t expose the media system to C#. There are &amp;#8220;capture&amp;#8221; devices but they incur a 500ms delay because you can&amp;#8217;t control buffer sizes. And playback, well, let&amp;#8217;s just say it has many problems too. I greatly miss Microsoft.Xna.Framework.Audio. (Oh, and while we&amp;#8217;re at it, fuck you MS for cancelling XNA, your only good API. I feel like I can swear now that we&amp;#8217;re way down in the list.)&lt;/li&gt;
&lt;li&gt;The &lt;strong&gt;graphics system of WinRT is very fragile&lt;/strong&gt;. I want to do real-time 2D vector drawing. Direct2D is perfect for this. But WinRT puts all sorts of limitations on onscreen rendering, most notably: you can only have 1 DirectX swap chain (view) per window. That means I can&amp;#8217;t use Direct2D for rendering the scope which means the scope is slower than it needs to be. Dear Microsoft, go spend a few minutes and see how beautifully CocoaTouch and OpenGL work together on iOS. You might get inspired.&lt;/li&gt;
&lt;li&gt;The &lt;strong&gt;App Store review process was crazy fast&lt;/strong&gt;. It took 5.5 hours for the app to be placed on the store. While I&amp;#8217;m ecstatic that the review process was so fast, it does leave me wondering. I spent days struggle over the &lt;a href="http://msdn.microsoft.com/en-us/library/windows/apps/hh465424"&gt;UX guidelines&lt;/a&gt; debating the right way to exposes this feature or that. In the end, it looks like it doesn&amp;#8217;t even matter. I wonder if they even looked at the app? It&amp;#8217;s big and complex. It contains a hand-written C compiler for God&amp;#8217;s sake. It has 5 UI views that are individually larger than most apps on the store. Ah well, it will be up to the users to tell me if the effort was worth it.&lt;/li&gt;
&lt;li&gt;This &lt;strong&gt;WinRT version lacks a natively optimized solver&lt;/strong&gt;. iCircuit for iOS uses &lt;a href="http://developer.apple.com/library/ios/#documentation/Performance/Conceptual/vecLib/Reference/reference.html#//apple_ref/doc/uid/TP40002498"&gt;Apple&amp;#8217;s Accelerate framework&lt;/a&gt; to do the heavy lifting in its solver to get wonderful performance that only gets better as the CPUs get wider and Apple&amp;#8217;s engineers optimize the library. Windows has none of this. I ran into many problems trying to get this C# app to use a WinRT C++ component but eventually gave up. It&amp;#8217;s too bad Microsoft doesn&amp;#8217;t care enough about high-performance computing to integrate useful numerical libraries.&lt;/li&gt;
&lt;li&gt;I need a better way to write cross-platform documentation.&lt;/li&gt;
&lt;/ul&gt;&lt;p&gt;Thanks for tuning in one more time! I hope you found this at least a tiny bit educational!&lt;/p&gt;
&lt;p&gt;So which platform is next? I&amp;#8217;m thinking of porting it to Windows 7, but will wait to see how sales do first. :-) In the mean time, &lt;a href="http://xamarin.com/monotouch"&gt;MonoTouch&lt;/a&gt; and I need to spend some quality time together&amp;#8230;&lt;/p&gt;
&lt;ul&gt;&lt;li&gt;&lt;a href="http://apps.microsoft.com/windows/en-US/app/icircuit/4041b312-408b-4bea-9c16-c49529230173" title="iCircuit on the Windows 8 Store"&gt;iCircuit for Windows 8&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="http://icircuitapp.com"&gt;iCircuit on iOS/OS X/Android/WP7&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;</description><link>http://praeclarum.org/post/42378027611</link><guid>http://praeclarum.org/post/42378027611</guid><pubDate>Tue, 05 Feb 2013 13:53:09 -0800</pubDate></item><item><title>Mobile Network Performance while Touring Seattle</title><description>&lt;p&gt;&lt;a href="https://dl.dropbox.com/u/6908183/Blog/Images/Results%402x.png"&gt;&lt;img src="http://media.tumblr.com/tumblr_mekoccptd41qbzjil.png"/&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;I recently journeyed around Seattle to get a sense of the impact motion has on the network performance of mobile applications.&lt;/p&gt;
&lt;p&gt;The image above is a graph of how long it took to download the homepage of Google News (588&amp;#160;KB) while I was traveling by bus and train throughout the city. Blue bars are successful downloads and red bars (and time entries with no bars at all) represent errors. The height of the bar shows how long it took to find out if it was successful download or an error.&lt;/p&gt;
&lt;p&gt;I wrote the &lt;a href="https://gist.github.com/4210793"&gt;test app&lt;/a&gt; using &lt;a href="http://xamarin.com"&gt;MonoTouch&lt;/a&gt; and ran it on an iPhone 5 with Verizon LTE.&lt;/p&gt;
&lt;h2 id="observations"&gt;Observations&lt;/h2&gt;
&lt;h3 id="when-youre-standing-still-performance-is-pretty-consistent-and-error-free"&gt;When you&amp;#8217;re standing still, performance is pretty consistent and error free&lt;/h3&gt;
&lt;p&gt;Whenever I gave the phone time enough to pair with a cell tower, the performance was pretty consistent with 2.5 second response times with 588&amp;#160;KB of data (240&amp;#160;KB/s). I never received errors (go TCP!).&lt;/p&gt;
&lt;h3 id="you-will-get-spikes-errors-when-moving"&gt;You will get spikes errors when moving&lt;/h3&gt;
&lt;p&gt;While most downloads took 2.5s, I received many 5s spikes. This is &lt;strong&gt;100% increase&lt;/strong&gt; in time. There was a even a time (look in the last 1/3rd of the chart) where 5s became the average and I received 10s spikes.&lt;/p&gt;
&lt;p&gt;The spikes happened quite spuriously so I can only guess that they occured in cell tower transition zones.&lt;/p&gt;
&lt;p&gt;While TCP is an insanely resiliant protocol, it would still fail from time to time. In a 2 hour interval, I recorded 2 errors that weren&amp;#8217;t tunnel-related. This means that there was a &lt;strong&gt;1% error rate&lt;/strong&gt; while moving. My only guess is that these happened whenever I was switching towers and the request happened just then.&lt;/p&gt;
&lt;h3&gt;3G sucks compared to LTE&lt;/h3&gt;
&lt;p&gt;Do you see those blue spikes near the center just after a little gap (the Mount Baker tunnel)? The one that peaks at more than 50s? That&amp;#8217;s 3G my friends: slower downloads by an order of magnitude and a huge variance increase. I can only wonder what this graph would be like if I was stuck on 3G the whole time&amp;#8230;&lt;/p&gt;
&lt;h3 id="timeout-and-readwritetimeout-control-these-spikes"&gt;Timeout and ReadWriteTimeout control these spikes&lt;/h3&gt;
&lt;p&gt;For the test, I used a &lt;a href="http://msdn.microsoft.com/en-us/library/system.net.httpwebrequest.timeout.aspx"&gt;WebRequest.Timeout&lt;/a&gt; of 20&amp;#160;s and a &lt;a href="http://msdn.microsoft.com/en-us/library/system.net.httpwebrequest.readwritetimeout.aspx"&gt;ReadWriteTimeout&lt;/a&gt; of 20s.&lt;/p&gt;
&lt;p&gt;You can see the affect of Timeout with all the errors that cap at 20s. Mono gave a &amp;#8220;System.Net.WebException: The request timed out&amp;#8221; at that mark. This is great because it&amp;#8217;s very predictable.&lt;/p&gt;
&lt;p&gt;So, how do bars go above 20s? That&amp;#8217;s the effect of ReadWriteTimeout. This is the timeout that affects each Read and Write call to the response object. I was using a 16&amp;#160;KB buffer for my reads so this means that I did about 37 read operations. Since each of these had a timeout of 20s I could have ended up waiting up to 740s (12 minutes)! Thankfully that never happened.&lt;/p&gt;
&lt;p&gt;About 50% of the time, ReadWriteTimeout was able to finish the download. On the other 50%, I ended up receiving &amp;#8220;System.Net.WebException: The operation has timed out.&amp;#8221; exceptions. I&amp;#8217;m not sure if I see much value in setting it up - I would prefer that errors come sooner rather than later.&lt;/p&gt;
&lt;p&gt;The system default of 300s (5 minutes) seems beyond ridiculous to me. Don&amp;#8217;t use that value.&lt;/p&gt;
&lt;p&gt;TL;DR ReadWriteTimeout is an important value that you should think about.&lt;/p&gt;
&lt;h3 id="thank-god-for-connectfailures"&gt;Thank God for ConnectFailures&lt;/h3&gt;
&lt;p&gt;While travelling through a tunnel, the request would fail immediately with &amp;#8220;System.Net.WebException: Error: ConnectFailure (No route to host)&amp;#8221;.&lt;/p&gt;
&lt;p&gt;These errors are represented by the white gaps in the chart. In the face of those 38&amp;#160;s errors, this is wonderful.&lt;/p&gt;
&lt;h3 id="all-errors-were-represented-by-webexceptions"&gt;All errors were represented by WebExceptions&lt;/h3&gt;
&lt;p&gt;I&amp;#8217;ve always wondered if a try-catch block of:&lt;/p&gt;
&lt;pre&gt;try {
    // Do some System.Net.WebRequest stuff
} catch (System.Net.WebException) {
    // OMG. OMG. OMG.
}&lt;/pre&gt;
&lt;p&gt;one that caught only &lt;a href="http://msdn.microsoft.com/en-us/library/system.net.webexception.aspx"&gt;WebException&lt;/a&gt; - was sufficient to catch all network related errors when using &lt;a href="http://msdn.microsoft.com/en-us/library/system.net.webrequest.aspx"&gt;WebRequest&lt;/a&gt;. It turns out that yes, yes it is. One less thing to think about&amp;#8230;&lt;/p&gt;
&lt;p&gt;Here are &lt;em&gt;all&lt;/em&gt; the errors MonoTouch emitted during this test (in Type.Name + Exception.Message format):&lt;/p&gt;
&lt;ul&gt;&lt;li&gt;System.Net.WebException: Error: ConnectFailure (No route to host)&lt;/li&gt;
&lt;li&gt;System.Net.WebException: The request timed out&lt;/li&gt;
&lt;li&gt;System.Net.WebException: The operation has timed out.&lt;/li&gt;
&lt;/ul&gt;&lt;h2 id="code-setup"&gt;Code Setup&lt;/h2&gt;
&lt;ul&gt;&lt;li&gt;&lt;strong&gt;Request Class:&lt;/strong&gt; &lt;code&gt;System.Net.HttpWebRequest&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;URL:&lt;/strong&gt; &lt;a href="http://news.google.com"&gt;&lt;a href="http://new.google.com"&gt;http://new.google.com&lt;/a&gt;&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;&lt;a href="http://msdn.microsoft.com/en-us/library/system.net.httpwebrequest.timeout.aspx"&gt;Timeout&lt;/a&gt;:&lt;/strong&gt; 20&amp;#160;s&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;&lt;a href="http://msdn.microsoft.com/en-us/library/system.net.httpwebrequest.readwritetimeout.aspx"&gt;ReadWriteTimeout&lt;/a&gt;:&lt;/strong&gt; 20&amp;#160;s&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;HTTP Keep-Alive:&lt;/strong&gt; No&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;ReadBuffer:&lt;/strong&gt; 16&amp;#160;KB&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Request Interval:&lt;/strong&gt; 30&amp;#160;s&lt;/li&gt;
&lt;/ul&gt;&lt;p&gt;The actual code for the netowork request can be found in the &lt;code&gt;HandleTimer&lt;/code&gt; method in the &lt;a href="https://gist.github.com/4210793#L98"&gt;gist for the test app&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;The app disabled the idle timer of the phone so that it could run continuously in the foreground. Every 30 seconds, it would download the full 588&amp;#160;KB of Google News. In all, I figure I burnt through 8% of my monthly data allowance.&lt;/p&gt;
&lt;h2 id="test-procedure"&gt;Test Procedure&lt;/h2&gt;
&lt;ul&gt;&lt;li&gt;&lt;strong&gt;Device:&lt;/strong&gt; iPhone 5 (white)&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Carrier:&lt;/strong&gt; Verizon (LTE, usually)&lt;/li&gt;
&lt;/ul&gt;&lt;p&gt;I started the test by getting a slice of pizza at &lt;a href="https://maps.google.com/maps?q=4529+University+Way+NE+Seattle,+WA+98105&amp;amp;hl=en&amp;amp;sll=47.775216,-122.310617&amp;amp;sspn=0.007153,0.010343&amp;amp;hnear=4529+University+Way+NE,+Seattle,+Washington+98105&amp;amp;t=m&amp;amp;z=17"&gt;Pagliacci&lt;/a&gt;&amp;#8217;s in the University District of Seattle. I figured this would be a good way to establish a baseline for staying still, and I was very hungry. I then took a bus to &lt;a href="http://www.soundtransit.org/Rider-Guide/Westlake-Station.xml"&gt;Westlake&lt;/a&gt;, downtown, wherein we entered the transit tunnels and I transferred to the light rail. I took the light rail through the tunnel and back into the open air as far as &lt;a href="http://www.soundtransit.org/Rider-Guide/Columbia-City-Station.xml"&gt;Columbia City&lt;/a&gt;. This journey consumed the first hour of the test. There, I switched trains to head back into the city. The trip back was essentially the same and even included another stop for pizza in the name of consistency (at &lt;a href="https://maps.google.com/maps?q=400+PINE+ST.+%23332,SEATTLE,WA,98101"&gt;Sbarro&lt;/a&gt; this time).&lt;/p&gt;</description><link>http://praeclarum.org/post/37273215875</link><guid>http://praeclarum.org/post/37273215875</guid><pubDate>Wed, 05 Dec 2012 11:15:00 -0800</pubDate></item><item><title>Programmatic Panning and Zooming with a UIScrollView</title><description>&lt;p&gt;Let&amp;#8217;s say you have a zoomable and scrollable UIScrollView all setup in your app. Great! Good job. But how do you programmatically zoom in on something particular? (For example, you may want to pan and zoom into an object that was double tapped.)&lt;/p&gt;
&lt;p&gt;UIScrollView exposes the &lt;strong&gt;SetZoomScale&lt;/strong&gt; and &lt;strong&gt;ScrollRectToVisible&lt;/strong&gt; methods, each of which can be animated. These are the methods that you will use but getting them to work together is a bit tricky. There was a lot of trial and error when I tried to get them to work together so I thought I would share my solution with you.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Step 1. Determine a rect that bounds the content you want to zoom into.&lt;/strong&gt;&lt;/p&gt;
&lt;pre&gt;var contentFrame = new RectangleF (x, y, width, height);
var scrollFrame = contentView.ConvertRectToView (contentFrame, scrollView);&lt;/pre&gt;
&lt;p&gt;First, we determine a bounding box for the content that we want to zoom into. Let&amp;#8217;s call it &lt;em&gt;contentFrame&lt;/em&gt;.&lt;/p&gt;
&lt;p&gt;We will also convert that bounding box to the coordinate system of the scroll view for use later.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Step 2. Determine the new zoom scale.&lt;/strong&gt;&lt;/p&gt;
&lt;pre&gt;var desiredZoomScale = 2;
var zooming = Math.Abs (scrollView.ZoomScale - desiredZoomScale) &amp;gt; 0.05f;&lt;/pre&gt;
&lt;p&gt;Now, determine the new desired zoom scale. This will depend on your app logic and perhaps on the contentFrame from Step 1. It&amp;#8217;s very app-specific, so I&amp;#8217;ll leave it at that for now.&lt;/p&gt;
&lt;p&gt;We will also record whether the zoom needs to happen by comparing the desired zoom scale and the current zoom scale. We&amp;#8217;re going to need to know this to work our magic in Step 3.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Step 3. Animate the pan and zoom.&lt;/strong&gt;&lt;/p&gt;
&lt;pre&gt;if (zooming) {
    scrollView.SetZoomScale (desiredZoomScale, true);
}
scrollView.ScrollRectToVisible (scrollFrame, !zooming);&lt;/pre&gt;
&lt;p&gt;The trick here is to perform the zoom operation before the pan operation and to toggle the automatic animation system depending on whether we&amp;#8217;re zooming or not.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;If we are zooming:&lt;/strong&gt; Then tell SetZoomScale to animate and ScrollRectToVisible not to animate.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;If we are only panning:&lt;/strong&gt; Then don&amp;#8217;t call SetZoomScale but do tell ScrollRectToVisible to animate.&lt;/p&gt;
&lt;p&gt;If you follow this simple procedure you will end up with nice smooth animations. If you don&amp;#8217;t, well, the results can be a bit jarring. Enjoy!&lt;/p&gt;</description><link>http://praeclarum.org/post/36673962005</link><guid>http://praeclarum.org/post/36673962005</guid><pubDate>Tue, 27 Nov 2012 09:57:00 -0800</pubDate></item><item><title>iCircuit Code Reuse, the Fourth Edition</title><description>&lt;p&gt;Hell has indeed frozen over and I have released the &lt;a href="https://play.google.com/store/apps/details?id=com.kruegersystems.circuitdroid"&gt;Android version of iCircuit&lt;/a&gt;! &lt;a href="http://icircuitapp.com"&gt;iCircuit&lt;/a&gt; is now on 4 platforms!&lt;/p&gt;
&lt;p&gt;I wrote the app using &lt;a href="http://xamarin.com/monoforandroid"&gt;Xamarin&amp;#8217;s Mono for Android&lt;/a&gt; so that I could reuse large amounts of code that I have painstakingly written and debugged on other platforms.&lt;/p&gt;
&lt;p&gt;That means it&amp;#8217;s time to run that &lt;a href="https://gist.github.com/1608597"&gt;code reuse script&lt;/a&gt; and find out how I did as a developer. How much of the Android code base had to be written anew and how much was I able to reuse from the other platforms?&lt;/p&gt;
&lt;p&gt;Here is a visualization of the code reuse. The percentage in green is the amount of code reused while the code in red is code I had to write for each platform.&lt;/p&gt;
&lt;p&gt;&lt;img src="http://media.tumblr.com/tumblr_majzkoGNIl1qbzjil.png"/&gt;&lt;/p&gt;
&lt;p&gt;We can see that Android was only (&amp;#8220;only&amp;#8221;, haha) an 81% code reuse - I had to write nearly 7,000 lines of code to port iCircuit to it. This is great, but I was aiming for closer to the 90% mark as the Mac was able to achieve.&lt;/p&gt;
&lt;p&gt;I can chalk this difference up to two new additions to the code base:&lt;/p&gt;
&lt;ol&gt;&lt;li&gt;Two new UI controls have been added that are unique to Android. The first is a &amp;#8220;mini-scope&amp;#8221; that is shown persistently on the screen. The other is a new dial that makes it much easier to input numbers on a multi-touch screen. The dial will eventually make it into the other platforms (iCircuit 1.5).&lt;/li&gt;
&lt;li&gt;Two new graphics drivers. The first uses &lt;a href="http://en.wikipedia.org/wiki/Skia_Graphics_Engine"&gt;Skia (Android.Graphics)&lt;/a&gt; to render scenes, and the other uses OpenGL. The Skia driver is used to render thumbnails, draw the scope, and other UI elements, while the OpenGL driver renders the main editor (very quickly).&lt;/li&gt;
&lt;/ol&gt;&lt;p&gt;Code reuse aside, I&amp;#8217;m very excited to have this released (it&amp;#8217;s taken me awhile), and hope all the Android engineers out there give the app a try!&lt;/p&gt;
&lt;p&gt;(This is a followup to the post &lt;a href="http://praeclarum.org/post/15789866032/icircuit-code-reuse-part-trois"&gt;iCircuit Code Reuse Part Trois&lt;/a&gt;. More details on my methodology can be found there.)&lt;/p&gt;</description><link>http://praeclarum.org/post/31799384896</link><guid>http://praeclarum.org/post/31799384896</guid><pubDate>Tue, 18 Sep 2012 09:06:00 -0700</pubDate></item><item><title>Speakers I can't wait to see at Lang.NEXT 2012</title><description>&lt;p&gt;The &lt;a href="http://channel9.msdn.com/Events/Lang-NEXT/Lang-NEXT-2012"&gt;speaker list for Lang.NEXT 2012&lt;/a&gt; has been released, and I found myself trying to decide which speakers to go see. There are a lot of fine choices so I thought I had better get organized!&lt;/p&gt;
&lt;p&gt;Here are the speakers I want to see because of a &amp;#8220;personal&amp;#8221; connections:&lt;/p&gt;
&lt;ul&gt;&lt;li&gt;&lt;a href="http://channel9.msdn.com/Events/Speakers/Andrei-Alexandrescu"&gt;Andrei Alexandescu&lt;/a&gt; was my C++ hero for years as I dove deeper and deeper into the language and metaprogramming.&lt;/li&gt;
&lt;li&gt;&lt;a href="http://channel9.msdn.com/Events/Speakers/Martin-Odersky"&gt;Martin Odersky&lt;/a&gt; created Scala and I loved Scala for a time.&lt;/li&gt;
&lt;li&gt;&lt;a href="http://channel9.msdn.com/Events/Speakers/Herb-Sutter"&gt;Herb Sutter&lt;/a&gt; because I&amp;#8217;ve read all his books and in doing so fooled myself into thinking C++ was a valid language. :-) Honestly, I really don&amp;#8217;t care what other ridiculous features have been bolted onto C this year, but it would be fun to see him present.&lt;/li&gt;
&lt;/ul&gt;&lt;p&gt;And then there are those I want to see because of their notoriety:&lt;/p&gt;
&lt;ul&gt;&lt;li&gt;&lt;a href="http://channel9.msdn.com/Events/Speakers/Gilad-Bracha"&gt;Gilad Bracha&lt;/a&gt; because he just seems ridiculously smart and continues to invent new and interesting languages.&lt;/li&gt;
&lt;li&gt;&lt;a href="http://channel9.msdn.com/Events/Speakers/Erik-Meijer"&gt;Erik Meijer&lt;/a&gt; because he is energetic and usually has something interesting to say.&lt;/li&gt;
&lt;li&gt;&lt;a href="http://channel9.msdn.com/Events/Speakers/Mads-Torgersen"&gt;Mads Torgersen&lt;/a&gt; for his C#ness. But really, do I need more C# knowledge. ;-)&lt;/li&gt;
&lt;/ul&gt;&lt;p&gt;Then there are the speakers I want to see because they sound fascinating:&lt;/p&gt;
&lt;ul&gt;&lt;li&gt;&lt;a href="http://channel9.msdn.com/events/speakers/Andrew-Black"&gt;Andrew Black&lt;/a&gt; says he understands OOP and mobile. I want to see if his ideas of OOP jive with my own.&lt;/li&gt;
&lt;li&gt;&lt;a href="http://channel9.msdn.com/Events/Speakers/Walter-Bright"&gt;Walter Bright&lt;/a&gt; seems to be a big compiler geek. Compilers are boring, but compiler geeks are not.&lt;/li&gt;
&lt;li&gt;&lt;a href="http://channel9.msdn.com/Events/Speakers/Kim-Bruce"&gt;Kim Bruce&lt;/a&gt; he said OOP and Java in the same sentence, but I&amp;#8217;ll forgive him for that since he sounds like a sincere smart one.&lt;/li&gt;
&lt;li&gt;&lt;a href="http://channel9.msdn.com/Events/Speakers/William-Cook"&gt;William Cook&lt;/a&gt; worked on AppleScript and more OOP.&lt;/li&gt;
&lt;li&gt;&lt;a href="http://channel9.msdn.com/Events/Speakers/Jeroen-Frijters"&gt;Jeroen Frijters&lt;/a&gt; because kangaroo vouched for him and IKVM is cool.&lt;/li&gt;
&lt;li&gt;&lt;a href="http://channel9.msdn.com/Events/Speakers/Andy-Gordon"&gt;Andy Gordon&lt;/a&gt; because his bio mentions machine learning and F#. Check, and check.&lt;/li&gt;
&lt;li&gt;&lt;a href="http://channel9.msdn.com/Events/Speakers/Robert-Griesemer"&gt;Robert Griesemer&lt;/a&gt; made Go and worked on the V8 engine. There must be some good stuff to learn from him.&lt;/li&gt;
&lt;/ul&gt;</description><link>http://praeclarum.org/post/19412873505</link><guid>http://praeclarum.org/post/19412873505</guid><pubDate>Fri, 16 Mar 2012 14:16:00 -0700</pubDate></item><item><title>A Two-year-old Bug Found by Microsoft</title><description>&lt;p&gt;I submitted the Windows Phone 7 version of iCircuit to Microsoft a few days ago and was shocked (shocked!) that it failed certification by their testers.&lt;/p&gt;
&lt;p&gt;I was in denial, how could this be? The engine is two years old, and, while it has issues, is very stable on a variety of platforms. Add to this the fact that I couldn&amp;#8217;t reproduce the bug right away, I was stymied.&lt;/p&gt;
&lt;p&gt;But after some patience and Diet Coke, I discovered that not only did they discover a bug in the engine, but one that&amp;#8217;s been there since its initial release. That means it has been hidden from thousands of users and many many rounds of testing. I have to hand it to Microsoft for finding it.&lt;/p&gt;
&lt;p&gt;I would like to discuss the nature of the bug in some detail here since I have never run into something of its kind before.&lt;/p&gt;
&lt;p&gt;As with all numerical apps, the bug lied in floating point precision problems.&lt;/p&gt;
&lt;p&gt;The Scope in iCircuit automatically determines a range for the value axis of the plot. If the signal ranges from -5 to 5&amp;#160;V, then the plot shows that range. To do the actual plotting it calculates a pixel ratio:&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;PPV = Height of the Plot / (Max Value - Min Value)&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;But what happens if you have a DC signal that ranges from, say, 5&amp;#160;V to 5&amp;#160;V? You would get a divide by 0 in the calculation of PPV. Being an electronics simulator where DC signals occur all the time, iCircuit had to have code to handle this case. And so, pseudo min and max values were introduced:&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;DV = Max Value - Min Value&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;if (DV == 0) { DV = 1e-6; }&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Pseudo Min Value = Min Value - DV&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Pseudo Max Value = Max Value + DV&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;PPV is then calculated as above but using these pseudo variables instead of the real values. DV is set to a value that makes the plot look decent but is any arbitrary value greater than 0. You can think of DV as creating a little gap around the constant values.&lt;/p&gt;
&lt;p&gt;This is the code that&amp;#8217;s been in iCircuit since v1.0 and has worked quite well. Until Microsoft got their hands on my app.&lt;/p&gt;
&lt;p&gt;Their tester decided to hook up an LED directly to a DC source. All electricians know that this is a bad idea - you&amp;#8217;ll burn out the LED since diodes have very little internal resistance. You always put some resistance in series with the LED. But he didn&amp;#8217;t.&lt;/p&gt;
&lt;p&gt;LEDs do have some internal resistance that iCircuit was simulating to produce a current of over &lt;strong&gt;1.9e19&lt;/strong&gt;. That&amp;#8217;s a huge current! Impossibly huge, but theoretically correct.&lt;/p&gt;
&lt;p&gt;When the tester went to observe that current on the scope, it was determined to be a DC value (DV == 0) and the pseudo values were calculated. Kinda.&lt;/p&gt;
&lt;p&gt;It turns out that &lt;strong&gt;1.9e19 +/- 1e-6 == 1.9e19&lt;/strong&gt; thanks to floating-point imprecision.&lt;/p&gt;
&lt;p&gt;Oh my. That means that the pseudo values were still the same and we hit the divide by 0 bug. When I tried to plot a NaN value (some more math is done on PPV), an unhandled exception was triggered. Oh my indeed.&lt;/p&gt;
&lt;p&gt;That is the crash that the Microsoft tester found. Good job, man.&lt;/p&gt;
&lt;p&gt;Now the solution. Instead of using a fixed minimum DV value of 1e-6, I calculate it as&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Min DV = |Max Value| * 1e-6&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;and DV becomes&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;DV = max(Min DV, Max Value - Min Value)&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;This makes sure that DV will be substantial enough to ensure Pseudo Min Value and Pseudo Max Value are different and the divide by 0 is avoided.&lt;/p&gt;
&lt;p&gt;Well, almost, there&amp;#8217;s still a bug there, but I&amp;#8217;ll let you discover it.&lt;/p&gt;</description><link>http://praeclarum.org/post/16194355039</link><guid>http://praeclarum.org/post/16194355039</guid><pubDate>Fri, 20 Jan 2012 15:43:00 -0800</pubDate></item><item><title>iCircuit Code Reuse Part Trois</title><description>&lt;p&gt;I have recently finished porting &lt;a href="http://icircuitapp.com" title="iCircuit Home Page"&gt;iCircuit&lt;/a&gt; to Microsoft Windows Phone 7 (WP7) and wanted to see how I performed on the code reuse front.&lt;/p&gt;
&lt;p&gt;I use &lt;a href="http://xamarin.com/monotouch" title="Xamarin MonoTouch"&gt;MonoTouch&lt;/a&gt; to do iOS development, and that was the first version of the application. Some months ago, I also released a Mac version of the app using &lt;a href="http://www.mono-project.com/MonoMac" title="MonoMac"&gt;MonoMac&lt;/a&gt;. It was then that I &lt;a href="http://www.infoq.com/presentations/3-Mobile-App-Development-Problems" title="My Boston presentation on particular problems faced by mobile app developers"&gt;gave a presentation&lt;/a&gt; giving some general stats on the amount of code I was able to reuse between the two versions.&lt;/p&gt;
&lt;p&gt;Now, with a third version, it&amp;#8217;s time to repeat the report. This is also the first version of the app not written using Mono tooling. That&amp;#8217;s right, I used a PC. It was weird.&lt;/p&gt;
&lt;p&gt;I wrote a little script to calculate the stats I&amp;#8217;m about to present. Here is &lt;a href="https://gist.github.com/1608597" title="Gist of script to calculate code reuse stats"&gt;gist of that script&lt;/a&gt; so that you can decide for yourself if these stats are worthwhile. All the compiled code for each project got put into two buckets: unique code and shared code. Unique code is code used only for that project while shared code is code that was used in more than 1 project (not requiring that it be used in all projects). The majority of the shared code comes from the iCircuit cross platform library, but also includes things like shared graphics drivers and file system abstractions.&lt;/p&gt;
&lt;p&gt;The raw output from that script is as follows:&lt;/p&gt;
&lt;p&gt;&lt;code&gt; &lt;/code&gt;&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;app     t       u       s       u%      s%
Mac     29954   3901    26053   13.02 % 86.98 %
WP7     30744   5760    24984   18.74 % 81.26 %
iOS     37518   11532   25986   30.74 % 69.26 %&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;code&gt; &lt;/code&gt;&lt;/p&gt;
&lt;p&gt;(t is Total lines of code, u is Unique lines of code, and s in Shared lines of code. Lines of code include comments and white space. I have a fairly consistent coding style, so this simple metric is adequate.)&lt;/p&gt;
&lt;p&gt;And here are some pie charts to make that data easier to visualize.&lt;/p&gt;
&lt;p&gt;&lt;img src="http://media.tumblr.com/tumblr_lxr9kwZeTi1qbzjil.png"/&gt;&lt;/p&gt;
&lt;p&gt;Green code is shared, and Red code is unique to the app. Lines of code and percentages are shown.&lt;/p&gt;
&lt;p&gt;The iOS version of the app has the most amount of platform specific code, 11,532 lines worth. I can give you 1,000 reasons for this, but the gist of it is that the platform has the most effort put into it and includes an iPhone version along with an iPad version.&lt;/p&gt;
&lt;p&gt;The Mac version did much better with only 3,901 lines of unique code needing to be written. It is particularly small because it not only shared the cross-platform code, but was also able to share a lot of driver code with the iOS version: things like the audio drivers and graphics drivers were directly shared between the two platforms thanks to the awesome work of the Mono team and Apple.&lt;/p&gt;
&lt;p&gt;I was hoping the WP7 version would be even less, but, it turns out, it still took a good amount of effort. 5,760 lines of code had to be written accounting for nearly 20% of the code base. New graphics drivers, and new audio drivers had to be written to support the Silverlight programming model along with a lot of IsolatedStorage tomfoolery. Now, when I release Windows 8, WPF, and Silverlight versions of the app, a lot of that code will also get reused, but for now it stands on its own.&lt;/p&gt;
&lt;p&gt;Overall, I&amp;#8217;m quite pleased with these results. I always talk about the 80/20 rule being applied to the cross-platform/platform-specific code split and so I&amp;#8217;m very happy that the number back me up pretty well.&lt;/p&gt;
&lt;p&gt;I can&amp;#8217;t wait to get on to the next platform!&lt;/p&gt;</description><link>http://praeclarum.org/post/15789866032</link><guid>http://praeclarum.org/post/15789866032</guid><pubDate>Fri, 13 Jan 2012 13:26:04 -0800</pubDate></item><item><title>My Presentation in Boston</title><description>&lt;a href="http://www.infoq.com/presentations/3-Mobile-App-Development-Problems"&gt;My Presentation in Boston&lt;/a&gt;: &lt;p&gt;This was my first professional speaking gig. So even if it went bad, please lie to me and tell me it was good.&lt;/p&gt;</description><link>http://praeclarum.org/post/12531956358</link><guid>http://praeclarum.org/post/12531956358</guid><pubDate>Tue, 08 Nov 2011 15:41:07 -0800</pubDate></item><item><title>My Great Wumpus Hunt</title><description>&lt;p&gt;There is a bug in &lt;a title="iCircuit Home" href="http://icircuitapp.com"&gt;iCircuit&lt;/a&gt; that is tarting to feel like my &lt;a href="http://en.wikipedia.org/wiki/Moby-Dick"&gt;white whale&lt;/a&gt;, my &lt;a href="http://en.wikipedia.org/wiki/Wumpus"&gt;wumpus&lt;/a&gt;. I know all about the bug: I know why it&amp;#8217;s happening, I know all its symptoms, and I know at least one way to squish it.&lt;/p&gt;
&lt;p&gt;&amp;#8220;So what&amp;#8217;s the problem?&amp;#8221; you might legitimately ask. The problem is that the only fix, that I know for certain, creates a very non-Apple-esque feel to my app, and that is preventing me from implementing the fix. Apple provides the wonderful &lt;a href="http://developer.apple.com/library/ios/#documentation/UIKit/Reference/UIScrollView_Class/Reference/UIScrollView.html"&gt;UIScrollView&lt;/a&gt; which, among other things provides momentum scrolling and very smooth animation. If I implement my own gestures, all my problems are solved except I miss out on the benefits of UIScrollView. End result for the user? The app feels &amp;#8220;laggy&amp;#8221;.&lt;/p&gt;
&lt;p&gt;I have tried 4 times to implement different strategies to fix this bug while maintaining the Apple-feel factor. I have failed 4 times. &lt;/p&gt;
&lt;p&gt;OK, enough generalizations, thanks for sitting through that. Here is the bug:&lt;/p&gt;
&lt;p&gt;iCircuit uses a &lt;a href="http://developer.apple.com/library/ios/#documentation/UIKit/Reference/UIScrollView_Class/Reference/UIScrollView.html"&gt;UIScrollView&lt;/a&gt; that contains 3 large (usually mostly off-screen) UIViews that componsite together to show you the circuit. This (amazingly) works fine thanks to the fantastic engineers at Apple. But I consider that implementation to be a bug because of these symptoms:&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Symptom 1: Everything is all blurry!&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;&lt;img src="http://media.tumblr.com/tumblr_ln0331MLYz1qbzjil.png"/&gt;&lt;/p&gt;
&lt;p&gt;When you zoom in to the circuit, everything becomes blurry. This is due to the simple nature of UIScrollView and the fact that I don&amp;#8217;t change the view hierarchy at all after a zoom operation. This is the default behavior of UIScrollView and drives me absolutely batty.&lt;/p&gt;
&lt;p&gt;&lt;a href="http://developer.apple.com/library/ios/documentation/WindowsViews/Conceptual/UIScrollView_pg/ZoomZoom/ZoomZoom.html#//apple_ref/doc/uid/TP40008179-CH102-SW9"&gt;Apple has a way to fix this&lt;/a&gt;! All you have to do is switch your code to be thread safe, stop using UIGraphics, and implement &lt;a href="http://developer.apple.com/library/ios/#documentation/GraphicsImaging/Reference/CATiledLayer_class/Introduction/Introduction.html"&gt;CATiledLayer&lt;/a&gt; in the content view of the UIScrollView. Easy huh? It actually is, and works surprisingly well. When you zoom, everything gets redrawn at screen resolution.&lt;/p&gt;
&lt;p&gt;You&amp;#8217;ve seen this beauty before in apps like Safari. When you first zoom in, everything is blurry and then (pretty quickly) everything gets redrawn at the new native resolution. Another +1 to Apple engineers.&lt;/p&gt;
&lt;p&gt;Great! But it doesn&amp;#8217;t work for iCircuit. The main UI of the app is animated at about 7 FPS (it adaptively changes the frame rate to keep your battery from dying) and this ends up being too much work for the CATiledLayer. The screen becomes a mish-mash of partially updated regions and smooth animation is out the door. This is an appropriate emoticon for my mood when discovering this: :-(&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Symptom 2: Way too much Memory&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;A lot of users of iCircuit run into one limitation before all others: I limit circuit sizes to 2048x2048 pixels. This size limitation is in place for one and only one reason, it&amp;#8217;s because the app runs out of memory if you increase it.&lt;/p&gt;
&lt;p&gt;Ugh. I feel like I&amp;#8217;m 16 again implementing code in the most naive fashion just hoping it works. It&amp;#8217;s ridiculous to tie the logical dimensions of a circuit to an OS-tracked-super-heavy-resource. If the circuit is 2048px across, I create 3 UIViews that are also 2048px across. iOS can handle this, but what if you want a circuit that&amp;#8217;s 10 kpx wide? The OS just doesn&amp;#8217;t have enough memory (nor CPU) to render UIViews of that size at the framerate that I want.&lt;/p&gt;
&lt;p&gt;So if I know this is the wrong thing to do, then why do I do it? Becuase it makes UIScrollView happy.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Symptom 3: Retina Display is Sloooow&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;Memory is one thing, but on iOS you get all the memory you ask for until the app is shut down. It&amp;#8217;s a good deal. CPU, on the other hand, well, there&amp;#8217;s only one of those and it has a lot of work to do. I&amp;#8217;m already asking it to do a lot in solving the circuit equation in the background. Asking it to draw 2048x2048px images at 7 FPS takes about 10% of the CPU on iPhone 3GS and iPad 1.&lt;/p&gt;
&lt;p&gt;Retina display doubles pixel counts. So my 2048x2048 circuit becomes 4096x4096px. This is an increase to memory, and worse, a burden to the CPU to draw lots of anti-aliased lines. It turns out that the iPhone 4 is not capable of this. Quickly, it falls to 3 FPS (lower limit) and the whole user experience is degrated.&lt;/p&gt;
&lt;p&gt;Alas, this is the current state of iCircuit 1.2. I surprisingly don&amp;#8217;t get a lot of emails about this since the app is really meant for the iPad, but it breaks my programmer heart. Again, I feel like a 16 year-old punk.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Solution 1: Wherein I try to fix it 4 times and fail every time&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;This post is really just an opportunity for me to vent. I hate this bug. I hate that I haven&amp;#8217;t been able to fix it. I have ideas of how to make it better, but I haven&amp;#8217;t been able to code any of those ideas to my satisfaction.&lt;/p&gt;
&lt;p&gt;In a nutshell, solving the problem involves keeping 1 huge UIView for the UIScrollView to deal with. Within that view, I will place a subview that draws only that part of the circuit that the user is viewing.&lt;/p&gt;
&lt;p&gt;Sounds simple, right? A two-hour hack, right? The devil is in the details in this one, but I still have high hopes. I lied to you before: this blog post is actually a rallying call for me. I&amp;#8217;m about to implement this solution for the fifth time. I really want it to work, wish me luck.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Solution 2: Ditch UIKit/Core Graphics/Core Animation&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;I love the Apple platform. After years of writing Windows apps where Microsoft said &amp;#8220;here&amp;#8217;s a push button and a window object, good luck with the rest&amp;#8221;, it&amp;#8217;s a real refresher to work with powerful APIs that are geared toward making the programmer&amp;#8217;s life (and thusly, the end user&amp;#8217;s experience) better.&lt;/p&gt;
&lt;p&gt;But if it doesn&amp;#8217;t work it doesn&amp;#8217;t work. The Apple platform has one last escape hatch when dealing with graphics-heavy apps: fall back to OpenGL. I know from past experiences that this will solve the majority of my problems:&lt;/p&gt;
&lt;ol&gt;&lt;li&gt;Drawing will be fast because OpenGL is a monster.&lt;/li&gt;
&lt;li&gt;This will free up the UI thread which means I can deal with the touch events. I won&amp;#8217;t be able to match 100% the smoothness of UIScrollView, but I can get close.&lt;/li&gt;
&lt;/ol&gt;&lt;p&gt;There are, of course, two hurdles preventing me from taking this path:&lt;/p&gt;
&lt;ol&gt;&lt;li&gt;OpenGL isn&amp;#8217;t great at anti-aliasing. 1px lines look like they&amp;#8217;re from 1990 and my sould dies a little death. Ironically, this isn&amp;#8217;t an issue on retina displays since the DPI is so ridiculously high. But on chunky-pixel devices, this makes the app look amateurish at best. (Actually it makes it look like all those Windows circuit editors that I&amp;#8217;m trying so hard not to be).&lt;/li&gt;
&lt;li&gt;Fonts. If you&amp;#8217;ve ever programmed OpenGL, you know what I mean. Fonts suck. They&amp;#8217;re blurry, they take effort to manage, and they&amp;#8217;re blurry.&lt;/li&gt;
&lt;/ol&gt;&lt;p&gt;&lt;strong&gt;THE END&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;Enough ranting and time to start coding. Please do wish me luck as I hunt and kill this monster. And, if, like times previous, the Wumpus should eat me for dinner, remember, it was all in the name of making an app worthy of the hardware.&lt;/p&gt;

&lt;ol&gt;&lt;/ol&gt;</description><link>http://praeclarum.org/post/6663989742</link><guid>http://praeclarum.org/post/6663989742</guid><pubDate>Sat, 18 Jun 2011 12:53:27 -0700</pubDate></item><item><title>Kangaroo's Pizza Dough Recipe</title><description>kangaroo: here's my recipe for ~2 10" pies&lt;br /&gt;&#13;
[4:44pm] kangaroo: adjust volume by bakers %ages accordingly&lt;br /&gt;&#13;
[4:44pm] kangaroo: 340g flour&lt;br /&gt;&#13;
[4:44pm] kangaroo: 241g water&lt;br /&gt;&#13;
[4:44pm] kangaroo: 7g yeast (I like a good sponge, you can adjust)&lt;br /&gt;&#13;
[4:44pm] kangaroo: 7g salt&lt;br /&gt;&#13;
[4:45pm] kangaroo: 7g sugar&lt;br /&gt;&#13;
[4:45pm] kangaroo: combine warm water and yeast to bloom&lt;br /&gt;&#13;
[4:45pm] kangaroo: put paddle hook on your mixer to combine dry stuff&lt;br /&gt;&#13;
[4:45pm] kangaroo: add wet stuff and paddle until combined&lt;br /&gt;&#13;
[4:45pm] kangaroo: let sit for 10 minutes&lt;br /&gt;&#13;
[4:45pm] kangaroo: change paddle for dough hook, and start getting your dough ball&lt;br /&gt;&#13;
[4:46pm] kangaroo: after about 10 minutes you should have a good ball, then add "enough" olive oil, I do this by eye&lt;br /&gt;&#13;
[4:46pm] kangaroo: but call it ~1tbsp&lt;br /&gt;&#13;
[4:46pm] kangaroo: dough hook until you get the gluten development you want&lt;br /&gt;&#13;
[4:46pm] kangaroo: put ball into well oiled dish (overnight ideally in fridge, if you're doing same day do it in the morning and put it in a warm spot)&lt;br /&gt;&#13;
[4:47pm] kangaroo: ~2-4hrs before pizza time, divide with dough scraper and reform into 2 dough balls&lt;br /&gt;&#13;
[4:47pm] kangaroo: dust the top with oil to avoid dough skin and put on a work surface and cover with a kitchen rag&lt;br /&gt;&#13;
[4:47pm] kangaroo: then just stretch/toss/whatever&lt;br /&gt;&#13;
[4:47pm] kangaroo: when its time to eat&lt;br /&gt;&#13;
[4:47pm] kangaroo: I do 550F oven preheated with stone for an hour (at least) preferably 2&lt;br /&gt;&#13;
[4:47pm] kangaroo: and cook for 7-9 minutes per pie, directly on the stone&lt;br /&gt;&#13;
[4:48pm] kangaroo: if you like a tarter dough, you can bloom a sourdough starter and use that, just drop the sugar and keep the bakers %s the same&lt;br /&gt;&#13;
[4:49pm] fak: how much gluten do I want?&lt;br /&gt;&#13;
[4:49pm] kangaroo: depends on personal taste&lt;br /&gt;&#13;
[4:49pm] fak: how does one recognize it?&lt;br /&gt;&#13;
[4:49pm] kangaroo: the thinner crust you want, the more gluten you want, but you dont want to over work&lt;br /&gt;&#13;
[4:49pm] kangaroo: I generally knead for 15-30 in my kitchenaid&lt;br /&gt;&#13;
[4:50pm] kangaroo: you can pinch off a dough ball and stretch it a bit and see the breaking point&lt;br /&gt;&#13;
[4:50pm] kangaroo: the thinner you want, the more stretch you want&lt;br /&gt;&#13;
[4:50pm] kangaroo: in the 20 minute range my dough is maybe 4-5mm&lt;br /&gt;&#13;
[4:50pm] kangaroo: but still with good air development&lt;br /&gt;&#13;
[4:50pm] kangaroo: and not too difficult to work with&lt;br /&gt;&#13;
[4:50pm] fak: must have air development&lt;br /&gt;&#13;
[4:51pm] kangaroo: you can push the yeast up to 8 or 9g if you want even more air&lt;br /&gt;&#13;
[4:51pm] kangaroo: but dont go much higher or you'll mess with the flavor&lt;br /&gt;&#13;
</description><link>http://praeclarum.org/post/3353529374</link><guid>http://praeclarum.org/post/3353529374</guid><pubDate>Thu, 17 Feb 2011 16:52:53 -0800</pubDate></item><item><title>Quantifying reflection's slowdown in sqlite-net</title><description>&lt;p&gt;Yesterday I posted R64 of &lt;a href="http://code.google.com/p/sqlite-net/"&gt;sqlite-net&lt;/a&gt; which included some performance upgrades thanks to &lt;a href="http://twitter.com/#!/joefeser"&gt;Joe Feser&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;The tweet spread and we were asked how this compares to native performance of Sqlite. I had no answer because I&amp;#8217;ve been drinking the MonoTouch kool-aid for awhile now and don&amp;#8217;t even think about native performance. But the questions did have me wondering.&lt;/p&gt;
&lt;p&gt;I know there is nothing I can do about the overhead of a managed runtime like .NET over native code, but I did wonder how much overhead my use of Reflection introduces. To keep the use of sqlite-net simple (no external tool requirements, no on the fly code compilation), I rely on reflection to read and write values from properties. That design probably won&amp;#8217;t change since I love the ease of use of the library, but I do think its time to measure the overhead.&lt;/p&gt;
&lt;p&gt;I wrote a little test app that serializes and deserializes 30,000 objects (most of whom&amp;#8217;s data is textual). The app performs those operations in three ways:&lt;/p&gt;
&lt;ol&gt;&lt;li&gt;Using .NET&amp;#8217;s built-in BinaryFormatter and the [Serializable] attribute on the class.&lt;/li&gt;
&lt;li&gt;Using a custom function that uses a BinaryReader/Writer that calls the appropriate Read/Write functions and sets the properties on the objects directly.&lt;/li&gt;
&lt;li&gt;Using BinaryReader/Writer again but using generic reflection code that is very similar to the code that sqlite-net uses to read data from the database.&lt;/li&gt;
&lt;/ol&gt;&lt;p&gt;Through this, I can compare the performance of the reflection code (#3) vs the non-reflection code (#2). The use of BinaryFormatter is also put in as a control.&lt;/p&gt;
&lt;p&gt;I ran the code 3 times on my iPhone 3GS using a Release build from MonoTouch. It writes approximately 7&amp;#160;MB files for each method and then reads those files back. Here are the average results:&lt;/p&gt;
&lt;ul&gt;&lt;li&gt;BinaryFormatter Serialize = &lt;strong&gt;10.74&amp;#160;s&lt;/strong&gt;&lt;/li&gt;
&lt;li&gt;Explicit BinaryWriter = &lt;strong&gt;1.30&amp;#160;s&lt;/strong&gt;&lt;/li&gt;
&lt;li&gt;Reflection BinaryWriter = &lt;strong&gt;7.79&amp;#160;s&lt;/strong&gt;&lt;/li&gt;
&lt;/ul&gt;&lt;ul&gt;&lt;li&gt;BinaryFormatter Deserialize = &lt;strong&gt;50.38&amp;#160;s&lt;/strong&gt;&lt;/li&gt;
&lt;li&gt;Explicit BinaryReader = &lt;strong&gt;2.93&amp;#160;s&lt;/strong&gt;&lt;/li&gt;
&lt;li&gt;Reflection BinaryReader = &lt;strong&gt;11.21&amp;#160;s&lt;/strong&gt;&lt;/li&gt;
&lt;/ul&gt;&lt;p&gt;Two things are immediately visible in this data: BinaryFormatter is slow, and the reflection code is much slower than the non-reflection code.&lt;/p&gt;
&lt;p&gt;(I have made the &lt;a href="http://spreadsheets.google.com/ccc?key=0AnbISxDzAVhOdHd4c1V1Sm9uNldhQ1hreVlJczVBdkE&amp;amp;hl=en"&gt;Google Spreadsheet&lt;/a&gt; with all the data publicly available.)&lt;/p&gt;
&lt;p&gt;Reflection introduced a slowdown of &lt;strong&gt;3.8x&lt;/strong&gt; for reads, and a slowdown of &lt;strong&gt;5.97x&lt;/strong&gt; for writes. I knew that the reflection code would be slower, but it&amp;#8217;s really good to now have that slowdown quantified.&lt;/p&gt;
&lt;p&gt;And those are not small numbers! I was hoping for 50% slowdowns, but I guess that was too much wishful thinking.&lt;/p&gt;
&lt;p&gt;Given the static compilation limitation of MonoTouch, the only ways to improve these performance number are to: (1) Force the user to hand-write the serialization code, or (2) Create a tool that generates that code automatically and integrate it into the build process. #1 seems like a really bad idea to me, so that leaves #2.&lt;/p&gt;
&lt;p&gt;A somewhat related side note: I have finally looked at the Entity Framework CTP4 - specifically their code-first work. They have the same goals of sqlite-net and applaud their effort. I am thinking now of writing a little database that has the intelligence and interface of EF4&amp;#8217;s code first but that uses a .NET database. That way, you could share code between your iOS, WinPhone, Android devices and your server. A nice thought&amp;#8230;&lt;/p&gt;</description><link>http://praeclarum.org/post/1572668275</link><guid>http://praeclarum.org/post/1572668275</guid><pubDate>Sun, 14 Nov 2010 07:51:00 -0800</pubDate></item><item><title>INotifyCollectionChanged for cleaner more reusable code</title><description>&lt;p&gt;My last post briefly described the work I did to port &lt;a href="http://icircuitapp.com"&gt;iCircuit&lt;/a&gt; to Windows Phone 7. In it, I described how the UI was broken into two large chunks: the graphical circuit editor and the &amp;#8220;chrome&amp;#8221;.&lt;/p&gt;
&lt;p&gt;The chrome is all the text input fields, buttons, selectable lists - it&amp;#8217;s really quite a monstrous amount of code. But this code is not easy to port to different platforms. Yes, I communicate between the business logic and the UI through interfaces, but those interfaces have very few implementation details. When I move to a new platform, I have to rewrite all of the chrome. This is not a technology limitation as I could write a cross platform UI library like Swing, or even port WinForms to the iPhone, but those are bad ideas. Different platforms have different interaction models that must be obeyed.&lt;/p&gt;
&lt;p&gt;That was my thinking ever since I saw &lt;a href="http://langnetsymposium.com/2006/speakers.aspx"&gt;Miguel de Icaza present at Lang.net 2006&lt;/a&gt;. And it still is. But now having worked on simultaneously porting iCircuit to 5 other platforms (Mac, Windows via Silverlight, Silverlight, WP7, Android), I am in real need of more code reuse even on the Chrome.&lt;/p&gt;
&lt;p&gt;My first step in that direction is to embrace &lt;a href="http://msdn.microsoft.com/en-us/library/system.collections.specialized.inotifycollectionchanged.aspx"&gt;INotifyCollectionChanged&lt;/a&gt;. This interface is part of the magic sauce that makes reactive UIs easier to code. It is used heavily throughout SIlverlight to great affect.&lt;/p&gt;
&lt;p&gt;Imagine a mail program with a list messages in one pane, and a single message in another. Imagine that the user deletes the selected message. A bunch of things have to happen:&lt;/p&gt;
&lt;ol&gt;&lt;li&gt;The UI has to close the selected message and probably show the next one in the list&lt;/li&gt;
&lt;li&gt;The app has to delete the message from its local database&lt;/li&gt;
&lt;li&gt;It then has to transmit the delete request to the server&lt;/li&gt;
&lt;li&gt;And then it needs to delete the message from the message list UI&lt;/li&gt;
&lt;/ol&gt;&lt;p&gt;This isn&amp;#8217;t hard to code, but gets really tedious. Now imagine moving the message from one folder to another. It has to be deleted from one list and placed onto another. All I want to do in code is say:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;var folder = ...;
var message = folder.GetSelectedMessage();
var otherFolder = AskUserWhere();
folder.Remove(message);
otherFolder.Add(message);&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;But I also have to write this code:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;var uis = FindAllUIsThatShow(folder);
foreach (var ui in uis) ui.Refresh();
uis = FindAllUIsThatShow(otherFolder);
foreach (var ui in uis) ui.Refresh();&lt;/code&gt;
&lt;/pre&gt;
&lt;p&gt;It&amp;#8217;s stupid to write that code. First it means I have to have a way of tracking which UI elements are looking at a folder, second it means I have to perform potentially costly Refresh operations. Those refreshes are complicated by having to manage selection states, finding minimal changes in lists, requerying, and on and on.&lt;/p&gt;
&lt;p&gt;With INotifyCollectionChanged, we have a way for the UI to react to changes in the data model. When the data changes, the UI intelligently updates. This relieves a mental burden when programming model changes, and an architectual burden when designing the UI code.&lt;/p&gt;
&lt;p&gt;It&amp;#8217;s not the greatest interface - I wish it was actually more capable - but I have decided to adopt it for all my apps since it&amp;#8217;s pretty well baked into Silverlight and, by extension, .NET.&lt;/p&gt;
&lt;p&gt;To that end, I have implemented a new UITableViewController in MonoTouch that knows how to listen to these collection change events and updates its data accordingly. It&amp;#8217;s a very small extension to UITableViewController, but I&amp;#8217;m already excited by its power and ease of use.&lt;/p&gt;
&lt;p&gt;To use it, simply assign the Collection property to an IList. The DecorateCell function is called each time the table needs to update a cell with a data item from the list. If the IList also implements INotifyCollectionChanged, then a little bit of magic happens and you get a table view that reacts intelligently to model changes. Even if your IList doesn&amp;#8217;t implement the interface, you still get a very easy way to present data using a UITableView.&lt;/p&gt;
&lt;p&gt;Enjoy!&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;
using System;
using MonoTouch.UIKit;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using MonoTouch.Foundation;
using System.Collections;

namespace ObservableTableView
{
	public class RowSelectedEventArgs : EventArgs {
		public object Item { get; set; }
		public NSIndexPath Path { get; set; }		
	}
	
	public delegate void RowSelectedEventHandler(object sender, RowSelectedEventArgs e);
	
	public class ObservableTableViewController : UITableViewController
	{		
		public UITableViewRowAnimation AddAnimation { get; set; }
		public UITableViewRowAnimation DeleteAnimation { get; set; }
		public UITableViewCellStyle CellStyle { get; set; }
		
		public event RowSelectedEventHandler RowSelected;
		
		Del _del;
		Data _data;
		
		IList _collection;
		INotifyCollectionChanged _not;
		
		public IList Collection {
			get {
				return _collection;
			}
			set {
				if (_not != null) {
					_not.CollectionChanged -= HandleCollectionChanged;					
				}
				_collection = value;
				_not = _collection as INotifyCollectionChanged;
				if (_not != null) {
					_not.CollectionChanged += HandleCollectionChanged;
					TableView.ReloadData();
				}
			}
		}		
		
		public ObservableTableViewController (UITableViewStyle withStyle)
			: base(withStyle)
		{
			AddAnimation = UITableViewRowAnimation.Top;
			DeleteAnimation = UITableViewRowAnimation.Fade;
			CellStyle = UITableViewCellStyle.Default;
			
			_del = new Del(this);
			_data = new Data(this);
			
			TableView.Delegate = _del;
			TableView.DataSource = _data;
		}
		
		protected virtual void DecorateCell(UITableViewCell cell, object item, NSIndexPath path) {
		}
		
		protected virtual void OnRowSelected(object item, NSIndexPath path) {
			if (RowSelected != null) {
				RowSelected(this, new RowSelectedEventArgs() {
					Item = item,
					Path = path
				});
			}
		}

		void HandleCollectionChanged (object sender, NotifyCollectionChangedEventArgs e)
		{
			TableView.BeginUpdates();
			
			if (e.Action == NotifyCollectionChangedAction.Add) {
				var paths = new NSIndexPath[e.NewItems.Count];
				for (var i = 0; i &amp;lt; paths.Length; i++) {
					paths[i] = NSIndexPath.FromRowSection(e.NewStartingIndex + i, 0);
				}
				TableView.InsertRows(paths, AddAnimation);
			}
			else if (e.Action == NotifyCollectionChangedAction.Remove) {
				var paths = new NSIndexPath[e.OldItems.Count];
				for (var i = 0; i &amp;lt; paths.Length; i++) {
					paths[i] = NSIndexPath.FromRowSection(e.OldStartingIndex + i, 0);
				}
				TableView.DeleteRows(paths, DeleteAnimation);
			}
			
			TableView.EndUpdates();
		}
		
		class Del : UITableViewDelegate {
			ObservableTableViewController _c;
			public Del(ObservableTableViewController c) {
				_c = c;
			}
			
			public override void RowSelected (UITableView tableView, NSIndexPath indexPath)
			{
				var item = _c.Collection != null ? _c.Collection[indexPath.Row] : null;
				_c.OnRowSelected(item, indexPath);
			}
		}
		
		class Data : UITableViewDataSource {
			ObservableTableViewController _c;
			NSString _ident;
			public Data(ObservableTableViewController c) {
				_c = c;
				_ident = new NSString("C");
			}
			public override int NumberOfSections (UITableView tableView)
			{
				return 1;
			}
			public override int RowsInSection (UITableView tableview, int section)
			{
				var coll = _c.Collection;
				return coll != null ? coll.Count : 0;
			}
			public override UITableViewCell GetCell (UITableView tableView, NSIndexPath indexPath)
			{
				var cell = tableView.DequeueReusableCell(_ident);
				if (cell == null) {
					cell = new UITableViewCell(_c.CellStyle, _ident);
				}
				
				try {
					var coll = _c.Collection;
					if (coll != null) {
						var obj = coll[indexPath.Row];
						_c.DecorateCell(cell, obj, indexPath);
					}
					
					return cell;
				}
				catch {
				}
				
				return cell;
			}
		}
	}
}

&lt;/code&gt;&lt;/pre&gt;</description><link>http://praeclarum.org/post/1564455979</link><guid>http://praeclarum.org/post/1564455979</guid><pubDate>Sat, 13 Nov 2010 12:22:32 -0800</pubDate></item><item><title>Interfaces + caches = Cross Platform</title><description>&lt;p&gt;iCircuit is a mobile app that lets you experiment with circuits on your iOS devices. Well, soon, it will also let you do it on your WinPhone7.&lt;/p&gt;
&lt;p&gt;It was implemented using the innovative and very rewarding &lt;a href="http://monotouch.net"&gt;MonoTouch&lt;/a&gt; system. MonoTouch lets you write native iOS apps in C# with full access to .NET. MonoTouch + the iPhone made programming fun again. It was the best decision I&amp;#8217;ve made in a long time.&lt;/p&gt;
&lt;p&gt;On the evening of Jul 21, I was frantic waiting for Apple to approve my baby, and somewhat curious as to how much effort it would take to port the app to Silverlight.&lt;/p&gt;
&lt;p&gt;The engine ported immediately, without change, since it was written in pure .NET and only communicated with the UI through interfaces. (Well, properly said, the UI only communicated with the engine through interfaces.)&lt;/p&gt;
&lt;p&gt;After that, I only had to port the UI which was broken into two nice big chunks: The graphical circuit editor and the &amp;#8220;chrome&amp;#8221; which handled file management and all that boring stuff that makes apps &amp;#8220;apps&amp;#8221;.&lt;/p&gt;
&lt;p&gt;The graphical UI was again coded against interfaces only. So to port it to a new platform, I would merely (haha, &amp;#8220;merely&amp;#8221;) have to implement those interfaces. Because drawing on the iPhone is immediate mode (DrawCircle(); DrawLine(); &amp;#8230;) I designed that interface along those lines. Nearly every graphic interface in existence is immediate mode: iOS, CoreGraphics, Windows GDI, GDI+, OpenGL, DirectX, whatever you call the rendering system on Android, the Canvas element in HTML, &amp;#8230; the list goes on and on. But there are two huge exceptions: Silverlight and WPF!&lt;/p&gt;
&lt;p&gt;Here I had a perfectly abstracted graphics driver that fit every platform in the world except Microsoft&amp;#8217;s new platform. Yawn. So I never got around to porting the app.&lt;/p&gt;
&lt;p&gt;But on July 21, again, I was frantic and needed to code something. So I remembered the golden rule of programming: caches fix everything. I went about writing an implementation of my immediate mode interface that translated all those Draw*() calls to the retained mode of Silverlight (line = new Line(), Add(line)). What followed was the following check ins:&lt;/p&gt;
&lt;p&gt;&lt;code&gt; &lt;/code&gt;&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;changeset:   305:ea9de0ac4a9e
user:        Frank A. Krueger 
date:        Wed Jul 21 17:49:19 2010 -0700
summary:     OMFG it's actually working

changeset:   304:7c5b310e602c
user:        Frank A. Krueger 
date:        Wed Jul 21 17:27:11 2010 -0700
summary:     Fixed bug in my crazy algo, now it works!!!

changeset:   303:fe1bd8e4a3be
user:        Frank A. Krueger 
date:        Wed Jul 21 17:17:08 2010 -0700
summary:     Work toward making the silverlight circuit render. Amazed that my idea actually seems to be working.

changeset:   301:0f223a67e40d
user:        Frank A. Krueger 
date:        Wed Jul 21 15:04:02 2010 -0700
summary:     Began the Silverlight port. CircuitLib is compiling. Yeah. Now I need to reimplement the actual UI :-(&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;code&gt; &lt;/code&gt;&lt;/p&gt;
&lt;p&gt;In a little less than 3 hours I had it working. God I love caches and interfaces.&lt;/p&gt;
&lt;p&gt;Making it work on the phone was just a matter of setting up the project in Visual Studio and recreating the chrome (something I&amp;#8217;m still working on today).&lt;/p&gt;
&lt;p&gt;Today, Nov 8, I got to find out if my method worked - and oh boy did it! The phone is chugging along right now rendering circuits.&lt;/p&gt;
&lt;p&gt;In conclusion: I love .NET. I love MonoTouch. My WinPhone7 is sweet. It&amp;#8217;s a great time to be a developer!&lt;/p&gt;</description><link>http://praeclarum.org/post/1520024382</link><guid>http://praeclarum.org/post/1520024382</guid><pubDate>Mon, 08 Nov 2010 16:19:31 -0800</pubDate></item><item><title>My First MonoMac App - Spy Touch</title><description>&lt;p&gt;The Mono team has recently given the world &lt;a href="http://tirania.org/blog/archive/2010/Apr-19.html"&gt;MonoMac&lt;/a&gt;, a framework that allows C# programmers to write native OS X (Cocoa) apps. This is wonderful news for those who simultaneously love OS X and C#.&lt;/p&gt;
&lt;p&gt;I decided to take her for a spin by writing a little (very little) app that will assist me in my app development.&lt;/p&gt;
&lt;p&gt;Windows developers have an app called &lt;a href="http://msdn.microsoft.com/en-us/library/aa242713(v=VS.60).aspx"&gt;Spy++&lt;/a&gt;. I grew up with this little beauty as I was learning Win32 programming. It was invaluable for learning the structure of GUIs and discovering the little tricks other programmers used to make their GUIs work the way they did. Later, we got &lt;a href="http://msdn.microsoft.com/en-us/magazine/cc163617.aspx"&gt;Managed Spy&lt;/a&gt; for WinForms and &lt;a href="http://snoopwpf.codeplex.com/"&gt;Snoop&lt;/a&gt; for WPF.&lt;/p&gt;
&lt;p&gt;We don&amp;#8217;t have anything like these tools for &lt;a href="http://monotouch.net/"&gt;MonoTouch&lt;/a&gt;. Well, now we do! (And by like, I mean: has 1/100th the features.)&lt;/p&gt;
&lt;p&gt;&lt;img src="http://media.tumblr.com/tumblr_l51qf5SDgY1qbzjil.png"/&gt;&lt;/p&gt;
&lt;p&gt;This little app (can I say little enough?) displays the active visual tree of your app while it is running. As you navigate the visual tree, the active view gets highlighted in a little visualizer on the right hand side.&lt;/p&gt;
&lt;p&gt;To use this tool, you just need to install a little stub client in your app. Include the file SpyTouch.cs, and put the line &lt;strong&gt;SpyTouch.SpyTouch.Run ();&lt;/strong&gt; somewhere in your startup code. Here is a &lt;a href="http://dl.dropbox.com/u/6908183/SpyTouch.zip"&gt;package containing Spy Touch, the stub, and its source code&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;Now you can monitor the visual tree of the app. It refreshes automatically every 2 seconds.&lt;/p&gt;
&lt;p&gt;The usefulness of this tool isn&amp;#8217;t very high because it is just a proof of concept of tools to assist me in the design of GUIs for iOS apps. Now that I have this tool, I am very excited about future possibilities in constructing UI designers.&lt;/p&gt;</description><link>http://praeclarum.org/post/770071583</link><guid>http://praeclarum.org/post/770071583</guid><pubDate>Sun, 04 Jul 2010 12:18:00 -0700</pubDate></item><item><title>Jabroni, Jabroney, or Jaboney</title><description>&lt;p&gt;&lt;strong&gt;Long story short:&lt;/strong&gt; &lt;em&gt;Jabroni&lt;/em&gt; is the modern form of &lt;em&gt;Jaboney&lt;/em&gt;, American slang used to mock someone, somewhat vaguely, since at least 1931. The &lt;a href="http://www.etymonline.com/index.php?term=jabroni"&gt;online etymology dictionary&lt;/a&gt; defines a jaboney as a &amp;#8220;naive person, immigrant, hoodlum.&amp;#8221;&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;The Long Story&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;Recently on &lt;a href="http://noagendashow.com"&gt;No Agenda&lt;/a&gt;, &lt;a href="http://curry.com/"&gt;Adam Curry&lt;/a&gt; was wondering about the etymology of &amp;#8220;Jabroni&amp;#8221;. Since I&amp;#8217;ve heard the word all my life, I was dismayed that the internet credits it to &lt;a href="http://www.urbandictionary.com/define.php?term=Jabroni&amp;amp;defid=1184851"&gt;The Rock&lt;/a&gt;&amp;#8230; almost everywhere.&lt;/p&gt;
&lt;p&gt;I started my search with the &lt;a href="http://google.com"&gt;Goog&lt;/a&gt; of course, Goog Books to be exact. I was looking for &lt;a href="http://books.google.com/books?lr=&amp;amp;as_brr=0&amp;amp;q=jabroni&amp;amp;btnG=Search+Books&amp;amp;as_drrb_is=b&amp;amp;as_minm_is=1&amp;amp;as_miny_is=1000&amp;amp;as_maxm_is=1&amp;amp;as_maxy_is=1990"&gt;a reference prior to 1990&lt;/a&gt;, that is, prior to The Rock. Some matches were found, but most of those matches seemed to be the Goog book OCR system incorrectly matching &lt;em&gt;Fabroni&lt;/em&gt;.&lt;/p&gt;
&lt;p&gt;And then I got lucky and ran into this internet question: &lt;a href="http://www.lemmingtrail.com/mb/199730/"&gt;Jaboney or Jabroney&lt;/a&gt;. The consensus on the form was to use the spelling with an &amp;#8220;r&amp;#8221;, but I was intrigued enough to try Goog Books again. I searched for &lt;a href="http://books.google.com/books?lr=&amp;amp;as_brr=0&amp;amp;q=jaboney&amp;amp;btnG=Search+Books&amp;amp;as_drrb_is=b&amp;amp;as_minm_is=1&amp;amp;as_miny_is=1000&amp;amp;as_maxm_is=1&amp;amp;as_maxy_is=1990"&gt;Jaboney prior to 1990&lt;/a&gt; and hit the jackpot.&lt;/p&gt;
&lt;p&gt;The first hit that caught my eye was &lt;strong&gt;&lt;a href="http://books.google.com/books?id=wOdaAAAAIAAJ&amp;amp;q=jaboney&amp;amp;dq=jaboney&amp;amp;lr=&amp;amp;as_drrb_is=b&amp;amp;as_minm_is=1&amp;amp;as_miny_is=1000&amp;amp;as_maxm_is=1&amp;amp;as_maxy_is=1990&amp;amp;as_brr=0&amp;amp;cd=5"&gt;A-18: a novel&lt;/a&gt;&lt;/strong&gt;&lt;a href="http://books.google.com/books?id=wOdaAAAAIAAJ&amp;amp;q=jaboney&amp;amp;dq=jaboney&amp;amp;lr=&amp;amp;as_drrb_is=b&amp;amp;as_minm_is=1&amp;amp;as_miny_is=1000&amp;amp;as_maxm_is=1&amp;amp;as_maxy_is=1990&amp;amp;as_brr=0&amp;amp;cd=5"&gt; by Thomas Taylor written in 1967&lt;/a&gt;. In the book, he uses the word just as we would today:&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;&amp;#8220;She got the jaboney to marry her, so I didn&amp;#8217;t have to support her too long.&amp;#8221;&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;(There is a second use, but Goog cut it off.)&lt;/p&gt;
&lt;p&gt;In addition to the reference in this novel, &lt;a href="http://books.google.com/books?id=7dk4AAAAMAAJ&amp;amp;dq=jaboney&amp;amp;lr=&amp;amp;as_drrb_is=b&amp;amp;as_minm_is=1&amp;amp;as_miny_is=1000&amp;amp;as_maxm_is=1&amp;amp;as_maxy_is=1990&amp;amp;as_brr=0&amp;amp;cd=9"&gt;American Speech vol. 6 from 1931&lt;/a&gt; lists the word but unfortunately there is no scan of the page available. Now I&amp;#8217;m off to the &lt;a href="http://www.worldcat.org/wcpa/oclc/1480854?page=frame&amp;amp;url=http%3A%2F%2Fcatalog.spl.org%2Fipac20%2Fipac.jsp%3Findex%3DISBNEX%26term%3D0003-1283%26checksum%3D245c8ffee7a9bb3925601f389f433633&amp;amp;title=Seattle+Public+Library&amp;amp;linktype=opac&amp;amp;detail=UOK%3ASeattle+Public+Library%3APublic+Library"&gt;Seattle Library&lt;/a&gt; to see if I can find it.&lt;/p&gt;
&lt;p&gt;There are further references in 1934, 1949, 1953, 1969, 1987, 1989, and more.&lt;/p&gt;
&lt;p&gt;So it&amp;#8217;s pretty certain that those WWE wrestlers didn&amp;#8217;t make this one up.&lt;/p&gt;</description><link>http://praeclarum.org/post/645201645</link><guid>http://praeclarum.org/post/645201645</guid><pubDate>Sat, 29 May 2010 18:14:00 -0700</pubDate></item><item><title>Obligatory First Post</title><description>&lt;p&gt;From custom blogging software, to blogspot, to tumblr, this blog has seen a lot of engines.&lt;/p&gt;
&lt;p&gt;I hope tumblr will be its final home.&lt;/p&gt;</description><link>http://praeclarum.org/post/644077933</link><guid>http://praeclarum.org/post/644077933</guid><pubDate>Sat, 29 May 2010 09:24:19 -0700</pubDate></item></channel></rss>
