05 July 2014

Bootstrap style WPF buttons

In my upcoming job, I will be writing a desktop app using WPF. Most of my work has previously been on the web, where there are many established libraries for layout and general behavior. One of those is called Bootstrap.

Some people dislike Bootstrap because many websites out there use the starting Bootstrap template, hence the notion that all Bootstrap sites look the same. Let me just say, they don't. It's probably fairer to say that website looks alike if their designers are lazy. Bootstrap itself is a great tool.

I commonly use Bootstrap buttons, because they come with good default styles which can give hints to the users. I mainly use the primary, default, and danger styles to indicate the kind of actions that are being performed. So today, I will be discussing how to get those Bootstrap-style buttons in WPF.

First, what do they look like? Here is a sample from the website (using Chrome):


This style matches pretty well with a so-called "modern ui" style.

Here is what my WPF attempt at these buttons looks like:


Here is the XAML style for these buttons, including disable, hover and click effects.

    <Style x:Key="btn" TargetType="Button">
        <Setter Property="FontFamily" Value="Helvetica Neue,Helvetica,Arial,sans-serif"/>
        <Setter Property="FontSize" Value="14"/>
        <Setter Property="Padding" Value="12,8"/>
        <Setter Property="BorderThickness" Value="1"/>
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="{x:Type ButtonBase}">
                    <Border Name="border" CornerRadius="4" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}" Background="{TemplateBinding Background}" SnapsToDevicePixels="True">
                        <Grid>
                            <Border Name="dropShadowBorder" CornerRadius="4" BorderBrush="Transparent" BorderThickness="0" Visibility="Hidden">
                                <Border.Background>
                                    <LinearGradientBrush StartPoint="0,0" EndPoint="0,0.16">
                                        <GradientStop Color="#22000000" Offset="0"/>
                                        <GradientStop Color="#00000000" Offset="1"/>
                                    </LinearGradientBrush>
                                </Border.Background>
                            </Border>
                            <ContentPresenter Name="contentPresenter" ContentTemplate="{TemplateBinding ContentTemplate}" Content="{TemplateBinding Content}" ContentStringFormat="{TemplateBinding ContentStringFormat}" Focusable="False" HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}" Margin="{TemplateBinding Padding}" RecognizesAccessKey="True" SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}" VerticalAlignment="{TemplateBinding VerticalContentAlignment}"/>
                        </Grid>
                    </Border>
                    <ControlTemplate.Triggers>
                         <!--default button highlight--> 
                        <Trigger Property="Button.IsDefaulted" Value="True">
                            <Setter Property="BorderBrush" TargetName="border" Value="{DynamicResource {x:Static SystemColors.HighlightBrushKey}}"/>
                        </Trigger>
                         <!--inner drop shadow when pressed / checked--> 
                        <Trigger Property="IsPressed" Value="True">
                            <Setter Property="Visibility" TargetName="dropShadowBorder" Value="Visible"/>
                        </Trigger>
                        <Trigger Property="ToggleButton.IsChecked" Value="True">
                            <Setter Property="Visibility" TargetName="dropShadowBorder" Value="Visible"/>
                        </Trigger>
                        <Trigger Property="IsEnabled" Value="False">
                            <Setter Property="Opacity" TargetName="border" Value="0.60"/>
                        </Trigger>
                    </ControlTemplate.Triggers>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>
    <Style x:Key="btn-default" TargetType="Button" BasedOn="{StaticResource btn}">
        <Setter Property="Foreground">
            <Setter.Value>
                <SolidColorBrush Color="#333"/>
            </Setter.Value>
        </Setter>
        <Setter Property="Background">
            <Setter.Value>
                <SolidColorBrush Color="#fff"/>
            </Setter.Value>
        </Setter>
        <Setter Property="BorderBrush">
            <Setter.Value>
                <SolidColorBrush Color="#ccc"/>
            </Setter.Value>
        </Setter>
        <Style.Triggers>
            <Trigger Property="IsMouseOver" Value="True">
                <Setter Property="Background" Value="#e6e6e6"/>
                <Setter Property="BorderBrush" Value="#adadad"/>
            </Trigger>
            <Trigger Property="IsPressed" Value="True">
                <Setter Property="Background" Value="#e6e6e6"/>
                <Setter Property="BorderBrush" Value="#adadad"/>
            </Trigger>
            <Trigger Property="ToggleButton.IsChecked" Value="True">
                <Setter Property="Background" Value="#e6e6e6"/>
                <Setter Property="BorderBrush" Value="#adadad"/>
            </Trigger>
        </Style.Triggers>
    </Style>
    <Style x:Key="btn-primary" TargetType="Button" BasedOn="{StaticResource btn}">
        <Setter Property="Foreground">
            <Setter.Value>
                <SolidColorBrush Color="#fff"/>
            </Setter.Value>
        </Setter>
        <Setter Property="Background">
            <Setter.Value>
                <SolidColorBrush Color="#428bca"/>
            </Setter.Value>
        </Setter>
        <Setter Property="BorderBrush">
            <Setter.Value>
                <SolidColorBrush Color="#357ebd"/>
            </Setter.Value>
        </Setter>
        <Style.Triggers>
            <Trigger Property="IsMouseOver" Value="True">
                <Setter Property="Background" Value="#3071a9"/>
                <Setter Property="BorderBrush" Value="#285e8e"/>
            </Trigger>
            <Trigger Property="IsPressed" Value="True">
                <Setter Property="Background" Value="#3071a9"/>
                <Setter Property="BorderBrush" Value="#285e8e"/>
            </Trigger>
            <Trigger Property="ToggleButton.IsChecked" Value="True">
                <Setter Property="Background" Value="#3071a9"/>
                <Setter Property="BorderBrush" Value="#285e8e"/>
            </Trigger>
        </Style.Triggers>
    </Style>
    <Style x:Key="btn-success" TargetType="Button" BasedOn="{StaticResource btn}">
        <Setter Property="Foreground">
            <Setter.Value>
                <SolidColorBrush Color="#fff"/>
            </Setter.Value>
        </Setter>
        <Setter Property="Background">
            <Setter.Value>
                <SolidColorBrush Color="#5cb85c"/>
            </Setter.Value>
        </Setter>
        <Setter Property="BorderBrush">
            <Setter.Value>
                <SolidColorBrush Color="#4cae4c"/>
            </Setter.Value>
        </Setter>
        <Style.Triggers>
            <Trigger Property="IsMouseOver" Value="True">
                <Setter Property="Background" Value="#449d44"/>
                <Setter Property="BorderBrush" Value="#398439"/>
            </Trigger>
            <Trigger Property="IsPressed" Value="True">
                <Setter Property="Background" Value="#449d44"/>
                <Setter Property="BorderBrush" Value="#398439"/>
            </Trigger>
            <Trigger Property="ToggleButton.IsChecked" Value="True">
                <Setter Property="Background" Value="#449d44"/>
                <Setter Property="BorderBrush" Value="#398439"/>
            </Trigger>
        </Style.Triggers>
    </Style>
    <Style x:Key="btn-info" TargetType="Button" BasedOn="{StaticResource btn}">
        <Setter Property="Foreground">
            <Setter.Value>
                <SolidColorBrush Color="#fff"/>
            </Setter.Value>
        </Setter>
        <Setter Property="Background">
            <Setter.Value>
                <SolidColorBrush Color="#5bc0de"/>
            </Setter.Value>
        </Setter>
        <Setter Property="BorderBrush">
            <Setter.Value>
                <SolidColorBrush Color="#46b8da"/>
            </Setter.Value>
        </Setter>
        <Style.Triggers>
            <Trigger Property="IsMouseOver" Value="True">
                <Setter Property="Background" Value="#31b0d5"/>
                <Setter Property="BorderBrush" Value="#269abc"/>
            </Trigger>
            <Trigger Property="IsPressed" Value="True">
                <Setter Property="Background" Value="#31b0d5"/>
                <Setter Property="BorderBrush" Value="#269abc"/>
            </Trigger>
            <Trigger Property="ToggleButton.IsChecked" Value="True">
                <Setter Property="Background" Value="#31b0d5"/>
                <Setter Property="BorderBrush" Value="#269abc"/>
            </Trigger>
        </Style.Triggers>
    </Style>
    <Style x:Key="btn-warning" TargetType="Button" BasedOn="{StaticResource btn}">
        <Setter Property="Foreground">
            <Setter.Value>
                <SolidColorBrush Color="#fff"/>
            </Setter.Value>
        </Setter>
        <Setter Property="Background">
            <Setter.Value>
                <SolidColorBrush Color="#f0ad4e"/>
            </Setter.Value>
        </Setter>
        <Setter Property="BorderBrush">
            <Setter.Value>
                <SolidColorBrush Color="#eea236"/>
            </Setter.Value>
        </Setter>
        <Style.Triggers>
            <Trigger Property="IsMouseOver" Value="True">
                <Setter Property="Background" Value="#ec971f"/>
                <Setter Property="BorderBrush" Value="#d58512"/>
            </Trigger>
            <Trigger Property="IsPressed" Value="True">
                <Setter Property="Background" Value="#ec971f"/>
                <Setter Property="BorderBrush" Value="#d58512"/>
            </Trigger>
            <Trigger Property="ToggleButton.IsChecked" Value="True">
                <Setter Property="Background" Value="#ec971f"/>
                <Setter Property="BorderBrush" Value="#d58512"/>
            </Trigger>
        </Style.Triggers>
    </Style>
    <Style x:Key="btn-danger" TargetType="Button" BasedOn="{StaticResource btn}">
        <Setter Property="Foreground">
            <Setter.Value>
                <SolidColorBrush Color="#fff"/>
            </Setter.Value>
        </Setter>
        <Setter Property="Background">
            <Setter.Value>
                <SolidColorBrush Color="#d9534f"/>
            </Setter.Value>
        </Setter>
        <Setter Property="BorderBrush">
            <Setter.Value>
                <SolidColorBrush Color="#d43f3a"/>
            </Setter.Value>
        </Setter>
        <Style.Triggers>
            <Trigger Property="IsMouseOver" Value="True">
                <Setter Property="Background" Value="#c9302c"/>
                <Setter Property="BorderBrush" Value="#ac2925"/>
            </Trigger>
            <Trigger Property="IsPressed" Value="True">
                <Setter Property="Background" Value="#c9302c"/>
                <Setter Property="BorderBrush" Value="#ac2925"/>
            </Trigger>
            <Trigger Property="ToggleButton.IsChecked" Value="True">
                <Setter Property="Background" Value="#c9302c"/>
                <Setter Property="BorderBrush" Value="#ac2925"/>
            </Trigger>
        </Style.Triggers>
    </Style>

