Month: February 2011

Bye bye Morgana!

This is an off-topic post and I want to spend a space on my wall to my dog, the best “friend” I ever had in my life and probably the best I will ever have.150245_1694100553588_1270026602_31873922_1816636_n

Morgana has been my dog since the end of 2001, as soon as I ended the school and I got the first job I left my parents house and I started to live with my actual wife. I always had the dream of having a Doberman and I decided with Debbie to go to a Doberman breeding farm and get one.

Morgana was there, in a corner, very shy. She didn’t want to leave the farm and at that time she probably didn’t like us at all; she was only 2 months old and we were taking her away from her mother …

After few weeks she got quickly used to us and I would say that we both felt in love. A love that never ended and that will never end.

I cannot tell you how many adventures and misadventures I had with my dog, you wouldn’t even imagine. I can just tell you that she was there when I got married, she was there when I lost my job and she was there when I left Italy to move to Bermuda! She was here in Bermuda and she was ready to come back with me in Italy when I lost my job in Bermuda 2 years ago. She has always been with me, she was part of the family!


Every person that met us (friends, parents, relatives or simply neighbors) knows how nice, sweet and smart Morgana was. She never gave us any problem, she was the perfect dog, the one that every person would like to have. The family dog, smart, sweet and dutiful but in the same time spiteful if I was not giving her the time she deserved!

Now she is not with us anymore, unfortunately. The pain is still big for me and I feel I am missing something now, like a piece of my life is now empty, gone. When I got her my father was not happy because he had a dog and he told me: “Raf, you can’t even imagine the pain you will have when your dog will die”  and he was absolutely right! The pain is a lot and I still do not know how to fill the gap she left.

I just want to write this post to remember her, to let her know that she will be always in my heart and that I will never, ever forget her!

Bye bye Morgana!

Winking smile

State pattern using C#. Part 02.

In the previous post we saw how we can implement the state pattern (I know, I didn’t show you the purist way of using the State pattern …) and include in the state execution the flow logic.

This technique is fine but … it requires a lot of effort in the implementation and requires a lot of maintenance, plus it has the GAP of forcing us to re-run the CanExecute delegate every time we want to execute a specific action.

On the web I have found some solutions that personally didn’t satisfy me at all. I personally believe that the best way of designing a state machine workflow is to use a workflow engine and NET Framework provides with NET 4 an amazing state engine. Anyway let’s see what the web offers instead of using WF 4.

Stateless Open source project

Stateless is an Open source project hosted on Google code and available here:; it is a C# implementation of a stateless workflow using the BOO language.

We have the same domain exposed in the previous post but in this case we modified a little bit the Order object and we do not use anymore the Command pattern.


The class Order has 5 different methods that can modify its state in the following way:

Create an Order
  1. public void Create()
  2. {
  3.     this.State = OrderState.Created;
  4. }

They do not verify anymore if the action can or cannot be execute, we just know that the Create method, for example, modifies the state of the Order to “Created”.

Now it is time to wrap this code in a separated class that we will call OrderService and that is identified in DDD as a Domain Service object, a service used in the domain space to wrap business logic and keep it outside the Entity object. The final result should like this one:


The trick with is to split the service in two parts, the first one is used to Bootstrap the stateless framework in the following way:

