Dennis van der Stelt

I care about technology; I care about users more

Community

Email Notifications

News

  • Addicted to Refactor! Pro
    <div class="sideNavItems">

I read...

I Use...

Tags

Recent Posts

Archives

Blog Subscription Form

  • Email Notifications
    Go

Template Method Pattern advanced example

This blogpost is part of a series

  1. Template Method Pattern explanation
  2. Template Method Pattern example
  3. Template Method Pattern advanced

So we’ve looked at the Template Method Pattern with an implementation as really simple example, and another real world implementation. We have additional requirements however. We also need to transform the template so that placeholders will contain the proper text, and have the value of the placeholders customized to our customers. Let’s first look again at the executing code, so we get an idea of what API we want.

static void Main(string[] args)
{
    TemplatedMessage message = new TemplatedMessage();
    message.Identifier = Guid.NewGuid();
    message.EmailAddress = "dvdstelt@gmail.com";
    message.Template = "So you're a {{Sex}} and like to play {{BestGameEver}}.";

    message.PlaceHolders.Add("Sex", "male");
    message.PlaceHolders.Add("BestGameEver", "Modern Warfare 3");

    MessageSenderBase emailMessageSender = new EmailMessageSender();
    emailMessageSender = new MessageSenderPlaceholderParserDecorator(emailMessageSender);
    emailMessageSender = new MessageSenderPlaceholderFormatterDecorator(emailMessageSender);

    List<MessageSenderBase> MessageSenders = new List<MessageSenderBase>();
    MessageSenders.Add(emailMessageSender);
    MessageSenders.Add(new HttpPostMessageSender());

    foreach (var sender in MessageSenders)
    {
        sender.Execute(message);
        Console.WriteLine("");
    }

    Console.WriteLine("The final message is:\n{0}", message.Template);
    Console.WriteLine("\n\nDone...\n\n");
}

It’s exactly the same code, with some additional lines added to it.

  • Line 6 shows a new template in the message. You can see the placeholders {{Sex}} and {{BestGameEver}}.
  • Line 8 & 9 show an additional property in the TemplatedMessage, knowing PlaceHolders, which is of type Dictionary<string, string>
  • Line 11 shows the initialization of the EmailMessageSender, which hasn’t changed since last post.
  • Line 12 shows the initialization of a decorator, to parse the placeholders and put in proper text from the PlaceHolders dictionary. As the decorator pattern defines, this decorator wraps the
  • Line 13 shows an additional decorator, which replaces values that our customer doesn’t understand. Our customer doesn’t understand “male”, so the MessageSenderPlaceHolderFormatterDecorator replaces its values.
  • Line 16 shows the previously instantiated EmailMessageSender being added, wrapped by two decorators.

Decorator pattern and a rewrite of the template method
So without changing anything in the current MessageSenderBase class or derivates, we want to add additional functionality to perform the parsing and formatting of the placeholders. I chose to implement the decorator pattern, which is a wrapper around the original class, where both have the exact same interface. A really nice decorator example of it can be found on Ruchit Surati his weblog.

The decorator normally has an interface with a public method. Every class that implements this interface has to implement the method, as do the decorators. Our public method is the Execute method, so we’ll override that method. In the original base class, it was the template method, calling the abstract methods Initialize, SendLead and Cleanup. We don’t need this behavior anymore, so we’ll break it. Instead, we’ll use it again to recreate it as an alternative template method. We’ll now make it call a new abstract method called Decorate and after that, run the Execute method on the MessageSender we are wrapping. We’ll also override and seal the SendMessage method, because our decorators never send messages.

The end result is shown in the Visual Studio class diagram below. Normal UML diagrams show the association from the MessageSenderDecorator to the MessageSenderBase a bit clearer; Visual Studio shows it as either a reference without a property, or a property without a clear reference. I’m mentioning this because from the perspective of the decorator pattern, this is an important reference. It shows the intent that we wrap the original MessageSender inside our decorator.

TemplateMethodPatternAdvanced

The code for the decorator base class.

public abstract class MessageSenderDecorator : MessageSenderBase
{
    protected MessageSenderBase MessageSender { get; private set; }

    public MessageSenderDecorator(MessageSenderBase messageSender)
    {
        MessageSender = messageSender;
    }

    // This method needs concrete implementation
    protected abstract void Decorate(TemplatedMessage message);

    // Close the SendMessage method, decorators don't send messages!
    protected sealed override void SendMessage() { }

    public override void Execute(TemplatedMessage message)
    {
        Decorate(message);
        MessageSender.Execute(message);
    }
}

Now we’ll implement the first decorator.

public class MessageSenderPlaceholderParserDecorator : MessageSenderDecorator
{
    public MessageSenderPlaceholderParserDecorator(MessageSenderBase messageSender) : base(messageSender) {    }

    protected override void Decorate(TemplatedMessage message)
    {
        message.Template = ParseTemplate(message.Template, message.PlaceHolders);
    }

    private string ParseTemplate(string template, Dictionary<string, string> placeHolders)
    {
        foreach (var placeholder in placeHolders)
        {
            var key = string.Format("{{{{{0}}}}}", placeholder.Key);
            var value = placeholder.Value.ToString();

            template = template.Replace(key, value);
        }

        return template;
    }
}

As you can see, our real decorator implementation now implements the Decorate method, which we had to implement based on our base class. What this class do is simply replace every placeholder with the actual value. Going back to our first code snippet of the static Main method, you can see that we first wrap the EmailMessageSender into the decorator to parse all placeholders. Then we wrap it inside the second decorator, for parsing all values of the placeholders. If we turn this around, first the template message will be parsed, and only then the values in the PlaceHolders dictionary will be replace. This is of course too late, and this is a bit of a downside to the decorator. When writing completely procedural code, not many developers would make this mistake. With the decorator pattern, you’ll have to think a bit about it. The intent here isn’t as clear as you’d want it to be.

Conclusion
It’s always hard for new developers to write software like this. From my own experience, when first coming into contact with design patterns, you start to search for a design pattern based on a problem you have. After a lot of experience with some design patterns, you’ll start thinking the other way around. Instead of starting with a problem and finding a good design pattern that solves it, you’ll immediately start thinking about a design pattern that matches the problem you’re solving. Again, this is experience and takes practice. Try playing around with design patterns until you know them and know what they do. It’s not that important to be able to draw them out in a UML class diagram, from the top of your head. As long as you can remember which problems they solve and how you should roughly implement them.