Then to utilize these, you only have to set the style on the button. It's style name matches the class name for the equivalent bootstrap button. For example:

<Button Content="Default" Style="{StaticResource btn-default}"/>

Notes: Xaml styling is not as robust as CSS, and is a lot more verbose. You can't set more than one style, but this capability wasn't needed in this case.

12 May 2014

More on CQRS and Actors

So today, I discovered the Orleans project. I also watched the excellent presentation on it from Build 2014. The actor model has a lot of appeal for easier creation of scalable, distributed systems. In trying to work out how it would resolve with a DDD/CQRS system, I came up with some observations.

In the Build example, the presenter listed statistics as an actor (aka "grain"). As described, this report-type actor would have the same downsides as a report from an N-tier system. In other words, their described system did not have the hallmark separation between reads and writes of a CQRS system. The report data updates are destructive, history is lost, and the reports can't be proven correct (replayed).
If doing actors in a CQRS system, the actors would only be used on the write side. Using event sourcing as the actor persistence mechanism, denormalizers would still come into play for the read side, not actors.

Actors seems to fit really well for aggregates, but what about Process Managers or Sagas? These are a harder fit because they are not necessarily explicitly called by a user or another actor. They are created and run as a result of events in the system. They are system automations, if you will. The best way that I can think of to implement these event-driven components as actors is to have a separate event listener that forwards the appropriate events to them.

