Starting with Code Contracts in VS2010

November 22, 2011 1 comment

Design By Contract

On a recent trip to Ireland I wiled away the hours sat waiting for my plane reading The Pragmatic Programmer. A very good book it is too, but what got me thinking was the sections on Design By Contract. Now I could just use ASSERT statements, or something similar to ensure that ‘contracts’ are met. While this is good practice, implementing contracts takes defensive coding a bit further. With a good set of tooling, checks can be done at build time, or even dynamically whilst coding. I don’t have to rely on catching the bug at run time. I am not going to go into details in the post on what DbC is all about, as there are plenty of good references, including the wikipedia link above, that do a much better job. If you have not heard about it, read about it. We sometimes need a certain level of paranoia in our approach to developing software and DbC is a valuable weapon in our arsenal against mistakes made by others and more importantly ourselves.

Eiffel -> C#

The pragmatic programmer book highlights how contracts are built into some languages, with specific reference to Eiffel. I’ve never used Eiffel and don’t plan to move away from my core skill set of C# and C++ in the near future, although no doubt a niche job in the city using Eiffel would pay off my mortgage quicker…. perhaps at the expense of my sanity! Anyway, what I needed was a C# toolkit to get playing with, but before I talk about that lets look at the problem we are trying to solve.

The Problem

A simple, very artificial problem to determine the square root of a number. This is purely to allow for the simplest demonstration possible and is, on its own, a little daft!

public class MyMath
{
    public double SquareRoot(double val)
    {
        return System.Math.Sqrt(val);
    }
}

Hopefully, as we are talking about defensive code, it is obvious that the problem is with negative values of val. The traditional solution would be to use an assertion:

...
public double SquareRoot(double val)
{
    Debug.Assert(val >= 0);
    return System.Math.Sqrt(val);
}
...

now the obvious problem with this is that the assertion is only done in debug builds of the software, which can of course be got round using Trace.Assert() instead or by taking the heavy handed approach of something like:

...
public double SquareRoot(double val)
{
    if (val < 0)
        throw new ArgumentException("val less than 0", "val");
    return System.Math.Sqrt(val);
}
...

On first glance these all look ok and indeed for runtime checking, probably are. However, if we want to catch problems early, we want to be thinking about catching them before they even have a chance to fail, either at build or at development time. Most contract framework toolkits provide this and more, which is why I went looking for a .NET Contract toolkit and as it turns out there class in .NET 4.0 under the System.Diagnostics.Contracts namespace. These on their own are not particularly useful without a decent tool set. This does not come as default with Visual Studio but can be downloaded here.

Code Contracts with VS2010

If the above code was to use contracts the code would look something like this:

...
public double SquareRoot(double val)
{
    Contract.Requires(val >= 0);
    return System.Math.Sqrt(val);
}
...

But I want to run through a slightly elaborated example, using the same square root wrapper, but go a bit further in order to expand your mind😉 Well, to get you thinking about the possibilities at least.

Get Source

Categories: Testing Tags: , , ,

Prism Part 3 – Bootstrapper

April 8, 2011 3 comments

source code

In my previous post, I introduced Dependency Injection as a starting point for looking at Prism. As you will know if you have read some of the other online material, Prism is primarily concerned with building modular applications, with a specific emphasis on the Model-View-ViewModel pattern implemented in WPF and Silverlight. As I hope you noticed, dependency injection is a solution to a common problem that is independent of MVVM. The example I gave in my previous post put DI in the context of an MVVM application.

From here on in, we will start adding features of Prism to our example application, hopefully in an order that will represent a logical sequence of features, starting with features that are most useful, leading to the more esoteric features. You will soon see why I say that Prism can be overkill for a lot of applications and as we progress through these articles, the features being added will need more thought as to whether your application really needs them or whether a simpler solution is more sensible.

Prism provides a very powerful framework to build an application but that comes at the cost of complexity.

The Bootstrapper

A bootstrapper in any application can be considered the entry point for running the application. In the case of Prism the bootstrapper is used to configure the IoC container, modules and the shell (modules and shell will be dealt with in later posts). If you have read my previous post, you will know about the IoC container in Prism. If you don’t now would be a good time to go and have a look at it.

To use a bootstrapper in Prism, we just override the UnityBootstrapper class overriding any methods we wish to. As we progress through this series, we will be adding functionality to our bootstrapper as we go, but for now, we will just create a bootstrapper and add the functionality to set up the IoC container as we did in the previous post.

source code

Categories: Uncategorized

Prism Part 2 – Dependency Injection

April 7, 2011 2 comments