Speaking of finding the right design pattern for a problem; this could very likely be solved in multiple ways, with different patterns. But it’s an example of how a problem could be solved using design patterns. I still have to completely implement this into our system and might come up with alternate solutions altogether. But I started this as a proof of concept and it seemed nice enough to blog about it. I hope you learned something from it, because that is still the reason for me to blog! ;-)

Download the source here.

Template Method Pattern example

This blogpost is part of a series

  1. Template Method Pattern explanation
  2. Template Method Pattern example
  3. Template Method Pattern advanced

So in my previous post I explained how I change the template method pattern a bit with protected abstract methods. In this post I’ll explain why I used this pattern and how I chose to implement it.

Requirements
At my current employer we send a lot of messages to customers. It varies per customer how message are being send. Some want a simple email, others want an xml document in their email, others want an xml document over HttpPost and others want us to send the message directly into a customers system, for example SalesForce. Most customers only have one option, some customers want multiple options.

When the software was first build, we only did send messages via email. A very simple solution was build. As more and more variations were required, a better solution was required. In our system, information is gathered, which is being inserted into the messages we send. We needed templated messages which contain placeholders. However, as some customers receive XML fed directly into their system, we needed to change some placeholder values, as not every system understands our values “male” and “female”, but rather have “1” or “0” for these values. Technical requirements are also important. We need to be able to store a successful or failed result to a datastore and needed to log exceptions as well.

First, we’ll have a look at how we solve different transport mechanisms. Additional requirements for templates will be explained in another post, where we’ll add the decorator pattern and implement an additional template method pattern.

Perhaps you’ll understand better what I implemented, if I show you the code that is executed to actually send out everything. In our system, we dynamically define which modules are being executed, in the following code I’ve defined a message sender for email and HttpPost.

static void Main(string[] args)
{
    TemplatedMessage message = new TemplatedMessage();
    message.Identifier = Guid.NewGuid();
    message.EmailAddress = "dvdstelt@gmail.com";
    message.Template = "Dude!";

    List<MessageSenderBase> MessageSenders = new List<MessageSenderBase>();
    MessageSenders.Add(new EmailMessageSender());
    MessageSenders.Add(new HttpPostMessageSender());


    foreach (var sender in MessageSenders)
    {
        sender.Execute(message);
    }

    Console.WriteLine("\n\nDone...\n\n");
}

First the message is defined. It contains a guid for reference, an email address and a template. The template is the actual message. Then we initialize the two message senders and execute these one at a time in the foreach loop. Let’s have a look at the implementation of the base class.

public abstract class MessageSenderBase 
{ 
    protected TemplatedMessage Message { get; private set; }

    public virtual void Execute(TemplatedMessage message) 
    { 
        Message = message;

        Initialize(); 
        SendMessage(); 
        CleanUp(); 
    }

    protected abstract void SendMessage();

    private void Initialize() 
    { 
        if (Message == null) throw new InvalidOperationException("Message cannot be null"); 
        Console.WriteLine("Initializing {0} for MessageId [{1}].", this.GetType().Name, Message.Identifier); 
    }

    private void CleanUp() 
    { 
        Console.WriteLine("Cleaning up {0} for MessageId [{1}].", this.GetType().Name, Message.Identifier); 
        Console.WriteLine("\tSaving state changes to datastore..."); 
        Console.WriteLine("\tSaving result to logfile..."); 
    } 
}

The base class of course cannot be instantiated, so we made it abstract. The message that was created in the first codeblock, is stored in a protected property (line 3), so we don’t have to pass it to every single method. Normally I don’t like vague global variables, but as it’s protected, I don’t see real harm. The SendMessage method is the abstract method that the derived classes must use to write code that they are responsible for. The Initialize method has a guard for a proper message, some might want this to be in the Execute method.

The Initialize and CleanUp method don’t do anything in the above code, but normally you’d use those for logging, storing state and exception handling. We have Enterprise Library code there for logging, and we log the current progress to a trace listener, rolling textfile and database. With the regular trace listener we can use DebugView from Sysinternals for live tracing.

The Execute method is the only public method. It is the method that will be executed and used to run every method in the right order. This will always run the SendMessage method of a derived class, simply because this base class has no implementation. So let’s have a look at our email sender.

public class EmailMessageSender : MessageSenderBase
{
    protected override void SendMessage()
    {
        Console.WriteLine("I'm sending the message via email.");
    }
}

This could not be a lot simpler. Of course the actual implementation isn’t here, but that’s the point of the example. There’s no other code in this class, but the code that’s related to sending the message over email. This is completely according to the Single Responsibility Principle. When a customer requires an additional way of sending the message, we don’t need to change any code. We simply add another class with the required functionality. That’s Open/Closed Principle for you!

I hope you understand why I like this implementation of the Template Method Pattern. For deriving classes, it’s completely clear what to implement. For external applications, it’s completely clear what to execute. In the last part of the Template Method Pattern series, we’ll introduce additional functionality and solve one problem with the decorator pattern and another template method pattern implementation. That post also includes a download if you want to play around with the code.

Template Method Pattern explanation

This blogpost is part of a series

  1. Template Method Pattern explanation
  2. Template Method Pattern example
  3. Template Method Pattern advanced

I’ve recently read a post about someone who hated the Template Method Pattern, because its intent wasn’t revealed. When based on the many examples out there, you might agree with this. First let’s see what the theoretical intent of the pattern is. You can look it up on wikipedia, but recently I’ve come across sourcemaking.com where a lot of patterns are described and I really like that site! Besides a good theoretical explanation it also has examples in many languages. About the intent of the Template Method Pattern it says:

  • TemplateMethodPatternSimpleDefine the skeleton of an algorithm in an operation, deferring some steps to client subclasses. Template Method lets subclasses redefine certain steps of an algorithm without changing the algorithm’s structure.
  • Base class declares algorithm ‘placeholders’, and derived classes implement the placeholders.

So you define a skeleton and derived classes have to implement the placeholders. The problem with the default pattern is that everything is public. This is something I don’t like myself. I’d rather have a protected and abstract skeleton so that derived classes exactly know what to implement, but external classes only see the public template method from the base class.

public abstract class AbstractClass
{
    protected abstract void StepOne();
    protected abstract void StepTwo();
    protected abstract void StepThree();

    public void TemplateMethod()
    {
        StepOne();
        StepTwo();
        StepThree();
    }
}

As you can see the skeleton (the StepOne, StepTwo & StepThree methods), is protected and abstract. Protected means the methods are private for outsiders, only derived classes can see the methods. Abstract means it has no implementation, but derived classes must implement it. The TemplateMethod however is public and can be called. Let’s have a look at an implementation.