Stateless boostrapping
  1. public sealed class OrderService
  2. {
  3.     private StateMachine<OrderState, OrderActions> workflow;
  5.     public OrderService()
  6.     {
  7.         workflow = new StateMachine<OrderState, OrderActions>(OrderState.Undefined);
  8.         workflow
  9.             .Configure(OrderState.Undefined)
  10.             .Permit(OrderActions.Create, OrderState.Created);
  11.         workflow
  12.             .Configure(OrderState.Created)
  13.             .Permit(OrderActions.Cancel, OrderState.Cancelled)
  14.             .Permit(OrderActions.Modify, OrderState.Modified)
  15.             .Permit(OrderActions.Approve, OrderState.Approved);
  17.     }

And then we add a method in the service that will be used to Fire a specific state change, like this one:

Command pattern
  1. public void Fire(Order order, OrderActions action)
  2. {
  3.     workflow.Fire(action);
  4.     order.State = workflow.State;
  5. }
  7. public bool CanFire(Order order, OrderActions action)
  8. {
  9.     return workflow.CanFire(action);
  10. }

Now, by default, Stateless raises an error (Exception) if the operation can’t be executed. The following test demonstrates the exception raised by stateless:

  1. [Test]
  2. public void CannotApproveAnOrderBeforeCreatingIt()
  3. {
  4.     var order = new Order();
  5.     var service = new OrderService();
  6.     Assert.Throws<InvalidOperationException>(() =>
  7.         service.Fire(order, OrderActions.Approve));
  8.     Assert.That(order.State, Is.EqualTo(OrderState.Undefined));
  9. }

The exception is of type InvalidOperationException.


Stateless is a good state machine framework, open source, easy to learn and it has a good and clear DSL language. Unfortunately the project is very young, the active developer is only one and it still has a huge list of ToDo and Bugs to be fixed.

It can be used to replace custom If and Switch in the Domain language but if you need to do some custom and more complicated evaluations, Stateless can result very verbose because it doesn’t have a UI so you have to prepare all the If and Switch using the Configure syntax.

State pattern using C#. Part 01

I have been busy for a while writing my two books about MVVM and WPF but I am almost done so be ready to get more posts in the next months. This one is the first of a series that I will write to solve the state pattern issue.

Today I want to start to talk about the state pattern, a design pattern used to represent the state of an object and how we can apply this pattern in a normal WPF application.

The problem we have is that based on the state of an Order we can or we can’t execute a specific action.

Before starting to talk about the pattern we need a sample application, right? So, what is better than having a nice WPF application that we will use to represents the problem? Smile

Process an order using States

The example I want to use is the classic Order entity that during the order process can be moved to different states. The following diagram create with Visual Studio shows you what I am talking about:


The previous image shows the state diagram applied to an Order:

  • You can create  an order and after it is created the state is of type Created
  • Then you can modified the order or you can cancel the order; if you cancel the order, its state is cancelled and you can’t do anything anymore
  • An order that has been created can be approved and its state will change to approved

So in the previous Use Case we have identified 4 actions (blue) and 3 states (white), for each action there is a specific state, in a specific state you can execute only a specific or a set of specific actions and from one state you can move only to one or more specific states. For instance, from the Approved state we can’t rollback to the Created state and so on …

Now, how would you express the previous diagram using a Domain Model composed by an Order entity and a State property? First thing first is to implement a Domain Entity.


Now we can implement the classic state pattern described by Martin Fowler.

Classic implementation of the State Pattern

If you are an MVVM developer you may believe that the first and almost the easiest way of implementing this pattern is to use the Command pattern, right? So, if we plan to extend that in the Order entity we should have a model like the following one:


Where the command implementation may be something like this:

Command Pattern
  1. CreateOrder = new Command(
  2.     () => true,
  3.     () =>
  4.         {
  5.             Code = “ABC123”;
  6.             State = OrderState.Created;
  7.         }
  8.     );
  9. ModifyOrder = new Command(
  10.     () => State == OrderState.Created,
  11.     () =>
  12.         {
  13.             State = OrderState.Modified;
  14.         });
  15. CancelOrder = new Command(
  16.     () => this.State == OrderState.Created || this.State == OrderState.Modified,
  17.     () => { this.State = OrderState.Cancelled; });


When an order is created, by default, we do not allow any state so the default state is undefined and these are the tests:

TDD – change state
  1. [Test]
  2. public void AssertThatANewOrderIsUndefined()
  3. {
  4.     var order = new Order();
  5.     Assert.That(order.State, Is.EqualTo(OrderState.Undefined));
  6. }
  8. [Test]
  9. public void AssertThatANewOrderCanBeCreated()
  10. {
  11.     var order = new Order();
  12.     order.CreateOrder.Run();
  13.     Assert.That(order.State, Is.EqualTo(OrderState.Created));
  14. }


The last step needs to verify that if we try to move from one state to a not allowed state, the action that we try to execute will throw an exception:

TDD – Not allowed method
  1. [Test]
  2. public void AssertThatCannotApproveANewOrderNotCreated()
  3. {
  4.     var order = new Order();
  5.     Assert.That(order.State, Is.EqualTo(OrderState.Undefined));
  6.     Assert.Throws<NotSupportedException>(() => order.ApproveOrder.Run());
  7. }


Conclusion using the Classic method

This technique is not clean and it is very verbose but it is absolutely testable, but not maintainable. For instance, if the number of state enum will increase we have to touch all over the code that execute the flow logic and probably we need also to refactor all the commands so we can say that this solution is fine but not maintainable at all.

Another gap of this solution is that every time we want to execute a command we need to fire the CanExecute method that may process some “long running” business logic behind:

Command Run() method
  1. public void Run()
  2. {
  3.     if (canExecute == null || canExecute.Invoke())
  4.     {
  5.         this.execute.Invoke();
  6.     }
  7.     else
  8.     {
  9.         throw new NotSupportedException(“The action can’t be executed.”);
  10.     }
  11. }

In the next blog post we will see a different approach. At the end of the series (04 posts) I will provide a WPF application on with the source code posted in this series; please be patient for now as I can’t upload the final source code yet.