// Arrange Act Assert

Jag Reehal on Agile Development, ASP.NET MVC, Silverlight and all manner of good stuff


How To Refactor And Build Better Microsoft Silverlight Applications

Posted on | June 10, 2010 | No Comments

As with all development technologies if you asked two developers how to solve a problem it’s unlikely both would come up with the same solution.

It’s no surprise then the same solution to a problem using Silverlight and WPF applications can be implemented in a number of ways.

In a series of posts I want to show how we can refactor a Silverlight application which “works” to be a lot cleaner, easier to maintain and adheres to good development practices.

Although I’m using Silverlight many of the changes and suggestions would also apply to a WPF application.

So what’s the application?

The application adds two numbers together.

Silverlight Calculator

Yes that’s it. Click here to see a live demo of the calclator.

Using a simple example (as opposed to a huge complex monster) allows us to focus on refactoring and making improvements rather than trying to understand what the application is doing and wading through hundreds of lines of code.

So what’s wrong with it?

The XAML is shown below

    <Grid x:Name="LayoutRoot" Background="White" Height="100" Width="350">
        <Grid.ColumnDefinitions>
            <ColumnDefinition/>
            <ColumnDefinition/>
            <ColumnDefinition/>
            <ColumnDefinition/>
            <ColumnDefinition/>
        </Grid.ColumnDefinitions>
        <Grid.RowDefinitions>
            <RowDefinition/>
            <RowDefinition/>
        </Grid.RowDefinitions>
        <TextBox Grid.Column="0" Text="0" Height="25" TextAlignment="Right" x:Name="tbFirstValue"/>
        <TextBlock Grid.Column="1" Text="+" Height="25" TextAlignment="Center"/>
        <TextBox Grid.Column="2" Text="0" Height="25" TextAlignment="Right" x:Name="tbSecondValue"/>
        <TextBlock Grid.Column="3" Text="=" Height="25" TextAlignment="Center"/>
        <TextBlock Grid.Column="4" Text="0" Height="25" TextAlignment="Left" x:Name="tbResult"/>
        <Button Grid.Row="1" Grid.ColumnSpan="5" Margin="0,5,0,0" Content="Calculate" x:Name="btnCalculate" Click="btnCalculate_Click" />
    </Grid>

and this is what the code behind looks like

public partial class MainPage : UserControl
{
    public MainPage()
    {
        InitializeComponent();
    }

    private void btnCalculate_Click(object sender, RoutedEventArgs e)
    {
        tbResult.Text = (Convert.ToInt32(tbFirstValue.Text)  + Convert.ToInt32(tbSecondValue.Text)).ToString();
    }
}

As it stands the application:

  • Contains code in the code behind file. OK it’s not so much of an issue for this example and is down to individual preference, but this can quickly become a nightmare to maintain during the life of an application
  • Isn’t unit testable – we can’t test two values can be added together
  • Has no separation of concerns – the code behind shouldn’t be responsible for adding the numbers together
  • A lot of repetition for the styling of the input boxes – if we wanted to make the input boxes bigger we would have to make multiple changes, ideally changes should only need to be made in one place.
  • No validation – if the user enters alphabetical characters into application and hits the calculate button the application crashes

So how are we going to improve it?

By taking an agile approach the aim at the end of each refactoring is to have a releasable application i.e. be able to add two numbers together. Therefore each refactoring will involve small incremental changes.

After each refactoring exercise we will review the application to see what improvements have been made and if any new problems have been introduced…

WPF and Silverlight Value Converter Example in VB and C#

Posted on | June 2, 2010 | No Comments

In this post I want to show how a value converter in Silverlight and WPF can be used to output the value of a slider control.

The code used in this post downloaded here.

Why Are Value Converters Useful?

In the screen shot below you can see a slider control and two numbers representing its value. As you can see the value not using a converter is somewhat lacking in its visual appeal and isn’t user friendly.

Silverlight Value Converter Example

The XAML used to create this is shown below