public class ConcreteClass : AbstractClass
{
    protected override void StepOne()
    {
        Console.WriteLine("Inside Step 1");
    }

    protected override void StepTwo()
    {
        Console.WriteLine("Inside Step 2");
    }

    protected override void StepThree()
    {
        Console.WriteLine("Inside Step 3");
    }
}

Here you can see that the template method is nowhere to be seen, but the abstract methods were implemented. When the template method is executed, all three methods will be called. In a console application this would look like this.

static void Main(string[] args)
{
    AbstractClass myObject = new ConcreteClass();

    myObject.TemplateMethod();

    Console.WriteLine("Finished, press a key to continue...");
    Console.ReadKey();
}

This is of course again one of the over simplified examples, in a following post I will show a concrete example that I had to develop for the company I work for.

nServiceBus synchronously

When you read a title like this, everything that makes you a developer should start worrying. Because nServiceBus is build on top of the concept of asynchronous messaging. Normally, it does not support the request/reply communication pattern as you would normally understand this pattern. You are able to send a reply message to the originator, the application that initially sent you the message. But this is inherently asynchronous.

However… With the company I work for, we’re investing a lot of time on messaging. One application needed to call a component that supported this asynchronous messaging. The application itself however is very linear and was very, very hard to interrupt, send a message and have a message handler wait for the result. This really required a Saga and this was too much work at the time. We already had plans for a refactoring where we’d introduce a Saga, but we needed the functionality that called out this other component now. So we created a small piece of code that actually waits for nServiceBus te receive the reply. After this the normal flow of the application can continue.

Again, I really need to clarify that this was a temporary solution and eventually we fixed this by refactoring the code and support a Saga, a long running process that was persisted while waiting for the response.

Here’s the code to do it though

DataResponseMessage response = null;

RequestDataMessage message = new RequestDataMessage() { DataId = g, SomeMessage = "Whatever" };

var synchronousHandle = Bus.Send(message)
                            .Register(asyncResult =>
                            {
                                NServiceBus.CompletionResult completionResult = asyncResult.AsyncState as NServiceBus.CompletionResult;
                                if (completionResult != null && completionResult.Messages.Length > 0)
                                {
                                    // Always expecting one IMessage as reply
                                    response = completionResult.Messages[0] as DataResponseMessage;
                                }
                            }
                            , null);

synchronousHandle.AsyncWaitHandle.WaitOne();

Console.WriteLine("Reply : {0}", response.ResponseMessage);

For completeness, I’ll include the message handler from the component the message was sent to. This is normal nServiceBus code.

public class RequestDataMessageHandler : IHandleMessages<RequestDataMessage>
{
    public IBus Bus { get; set; }

    public void Handle(RequestDataMessage message)
    {
        var response = Bus.CreateInstance<DataResponseMessage>(m => 
        { 
            m.DataId = message.DataId;
            m.ResponseMessage = "I got the message : " + message.SomeMessage;
        });

        Bus.Reply(response);
    }
}
How to unit test a method that has void as return type

How do I test a method that returns void? For example a method like this.

public void Process(int leadId)
{
    decimal price = _calculator.CalculateNormalLead(leadId);

    Lead lead = new Lead(leadId, price);

    _leadRepository.Save(lead);
}

How to test what the state of the lead object is? This is a question that comes up a lot of the time. It has many different answers. Some options:

  • Return a type anyway, even though you don’t use it. Or expose a property with the result. This are design changes that are only neccesary for testing. I’m sure that’s not what we want.
  • Check what the method changed, like records in the database. That’s a slow integration test.
  • Split the methods so that one portion of it returns something, and the second method just takes the result and uses it. This way however, you’ll have to make two calls to your class, which I think is even worse than the previous two options!
  • Expose internals by using the InternalsVisibleTo attribute. But now you have to make changes to the design of your class again, making private methods or properties internal.
  • Another option is to accept you can’t test everything. What you can however check is
    • Check if it throws exceptions
    • Check if it changes mutable objects you pass in as parameters
    • Do interaction based testing. Either write mocks or use a mocking framework to verify if calls were made to another method.

This last thing is something we can really use. Now this might not always work, but in our case it’s very usable. Imagine we have a repository that in production kind of works like this.

public class LeadRepository : ILeadRepository
{
    public void Save(Lead lead)
    {
        throw new NotImplementedException("Sorry, this is for an integration test.");
    }
}

Now I said kind of, because I don’t want to bother you with a lot of database and query stuff. But our lead enters this class and we’d really like to have this one! This repository implements an interface and the class is injected into the Invoicing class, where our Process method is. For the complete example, check the solution. But for now, check out this FakeRepository I created to use during testing.

public class FakeRepository : ILeadRepository
{
    public Lead CreatedLead { get; private set; }

    public void Save(Lead lead)
    {
        CreatedLead = lead;
    }
}

The only thing this repository does, is put the lead it receives into a property of the FakeRepository class. Remember that the repository in production does not have this property, so normally it’s never exposed.

Now we can write a test that injects our own fake objects and when asserting, we use the property of our FakeRepository to check the state of our lead.

[TestMethod]
public void Does_MapPropertiesCorrectly_When_CalculatingALead()
{
    // Arrange
    int leadId = 1;
    decimal leadPrice = 0.5m;
    FakeRepository fakeRepository = new FakeRepository();
    FakeCalculator calculator = new FakeCalculator(leadPrice);

    // Act
    Invoicing invoicing = new Invoicing(calculator, fakeRepository);
      invoicing.Process(leadId);

    // Assert
    Lead result = fakeRepository.CreatedLead;
    Assert.AreEqual(leadId, result.LeadId);
    Assert.AreEqual(leadPrice, result.Price);
}

See how easy it sometimes is? Download the complete solution here.

Locking in SQL Server and the nolock and readpast hints

I’ve written about transactions, the TransactionScope in .NET before.

Still I was recently surprised with the comment that I had to use the READPAST in my queries. So I started investigating and felt I had to blog about this. First of all, I’m not going to discuss every option here, just a few basics so you get what the differences are.  If you want to know  more, check out the BOL/MSDN documentation. Here’s a good starting point.

I’ve created a demo to show locking mechanisms. The database I used was the only one at hand at the time I wrote this, and it’s the Cookbook database from Dennis Doomen his Silverlight Cookbook example. It only has one table and a full select outputs the following result in my case.

cookbookdatabase

Shared Locks
First I want to tell about Shared Locks. Normally when you start a transaction like the code below, you place a shared lock until the transactions is over. A shared lock means someone else is still able to read the data you’ve locked, they just now allowed to update it. Because you want to be sure that the data you read, is still the same at the time you commit a transaction (to update data, for example).