To my thinking, the main purpose of actors in a DDD/CQRS system is to give aggregates (and maybe process managers) a structure that can be interacted with for computation. Ideally, the actor subsystem comes with the necessary architecture to abstract away technical concerns such as message dispatch, scale, distribution, etc. The Orleans project seems to provide a lot of that and apparently does it pretty well for the Halo 4 team.

The main thing that I find really weird about it is their "message passing" method. I like to store the commands I send to the system as well as the events they produce for traceability. Orleans doesn't allow this because it hides the message passing from you. Instead, you load a faux actor and call a proxy method on it. The system takes care of serializing your method call with parameters and delivering that message to the real actor on the server.

I'm eager to see what comes of Orleans. I hope Microsoft decides to bring it out of research and turns it into a proper product. It has the potential for great things in the DDD/CQRS space.

07 March 2014

Software Architecture Traps

As developers, we like to solve problems with code. Sometimes business problems aren't hard enough, and without even thinking about it, we expand the problem so it becomes harder. We want to solve all problems in the same general category as that problem. Once and for all, so we can reuse it later. Maybe we want to build a framework or integrate multiple frameworks (ORM, IOC, AOP, etc.) to solve our problems once and for all. Well, I wish I had run across this video sooner.

http://www.infoq.com/presentations/8-lines-code-refactoring