<UserControl x:Class="ValueConverterExample.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:local="clr-namespace:ValueConverterExample" mc:Ignorable="d"
    d:DesignHeight="300" d:DesignWidth="500">
    <UserControl.Resources>
        <local:SliderValueConvertor x:Key="SliderValueConvertor"/>
    </UserControl.Resources>

    <Grid x:Name="LayoutRoot" Background="White" Height="Auto" Width="500" Margin="0,50,0,0">
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto" />
            <RowDefinition Height="Auto"/>
        </Grid.RowDefinitions>

        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="4*"/>
            <ColumnDefinition Width="3*"/>
            <ColumnDefinition Width="3*"/>
        </Grid.ColumnDefinitions>

        <TextBlock Grid.Column="1" Text="Without a Convertor" Margin="5" HorizontalAlignment="Center"/>
        <TextBlock Grid.Column="2" Text="With a Convertor" Margin="5" HorizontalAlignment="Center"/>
        <Slider x:Name="mySilder" Grid.Row="1" Minimum="0" Maximum="10" Margin="5" SmallChange="1" />
        <TextBlock x:Name="txtBlkWithoutConverter" Grid.Row="1" Grid.Column="1" Text="{Binding ElementName=mySilder, Path=Value}" VerticalAlignment="Center"  HorizontalAlignment="Center"/>
        <TextBlock  x:Name="txtBlkUsingConverter" Grid.Row="1" Grid.Column="2" Text="{Binding ElementName=mySilder, Path=Value, Converter={StaticResource SliderValueConvertor}}" VerticalAlignment="Center"  HorizontalAlignment="Center"/>
    </Grid>
</UserControl>

Note how in the text binding for the txtBlkUsingConverter text block a SliderValueConvertor is used.

The code for the value converter looks like this in VB

Public Class SliderValueConvertor
	Implements IValueConverter
	Public Function Convert(value As Object, targetType As Type, parameter As Object, culture As CultureInfo) As Object
		Return Math.Round(CDbl(value))
	End Function

	Public Function ConvertBack(value As Object, targetType As Type, parameter As Object, culture As CultureInfo) As Object
		Return Nothing
	End Function
End Class

and like this in C#

public class SliderValueConvertor : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        return Math.Round((double) value);
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        return null;
    }
}

By implementing the IValueConverter interface the slider value can be rounded to show a whole number. There’s no need to support the ConvertBack method because the text block isn’t editable.

I could have done this using code behind…

Yes if you created a handler for the slider value changed event in the code behind it’s possible to achieve the same result. But I find this solution much cleaner and can be used if you’re implementing the MVVM pattern.

How to Convert a SketchFlow Prototype into a Production Application… And why you shouldn’t!

Posted on | April 28, 2010 | 3 Comments

One of the first questions I’m getting asked after my SketchFlow presentation is about converting a SketchFlow prototype to a production application.

Now before I answer this question, I know some of you may have arrived here from a search engine, so if you want a solution check out the MSDN article on converting into a production project in 16 steps but just because you can it doesn’t mean you should!

SketchFlow Prototype showing the text convert or not to convert.  That is the question.

One of the problems with prototyping tools like SketchFlow is they can sometimes leave your client with the impression that all the work is done the and product is in some way releasable or production ready.

Now I’m not saying nothing can be shared between the two solutions (e.g. resources) because that depends on the design and project you are working on.

What is clear however are the aims and mindsets used to create a SketchFlow prototype are different from how you would go about creating a real world production solution.

From a design perspective the layout of controls in SketchFlow are done using a single grid and their margin property. In a real world application you would pay more consideration into the layout of the design and think about things like how the page would scale.

From a developer perspective a SketchFlow prototype doesn’t easily lend itself to good development practices such as SOLID design principles, code reusability and testing.

And in any case would you really deploy files called something like Screen_1.xaml to a production server?

Even if these things don’t matter to you, I still don’t recommend using Microsoft’s solution because

  • there are still references to the Microsoft.Expression.Protyping libraries in a supposedly production ready solution. Having libraries in your application that you not sure are being used before you launch will only get worse as time goes on.
  • Microsoft’s solution is not 100% successful, lots of people are having problems with navigation not working properly.

So what should I do?

  • Focus on creating designs that satisfy the customers’ requirements and not about the final design. You can think what resources could be reused later in the prototyping cycle.
  • Deliver prototypes to your customers early and often. This will allow your customer to give feedback early so you can inspect and adapt.
  • Keep your screen designs simple and lightweight so changes can be done quickly and with the knowledge that you won’t be breaking anything.
  • Keep an eye on how many events and behaviors are used on a control or screen. It’s too easy to get carried away remember it’s only supposed to be a prototype.
  • Take advantage of the sample data resources available and not bind to databases or web services.
  • Keep code behind to a minimum, ideally having none at all.

Jag Reehal’s Final Thought on ‘Converting a SketchFlow Prototype into a Production Application’

I can understand why people are looking for a solution where they can use a prototype and a production application interchangeably because like documentation prototypes can easily get out of date and no longer reflect the design used in the production version. Unfortunately the only answer is to adhere to good practices and always start by prototyping and not by retrospectively making your prototype match your production design.

Prototypes are extremely useful… as prototypes and nothing more!

Have fun using SketchFlow I love it, and it’s definitely my prototyping tool of choice.

Barcamb and my talk about SketchFlow

Posted on | April 25, 2010 | No Comments

This weekend I attended barcamb3 in Cambridge, UK.

I really liked the event.