SqlCommand cmd = new SqlCommand();
cmd.Connection = GetConnection();
cmd.CommandText = "select * from Recipes with (readpast)";
var reader = cmd.ExecuteReader();

The GetConnection() method initiates and opens a connection to my database.

ReadCommitted transaction
A regular transaction is done with isolation level ‘ReadCommitted’. This means that you cannot read data that has an exclusive lock on it. This is achieved when you update a row and another transaction tries to read it while you still have your transaction open. Here’s the update code.

TransactionOptions transactionOptions = new TransactionOptions();
transactionOptions.IsolationLevel = IsolationLevel.ReadCommitted;

using (TransactionScope scope = new TransactionScope(TransactionScopeOption.RequiresNew,transactionOptions))
{
    SqlConnection con = new SqlConnection();
    con.ConnectionString = ConnectionString;
    con.Open();

    SqlCommand cmd = new SqlCommand();
    cmd.Connection = con;
    cmd.CommandText = "update Recipes set Description = 'ChangedDescription' where Id = 1";                
    cmd.ExecuteNonQuery();
}

And here’s the code in another transaction that tries to read it.

SqlCommand cmd = new SqlCommand();
cmd.Connection = GetConnection();
cmd.CommandText = "select * from Recipes";
var reader = cmd.ExecuteReader();

while (reader.Read())
{
    Console.WriteLine("Description : {0}", reader["Description"].ToString());
}

The second method should not be able to retrieve data from the table until the transactions is closed. The original transaction can place multiple kinds of locks, including a lock that concerns the entire table. The select query I wrote just simply retrieves everything, and as the first row (at least) is locked, it’s not able to retrieve anything. If you add a where clause to filter out just the second row, it should be able to load the data anyway.

NOLOCK hint
So with the NOLOCK / READUNCOMMITTED hint/isolation-level, you tell your transaction (or query) that you want to read dirty data. Even though the transaction hasn’t been committed yet, you still want to read its data. A problem can occur that when the other transaction is rolled back, you’ve loaded data that isn’t there anymore. Worse yet, when SQL Server decides to shift data between different pages, you might simply loose a lot of data because it’s not there!

SqlCommand cmd = new SqlCommand();
cmd.Connection = GetConnection();
cmd.CommandText = "select * from Recipes with (nolock)";
var reader = cmd.ExecuteReader();

The result is that you get the change from the update statement. But because we never commit anything, everything is rolled back and we’ve read a dirty state.

Description : ChangedDescription
Description : Description2
Description : Description3
Description : Description4

READPAST hint
Now with the READPAST hint you’re telling SQL Server you do NOT want to read dirty data. Instead, it skips the rows that are locked.

SqlCommand cmd = new SqlCommand();
cmd.Connection = GetConnection();
cmd.CommandText = "select * from Recipes with (readpast)";
var reader = cmd.ExecuteReader();

Result is first row not being shown at all! So when we change the update query to ‘where Id = 1 or Id = 2’ we get one row less in the other select query.

Description : Description2
Description : Description3
Description : Description4

Conclusion
Be very, very aware of the problems you might introduce when using these table hints!

Download the demo solution here.

Value of Unit testing

There are probably uncountable amount of articles, posts and arguments on to why Unit Testing is so valuable. I just found a nice example that would’ve (or at least should’ve) been caught using Unit Tests. The following code was a bit adjusted to the need of this post, but has a mistake. See if you can spot it.

public class Discount
{
    public Discount(decimal percentage, DateTime startDate, DateTime endDate)
    {
        endDate.Add(new TimeSpan(23,59,59));

        Percentage = percentage;
        StartDate = startDate;
        EndDate = endDate;            
    }

    public decimal Percentage { get; private set; }
    public DateTime StartDate { get; private set; }
    public DateTime EndDate { get; private set; }
}

If you haven’t spotted it, I’d advise you to write a unit test to show that it’s failing. Here’s mine.
I’ve used FluentAssertions by the way, a library I love that helps me assert my code more easily.

[TestMethod]
public void Does_MapPropertiesCorrectly_When_CreatingNormalDiscount()
{
    // Act
    Discount discount = new Discount(5, new DateTime(2001, 9, 11), new DateTime(2011, 9, 11));

    // Assert
    discount.EndDate.Should().Be(new DateTime(2011, 9, 11, 23, 59, 59));
}

What is says is that it’s still 2011/9/11 00:00:00 instead of at the last second of that day. The problem here is that the endDate.Add method adheres to the framework guidelines. That is that you can’t edit an object you get passed by external source, only return new values. So the Add method returns a new DateTime object. We can make the test working with the following adjustment.

public class Discount
{
    public Discount(decimal percentage, DateTime startDate, DateTime endDate)
    {
        endDate = endDate.Add(new TimeSpan(23,59,59));

        Percentage = percentage;
        StartDate = startDate;
        EndDate = endDate;            
    }

    public decimal Percentage { get; private set; }
    public DateTime StartDate { get; private set; }
    public DateTime EndDate { get; private set; }
}

The only change I made was on line 5.

Scrum guide 2011

scrumguideIn July a new update was provided to the Scrum Guide by Jeff Sutherland and Ken Schwaber. There are a few adjustments that are really nice, for example project grooming was added.

One quote from the guide

The Scrum framework consists of Scrum Teams and their associated roles, events, artifacts, and rules. Each component within the framework serves a specific purpose and is essential to
Scrum’s success and usage.

Language was added to emphasize that Scrum is an all or nothing proposition. You either do all the practices, or you’re not doing Scrum. I have to agree on it, after visiting a Scrum training by Jeff Sutherland. Before the training it was my believe that with knowledge from the past and by trial and error the framework was build. Instead due to a lot of studies, whitepapers and other resources it was how the framework was initially introduced at OOPSLA’95. During the two day course, Jeff Sutherland took little over half a day to emphasize this. Also by providing lots of examples on how Scrum succeeded and how we should implement and use Scrum.

I’m a believer and want and will to advocate Scrum wherever I come and to whomever may ask. Winking smile

Publish / Subscribe with nServiceBus tutorial

When starting to dig into nServiceBus, you’ll notice almost every single example is executed via the NServiceBus.Host.exe instead of doing it in-process. In my opinion this might be more likely on the receiving side (the subscriber) that just does some stuff in the background. But on the sending side (the publisher) this is mostly triggered by an interactive process, like a website or application where a user triggers the publishing of the message.