Apologies for taking such a long time in writing this post, hopefully now that another part is done, the other’s may flow a bit more quickly. Whilst I’ve been busy with other stuff, MSP have brought out a Developers Guide to Prism 4, which I intend to buy and provide a review of soon.

Source Code

For those familiar with Prism, it may seem odd to start with Dependency Injection when dealing with a framework that is designed for modular development. However, Prism is a very large beast and taking it on wholesale can be both daunting and frankly unneccessary. What I intend to do with the remaining sections is deal with problems frequently encountered when developing MVVM based applications, look at how Prism attempts to solve them and put forward some alternatives, which will probably not be comprehensive, and weigh up the pros and cons of each approach.

Dependency Injection and Inversion of Control

The two terms DI (Dependency Injection) and IoC (Inversion of Control) are two terms that are often used together and not without good reason as the following example will show.

public class A
{
 public A()
 {
 }

 public void DoSomethingElse()
 {
 }
}
public class B
{
 A _a;

 public B()
 {
  _a = new A();
 }

 public void DoSomething()
 {
  _a.DoSomethingElse();
 }
}

This is of course a very simple example, but there still exists issues:

  1. Class B controls the creation of object _a.
  2. There is a tight coupling between type A and B, due to class B containing a reference to A.
  3. There is a dependence in B on the type A, so as we add new add classes that derive from A, B will need to know about them.

This has implications for testing and maintanance, but is very simple to fix, by allowing creation of A outside class B. This is a simple example of Inversion of Control, the construcion control is taken outside class B. Of course IoC does not apply to object construction, but can apply to all kinds of code that couples the calling class to the implementation of the callee.

Inversion of Control, is an abstract concept. In order to implement it we need to choose a strategy. We are going to choose Dependency Injection, but could equally choose a Service Locator Pattern or something else as we feel appropriate. (Prism also provides a Service Locator based IoC via the IServiceLocator interface, a discussion on DI vs Service Locator can be found here.)

Implementing (Constructor) Dependency Injection would result in the code above looking more like this:

public interface IA
{
 void DoSomethingElse();
}
public class A : IA
{
 public A()
 {
 }

 public void DoSomethingElse()
 {
 }
}
public class B
{
 IA _a;

 public B(IA a)
 {
  _a = a;
 }

 public void DoSomething()
 {
  _a.DoSomethingElse();
 }
}

As you can see, a very simple change and one I am sure many of you are more than familiar with. This way remove any object creation and concrete type dependency, allowing us to provide any implementation of IA to B, B is now no longer responsible for that decision, which is as it should be in this case.

I have specifically chose Constructor DI, as this is the way that Prism manages DI. We shall now look at how Prism ties this together.

Prism and the UnityContainer

In a simple case, something like Prism would be unneccessary to implement Dependency Injection. Any more than the following would be unneccessary and overkill:

IA a = new A();
B b = new B(a);
b.DoSomething();

Not exactly rocket science! But Dependency Injection itself is a very simple concept, even if there can be a challenge in recognising when Inversion of Control needs to be applied. However, in a larger project, where dependencies are numerous and need some sort of centralised management, often it is neccessary to implement some form of container to manage the object creation and injection. These containers are usually known as IoC Containers and Prism’s particular brand is the UnityContainer class. The full documentation for Prism and Managing dependencies can be found here, but I shall give a quick example of using the UnityContainer to manage the dependency above:

firstly we would create an interface for class B as we did with A:

public interface IB
{
void DoSomething();
}

We could then use the UnityContainer as follows:

public class IoCExample
{
 static void Main()
 {
  UnityContainer container = new UnityContainer();
  container.RegisterType<IA, A>();
  container.RegisterType<IB, B>();

  IB b = container.Resolve<IB>();
  b.DoSomething();

 }
}

In this code, we create the container, register the two types as the implementation of the interfaces, using RegisterType<>() on the container. Then, rather than instantiating an instance of B directly, we resolve, using the container. This allows the container to inject any dependencies in the constructor of the registered implementation.

A More Realistic Example

So the example above was not just trivial, but was a completely unrealistic scenario, it may have demonstrated some principles but it hasn’t really shown how to apply IoC and DI using Prism/Unity. This walkthough of adding DI to the MVVM Application I previously demonstrated may help demonstrate it in a bit more context:

Source Code

Summary

So to summarise. Inversion of Control is a good thing, it decouples code and maintains a Separation of Concerns in our code base. Dependency Injection is one way to achieve this, although some people prefer the Service Locator Pattern. Prism, or rather Unity, which is distributed as part of Prism, provides a container for managing Dependency Injection, which becomes appropriate when projects get larger and dependencies get more complex.

WPF MVVM Presentation – V2

January 30, 2011 1 comment