Around eighty people with different interests and backgrounds attended the event and this is what made it work so well.

The .Net events I attend and enjoy in Cambridge are good but you don’t get start ups that are passionate about what they are doing, or hearing about the problems they have had to overcome and what they hope to achieve.

The mix of attendees also meant that the talks on the day covered a variety of topics from abusing social media sites like Facebook/Twitter to get more traffic to talks about geo location. Not everyone was a developer so there were good discussions which weren’t about programming such as how paperless could we become.

There was also a talk on TDD. I learned that developers going for a job at the Guardian newspaper have to take part in a TDD exercise as part of their interview process! As soon as the presenters mentioned pair programming, it became the main topic. Having written a blog post called ‘Pair Programming Is Not a Silver Bullet’ it was reassuring to hear other developers experiences were the same as mine… both good and bad!

My talk about developing prototypes with SketchFlow

Jags SketchFlow talk at barcamb3

I did a talk about using Expression Blend and SketchFlow for developing prototypes covering topics such as

  • Lo-fidelity vs high-fidelity prototypes
  • Advantages over other prototyping tools such as Visio and Balsamiq
  • Navigation
  • Component screens
  • Animation
  • The Visual State Manager
  • Feedback
  • Converting a SketchFlow prototype into a real world app

Alfred – Mac App of the year 2010?

One of reasons I make an effort to attend events such as these is to get inspiration from other developers.

I talked to so many people over the weekend and found out some interesting information about developing sites that streamed music, search applications and content management solutions.

But without a doubt the most innovative and interesting was Alfred, an application for the Mac.

How did I find out about it? By just saying hi to Andrew Pepperrell. We got talking about each other do, then he grabbed a Mac and showed the application to me.

If you have a Mac get this application now! Calling it a quick launch application doesn’t do it any justice. If I knew how I would develop a Windows version because it’s so good.

I’m really happy for Andrew because he has dedicated so much of his own time developing an application which is getting positive feedback from the IT community around the world.

Thank You!

I would like to thank all them who organised this fantastic event and am really looking forward to barcamb4!

How NBuilder Could Help You Write Better .Net Unit Tests

Posted on | March 10, 2010 | 1 Comment

One of the biggest challenges when creating unit tests is to come up test data. It makes sense having someone other than you test your code, so how about having someone other than you generate the test input for your .Net unit tests.

Data generation tools aren’t new concept and they come in many different forms. When I first saw Red Gate Sql Data Generator a couple of years ago, I thought to myself it’s a shame you need a database because this would have been great for unit and integration tests.

In this blog post I want to show you how NBuilder can be used when unit testing with .Net objects. The NBuilder assembly can be downloaded here http://code.google.com/p/nbuilder/.

In this blog post we will be using the product and category classes below

public class Product
{
    public Product()
    {
        Categories = new List<Category>();
    }

    public Guid Id { get; set; }
    public string Name { get; set; }
    public int Rating { get; set; }
    public decimal Price { get; set; }
    public bool InStock { get; set; }
    public List<Category> Categories { get; set; }

    public override string ToString()
    {
        return String.Format("Id:{0}, Name:{1}, Rating:{2}, Price:{3}, InStock:{4}, Categories:{5}", Id, Name, Rating, Price, InStock, Categories.Count);
    }
}

public class Category
{
    public string Name { get; set; }
}

NBuilder default values

The product class contains a variety of types. When you run the following code to create 10 products

[Test]
public void Should_Create_Ten_Products()
{
    var products = Builder<Product>.CreateListOfSize(10).Build();
    products.Count().ShouldEqual(10);
}

this is the output

Id Name Rating Price InStock Categories Count
00000000-0000-0000-0000-000000000001 Name1 1 1 False 0
00000000-0000-0000-0000-000000000002 Name2 2 2 True 0
00000000-0000-0000-0000-000000000003 Name3 3 3 False 0
00000000-0000-0000-0000-000000000004 Name4 4 4 True 0
00000000-0000-0000-0000-000000000005 Name5 5 5 False 0
00000000-0000-0000-0000-000000000006 Name6 6 6 True 0
00000000-0000-0000-0000-000000000007 Name7 7 7 False 0
00000000-0000-0000-0000-000000000008 Name8 8 8 True 0
00000000-0000-0000-0000-000000000009 Name9 9 9 False 0
00000000-0000-0000-0000-00000000000a Name10 10 10 True 0


  • For strings NBuilder suffixes the index number to the name of the property e.g. Name1
  • For numeric values such as int and decimal the default value is the index number
  • For guids a hexadecimal range is used
  • Boolean values alternate between true and false for each product
  • The categories collection is left empty. This would have been null if we didn’t create a new collection in the constructor of the product class

Changing how NBuilder default values are created