Sometimes the pain I experience while coding something doesn't indicate that I need to bring in (or create) another framework to avoid that pain. Maybe that pain is simply telling me that there is a non-technical problem (i.e. analysis problem) that a framework isn't going to solve (but might hide).

I realized I had done this with my LocalBus project. If I wasn't trying to fit a square peg in a round hole, then the "overhead" of writing wire-up code wouldn't have been so painful. I would never have needed to write it.

I also really liked how this video shows handler wire-up with dependencies (e.g. repositories). It's manual, but it is also customizable (varying dependencies between use cases), and (using functional language features) it's pretty low overhead.

06 February 2014

No Goldilocks Serializers

So in any architecture that uses messaging for communication, one of the key pieces is serialization. Along those lines, I tried several different serializers and benchmarked the ones that would actually work in my scenario. I borrowed a lot of the serializer test code from various examples on stack overflow (e.g. this one).

Here are ones that I tried:

protobuf-net
Avro
MsgPack
fastJSON
XSockets (ServiceStack.Text)
JSON.NET

I didn't test ServiceStack on purpose, but instead was using the XSockets serializer, which turned out to just be ServiceStack. I didn't care to test ServiceStack at first because of its AGPL license, which is incompatible with my desired freedoms. The XSockets version of ServiceStack is licensed differently as part of the XSockets project. (Since they don't mention AGPL in their license page.)

Here are my requirements for messages I want to serialize:
  1. No attributes (not even Serializable in my tests)
  2. All public members are read only
These requirements killed Avro, MsgPack, and fastJSON right out of the gate. The .NET libraries for Avro and MsgPack wouldn't even instantiate a serializer. fastJSON crashed when trying to serialize. I didn't investigate why.

To get it to work with the XSockets JsonSerializer (which comes with XSockets Core on nuget and again is just ServiceStack.Text), I had to change my readonly fields to properties with private setters. Apparently it ignores fields, even public ones. Later, I figured out how to make it pick up fields, but it didn't really affect the test.

For both ServiceStack and JSON.Net, I serialized to/from an interface to force it to embed the type. This is important for my use case.

Protobuf-net doesn't support type embedding per se, so I had to send two messages. The first (header) message contained the type of the subsequent message. This test includes the time it took protobuf-net to serialize and deserialize both messages for fairness. I do know about the prefix in which I can send an integer to represent the message type, but try consistently hashing and arbitrary type to the same integer value and tell me how that works for you...

Protobuf-net has the added wrinkle that I have to dynamically add the classes to its serializer at runtime (remember, no attributes). This is a huge negative. It's not too bad for simple messages, but if you have any polymorphic properties, this code could get complicated. E.g. Find all inheritors for this type; Find all implementors of this interface; Oh, and if those objects also have reference type properties, recurse. It would be so much easier if I could just embed the type Marc... not that you will ever see this. I write this for myself, you know.

Ultimately, my conclusion for messaging is that there's not an absolute win for any one serializer. Nothing was "just right". Protobuf-net  was the fastest, but the hardest to deal with. ServiceStack.Text is the fastest JSON serializer for my use case, but the AGPL license destroys too many of my freedoms. JSON.Net performed the poorest (but still light years ahead of the default .NET serializers). Deserialization was its weakness. For now I will try out the XSockets version of ServiceStack.Text since I'm planning on using it with XSockets anyway, and I can actually stomach the XSocket license it comes under (BSD 2-clause).

Below are the results for 100000 iterations.

protobuf-net (header + message)
Length: 285
Serialize: 213
Deserialize: 897

XSockets Serializer
Length: 508
Serialize: 933
Deserialize: 1606

JSON.Net BSON
Length: 404
Serialize: 1127
Deserialize: 3417

JSON.Net JSON String
Length: 540
Serialize: 928
Deserialize: 3644

Here are the classes used:

    public class Header
    {
        public Type T { get; private set; }
        public Header(Type t)
        {
            T = t;
        }

    }

    public class TestMessage : IMessage

    {
        public Guid SenderId { get; private set; }
        public Guid ReferenceId { get; private set; }
        public Guid OrderId { get; private set; }
        public Guid CustomerId { get; private set; }
        public LineItem[] LineItems { get; private set; }
        public DateTime OrderedOn { get; private set; }
        public TestMessage(Guid senderId, Guid referenceId, Guid orderId, Guid customerId, LineItem[] lineItems, DateTime orderedOn)
        {
            SenderId = senderId;
            ReferenceId = referenceId;
            OrderId = orderId;
            CustomerId = customerId;
            LineItems = lineItems;
            OrderedOn = orderedOn;
        }
    }

    public class LineItem

    {
        public Guid ProductId { get; private set; }
        public int Quantity { get; private set; }
        public LineItem(Guid productId, int quantity)
        {
            ProductId = productId;
            Quantity = quantity;
        }

    }

    public interface IMessage { }




31 January 2014

Asynchronously Synchronous Commands

I have typically be against asynchronous commands for the simple fact that it leaves the user hanging. However, when considering responsiveness under load, there is something to be said for making this asynchronous.

My current line of thinking is to send the command asynchronously with the expectation that the result of that command (success for failure) will eventually be sent back to the client. That way, at least the client knows if there is a problem. This is what I'd call asynchronously synchronous.

This brings up a couple of interesting issues. One is what to do with the UI while that is going on. Do I show a spinner and make the user wait? The response will happen pretty quickly, so I'm leaning toward this initially. Maybe instead, I should just keep track of running commands and notify the user if one fails. How do they recover from the failure in this case? There are interesting opportunities for design here. Some of the right answer depends on the user's workflow.

So now the other issue is brought up here: Getting a positive command result doesn't mean that the read models have been updated, since this also happens asynchronously. This introduces the idea of the client being able to subscribe to read model changes. Ultimately, the user only wants one of two things to happen when they submit a command. 1) Ideally, the command succeeds and their view is updated (to verify). 2) Their command fails and they are given enough information to resolve the problem. Therefore the the only 2 things the client program will be interested in listening for are: command failure and read model updates.

That obviously doesn't cover some edge cases like network failure. After all if the network fails while I am blocking for it, then I get notified about it, but if I just never receive a message that I was expecting, then I need to account for that.

29 January 2014

CQRS and Actors

In looking through the DDD/CQRS google group, I came across a discussion about using the Actor model as the computational model for DDD/CQRS.

This immediately struck me as interesting, and even more so after listening to the episode of the Being the Worst podcast. Part of the overhead of CQRS/Messaging/ES, and a regular pain for me, is the whole handler piece. Most handler methods seem pretty boilerplate. Load something (e.g. aggregate or process manager), collect resources for it, do something with it, save it. All of this is pretty dull, and it must be written for every message. I think the actor model could have some good ideas to offer here.

The handler has been the catch-all for any infrastructure concerns related to delivering a message, but has typically been observed doing the above-mentioned 4 steps. Load and Save are exactly the same for every event sourced object, so these could be pushed higher in the infrastructure. Ignoring resources for now, the execute step could be characterized as executing a method on the aggregate with the message contents as parameters. The aggregate can be changed to just receive the message directly. This could be implemented similarly to the typical actor semantics of tell(message). There now just needs to be a way to provide resources to the aggregate at the infrastructure level, so the domain stays isolated per DDD.

So perhaps we should formalize the arrangement of there being a resource factory for a particular aggregate type. This factory could be directly used as needed by the aggregate via an interface and dependency injected by the infrastructure (not that you need a DI or IoC container for this). The resource factory is not exactly a repository, since there are no writes to it, only reads, and so there are still no persistence entanglements in the domain.

So now we have increased the burden of the infrastructure code. Namely, matching resources with actors. But we have eliminated most of the need for handlers. (You could also say that we increased the burden with load and save code, but this code was duplicated so much in handlers, that I see it as a net savings.) There may still be a case I can't think of for having handlers for one-off purposes, but now they don't have to be created perfunctorily in every case. We have also formalized another infrastructural role for servicing the domain, the Resource Factory. This role already existed informally in handlers.

I will be experimenting with this approach.

06 January 2014

Mass Effect: How Not to End a Series

To say the Mass Effect series was good is a drastic understatement in my opinion. The series as a whole is in fact one of the best I've ever played. However, when the folks at BioWare decided they were tired of making Mass Effect games, they took it out on us fans.

To set the stage for my utter disappointment, I must tell you that I played all the Mass Effect games, and played ME3 right after release. That was before the extended endings were released, although they had little to no effect in "fixing" anything.

First, I go through the hybrid ending (green), figuring it would be an optimal ending. After seeing it, it twinged as slightly evil because you were forcing a fundamental change on the entire universe that no one asked for. Then I do the "good" (blue) ending thinking it would be... well... good. However, the "good" ending realized the goal of a power-hungry villain and leads your character to not only sacrifice himself, but also his moral center. Also, the cut scenes were the EXACT SAME with minor animation differences and a different color explosion. So I thought, "oh the colors must just be reversed or something". So then I did the red ending, thinking it would be the good ending. It also had the EXACT SAME cut scenes with minor animation differences and a different color explosion. The red ending was also bad and a temporary solution, but it seemed the only ending to fit with themes from the previous titles in the series. If you have enough war assets, it's also the only ending with even a hint of the main character surviving. There's also a fail condition that you could call an ending that simply kills every one and resets technology back to zero. And none of the endings made any sense in context with the rest of the series. They were explained away in the extended endings, but still didn't really seem to fit the way the previous games ended. The fact remained that in ME3, BioWare had decided to take a different direction with the series (i.e. push it off a cliff).

So basically, the series ends on the main character only having selfish choices which also force him to die for completely arbitrary reasons (because that's the way the star kid designed it, and the main character suddenly lacks the capability to come up with independent solutions). And since BioWare seemingly intended to converge all the endings around you being a jerk and dying, they only bothered to make 1 ending cut scene, with minor animation tweaks and color changes between them. The extended ending didn't change that, it just added more filler.

All this leads me to believe the Mass Effect team was tired of making Mass Effect games and sabotaged the ending. This way, they theoretically have less fans begging for them to make a sequel (the main character died and ended up being a tool anyway). However, this hit me as a betrayal by the characters and universe I had come to love. The "mass effect" for me has been to no longer be a fan of BioWare. Their games have some of the greatest story, which makes the series-ending betrayal all the more bitter.