Devlico.Us
CodeBetter.Com
RSS 2.0 via Feedburner
           Do you Twitter? Follow us @devlicious

Christopher Bennage

Our WPF book is now available!
  • Building a WPF Application: Part 1

    I actually meant to say in my last post that I had investigated the API options for FriendFeed and they have a C# wrapper already available here. It's packaged up in a single download with its Python and PHP counterparts.  Unfortunately, it has compilation errors. I fixed the errors and then I let ReSharper (R#) have its way with it [R#: Ctrl+Alt+Shift+F]. Yes, I do understand that the Code Cleanup feature of R# can be a nuclear bomb of churn for diffing your source, but egads I do love it so.

    FriendFeed project in the solution explorerI also broke out the FriendFeed classes into separate files [R#: F6].

    Hmm, I just decided that I'll notate R# and VisualStudio keyboard shortcuts like this [app:shortcut]. Is there already a convention for that out there?

    I also decided to keep the FriendFeed code in a separate assembly. I don't always advocate assembly proliferation, but it made sense in this case. I created a project called FriendFeed and moved all their classes there.  I also preserved their namespace, FriendFeed, as well. (I'm getting tired of typing "FriendFeed".)

    At this point, I just wanted to get a feel for the API. So I read over what appeared to be the significant classes, and I used a couple of tests to see how it really works. Simple enough, instantiate the client and call FetchHomeFeed().

    Building in Seams

    I picked up the term seam from Ayende in this post. You can think of a seam as a natural boundary in an application. It's a place where you easily extend or modify an application. It's a little bit like a Bounded Context, but just a little. I used to try to coerce my design into the metaphor of layers, but seams are a more natural concept. You might also think of them as a way of describing componentized architecture.

    Consider the example of a desktop computer: you have a motherboard, CPU, memory, video card, etc. All of the components are required for the computer to function, but you can replace any one of them. You can extend the functionality of the computer by adding more hardware. Some things might be tightly coupled, like those wretched integrated video cards. But you don't think of these components as layers. This is a flexible way to architect your application.

    Seams are a standard consideration for me when it comes to designing an application. Yes, you can go crazy with it, you can go crazy with anything. In the case of ChumChase, I don't want to be tightly coupled to the official API. I have a few reasons right now: [a] the official API might change. [b] I might want to implement my own API against their web services just for kicks [c] it's a good excuse to demonstrate the technique. I'm going to hide the FriendFeed API behind a repository. The IFeedRepository interface will be a seam in my application.

    MVP

    I mentioned before that I'm going to use Model-View-Presenter. This pattern is similar to MVC, and like barbeque sauce, everyone has their own flavor. In my case, a presenter is a class that represents the behavior of the UI, and possibly some state. It is ignorant of how the UI visually appears. The view will be a user control, window, page, tab item, etc. We'll use data binding to glue the two together. The ignorance of the presenter about the view is important because it helps us to isolate the presenter in our unit tests.

    TDD

    It's sometimes hard to decide where to start writing to tests. I tend to write tests that reflect the behaviors of the user interacting with the application. This is as opposed to testing how the application might interact with a data source, or some other more internal function of the application. This approach of working from the outside in helps prevent me from making too many assumptions about the internals.  The negative is that I have to provide mocks or stubs for the dependencies that I haven't written yet.

    My core story, that is the basic behavior that I'm interested in, is for the application to fetch my home feed. I'll place this feature on a class called HomePresenter. HomePresenter might end up being my only presenter, I don't know yet. It common though for applications to have several presenters. We'll talk later about how to logically organize presenters.

    Let's look at a test:

    [TestFixture]
    public class The_presenter_for_the_home_feed : TestFixtureBase
    {
        private HomePresenter _presenter;
        private IFeedRepository _feedRepository;
    
        protected override void given_the_context_of()
        {
            _feedRepository = Mocks.StrictMock<IFeedRepository>();
            _presenter = new HomePresenter(_feedRepository);
        }
    
        [Test]
        public void can_refresh_the_home_feed()
        {
            using (Record)
            {
                Expect.Call(_feedRepository.FetchHomeFeed())
                    .Return(new List<Entry>());
            }
    
            using (Playback)
            {
                _presenter.RefreshHomeFeed();
            }
        }
    }

    First, my TestFixtureBase is just an abstract class to reduce clutter. The Mocks, Record, and Playback properties all exist on it and they are really just pass-throughs to Rhino.Mocks. Likewise, I have a setup method in TestFixtureBase that calls given_the_context_of() before each test is executed. It's meant to reset the system-under-test (SUT) into a consistent and pristine state.

    Notice that I named my class and method such that they read as a specification for the behavior I'm testing: The presenter for the home feed can refresh the home feed. I'm not sure that I like saying "presenter" in the specification. If I was working with non-technical users, that wouldn't make sense to them. I could replace it with "UI" or "interface" or "screen" perhaps.

    The test has two blocks or phases: record and playback. This is generally a big stumbling block for people. I know when I first encountered it I was thoroughly confused. The record phase is where I tell the test what I'm expecting to happen during the playback phase.  The record phase plays the same roles as asserts.

    The function we are really testing here is:

    _presenter.RefreshHomeFeed();

    Since there is not a state that I can verify after calling RefreshHomeFeed(), I am checking to make sure that it's doing what I expect it to do. That is, I expect it to get a list of entries from a repository of feeds.

    The Expect.Call().Return() is Rhino.Mocks syntax that allows me to say: I expect my SUT to execute _feedRepository.FetchHomeFeed() and I expect that to return a List<Entry> instance. Right now Entry is just an empty class, but conceptually it represents a single item in the feed. You should also note that the relationship between my presenter and the repository is established in given_the_context_of().

    Yes, this is a simple test, but writing this test helped me to shake out what I needed.  Unfortunately, the test as it stands here does not reflect the process of writing it.  I wrote some things, decided they didn't look right, changed them a bit and so on. It probably took me 10 minutes or so before I settled on what you see.

    Moving on to the next test. This is in the same class, so you can read it as: The presenter for the home feed notifies the UI when the home feed is refreshed.

    [Test]
    public void notifies_the_UI_when_the_home_feed_is_refreshed()
    {
        var property_has_changed = false;
    
        _presenter.PropertyChanged +=
            (s, e) => { property_has_changed = (e.PropertyName == "HomeFeed"); };
    
        _presenter.RefreshHomeFeed();
    
        Assert.That(property_has_changed);
    }

    I want to verify that when I call _presenter.RefreshHomeFeed() a change notification is raised for the HomeFeed property. This means my presenter needs a HomeFeed property. I have a boolean flag that helps me track the state and I'm using an inline delegate to set my flag when the property is changed. (There's actually a flaw in this test that we'll examine later, can you see it?) 

    I don't like strings though. If I happen to change the name of the HomeFeed property and forget to change the string in the test, I've broken my test. Of course, I'll notice as soon as I run the tests, but it would sure be nice to eliminate the string. So I wrote this extension method for PropertyChangedEventArgs:

    public static bool HasChanged<T>(this PropertyChangedEventArgs args, Expression<Func<T>> property)
    {
        var expression = (MemberExpression)property.Body;
        return expression.Member.Name == args.PropertyName;
    }

    Now I can change my test to the following and eliminate the string:

    [Test]
    public void notifies_the_UI_when_the_home_feed_is_refreshed()
    {
        var property_has_changed = false;
    
        _presenter.PropertyChanged +=
            (s, e) => { property_has_changed = e.HasChanged(() => _presenter.HomeFeed); };
    
        _presenter.RefreshHomeFeed();
    
        Assert.That(property_has_changed);
    }

    Of course, in between these tests I was writing code to make them pass. (Red -> Green -> Refactor, right?) Here's what my presenter class looked liked afterwards:

    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Linq.Expressions;
    using ChumChase.Extensions;
    
    namespace ChumChase.Presenters
    {
        public class HomePresenter : INotifyPropertyChanged
        {
            private readonly IFeedRepository _feedRepository;
            private IList<Entry> _homeFeed;
    
            public HomePresenter(IFeedRepository feedRepository)
            {
                _feedRepository = feedRepository;
            }
    
            public IList<Entry> HomeFeed
            {
                get { return _homeFeed; }
                private set
                {
                    _homeFeed = value;
                    OnPropertyChanged( ()=> HomeFeed);
                }
            }
    
            public void RefreshHomeFeed()
            {
                HomeFeed = _feedRepository.FetchHomeFeed();
            }
    
            public event PropertyChangedEventHandler PropertyChanged;
    
            private void OnPropertyChanged<T>(Expression<Func<T>> property)
            {
                if (PropertyChanged != null) PropertyChanged(this, property.CreateChangeEventArgs());
            }
        }
    }

    The source is now available here. More to come!

  • Building a WPF Application: Part 0

    In a rather indirect way, I was inspired by a commenter on one of Scott Hanselman's posts to begin a series that walks through building a WPF application from start to finish. We did this for four different applications in our book, but those where targeted to demonstrate particular facets of WPF whereas in these (yet unwritten) posts I'd like to focus more on "this is how I build my WPF apps". Not to say that my way is the *right way*, but so that we might learn together. In the spirit of the aforementioned post, I'm bound to make mistakes, so please (gently) correct me when you think you see one.

    What to build?

    You might not have noticed, but there's quite a bit of .NET chatter in twit-space. There are already lots of Twitter clients, and some are WPF, so that path has been rigorously trod. However, the technical difficulties surrounding Twitter has given rise to the popularity of another mash up web 2.0 thingy app called FriendFeed.  Everyone seems to agree that the web interface for FriendFeed is all stinky bad, and there's an API readily available, so I think a FriendFeed client is in order.

    ff_logo Briefly, FriendFeed is a way to consolidate all of your creepy Internet voyeurism in one spot. You can track a friend's Flickr account, NetFlix queue, Amazon wishlist, and yes, their Twitter tweets and much, much more. Oh yeah, and you can subscribe to me here. (I'm such a loser.)

    What to do?

    I'm not going to set an agenda or outline a detailed plan. I'm just going to post as I have time to work on it. I started tonight, so I'm expecting to have a real Part 1 posted by midweek. I've already set up a project at CodePlex (though it won't be published for a few more days still.) I named it ChumChase. Isn't that great?

    Part of my plan is to step you through my thinking and decision making process in sort of Nilssonian way. I've only just begun but here's what I can tell you so far.

    • I'm going to use a Model-View-Presenter pattern
    • Expect to see some DDD artifacts.
    • I'm going to use NUnit and RhinoMocks.
    • I'll probably use Windsor too (or maybe StructureMap though, anybody have a preference?)

    I had intended to write a set of user stories  using the issue tracker of CodePlex. However, I got tired of retyping them every time the site errorred out, which was about 60% of the time. (Is that typical for the CodePlex issue tracker? This was my first usage.)  It also occurred to me that I am lazy and ought to have a life outside of coding, so sorry no user stories.

    What to think?

    I'm all about conversation. If this interests you, please let me know. I welcome (friendly) criticisms as well. The more I hear, the more motivated I'll be to do it. (Believe me there's a lot to distract right now. I had a new baby son born on the 10th.)

    Continue to Part 1

  • Using Lambdas to get at properties

    This is a somewhat made-up scenario based on a recent project. My client has not given me permission to discuss the specifics of the application (yet), so I apologize for keeping it vague. I hope you don't give up before the payoff.

    The Problem

    Imagine an application, where a user can create "styles" and those styles can be applied to shapes. The application uses WPF to visualize the shapes with the styles applied.  (Perhaps it's a design tool meant for Hanselman's BabySmash?) Let's say that there are three kinds of shapes: a line, a circle, and a bull's eye.

    styled_shapes Each shape has specific attributes that can be styled, and the these attributes are unique to each shape.  Here's a simple listing of possible attributes:

    Line Circle Bull's Eye

    Stroke

    Fill

    Outer Fill

    Thickness

    Stroke

    Inner Fill

     

    Now, we have three classes to represent the styles: LineStyle, CircleStyle, BullsEyeStyle. The Fill and Stroke attributes are all of type Brush. Furthermore, all three classes derive from ShapeStyle.

    Now, imagine that we have to construct instances of these styles for some data that comes in the form of an API that we don't control. The constructor for LineStyle might look like this:

    public class LineStyle : ShapeStyle
    {
        public LineStyle(ForeignLineStyle style)
        {
            Thickness = style.StrokeThickness;
            Stroke = style.StrokeBrush;
        }
    
        public Brush Stroke { get; set; }
        public double Thickness { get; set; }
    }

    That's simple enough, but remember the properties are of type Brush, and we don't really want our instances of LineStyle to share the same Brush with instances of ForeignLineStyle.  Luckily, Brush has a Clone method! Yeah!  Only, what if the Brush is null? Okay, we'll change it to this:

    public class LineStyle : ShapeStyle
    {
        public LineStyle(ForeignLineStyle style)
        {
            Thickness = style.StrokeThickness;
            Stroke = (style.StrokeBrush != null)
                         ? style.StrokeBrush.Clone()
                         : null;
        }
    
        public Brush Stroke { get; set; }
        public double Thickness { get; set; }
    }

    Now, every time I have a property of type Brush on one of these style classes the pattern is the same.  I  start copying and pasting. (Do you smell something?)  Hmm, what if I have lot of Brush properties? Many more than I initially listed in the table. I sure feel like I am repeating myself.

    At this point, my instinct is to extract this pattern into a method. But how do I do this? The properties are unique to each class, and using reflection would be way overkill.

    Lambda Magic

    What I want is a method that takes the brush from ForeignLineStyle, and the setter for a property of type Brush. Using a lambda for the setter, I am able to create:

    public static void SetBrush(Brush brush, Action<Brush> property)
    {
        var value = (brush != null)
                ? brush.Clone()
                : null;
    
        property.Invoke(value);
    }

    For this to make sense, you need to recognize that a setter is a essentially a method with a signature like this:

    delegate void PropertySetter<T>(T value);

    That signature is the same as Action<T>.

    Now, I can modify LineStyle to look like this:

    public class LineStyle : ShapeStyle
    {
        public LineStyle(ForeignLineStyle style)
        {
            Thickness = style.StrokeThickness;
            SetBrush(style.StrokeBrush, brush => Stroke = brush);
        }
    
        public Brush Stroke { get; set; }
        public double Thickness { get; set; }
    }

    Notice that the second parameter is :

    brush => Stroke = brush

    and not simply

    ()=> Stroke

    The latter is for the getter and would match Func<T>.

    After Thoughts

    Arguably, this doesn't accomplish much.  The repetitive code had a small footprint, and the SetBrush method is likely to throw off other developers.

    It's up to you to decide it's applicability, but a least it's one more tool in the box.

    (Thanks to Rob Eisenberg, who wrote some code that planted this ideas in my head.)

  • TemplateBinding: a bridge between styles and templates

    This is partially a follow-up to my last post contrasting control templates and styles. Like I mentioned before I've been working on an application that has required a custom theme. In addition to styling the standard controls like text boxes and expanders, we've had to create a number of custom controls as well. That has added up to a lot of control templates.

    This recent work has emphasized the importance of the template binding. (Beatriz Costa first helped me get a handle on template binding here.)  TemplateBinding is a special markup extension specifically designed for binding values in a template. (That's a bit of a circular definition, isn't it?) TemplateBinding is the mechanism that allows us to inject values into our templates, or to parameterize them.

    An Example

    First, imagine that we have a resource dictionary where we have defined a set of brushes that we'll use as the palette for our application. We might go about building a control template for the ToolTip control like this:

    <ControlTemplate x:Key="ToolTipTemplate"
                     TargetType="ToolTip">
        <Grid>
            <Border x:Name="DropShadow"
                    Focusable="False"
                    CornerRadius="3"
                    Background="Black"
                    Opacity="0.4"
                    Margin="3 3 0 0" />
            <Border Background="{DynamicResource NormalControlBackground}"
                    BorderBrush="{DynamicResource NormalControlBorder}"
                    BorderThickness="1"
                    Margin="0 0 3 3"
                    CornerRadius="3"
                    Padding="6">
                <ContentPresenter TextBlock.Foreground="{DynamicResource NormalControlText}" />
            </Border>
        </Grid>
    </ControlTemplate>

    This control template is too rigid. What if another team member needs to create a special ToolTip in just one place with a background color other than NormalControlBackground?  They would probably write some markup like this:

    <Button Content="History Eraser Button">
        <Button.ToolTip>
            <ToolTip Background="Red" 
                     Foreground="White"
                     Content="Don't press it!" />
        </Button.ToolTip>
    </Button>

    Sadly, they would discover that it wouldn't work. The control template doesn't know anything about the properties we set on the ToolTip in the markup. Everything is defined in the control template and it's self contained.  We really want the template to be able to use the properties that are set on the control. The template above can be rewritten to do that:

    <ControlTemplate x:Key="ToolTipTemplate"
                     TargetType="ToolTip">
        <Grid>
            <Border x:Name="DropShadow"
                    Focusable="False"
                    CornerRadius="3"
                    Background="Black"
                    Opacity="0.4"
                    Margin="3 3 0 0" />
            <Border Background="{TemplateBinding Background}"
                    BorderBrush="{TemplateBinding BorderBrush}"
                    BorderThickness="{TemplateBinding BorderThickness}"
                    Margin="0 0 3 3"
                    CornerRadius="3"
                    Padding="{TemplateBinding Padding}">
                <ContentPresenter TextBlock.Foreground="{TemplateBinding Foreground}" />
            </Border>
        </Grid>
    </ControlTemplate>

    Using the template bindings allows the control template to pick up the values that are supplied directly on the element, or on the style applied to the element. That means that the Button markup above would work, or we could even create a style for the special case tool tip that looks like this:

    <Style x:Key="WarningStyle" TargetType="ToolTip">
        <Setter Property="Background" Value="Red" />
        <Setter Property="Foreground" Value="White" />
    </Style>

    Handling the Default Values

    If you use a control template with template binding, and don't provide any values on the control, what happens? The default values of the bound properties are used. There are many cases where this is not what you want though. If your intent was to have a global look for tool tips based on our first example, then you want the template to use some specific brushes as well a few other things.

    In this case, you can use a style to set the desired defaults. To apply a style to a control for an entire application, set its TargetType and don't provide a key. The style will also need to be added to (or merged into) the resource dictionary of application. The style is also used to set the custom template for the control (otherwise you'd have to set the Template property on every instance of the control.)

    Here's an example style to accompany our template:

    <Style TargetType="ToolTip">
        <Setter Property="Background" Value="{DynamicResource NormalControlBackground}" />
        <Setter Property="BorderBrush" Value="{DynamicResource NormalControlBorder}" />
        <Setter Property="BorderThickness" Value="1" />
        <Setter Property="Foreground" Value="{DynamicResource NormalControlText}" />
        <Setter Property="Padding" Value="6" />
        <Setter Property="Template" Value="{DynamicResource ToolTipTemplate}" />
    </Style>

    I'm interested in feedback. If you find this useful, or too basic, or whatever, please let me know!

  • Contrasting Control Templates & Styles in WPF

    We've had a few projects that involved custom styling for many of the standard controls. At first, I found myself swimming in a sea of XAML and rather double-minded about where to put things. Now, an approach has begun to coalesce for me.

    When it comes to customizing the look of controls, there are two concerns: styles and control templates. Knowing when to use one or the other can be confusing, as there is really a lot of overlap in what they each do.

    Styles

    Styles are frequently compared to cascading styles sheets (css) in the html world. WPF styles are like css in that they can be used to globally define the looks of certain elements, they can be paired to specific element by way of a key, or they can even be declared inline directly on an element.

    I've come to view styles as a way to set default values on the public properties of WPF elements. (Really, it's dependency properties, but most public properties on WPF controls are dependency properties anyway .) When you associate a style with an element you are essentially saying "here's the set of properties and corresponding values that I'd like to set." This distinction is important for two reasons:

    • Styles can only affect the public dependency properties.
    • Styles can affect non-visual properties.

    This concept of setting properties is inherent in the syntax of styles:

    <Style>
        <Setter Property="X" Value="Y" />
    </Style>

    This also means that styles are limited in what they can do by the public API of the element that they are applied to.

    Control Templates

    Control templates are used for manipulating the composition of a control.  They are a means of modifying the structure of a control.

    First, you need to recognize that every control in WPF is composed out of other WPF elements. If you were to examine a Button control, you would discovered that internally it's composed of something like this:

    <ms:ClassicBorderDecorator x:Name="ContentContainer"
                               SnapsToDevicePixels="True"
                               Background="{TemplateBinding Background}"
                               BorderBrush="{TemplateBinding BorderBrush}"
                               BorderStyle="Raised"
                               BorderThickness="3,3,3,3">
        <ContentPresenter />
    </ms:ClassicBorderDecorator>
    

    ClassicBorderDecorator is an element Microsoft built for emulating the look of the existing Windows UI (that's pre-WPF elements). It's very much like a Border, and tucked away in the theme-specific assembly PresentationFramework.Classic.dll. (Ok, maybe that's a lame example).

    There are certain internal elements that the control looks for in its template.  In the case of Button, it look for a ContentPresenter, though it might be something else depending on the control.

    button exampleNow, let's say you want a button that has rounded corners, with a black background, and gray outline.  You can use a style to set the background and outline using the Background and BorderBrush properties, and you might hope for a CornerRadius property similar to that of a Border, but there isn't one. In short, you can't make a button have rounded corners using a style.

    I'm sure someone out there is thinking that you can use a style and set Background to a DrawingBrush that looks like that, and well, yes, you could, but um, that's a different matter and I need a simple example at the moment.

    We could achieve this with the following control template however:

    <Button>
        <Button.Template>
            <ControlTemplate TargetType="Button">
                <Border CornerRadius="4" 
                        Background="Black"
                        BorderBrush="Gray"
                        BorderThickness="1"
                        Padding="10 6">
                    <TextBlock Foreground="White"
                               Text="Click Me"/>
                </Border>
            </ControlTemplate>
        </Button.Template>
    </Button>

    You are afforded much more liberty with control templates than you are with styles, but the control templates are also trickier to use. In the template above, we completely bypassed the Content property on the button, and we manually created the "content" in the template.  That makes the template not so reusable and the above example is not a good template. Here's one that's a bit more generic:

    <Button Content="Click Me">
        <Button.Template>
            <ControlTemplate TargetType="Button">
                <Border CornerRadius="4" 
                        Background="Black"
                        BorderBrush="Gray"
                        BorderThickness="1"
                        Padding="10 6">
                    <ContentPresenter TextBlock.Foreground="White" />
                </Border>
            </ControlTemplate>
        </Button.Template>
    </Button>

    We replaced the TextBlock with a ContentPresenter. We use an attached property to make any text inside the ContentPresenter white.

    Why Both?

    So we've redefined the look of a Button, and we didn't touch the style.  Why do we need styles?

    There are a few good reasons:

    • Styles are easier to use. You don't need to be concerned about the internal composition of the control or making sure that you've included all the necessary pieces.
    • Styles can affect properties on the control that don't have anything to due with the composition.  That means they can affect things that control templates cannot.
    • If you want to globally replace a template for a control in your application, you have to do it with a style.
    • It's not uncommon to "break" your controls when you start creating custom templates. You don't need to worry about this so much with styles.

    More to come ...

  • Styling Separators in WPF

    Separators are the little tiddly-bits that, um, separate items in a menu or tool bar. Examples of SeparatorsThe intention is to divide the items on the menu or toolbar into logical groups. Separators are controls, but they don't have any real behavior.

    One of our current projects includes an exhaustive custom styling of a WPF application.  Last week, I was working on the top level menu as well as context menus.  I wanted all of my separators to look the same.  So I ignorantly created a style, the same way that I would for any other control. It looked something like this:

    <!-- Separator -->
    <Style TargetType="Separator">
        <Setter Property="Height" Value="1" />
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="{x:Type Separator}">
                    <Rectangle Height="{TemplateBinding Height}"
                               Fill="{StaticResource NormalBorderBrush}" />
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>
    
    

    In case you're not familiar with it, WPF allows to specify a default style for a control by setting the TargetType and omitting the x:Key.

    But that doesn't work for separators.

    The reason is that MenuItem and ToolBar both use separators, and thus creating global style for both wouldn't make sense. (At least, I'm guessing that's what the designers of WPF were thinking.) Instead, both of these MenuItem and ToolBar expose a static property, SeparatorStyleKey. This acts as the key for locating the corresponding separator style.

    If you want to style the separators for all menu items, your need to set x:Key to this static property. The resulting style would look like this:

    <!-- Separator -->
    <Style x:Key="{x:Static MenuItem.SeparatorStyleKey}"  
           TargetType="{x:Type Separator}">
        <Setter Property="Height" Value="1" />
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="{x:Type Separator}">
                    <Rectangle Height="{TemplateBinding Height}"      
                               Fill="{StaticResource NormalBorderBrush}" />
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>
  • ALT.Consultancy: Reflections on doing it my way

    Awhile back there was some discussion on the new ALT.NET list about what it would be like to start a consultancy with a bunch ALT.NET minded people. The hypothetical scenario proposed there wasn't quite what I did, but I thought I'd go ahead and share my experiences and how we addressed (or are still addressing) some of the problems in running a business like this.

    The Background

    Rob Eisenberg and I founded our company Blue Spire in October 2006. We were long time friends, and had worked together for about two years prior to starting the company. In that time, we were learning about Agile in general, as well as patterns, TDD, OR/M, the myriad of awesome OSS tools, etc.  We didn't know it, but we were developing a culture between the two of us. The elements of this culture included:

    We started our consulting firm with the belief that we could deliver quality, human friendly software in less time and for less cost that the majority of other firms. (The genesis of this thought occurred over a decade ago when I was subcontracting for a large consulting shop, working on an 18 month project with a team of around 25. I'm sure I was pretty cocky back then, but I felt at the time that a team of 5 could have delivered more in less than a year.)

    We began with just the two of us, and we envisioned growing to a team of 4 to 6. Smaller is better. Even at the beginning though, we felt that consulting was just a stepping stone to something else.

    Kicking It Off

    The question was asked on the list if such a shop could compete.  What kind of sales and marketing would you need? How do you break in and demonstrate to potential clients that you can provide a better value than super consulting company X?

    We've had zero down time since we started, and we've had almost zero sales and marketing efforts.  We started off having lunch with other software development shops in the area. We told them what we were doing (without being derogatory) and we talked about overflow work, and subcontracting. There's enough business out there that the competition is pretty friendly.  We also offered ourselves at very, very reasonable rate. (We're now charging double from what we started, and we're probably going to raise our rates again this year.)

    The majority of our clients have been other software shops. What's cool is that they saw our value pretty quickly. What's bad is that we were sometimes restricted from using the practices and tools that we wanted.

    We also decided it was important to connect with the local developer community. Both for our own continuing professional development, but also for growing the reputation of our company. Rob has especially put in efforts to speak at Code Camps, and the local user group. It helps that we are genuinely excited about sharing. (This even helped us land a really fun agile coaching gig for the internal development team of a state agency.)

    Convincing Clients

    We've focused on Scrum for project management, and we were lucky to have a client who was already intent on using it. Nonetheless, even that client (who was not a software shop) required a statement of work. We estimated as best we could, and the client agreed that the SOW was a target and not a guarantee.

    In our "sales pitch", we tell clients that software development in inherently unpredictable. We contrast "release early, release often" with "throwing the spec over the wall".  (There's usually a lot of resonance if they've had software developed before.) We (cautiously) explain to them that no one really knows exactly what they need up front. Change is inevitable.

    What Really Happens

    Our projects have usually taken one of the following forms:

    • The client budgets a set amount of hours.  We provide a conservative statement of what we think can be accomplished in that time.  We explicitly qualify the risks as soon as they are known.
      We get the client to buy into the project, by allowing them to manage the priorities for each iteration in the project (usually 2 - 4 weeks). In this way, they share the responsibility with us for hitting the desired target.
      Because of the iterative nature, they are aware of risks and problems early.
    • Some client are too deeply rooted in the idea of "build me X, in Y hours, for Z dollars".  We try to avoid that situation, but we've been there.  When that occurs we greatly exaggerate the hours (3x or 4x).  Funny enough, the exaggerated estimate is often within the client's expectations.  We've alternately benefited and been burned by this arrangement.  I don't like to do it this way.
    • This last arrangement is a mixture of the other two, and it's only been useful for periods where we would would have been between projects and when a client has some flexibility in scheduling.  Essentially, we budget some initial time to size tasks.  Again we pad the hours to mitigate risk, and then we allow the client to pick and choose the tasks.  We commit to delivering an individual task for the number of hours we estimated, but we are not committed to delivering the entire project for a set amount.

    The first option is preferred and honestly it is the one that provides the most cost effectiveness for the client.  We only use the other arrangements when the client isn't comfortable with the first.

    Some Final Thoughts

    Here's a few additional observations:

    • Having the right clients is paramount.  You want a genuine trust relationship.  We had one project where trust was eroded (if it was ever present on their side) and it was by far the most stress I've had in years.  It's hard to turn down business, but sometimes you really need too.
    • Scheduling is difficult. Managing the pipeline is one of the more difficult tasks in managing a small shop.  When is this project really going to be over? What if the client wants to extend? How much downtime can we afford? At what point are we over extended?
      Everyone that I've talked to that has a small project-based business seems to have the same difficulty.  So far, we haven't made any clients mad, but we've had a few periods of overtime.  This would be easier if we were a larger company, but size has many disadvantages too.

    I'm a developer at heart, and running a business has been challenging (and distracting). So I'd love to hear from anyone else who is doing this sort of thing.

  • The Roots of Best Practices

    I've been asked about best practices and good design several times over the last few months. A few questions have been from students, or newcomers to .NET, and I have found their questions very insightful. They ask questions I remember asking myself. One good example was "I know I should separate my app into three layers, but how should I do it?"

    Getting to the RootsI'm rather to sensitive to the idea of "answering the wrong question". I believe that it's easy to do that when talking about best practices.  My intention with this post is build a foundation for discussing good design. A starting point to make sure we are solving the right riddle. I certainly don't consider myself a master on this topic, but I do have a lot of thoughts.

    Acknowledging My Bias

    I'm a fan of Object Orient Programming, Domain-Driven Design, Design Patterns, Test Driven Development, and agile methodologies. I use a lot of open source software, and I'm ALT.NET. Foremost, I like to think that I am pragmatic.   I'm motivated by getting stuff done.

    The Point of Best Practices

    There are a long list of principles out that are generally acknowledged as best practices. They range from generalities like "your code should be well commented" to very specific and named rules such as the Liskov substitution principle. Regardless of the type, I think it's important to know why a given principle is better than its alternatives.

    I'll use the Law of Demeter (LoD) as an example. Overly simplified, the law says that an object should only invoke methods that it owns.  In other words, you'll break the law with something.child.Method() whereas something.Method() does not. 

    Why is LoD good? One quick answer is that you never know when something.child might be null, and applying LoD helps you avoid the nasty NullReferenceException. Wikipedia has a nice summary the benefits:

    The advantage of following the Law of Demeter is that the resulting software tends to be more maintainable and adaptable. Since objects are less dependent on the internal structure of other objects, object containers can be changed without reworking their callers.

    Now we are approaching the real heart of the matter, we want software that is easy to maintainable, and easy to extend. LoD promotes those values. In facts, most of the generally accepted principles are meant to produce software that is maintainable and extensible. Here is my Grand Unification Theory of software best practices: the guiding, or root, principles are Maintainability and Extensibility. (These two are close cousins, and you might arguably combine them.)

    The Root of the Matter

    Now, let's deconstruct further.  Why do we care about Maintainability and Extensibility? We care because they result in reduced costs.  The bulk of cost with custom software is not building it, but maintaining it. If you are in business, reduced costs equals more money; if you are a hobbyist or open source developer then reduced costs means getting to the desired result in less time.  That's the bottom line: time and money. We employ best practices to save ourselves time and money.

    Okay, well, nothing new here. You probably already knew this.  I emphasize it though because I've found that "best practices" have a tendency to degrade into a set of arbitrarily applied rules, enforced without exception, irrespective of whether or not they are useful. A great example is "always comment your code". The intention of this rule is improve maintainability.  We've all seen the end result.

    //open the file 
    FileStream stream = File.Open(pathToFile, FileMode.Open);

    Does this improve maintainability? Perhaps if you can't read C#, but even then it seems unlikely. Does one extraneous little comment hurt? Not by itself. A poppy flower is beautiful, a thousand poppies is dangerous. If 50% of your source is extraneous comments, it's nothing but noise and it's reducing maintainability.

    My Point

    Let's take a look at the question I was asked again:

    "I know I should separate my app into three layers, but how should I do it?"

    To answer this correctly, we need to start with the motivation for layering an application in the first place. "Three-tier architecture" has a good intention, just as "well commented code" does. However, the principle has can easily be lost in the arbitrary application of the rule.

    In a soon-to-follow post, I'll examine this specific question of layering an application from its roots.

    Epilogue

    For some reading in the meantime, check out the series of posts over at Los Techies on SOLID Principles. There is some great discussion in the comments too.

    What do you think?

  • Thoughts on ALT.NET

    I just listened to Scott Hanselman interviewing Dave Laribee regarding ALT.NET. I really like what Dave had to say, and I encourage everyone to go and listen.  I've been reticent about the ALT.NET movement (aside from my initial surge of enthusiasm.) I'm a bit shy when it comes to controversy, and even though I have strong evangelistic tendencies, I am also quick to shut up. ALT.NET has had its share of controversy.

    Now we're an institution!I really like that Dave said it's not about the tools, it's about the principles.  I am frequently asked about "good design" and "best practices".   This is why I'm ALT.NET. (In fact, I have a series of posts on this topic that I intend to start after we're done with the book.)

    There's an item in the interview that I'd like to comment on.

    Scott asks (pardon my paraphrasing) why would the hypothetical Chief Architect of the Nebraska Department of Forestry have any interest in ALT.NET? The mythical Mort has pressing concerns, he just needs to get work done, why would he care about these conversations, discussions, and principles? Listen to the podcast for Dave's answer.  However, my answer is this: he probably doesn't care and that's okay. I think that ALT.NET is about bringing good design and principle to the forefront.  However, good ideas take a while to be adopted, to be democratized.  Those who are hungry, we'll feed.  Those who aren't, we'll wish them well.  No hard feelings. Eventually, the good ideas will be institutionalized and they'll trickle down. (Have you noticed the "refactor" menu in Visual Studio?) I'm more concerned about convincing the institutions and the thought leaders.  (Perhaps "convincing" is the wrong word, ALT.NET is more about "conversing" to me.) That's why it's good that ALT.NET is conversing with Microsoft, and that's also why I'm encouraged to see Microsoft paying attention to things like open source (though I know many people are angry about the kind of attention being paid).

    Now go learn Ruby!  :-)

  • Identifying Control Templates Parts in WPF

    I'm currently writing the chapter about control templates in our WPF book, and I wanted to include a list of all of the named parts that are hidden away in the dark recesses of the various controls.  Before I even started googling, I had an idea that I thought I'd share.

    For those of you not yet familiar with control templates, WPF allows you to redefine the visual appearance of controls. The problem is that some of the controls have special named parts, that is, there are visual elements with specific names that the code expects to be there.  Luckily, there is the TemplatePartAttribute that's meant to decorate controls with named parts. If you look at the documentation for a given control, the attributes are listed and you'll know what named elements a new template requires.

    Given an assembly though, it's quite easy to identify the controls programmatically. Here's some C# that does just that:

    using System;
    using System.Linq;
    using System.Reflection;
    using System.Windows;
    using System.Windows.Controls;
    
    namespace TemplatesParts
    {
        class Program
        {
            static void Main()
            {
                var assembly = Assembly.GetAssembly(typeof (Control));
                var attributeType = typeof (TemplatePartAttribute);
    
                var controls = from c in assembly.GetTypes()
                               where c.GetCustomAttributes(attributeType, false).Length > 0
                               orderby c.Name
                               select new {c.Name,Parts=c.GetCustomAttributes(attributeType, false)};
    
                foreach (var control in controls)
                {
                    Console.WriteLine(control.Name);
                    foreach (var part in control.Parts)
                    {
                        Console.WriteLine( "   " + ((TemplatePartAttribute)part).Name);
                    }
                }
                Console.ReadLine();
            }
        }
    }
    

    Now, if I can just look this up in the documentation, why bother with this code? It was fun, what can I say?

  • Discovering Empty Try/Catch Blocks

    I've been burned by a few bugs recently due to swallowed exceptions.  In case you don't know, empty catch blocks will hurt you. Really, they will.

    I wanted a way to locate all of the empty blocks in our code base, I was playing around with NDepend and the amazing Code Query Language, but it's not able to do something like this yet.  (Patrick said that it will in the next version!)

    Then I realized that I was missing the simple solution. The Find and Replace dialog in Visual Studio.Ctrl+F and a regular expression!

    Here is the regex you'll need to find empty catch blocks in your solution:

    catch:Wh*\{:Wh*\}

    ":Wh" designates whitespace

    * means zero or more

    You have to escape the {} as they are special characters.

    Update: Note Dan's comments below. Here's an updated regex to cast a wider net:
    catch(\(.*Exception.*\))*:Wh*\{:Wh*\}
  • VS2008 Demo Challenge

    Last week or so, I stumbled on to the site for the Visual Studio 2008 Demo Challenge. The gist of the contest is to make a video explaining why VS 2008 is great, and then win stuff. Your video is played backed in a Silverlight app that your host at silverlight.live.com.

    So I make a video, and I think it's pretty funny.  I setup an app with Expression Encoder, and I'm feeling great.  I go to submit the video on the contest site and ... nothing. The site seems broken, which would explain the lack of videos in the gallery. (I had a bad feeling about the absence of competition.)

    I just don't have good luck with Microsoft contests. :-(

    Click here to watch the video. You'll need Silverlight 1.0 to view it.

    Update: I just heard that the contest died. Would someone still like to give me an Xbox for kicks? :-)

  • The Words We Use

    I just read this great post by Jimmy Bogard over at  Los Techies. He talks about user stories and the fact that what you call a user story is very important. (A rose by another other name would not smell as sweet. ) Words affect how we think about things; though we don't like to admit it.  I've definitely struggled with this myself.

    If you ever communicate with your clients, then I recommend checking out the post.  It's short too.

    I particularly like his comment that prioritizing a requirement is like putting lipstick on a pig.

  • XAML Only WPF Example (Font Viewer)

    The very first application I attempted to write in WPF was a utility to help me with choosing fonts. I'm a developer who has one foot in the designer world, and I am always looking for just the right font. I think that was about 2 years ago, and I was ecstatic that my prototype application took about 15 minutes to write and contained 3 or 4 lines of code (that's not counting the XAML markup.)

    When Rob and I began outlining our upcoming book on WPF, we decided to structure the it around four example applications.  The font viewer seemed like a natural choice for the first application because it's so simple to write., and easy to understand.  I showed the source to Rob, and in less than 10 minutes we had a 100% XAML version of the application. Yes, we removed those troublesome 3-4 lines of code.  :-)

    I decided to play around with it some more, and here is the result. It's a 24KB text file containing just XAML.  If you have .NET 3.5 installed, it should execute in your browser (both Firefox and Internet Explorer work).  It's a very simple application, but I think it's fun. I'm especially fond of the built-in tutorial (be sure to click the help icon).

    This version is a lot more complicated than the one we build in the book.  We don't introduce the concepts of styles, templates, animation, etc until after we're done with the font viewer. 

    In a nutshell, here is how it works. The list box is bound to the set of installed fonts on your system (System.Windows.Media.Fonts.SystemFontFamilies). There are series of four text blocks, whose font family is bound to the selected item on the list box.  Finally, the four text blocks get their content from the text box at the bottom. That's it.

    Please feel free to analyze, dissect, assimilate as you like.  You can get to the source using your browser's "view source" feature.

    Disclaimer: Only very recently did I bother to see if anyone else had done the same thing.  Yes, they had, and more.

    Bonus Question: How would you handle building an application like this with TDD\BDD? How does declarative programming collide with TDD\BDD?

  • You should blog++

    Jeremy Miller recently posted a general encouragement to blog. I'll add my voice to his and as well as confess that I have avoided posting sometimes out of fear of being stupid.  The truth is, I am stupid.  But blogging helps me unstupid, so I'm deliberately posting more.

    Francis Bacon said:

    Reading maketh a full man, conference a ready man,
    and writing an exact man.

    Participating in the blogosphere covers all three.

    Oh, here's some more bacon.

More Posts Next page »

Red-Gate!