I really like how you can customize NBuilder and use your own convention for creating default values.

For example what if we wanted to change how guids are created.

One way to do this is to inherit from the RandomValuePropertyNamer class and override the GetGuid method as shown below.

public class JagsRandomValuePropertyNamer : RandomValuePropertyNamer
{
    protected override Guid GetGuid(System.Reflection.MemberInfo memberInfo)
    {
        return Guid.NewGuid();
    }
}

After setting the default property namer, all guids are created by calling Guid.NewGuid()

[Test]
public void Product_Should_Have_Guid_Assigned()
{
    BuilderSetup.SetDefaultPropertyNamer(new JagsRandomValuePropertyNamer());

    var product = Builder<Product>
        .CreateListOfSize(10)
        .WhereAll()
            .Have(p => p.Id = Guid.NewGuid())
        .Build();

    product[0].Id.ToString().ShouldNotEqual("00000000-0000-0000-0000-000000000001");
}

Using the WhereAll method to set the InStock to always be true

What if we wanted to change the InStock value to true for all the products in the collection. This can be done using the WhereAll method as shown in the code below

[Test]
public void All_Products_Should_Be_In_Stock()
{
    var products = Builder<Product>
        .CreateListOfSize(10)
        .WhereAll()
            .Have(p => p.InStock = true)
        .Build();

    products.All(p => p.InStock).ShouldBeTrue();
}

Using NBuilder to set parts of a collection

There are two ways you can use Nbuilder to set values in parts of a collection. The first is by using the first or last methods like so

[Test]
public void First_Two_Products_Should_Be_In_Stock()
{
    var products = Builder<Product>
        .CreateListOfSize(10)
        .WhereTheFirst(2)
            .Have(p => p.InStock = true)
        .Build();

    products[0].InStock.ShouldBeTrue();
    products[1].InStock.ShouldBeTrue();
}

the other is to use sections

[Test]
public void Mixture_Of_Products_In_Stock_Using_Sections()
{
    var products = Builder<Product>
        .CreateListOfSize(10)
        .WhereSection(0, 1)
            .Have(p => p.InStock = true)
        .WhereSection(2, 9)
            .Have(p => p.InStock = false)
        .Build();

    products[0].InStock.ShouldBeTrue();
    products[2].InStock.ShouldBeFalse();
}

Using the UniqueRandomList to create unique random lists…

So far we haven’t done anything with the category property.

What if you wanted to build a product collection with each product having a random number of categories?

By calling the HaveDoneToThem and the UniqueRandomList methods we can create a set of products with having different categories to one another

[Test]
public void Products_With_Random_Categories()
{
    var categories = Builder<Category>
        .CreateListOfSize(100)
        .Build();

    var products = Builder<Product>
        .CreateListOfSize(10)
        .WhereAll()
        .HaveDoneToThem(p => p.Categories.AddRange(Pick<Category>.UniqueRandomList(2).From(categories)))
        .Build();

    var productCategoryOne = products[0].Categories[0].Name;
    var productCategoryTwo = products[1].Categories[0].Name;

    productCategoryOne.ShouldNotBeTheSameAs(productCategoryTwo);
}

Extending NBuilder with a Lorem Ipsum string generator

One thing I really like about NBuilder is the ability to extend it.

The code below shows how easy it is to have product names randomly using Lorem Ipsum just by creating a extension method like this

public static class StringExtensions
{
    public const string LoremIpsum = "Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.";

    public static IOperable<Product> HavingRandomLoremIpsumProductName(this IOperable<Product> operable)
    {
        ((IDeclaration<Product>)operable).ObjectBuilder.With(x => x.Name = LoremIpsum.Substring(0, new Random().Next(446)));
        return operable;
    }
}

this can be used to generate products with random names like this

[Test]
public void Products_With_Random_LoremIpsum_Names()
{
    var products = Builder<Product>
        .CreateListOfSize(10)
        .WhereAll()
            .HavingRandomLoremIpsumProductName()
        .Build();

    var nameOfProductOne = products[0].Name;
    var nameOfProductTwo = products[1].Name;

    nameOfProductOne.ShouldNotBeTheSameAs(nameOfProductTwo);
}

Jag Reehal’s Final Thought on ‘How NBuilder Could Help You Write Better .Net Unit Tests’

I think frameworks like NBehave could really have a big impact on how you go about having to create test data. The fluent interface is fantastic and it’s so easy to customize.

NBuilder contains a lot more features than I have covered in this post so if you like what you’ve seen make sure you check out the NBuilder documentation.

For the future I’m hoping Fluent NHibernate and NBuilder could work together. For example when you define class maps in Fluent NHibernate you can specify the length of string column. If NBuilder could use information like this when generating data that would really be something special.

« go backkeep looking »