My problem was that I had an interactive process triggering the message and the receiving side was a Windows application. So not much use for the nServiceBus host here. Now there’s a lot of documentation and videos on why someone would want to use nServiceBus and how to use its principles. There’s also quite some documentation on different options, but binding them together in a tutorial so you can really get a grasp on what’s happening and why this is happing is something I really missed. And as I like explaining stuff, here’s my version.

Intoduction

In this tutorial we’ll create 3 projects in a single solution.

  1. One class library (a .dll) that will contain the message.
  2. One console application for the publisher.
  3. One console application for a subscriber.

The publisher will send messages without knowing if none, one or multiple subscribers are interested in that message. The pub/sub sample that comes with nServiceBus shows you how you can subscribe via configuration and code and how different subscribers can process a ‘single’ message differently. This is also explained in the two online videos at the official site or download the videos.

Creating the message

The smartest thing you can do, when defining event messages with nServiceBus, is use interfaces, which is explained in the mentioned videos. As an example we’ll create a message for the event when an order is processed. First create a class library named “PubSubTutorialMessages” and add a single class called IOrderProcessed. Remember that this is an interface.

public interface IOrderProcessed : IMessage
{
    int OrderId { get; set; }
    int CustomerId { get; set; }
}

I like to put in as little information as possible, but that’s a personal preference and also with the thought that you should not put information in messages that can change. Of course if the other system has no knowledge of your original database, it can’t query this information. An idea is to have a webservice provide this information, instead of putting every bit of information in the message. But it always depends and I make decisions on this with every single message I need to send/publish.

Creating the publisher

This is all we need for our first solution. Now we’ll build the publisher. First we need a new project, create a console application this time with the name “Publisher”. Add some references first

  1. NServiceBus.dll
  2. NServiceBus.Core.dll
  3. log4net.dll
  4. PubSubTutorialMessages (our own project)

Now we’re set up and we’ll start writing code to host nServiceBus ourselves. If you run into problems at the beginning, there are two things you should check.

  1. Did you add a using statement for NServiceBus?
    If not, the extension methods for DefaultBuilder, XmlSerializer, etc. won’t be visible
  2. Make sure your console application does not use the .NET Framework 4 client profile.
    Right-click the project, select properties and check the target framework on the Application tab.
using NServiceBus;
using PubSubTutorialMessages;
IBus bus = NServiceBus.Configure.With()
    .DefaultBuilder()
    .XmlSerializer()
    .MsmqTransport()
        .IsTransactional(true)
    .UnicastBus()
    .MsmqSubscriptionStorage()
    .CreateBus()
    .Start();

Here you can see how I configured my bus in code. There’s not much to say about this, it’s really basic. Xml serialization, Msmq, Unicast (the only available option), we use MsqmSubscriptionStorage for registering who subscribes to what and we’re telling the IoC to create the bus. Additionally you can add .Log4Net() to enable logging. By default the console window will be filled with debug messages that might help out. Check out the documentation for more info.

This needs some configuration, which we’ll add next in our app.config

<?xml version="1.0"?>
<configuration>
    <configSections>
        <section name="MsmqTransportConfig" type="NServiceBus.Config.MsmqTransportConfig, NServiceBus.Core"/>
        <section name="UnicastBusConfig" type="NServiceBus.Config.UnicastBusConfig, NServiceBus.Core"/>
        <section name="Logging" type="NServiceBus.Config.Logging, NServiceBus.Core" />
    </configSections>

    <MsmqTransportConfig
        InputQueue="PublisherQueue" 
        ErrorQueue="error"
        NumberOfWorkerThreads="1"
        MaxRetries="5"/>


    <Logging Threshold="WARN" />
</configuration>

The config sections are default .NET behavior. What we see is the MsmqTransportConfig configuration.

  1. InputQueue is the queue where our publisher will be accepting subscription requests on. Our subscriber will post an initial message here.
  2. ErrorQueue is simply the queue where errors will appear in. This can be locally or a remote machine.

On the official website you can find more information on msmq settings and on how to handle the error queue.

Now we need to send the message. We’re working with an interface for our messages and we can’t instantiate these. nServiceBus can do this for us however.

var message = bus.CreateInstance<IOrderProcessed>();
message.CustomerId = 10;
message.OrderId = 15;

bus.Publish(message);

This is all you need to do now to publish messages. When you publish them, they’ll disappear into thin air, because no one is listening currently. We need a subscriber for that.

Creating the subscriber

Create another console application called “Subscriber” and add the 4 references to it as with the publisher. After that we have to configure the bus in code first, but this time it needs a one additional line.

IBus bus = NServiceBus.Configure.With()
               .Log4Net()
               .DefaultBuilder()
               .XmlSerializer()
               .MsmqTransport()
                   .IsTransactional(true)
               .UnicastBus()
                   .LoadMessageHandlers()
               .MsmqSubscriptionStorage()
               .CreateBus()
               .Start();

Console.WriteLine("Press any key to quit...");
Console.ReadLine();

You can see I added a call to the LoadMessageHandlers() method. This is because the subscriber must process the messages sent and with this line, nServiceBus will iterate over all assemblies and classes to find out which ones implement the IHandleMessages<T> interface. So what we should do is implement this interface first. On a side, as you can see that I simply wait for a keypress in this demo, as the class the will implement the IHandleMessages<T> interface will handle the messages async.

public class TutorialMessageHander : IHandleMessages<IOrderProcessed>
{
    public IBus Bus { get; set; }

    public void Handle(IOrderProcessed message)
    {
        Console.WriteLine(String.Format("Processed order {0} for customer {1}", message.OrderId, message.CustomerId));
    }
}

We implement the interface and specify T as IOrderProcessed, because that’s the message the publisher will send. Put the cursor over the IHandleMessages<IOrderProcessed> and press CTRL + . and you’ll get a widget in Visual Studio 2010 with the option to implement the interface, like the image below.

ctrlpunt

After you did this, you can write the code to handle the message. In my case, I simply write it to the console. The funny thing is, because everything happens asynchronously, you have no idea when this will be outputted. This normally isn’t a problem at all, except for when logging is turned on. Because logging and our own Console.WriteLine will happen asynchronously, our own line will be somewhere inside the nServiceBus messages. You can turn of logging by removing the .Log4Net() line or setting the log level way lower, as you can read in the documentation (bottom of the page).

Now all we need is to configure our subscriber.