A couple of months ago, I posted some slides on MVVM. This was to be the basis of a session I was doing on introducing a few colleagues to the MVVM pattern. As it turned out, the presentation had a little too much content that should have been left out. For example it introduced concepts such as Dependency Injection, Dialog Services and others that muddied the waters a bit.

The aim of the session was to introduce the MVVM pattern from a WPF perspective. As a result, I have put together some resources, post presentation, that do not deal with extra details, but rather look at the MVVM pattern as it is implemented in a very basic form, in order to put across the concepts.

Warning: Some of these presentations are a bit raw!:)

1. A walkthrough of a simple WPF Application.

This presentation outlines a simple WPF application for managing simple notes, containing a title and content. The application allows users to add, delete and edit notes, as well as view them. The intention of this presentation is to demonstrate a quick and dirty WPF solution, highlight briefly its issues and use it as a basis for developing a MVVM based solution. The application is not exactly spectacular looking and if you know how to write WPF applications using code behind, this presentation may be worth skipping. The video is about 30mins long.

2. My original adopting MVVM presentation

This is the original post that contains an overview of the MVVM pattern before going on to introduce an example that contains implementation detail that detracts from presenting MVVM. It is still worth viewing as it does outline MVVM as a pattern. The video is about 20 mins long.

3. An MVVM Version of the WPF Application

This is the application walkthrough that shows how to construct the application presented in the first part of this post, but using the MVVM pattern. It highlights the key concepts of MVVM and how these can be implemented simply using WPF. The presentation does not demonstrate concepts such as DI and does not use extra libraries, such as Prism, that my first application demo did.

4. The Source Code

Finally, I have added the source code for this application, which may be of interest if you want to play around with the code and look at it in a bit more detail. Be aware that this is a very rough and ready application, intended as a demonstation.

Categories: MVVM, Training, WPF Tags: , , ,

An Introduction to WPF

January 25, 2011 Leave a comment

I’ve recently been putting together another MVVM intro presentation. Whilst doing so, I have put together some screen capture videos of developing a WPF with code behind and using the MVVM pattern. This post contains the video recorded for that presentation. It’s a bit raw and there are some references to other parts of the presentation, but I still thought it would be worth posting here for those interested in a quick introduction to a WPF/XAML application. The video is about 30mins long and contains me rambling on a bit. Sorry, I’ll get better at these with practice:)



WPF Presentation

Categories: Training, WPF Tags: , , ,

Microsoft WebMatrix released.

January 25, 2011 1 comment

Microsoft recently released WebMatrix as a tool for developing web apps, with particular emphasis on deploying solutions based on open source web applications such as wordpress. As I have been thinking about moving this blog to my own server, I thought I’d give it a go… this may well be my last blog before moving to a new domain!

On startup of WebMatrix, I am presented with a simple quick start screen:

As I want to build a WordPress site, I select ‘Site from Web Gallery’. This is where I have the option of installing a whole range of web applications (40 at present) as the following screenshot suggests:

So I call my site name sputnikdev, select WordPress and click ‘Next’. It then asks some questions about installing MySQL if you want to run against a local copy. I chose to use MySQL on my web host. It then goes through the process of downloading and installing the required files. It then asks for some MySQL connection details, before confirming that everything is installed correctly and presenting you with the application screen:

Clicking on the URL then successfully brought up the WordPress start page for setting up an initial user and the database.

I then clicked on “Set up the remote publishing location for your website” link at the bottom of the screen, to set up my ftp connection, which allows you to test the connection…. always a handy feature those who are developing a user configurable server connection in their app.

Once this was done, I was already to publish my site.

I clicked on Publish. WebMatrix tests that the connection has certain compatibility. This all came back with errors, but then this was to be expected over FTP on my web host, so I selected continue anyway. WebMatrix then gives you a preview of changes (in this case all files). There was a warning about overwriting local databases, which was irrelevant in my case, so I hit continue and crossed my fingers.

And then off it went, copying the files in the background, which was a nice touch.

Once it was done, a quick look at my site (ignore the URL for the moment, it will be published here once the site is ready) revealed I probably needed to add PHP to my hosting package and wait for that to be ready, perhaps I should have paid closer attention to those compatibility errors.

And here it is, wordpress installed with very few steps using WebMatrix:

In conclusion, WebMatrix was incredibly simple to use for setting up a standard site, obviously the advantage with open source web apps is that they can be customised and extended. WebMatrix assists in simplifying the process of doing this and then testing and deploying. Now all I have to do is get my new sputnikdev blog set up, the data exported from my wordpress.com site and get that imported. Maybe I’ll also add a gallery for my collection of paintings.

Update:

Because I chose to run against a remote database when testing, the deployment was not setting site URLs correctly. This site URL is stored in the database. More details on how to fix it, if you come across this problem, can be found here: http://drewby.com/2010/09/using-web-deploy-to-sync-your-webmatrix-site/

Categories: Web Tags: ,

BDD with Gherkin for WPF Apps

December 10, 2010 4 comments

If you’ve read my post on the value of automated UI testing, you’ll know that I value it over Unit Testing. That’s not to say Unit Testing isn’t important, just that there is greater business value in Automated UI testing, if you can get it to work for you. 

In this post I’m going to describe how SpecFlow could be used to achieve this with WPF applications. I’m not going to pretend that my small example here is going to solve problems of applying this to large projects, but hopefully it will provide a start point, a trigger to further investigation and establishing some best practices, appropriate for the product being tested.

Demo App

Firstly then, a quick description of my Demo App. If you’ve read some of my other posts you will be familiar with the groundbreaking WPF media player. It allows user to select a folder, display the media in that folder and play that media:

Media Player App Screenshot

Media Player App Screenshot

Unit Tests in VS

Unit Testing is now an integrated part of Visual Studio and has been for a number of years. Everyone reading this is no doubt very familiar with this, so I won’t venture to explain it. Suffice it to say, that ideally we want to do UI testing in a testign framework that is well supported in Visual Studio. SpecFlow supports both MSTest as well as nUnit.

Introduction to Gherkin

Specifying User Acceptance Criteria for stories is always in danger of being ambiguous. Capturing them in a standardised notation often helps make thes acceptance criteria more explicit. Whilst at Nokia, our sprint planning sessions involved the PO describing the story and then the team defining UACs as Gherkin scenarios. 

Gherkin is a simple notation based on scenarios that can be written using Given – When – Then clauses. Given being the system state, When being a user action and Then being the outcome. Gherkin is ‘Business Readable’, so can be fully understood by the PO and the business.

Introduction to UI Automation

Microsoft have helped matters in testing UI written in WPF through their UI Automation API. This API enables us to drive WPF applications and check content of controls. Again, I am not going into too much detail as there is more than enough elsewhere and to be honest I have only recently started looking at the UI Automation API. The reason I bring it up here is that we need a way of pulling Unit Tests with MS Test, UI Automation to drive the UI and Gherkin to allow a simple notation for defining Scenarios and ultimately User Acceptance Criteria. Enter SpecFlow….

Introduction to SpecFlow

Lifted straight from their website: “SpecFlow aims at bridging the communication gap between domain experts and developers by binding business readable behavior specifications to the underlying implementation.”

Specflow is designed for .NET, supports MS Test and integrates with Visual Studio. On initial inspection, this looked like what I had been looking for. I shall now go through an example of writing tests using SpecFlow for the application described above. There is obviously plenty more information on the various product web sites so I would advise going there rather than copying my example. This example is here to fire the imagination, if that is what you are after.

Add a feature

We are starting from an empty Test Project in Visual Studio and adding a feature is as simple as selecting the “SpecFlow Feature File” on “Add New Item”. The dialog also includes Event Definition files and Step Definition files, which we will use later.

Add New Item

This adds a new .feature file which contains a basic feature and scenario. I edited this to add a couple of scenarios which should be self explanatory. After all, that is the purpose of Gherkin:

A Simple Feature

Here you can see the Scenarios as Give, When, Then steps. Once this file has been added the tests will build and run as inconclusive. Each scenario forms a test case. SpecFlow does some magic in generating the code for the feature file. What must be done now is the writing of any setup / tear down code and methods for each step.

Add Event Defs

An event definition file can be added which has methods for executing  code at various stages during the running of scenarios and tests. In our case we just want to kick off the application on each feature test and kill it after:

Event Definitions

Add Steps for feature

The bulk of the coding must be done in the Steps Code. Taking the example of the first scenario we want to write 3 steps for the given / when / then clauses in the gherkin:

Scenario Step Code

As you can see, SpecFlow uses attributes to match steps to methods, really very simple. Most of this code is the neccessary boilerplate for UI Automation, which leads us on to how we might deal with this in a real application

Next Steps

The first thing I noticed, which was really to do with the UI Automation, was the amount of boilerplate that was needed. In a real application, this would get significantly more complex than this exmaple, very quickly. Ideally each View would have a UI Automation wrapper written for it that would encapsulate the UI Automation code, allowing the test developer to call single methods to perform opearions on the UI and to check values in controls. I am guessing that at this point it would be worth investigating F# to do this, as it seems that a more functional language may help in this. Any comments on that will be gratefully recieved.

Categories: Agile, Testing, WPF Tags: , , , ,
Follow

Get every new post delivered to your Inbox.