<?xml version="1.0"?>
<configuration>
    <configSections>
        <section name="MsmqTransportConfig" type="NServiceBus.Config.MsmqTransportConfig, NServiceBus.Core" />
        <section name="UnicastBusConfig" type="NServiceBus.Config.UnicastBusConfig, NServiceBus.Core"/>
        <section name="Logging" type="NServiceBus.Config.Logging, NServiceBus.Core" />
    </configSections>

    <MsmqTransportConfig
    InputQueue="SubscriberQueue"
    ErrorQueue="error"
    NumberOfWorkerThreads="1"
    MaxRetries="5"
  />

    <Logging Threshold="WARN" />
    
    <UnicastBusConfig>
        <MessageEndpointMappings>
            <add Messages="PubSubTutorialMessages" Endpoint="PublisherQueue"/>
        </MessageEndpointMappings>
    </UnicastBusConfig>

</configuration>

Let’s go over this a bit.

  1. The MsmqTransportConfig is about the same, except for the InputQueue. This states the queue in which we want to receive messages that concern us! So the publisher will put messages it publishes, in this queue, after we subscribed ourselves.
  2. Logging is turned down and only shows warning messages.
  3. The UnicastBusConfig configuration has two important options.
    1. Messages is set to PubSubTutorialMessages.
      This tells nServiceBus that all messages in the PubSubTutorialMessages.dll assembly should be routed to this subscriber.
    2. Endpoint is set to PublisherQueue.
      This is the endpoint the publisher is using to listen to new subscriptions.

If the publisher is on ServerA, we should set UnicastBusConfig’s Endpoint to PublisherQueue@ServerA. If you want another subscriber, copy the subscriber project and change the InputQueue. That’s all.

Now you should be able to run the application and have it send messages. Here’s the solution so you can test it out for yourself.

ClickOnce deployment and customHostSpecified error

Some time ago now I wrote about doing manual ClickOnce deployment using the command line and FinalBuilder. One of my readers posted a reaction about the following error.

The customHostSpecified attribute is not supported for Windows Forms applications.

I did not have that specific error at the time, and the reader didn’t follow up on my reactions. But now I had the problem myself. Luckily I found the answer pretty fast. I used the old version of mage.exe from the .NET Framework 2.0 SDK. I needed to use the .NET Framework 4.0 SDK mage and my problem was solved. You can find that version right here:

C:\Program Files (x86)\Microsoft SDKs\Windows\v7.0A\Bin\NETFX 4.0 Tools\mage.exe

Silverlight vs. Windows Forms or ASP.NET

Some time ago I went to a great presentation, organized by DotNed, held at Vicrea and given by Dennis Vroegop and Thomas Huijer. At some point Dennis Vroegop mentioned that he saw a lot of old Windows Forms developers, create WPF applications like they were still developing Windows Forms applications. What Dennis meant was that these developers were handling click events the same way they did before. At first I thought that he was talking about boring line of business (LOB) applications with just textboxes and buttons in them, without a cool design or something different in user experience (UX). In a series of posts I’ll see if I can lighten up both of our points. So this is not really a one versus the other, but more on showing you how Silverlight can help you create a better user interface and have more powerful databinding.

First I’m going to explain what I meant by creating a normal ListBox with layout that’s extremely hard to accomplish in Windows Forms. We’ll keep it extremely simple. After that I’ll show how you can do this with Master-Detail as well, very easily. And later I’ll show you how to do this with an MVVM implementation.

1. Creating a class and repository
We need some data and we normally get this from a database using webservices. In this example I’ll create a repository class, as I said I’m going to keep it extremely simple. Building webservices via WCF is discussed extensively throughout this weblog elsewhere.

We’ll take on of my favorite subjects, games. Let’s create a class that contains our data.

public class Game
{
    public string Name { get; set; }
    public int YearOfRelease { get; set; }
    public string Developer { get; set; }
    public string ImageUrl { get; set; }
}

Now let’s create our repository.

public class Repository
{
    public static ObservableCollection<Game> GetAllGames()
    {
        return new ObservableCollection<Game>()
        {
            new Game() { Name = "Assassin's Creed : Brotherhood", Developer = "Ubisoft", YearOfRelease = 2010, ImageUrl = @"http://upload.wikimedia.org/wikipedia/en/2/2a/Assassins_Creed_brotherhood_cover.jpg" },
            new Game() { Name = "Call of Duty: Modern Warfare 2", Developer = "Infinity Ward", YearOfRelease = 2009, ImageUrl = @"http://upload.wikimedia.org/wikipedia/en/d/db/Modern_Warfare_2_cover.PNG" },
            new Game() { Name = "FIFA 11", Developer="Electronic Arts", YearOfRelease = 2010, ImageUrl = @"http://upload.wikimedia.org/wikipedia/en/9/97/Fifa11_keyart_uk-492x600.jpg" },
            new Game() { Name = "Quake", Developer = "id Software", YearOfRelease = 1996, ImageUrl = @"http://upload.wikimedia.org/wikipedia/en/4/4c/Quake1cover.jpg" },
            new Game() { Name = "Half-Life", Developer = "Valve", YearOfRelease = 1998, ImageUrl = @"http://upload.wikimedia.org/wikipedia/en/f/fa/Half-Life_Cover_Art.jpg" }
        };
    }
}

I’ve put these two classes inside the Silverlight Application I’ve created. Now that we’ve got our data, let’s first create some layout that can present our games.

<UserControl x:Class="BindingExample.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"
    mc:Ignorable="d"
    d:DesignHeight="300" d:DesignWidth="400">
    <StackPanel Orientation="Horizontal" VerticalAlignment="Top" Margin="10">
        <ListBox x:Name="gamesListBox" ItemsSource="{Binding}" Width="300" Height="300">
        </ListBox>
    </StackPanel>
</UserControl>

This is very basic and it doesn’t even show the right results as you can see in the first image below. Let’s change the XAML so that it’ll show the results we’d normally expect.

WeirdData NormalData

<StackPanel Orientation="Horizontal" VerticalAlignment="Top" Margin="10">
    <ListBox x:Name="gamesListBox" ItemsSource="{Binding}" DisplayMemberPath="Name" Width="300" Height="300">
    </ListBox>
</StackPanel>

As you can see, the only thing changed is the added DisplayMemberPath attribute. But we can do this in Windows Forms as well. Let’s do some magic.

<ListBox x:Name="gamesListBox" ItemsSource="{Binding}" Width="300" Height="300">
    <ListBox.ItemTemplate>
        <DataTemplate>
            <StackPanel Grid.Column="1" Margin="3,0,0,0">
                <TextBlock Text="{Binding Path=Name}" FontWeight="Bold" Margin="0" Padding="0"/>
                <StackPanel Orientation="Horizontal" Margin="3,0,0,0">
                    <TextBlock Text="Released" Width="80" />
                    <TextBlock Text=": " />
                    <TextBlock Text="{Binding Path=YearOfRelease}" Width="50" Margin="0" Padding="0"/>
                </StackPanel>
                <StackPanel Orientation="Horizontal" Margin="3,0,0,0">
                    <TextBlock Text="Developer" Width="80" />
                    <TextBlock Text=": " />
                    <TextBlock Text="{Binding Path=Developer}" />
                </StackPanel>
            </StackPanel>
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>

DataTemplate_WithoutImage

Now this is nice. What’s happening here?

  1. We removed the DisplayMemberPath attribute, as we are going to very specifically define how we want to see the data.
  2. We’ve added a DataTemplate, which describes the visual structure of a data object, according to MSDN :-)
  3. Next we’ve defined some StackPanels and TextBlocks to define where and how to show the data.
    We’ve used more than one property from our Game class, some bold text and margins to make it more attractive.

I think this is very user friendly. Imagine a lot of customers in your database, some of them with names very alike or with offices in different locations. Instead of just seeing the name of the customer, you also get presented the location, etc. Now as these are games, there’s probably a little box art available somewhere on the web. Let’s show this as well. Imagine that instead of box art, you present photos of your customers their faces! ;-)

<ListBox x:Name="gamesListBox" ItemsSource="{Binding}" Width="300" Height="300">
    <ListBox.ItemTemplate>
        <DataTemplate>
            <Grid>
                <Grid.ColumnDefinitions>
                    <ColumnDefinition />
                    <ColumnDefinition />
                </Grid.ColumnDefinitions>
                <Image Source="{Binding Path=ImageUrl}" Width="50" Stretch="UniformToFill" Grid.Column="0" />
                <StackPanel Grid.Column="1" Margin="3,0,0,0">
                    <TextBlock Text="{Binding Path=Name}" FontWeight="Bold" Margin="0" Padding="0"/>
                    <StackPanel Orientation="Horizontal" Margin="3,0,0,0">
                        <TextBlock Text="Released" Width="80" />
                        <TextBlock Text=": " />
                        <TextBlock Text="{Binding Path=YearOfRelease}" Width="50" Margin="0" Padding="0"/>
                    </StackPanel>
                    <StackPanel Orientation="Horizontal" Margin="3,0,0,0">
                        <TextBlock Text="Developer" Width="80" />
                        <TextBlock Text=": " />
                        <TextBlock Text="{Binding Path=Developer}" />
                    </StackPanel>
                </StackPanel>
            </Grid>
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>

DataTemplate_WithImageAnd this results in a very simple but very nice ListBox with very usable items. And the best part is that you can still use gamesListBox.SelectedItem to get the complete Game object, as you’d expect.

Of course it’s even better to add the DataTemplate to a resource, which will result in the following XAML.

<UserControl.Resources>
    <DataTemplate x:Key="gameDataTemplate">
        <Grid>
            ...
        </Grid>
    </DataTemplate>
</UserControl.Resources>
<StackPanel Orientation="Horizontal" VerticalAlignment="Top" Margin="10">
    <ListBox x:Name="gamesListBox" ItemsSource="{Binding}" Width="300" Height="300"
             ItemTemplate="{StaticResource gameDataTemplate}" />
</StackPanel>
I hope this clarifies my point on how you can enhance your boring Line of Business (LOB) application with better usability for your end users.
Embedding images in an app_offline.htm

We have a public website running that we needed to take offline for maintenance. So we created an app_offline.htm file to put on the website. The result is, as we all (should) know, the website goes completely offline immediately. Every webpage and every file cannot be accessed from the web any longer.

The problem with this is that images also aren’t accessible anymore. One option is to place the images you need on another domain and link to those. I don’t like this solution to begin with, but our problem was that our website runs under SSL. You get an https:// url with that, resulting in the fact that if you try to access images from any other domain than the original site, you’ll get warnings in the browser. Something not preferred. End users might think the site isn’t secure or anything.

You have the option however, to embed images into your HTML as Base64 encoded images. This looks like this:

<img src="data:image/gif;base64,R0lGODlC9AIcAAAAAAAAAMwAAZgAAmQAAzA..." />

Of course I kept the Base64 image very short, because they can result in insane long strings. Question however is, how do you get the Base64 encoded string? Here to the rescue, the C# code. :-)

class Program
{
    static void Main(string[] args)
    {
        Image image = Image.FromFile(@"C:\temp\logo.gif");

        string result = ImageToBase64(image, ImageFormat.Gif);

        Console.WriteLine(result);
    }

    /// <summary>
    /// Images to base64.
    /// </summary>
    /// <param name="image">The image.</param>
    /// <param name="format">The format.</param>
    /// <returns></returns>
    private static string ImageToBase64(Image image, ImageFormat format)
    {
        using (var ms = new MemoryStream())
        {
            image.Save(ms, format);
            var imageBytes = ms.ToArray();

            var base64String = Convert.ToBase64String(imageBytes);

            return base64String;
        }
    }
}
Have fun!
Doesn’t take a genius to build massively scalable systems

I was just watching Bytes by MSDN where Billy Hollis interviews Ron Jacobs, Sr. Technical Evangelist for the Microsoft Server AppFabric platform. Billy Hollis asked him if it’s a big cliff to start using this awesome power that is AppFabric. Here’s what Ron said:

It’s not a big cliff. It’s similar to what you do now. I would say, the biggest thing is, first of all, you’ve got to get workflow. I know a lot of people look and they are like : “Workflow?” Trust me, it’s great! And once you get your grip on workflow, if you can write apps that work on Windows Workflow, on a local machine, you can throw that thing in the cloud, it will desume.

I have no idea what ‘desume’ is, but I guess it means ‘it will rock’ or something like that! And I agree!

But I don’t really have a clue to why you’d have to throw it in the cloud. I understand that Microsoft is betting big on the cloud and want all their evangelists to push the cloud into our brains. But what Ron Jacobs is talking about isn’t possible in the cloud right now, or at least not with AppFabric. Windows Server AppFabric and Windows Azure AppFabric might be more aligned in the future, but right now they’re definitely not.

Billy Hollis and Ron Jacobs interview HollisJacobs2

I think we’ve got some great new opportunities when using Windows Server AppFabric for hosting our applications. In the past I had some major issues with WF3 while I did not even know the technology that well. My concerns were

  • Hosting your workflows
  • Monitoring your workflows
  • Persisting your workflows

These three have all been solved by AppFabric. But how about that massively scalability that Ron Jacobs is talking about? When I first tried to look up what it took to get a cluster of AppFabric servers up and running, I could not find a lot of information on what to do. Until I discovered I actually did not have to do anything! Just make sure every single server is pointing towards the same database, has the same version of the workflows and you’re done!

So as the title says, it doesn’t take a genius to build a massively scalable system. Doesn’t mean you can brainlessly start building workflows and expect AppFabric to solve it all. You just don’t have to be a genius anymore.

Miracles still do happen

It’s been six weeks since my last blogpost. And although people could’ve kept up with the current situation via my Twitter account, I’ve decided to make one more post on what happened in the previous weeks, since people asked for it in comments and via other channels.

The past weeks have been very, very hard. The fact that my wife could die (which was enough stressful on its own), organizing a lot of help, talking to hundreds of people over the past few weeks, dealing with a lot of kind people offering help but also a lot of idiots, etc, demanded a lot of me. This resulted in that I did not have a single moment for myself to take my mind off of what was happening. My children were also very upset about what happened and tested me way beyond my limits. Which is very understandable, but doesn’t mean it was fun. I found out what it was to have your body and mind running on adrenaline and having the adrenaline run out. But so far about me…

Last Monday it was exactly 6 weeks ago and this Tuesday my wife was formally discharged from the rehabilitation center. She won’t receive any outpatient treatment either. The part of her skull which they removed still has to be put back, but that’s about it. In 4 weeks we’ll have an appointment with the rehabilitation specialist about how things are going and to see if we think we still need some help. How about that?

And to think that the hospital asked me to bring a photo-camera on the Wednesday after it happened; they brought our daughter to her mother and advised me to take pictures of them both. So that when my wife would never wake up again, our daughter would have pictures of herself and her mother for when she was grown up. Believe me, that message wasn’t received well by me. And the pictures aren’t nice either, because my wife was still in induced coma and got mechanical ventilation. Afterwards I heard they gave her a 5% change of ever waking up and some doctors were certain it would never happen at all. They came very close to not operating her at all, because of the prognosis.

Before the first week was over they removed the mechanical ventilation. When I came onto intensive care that they, she immediately spoke to me and asked where I had been. I can tell you, that was about the happiest event ever for me. After that she pushed herself really, really hard to get out of bed and do things herself. Before 4 weeks were over, she had already taken a shower and dressed herself before the nurses came in to help her.

She was on the waiting list to get into Rijndam for (inpatient) rehabilitation, but we asked if she could stay at home while waiting for her rehabilitation. When she got into Rijndam almost everyone asked themselves why she was there, that’s how good she was doing. So after a few days and some observation the rehabilitation specialist asked us if we were okay with the fact that she actually didn’t need any help at all anymore. There’s no physical loss in any way and also cognitive there seems to be nothing wrong.

So now she’s at home and we’re trying to pick up life again where we left it, almost as if nothing has happened. Of course it’s nothing short of a miracle. The neurologist and nurses who are working for dozens of years on neurology haven’t seen anything that comes close to what happened to my wife. They can’t explain how it could’ve happened that she recovered so well, especially with the severity of the two intracranial hemorrhages she had. All I can say is that a lot of people prayed for her and that I’m more certain of it than anything else in life that He has listened. He showed us that miracles still do happen.

Naomi, Bart and Emma with Marith Marith Me looking pretty tired

Worst day of my life

Today was most definitely the worst day of my life. I’ve decided to not use my weblog for personal matters, but this is an exception. Partly because I’ve talked on Twitter and MSN with a lot of folks about the pregnancy lately and partly because I need to spill my guts out on what happened. And maybe keep this for personal records so I can look up what happened in the future.

Last week, on Tuesday, my wife was taken to the hospital because of some stuff that doesn’t need to be mentioned here. It was because of high blood pressure. They kept her from Tuesday until Thursday and monitored her occasionally if everything was alright again. The send her home with an appointment for Monday morning to recheck if everything was alright.

This night, from Sunday to Monday, my wife felt a little pressure on her chest. We went to bed and a little later, around 12:00am she woke up because of the pain in her chest. She was really, really worried and told me I had to call the hospital. She had trouble breathing also. The hospital confirmed we should come.

So some time before 01:00am we arrived at the hospital and things started getting worse very rapidly. See hard major pain in the chest, constant pressure and had a hard time breathing. At some point the nurses were away, organizing stuff and I had the idea she fainted repeatedly. So I went to search for a nurse and a few minutes later four nurses gathered around my wife.

They then transported her to the delivery room because they have equipment there to monitor her and the baby. They gave her an intravenous for her high blood pressure. But the pain and breathing problems got worse and worse. They gave her an injection for the pain at around 02:00am for the pain, which seemed to really start kicking in around 02:30am. But instead of just removing the pain, it looked like she was seriously drugged. She spoke everything double (doublespeak) and didn’t respond very well to inquiries from either me nor the nurses.

At around 06:00am or so she had slept for almost the entire time. Occasionally she puked and spoke with doublespeak but almost immediately fell asleep afterwards. But at this time, the heartbeat of the baby started to faint. So the gynecologist was called and he arrived 15 minutes later or so. He felt the baby was asleep because of the drugs (the injection for the pain) and tried to wake it up. The heartbeat rose again, but he decided ten minutes later they’d do a Caesarean section after all.

They prepared her, moved her away to surgery and I had to put on some clothes so I could be with her. When I came in, no communication was possible with my wife at all. The baby was delivered and while I was with the baby, someone came in mentioning they noticed something and would put her to sleep. Also because she might choke in her own vomit if so would throw up again.

I went with the baby to the maternity ward where after a short time, the doctor came in mentioning my wife was put to sleep because she had a Intracranial hemorrhage.

I can tell you, my life came almost to a full stop at that moment.

I was later informed that she had two major intracranial hemorrhages and they needed to transfer her to Erasmus MC, a specialized hospital in Rotterdam. Multiple doctors went with the ambulance and the ambulance itself got police support to get there as quick as possible.

I’m now at home, ready to see my other three children who are at my brother-in-law. I went to Erasmus MC myself to check on my wife. She was in a three hour surgery where they removed a part of her skull and fixed one intracranial hemorrhage. The other was too deep into her brain to reach. The operation was successful, if you can call it that.

I’m going to the hospital tomorrow to check on my wife. She’s kept asleep right now with medication. They’ll stop the medication tomorrow and then we’ll have to wait and see if she’ll ever gain consciousness again. And if she does, in what state that will be.

Still in the first hospital is my new born daughter Marith, who might never know her mother. I’m seriously constantly praying if she will be alright, as He is the only one who can help her now.

More Posts Next page »