This is an old article by Ted Neward that I’ve been trying to find for ages, as the original website isn’t online anymore. Until I remember the WayBackMachine and found the original article. As the WayBackMachine doesn’t always remember (or keeps remembering) everything, I’m reposting the article here for safekeeping. If the owner ever decides that it should be up here but somewhere else, let me know. 
As many of you know, I've leveraged and extended "The Eight Fallacies of Distributed Computing" originally created by Peter Deutsch (and extended by James Gosling) to add two more and call them "The Ten Fallacies of Enterprise Computing" for the Effective Enterprise Java book. At the Reston, VA No Fluff Just Stuff Symposium, though, an attendee suggested, in response to an answer I gave, that perhaps I was missing one more, the 11th Fallacy:
11. Business logic can and should be centralized.
The reason this is a fallacy is because the term "business logic" is way too nebulous to nail down correctly, and because business logic tends to stretch out across client-, middle- and server- tiers, as well as across the presentation and data access/storage layers.
This is a hard one to swallow, I'll grant. Consider, for a moment, a simple business rule: a given person's name can be no longer than 40 characters. It's a fairly simple rule, and as such should have a fairly simple answer to the question: Where do we enforce this particular rule? Obviously we have a database schema behind the scenes where the data will be stored, and while we could use tables with every column set to be variable-length strings of up to 2000 characters or so (to allow for maximum flexibility in our storage), most developers choose not to. They'll cite a whole number of different reasons, but the most obvious one is also the most important--by using relational database constraints, the database can act as an automatic enforcer of business rules, such as the one that requires that names be no longer than 40 characters. Any violation of that rule will result in an error from the database.
Right here, right now, we have a violation of the "centralized business logic" rule. Even if the length of a person's name isn't what you consider a business rule, what about the rule stating that a person can have zero to one spouses as part of a family unit? That's obviously a more complicated rule, and usually results in a foreign key constraint on the database in turn. Another business rule enforced within the database.
Perhaps the rules simply need to stay out of the presentation layer, then. But even here we run into problems--how many of you have used a website application where all validation of form data entry happens on the server (instead of in the browser using script), usually one field at a time? This is the main drawback of enforcing presentation-related business rules at the middle- or server-tiers, in that it requires round trips back and forth to carry out. This hurts both performance and scalability of the system over time, yielding a poorer system as a result.
So where, exactly, did we get this fallacy in the first place? We get it from the old-style client/server applications and systems, where all the rules were sort of jumbled together, typically in the code that ran on the client tier. Then, when business logic code needed to change, it required a complete redeploy of the client-side application that ended up costing a fortune in both time and energy, assuming the change could even be done at all--the worst part was when certain elements of code were replicated multiple times all over the system. Changing one meant having to hunt down every place else a particular rule was--or worse, wasn't--being implemented.
This isn't to say that trying to make business logic maintainable over time isn't a good idea--far from it. But much of the driving force behind "centralize your business logic" was really a shrouded cry for "The Once and Only Once Rule" or the "Don't Repeat Yourself" principle. The problem is that we just lost sight of the forest for the trees, and ended up trying to obey the letter of the law, rather than its spirit and intentions.
Now, the question remains, is this a fallacy of all enterprise systems, worthy of inclusion in the fallacies list? Or is this just a fragment of something more? Much as I hate to admit it, I'm leaning towards the idea that it's worthy of inclusion (which means Addison-Wesley is going to kill me for trying to make a change this late in the game).
I’ve written in SDN Magazine about messaging and how it relates to RPC. It isn’t about messaging vs. RPC, but more or less an attempt to explain what benefits messaging can add to your software. Monday April 23rd I gave a presentation about the same subject. With this post I want to show the code so people can have a better look at it. Remember that there’s so much more possible than I show. I’m not going all the way, just showing how spatial coupling can be solved. Platform coupling is solved by WCF and nServiceBus self and temporal coupling can be achieved by doing it asynchronously over MSMQ, for example. nServiceBus does this by default, WCF can do this by marking operations as OneWay and selecting the msmqBinding.
So what did I show? First of all, let’s look at code that Visual Studio 2010 has in its WCF Service Application template. I sometimes get remarks that the info in a post is not complete, so here it goes
- Do File –> New Project
- Select “WCF” on the left and then the “WCF Service Application” template.
You can see IService1 interface with a method named “GetData” which expects a single parameter and returns a string value. The client knows the method to execute and when something changes, the coupling of the client to the service might break the client. Versioning is only on of the many problems that might hit you. This is the implementation in the Service1 class.
public string GetData(int value)
{
return string.Format("You entered: {0}", value);
}
Add a new Console Application to your solution, add a Service Reference without changing anything of the defaults. Then create the code to call this service. Your console application should look like this.
class Program
{
static void Main(string[] args)
{
ServiceReference1.Service1Client svc = new ServiceReference1.Service1Client();
string result = svc.GetData(10);
Console.WriteLine("Result : {0}", result);
}
}
So the idea is that we don’t create separate methods for everything we want to send, but rather have something in place that finds the correct handler class for our message. So what we need is a single generic method in our service contract that accepts anything that conforms to a message we specify. Add the following method to your IService1 interface and make sure your code compiles. This means you’ll have to implement the method in the Service1 class.
[OperationContract]
void Execute(Message message);
As you can see we specified the class Message as parameter so we’ll need to define it as well.
public class Message
{
}
Now the Execute method on our Service1 class needs to call a handler class that will contain our code. We’ll specify a default interface so that all our handlers adhere to this interface. That way we’ll be able to easily find all handlers via reflection. Let’s have a look at the interface.
public interface IHandleMessages<T> where T : Message
{
void Handle(T message);
}
Now all we need to do is create a real message and a handler that will be able to work with this message.
public class GameOfTheYear : Message
{
public string Name { get; set; }
public int Year { get; set; }
}
public class GameOfTheYearHandler : IHandleMessages<GameOfTheYear>
{
public void Handle(GameOfTheYear message)
{
Debug.WriteLine("Game : " + message.Name);
}
}
The message is quite simple and the implementation of our handler maybe even simpler. But these aren’t the point currently. What is important is how we actually execute the Handle method from our service. Here’s the code for it and we’ll go through it line by line.
public void Execute(Message message)
{
Assembly assembly = (message.GetType()).Assembly;
var allMessageHandlers =
from type in assembly.GetTypes()
where !type.IsAbstract
from interfaceType in type.GetInterfaces()
where interfaceType.IsGenericType
where interfaceType.GetGenericTypeDefinition() == typeof(IHandleMessages<>)
select type;
Type messageInterface = typeof(IHandleMessages<>).MakeGenericType(message.GetType());
var myMessageHandlers = allMessageHandlers
.Where(type => type.GetInterfaces()
.Any(it => it == messageInterface))
.Distinct();
foreach (var handler in myMessageHandlers)
{
object handlerInstance = Activator.CreateInstance(handler);
MethodInfo methodInfo = handler.GetMethod("Handle");
methodInfo.Invoke(handlerInstance, new[] { message });
}
}
At line 3 we get the assembly of the message we’ve received. This is part of the convention over configuration you can use, which states that the handler for the message should be in the same handler. Of course you could scan every single assembly in the same folder as you. For performance benefits you can scan it a single time and store all handlers and its methods in memory. Again, we’re keeping it simple so it’s easier to understand. At line 5 we’re searching for all types that are not abstract (line 7), implement a generic interface (line 9) that are of type IHandleMessages (line 10).
Then in line 13 we compose a type of the generic IHandleMessages interface with the type of our message. In line 14 we filter our just selected handlers so that we’ll only have the ones that actually implement our exact interface. Now that we have our actual handlers, we can try to create an instance of it (line 21), find the Handle method and invoke it with our message as its parameter.
Now refresh your ServiceReference in your console application client by right-clicking the service reference and selecting the update item in the context menu. Now you should be able to create a GameOfTheYear object. However, although our service does recognize the “Execute” method, it has no knowledge of the GameOfTheYear class. This simply is because WCF doesn’t automatically provides every single class in its WSDL/MEX-endpoint so we need to provide this information to it. Open the IService1 interface again and change the contract for our Execute method so it looks like this.
[OperationContract]
[ServiceKnownType("GetKnownTypes", typeof(MessageTypeFinder))]
void Execute(Message message);
Now recompile the project and update the service reference again. Everything should work flawlessly again. If this works, we can try to see if we can do something very valuable; create an additional handler that logs our messages to disk.
public class GameOfTheYearLogHandler : IHandleMessages<GameOfTheYear>
{
public void Handle(GameOfTheYear message)
{
Logger.Write("We've processed " + message.Name);
}
}
The same code will execute both handlers without any changes. We’ve really decoupled the execution and handling of the message we’re sending from the initial service. As you can see we can create multiple handlers for a single message. What we can also do is create a single handler for multiple messages. We’ll first define the message and add an additional interface to our GameOfTheYearHandler.
public class GameReview : Message
{
public string NameOfGame { get; set; }
public string Review { get; set; }
}
public class GameOfTheYearHandler : IHandleMessages<GameOfTheYear>, IHandleMessages<GameReview>
{
public void Handle(GameOfTheYear message)
{
Console.WriteLine("Game : " + message.Name);
}
public void Handle(GameReview message)
{
Console.WriteLine("Revied : " + message.NameOfGame);
}
}
First thing to remember is that we need to make sure the GameReview message is specified as a KnownType to our service. As we don’t want many lines with ServiceKnownTypeAttribute statements there, we need a different solution. Add the following class to your code and then replace the original ServiceKnownType line with the last line in the following code.
public class MessageTypeFinder
{
public static IEnumerable<Type> GetKnownTypes(ICustomAttributeProvider provider)
{
IEnumerable<Type> query =
from type in typeof(Message).Assembly.GetTypes()
where typeof(Message).IsAssignableFrom(type)
select type;
return query.ToArray();
}
}
[ServiceKnownType("GetKnownTypes", typeof(MessageTypeFinder))]
Now we only need to tweak the execution of the handlers in the foreach loop to the following code.
foreach (var handler in myMessageHandlers)
{
var methods = from m in handler.GetMethods()
where m.Name == "Handle"
from p in m.GetParameters()
where p.ParameterType == message.GetType()
select m;
object handlerInstance = Activator.CreateInstance(handler);
var methodInfo = methods.Single();
methodInfo.Invoke(handlerInstance, new[] { message });
}
We can’t simply select the Execute method anymore, as there are multiple. So we’re checking the parameter type and see if it’s the same type as our incoming message. There obviously cannot be more than one method with the exact same parameters, so we can select Single() on line 10 and then we’ll be able to execute the method.
FYI: During the SDN event I forgot to create the actual instance of the handler and was trying to execute the Handle method on the type. This is obviously not possible. So now you know why it didn’t work during the presentation.
nServiceBus
So during the presentation I also mentioned nServiceBus. If you look at the code you need to write to use nServiceBus, this is exactly the handlers and messages as I’ve shown in the code above. However with nServiceBus you can use interfaces as messages so you can create message with complex inheritance trees. A method to “initiate” an interface is provided, which creates a proxy which you can then fill with your information. Since version 3.0 of nServiceBus you no longer need to implement the IMessage interface on your messages which makes creating libraries with messages that are shared, much easier, since you don’t need an assembly reference to nServiceBus anymore.
Of course we have no need to write plumbing code, as nServiceBus has done this all for you.
- Transactions are supported in WCF, but with nServiceBus everything is transactional by default.
- As said, in WCF you can mark messages OneWay and select the msmqBinding to use msmq. nServiceBus does this by default.
- nServiceBus makes it possible to do request/reply asynchronously. Due to the nature of queuing, it’s not possible to immediately send a response. The sending application however can specify a return queue in it’s message (nServiceBus does this for you) and with a Bus.Reply(myMessage) you send the return message.
- Retry of message is supported with a variable amount of retries. After final failure the messages get enriched with exception information and transferred to a (configurable) error queue.
- Publish/Subscribe is possible where one publisher has no knowledge of any clients receiving the messages. A variable number of clients can subscribe to the messages and nServiceBus takes care of subscriptions. Since version 3.0 you can store these in RavenDB.
- Long running processes (called sagas) are supported where you can wait for multiple incoming messages before continuing.
- Timeouts are supported so when within a saga messaging don’t arrive on time, you can send yourself a warning. Since version 3.0 you can also send messages to yourself in the future. These messages don’t arrive before the time you specified.
Conclusion
Again, messaging isn’t the silver bullet to your problems. It is however another way to communicate out of process to other applications or business components. It should provide additional options to implement without your architecture and you should seriously consider it if you haven’t used messaging and/or queuing frameworks before. Messaging has a lot of additional perks which I wrote about in my SDN article. When the new magazine arrives, I’ll post the PDF on my weblog. Until then, you are allowed to contact me and request the article.
Download the source here.
Microsoft Patterns & Practices team has started a journey to CQRS with the idea to create a guidance document to provide developers with a map that will help them find a way with the Command and Query Responsibility Segregation (CQRS) and Event Sourcing (ES) patterns and related techniques. Everything is extremely public and a lot of information about the journey can be found here on GitHub.
As a member of the Advisory Board it’s been a journey of my own. It’s really great to see a lot of opinions and discussions happen during the conference calls with the advisory board. The journey is really taking form and more documentation is put online every two week sprint. Also code is available for download so you can see what is happening over time. Every sprint is also shortly documented on the github site, so you get an idea what was achieved.
Last meeting a discussion was started by Udi Dahan that too little effort was put in thinking properly about the domain so that BC’s (be it Bounded Contexts in DDD, Services in SOA or Business Components by others) weren’t properly modelled. He wrote a lengthy post about it with some additional information in another post. When you’ve been to his Advanced Distributed Systems Design course you will understand his problems with this, as it’s a very crucial part of the architecture he proposes. This isn’t a silver bullet architecture from a technical perspective, as you have all kinds of technical options to solve every single Business Component and Autonomous Component as you see fit. But it’s very important from a functional perspective and helps solve a whole lot of problems related to coupling of information. Which in turn should make things a whole lot easier to solve when maintaining the system or adding new features to it.
After trying to enhance our current system at Tellus and making steps to enhance it according to these ideas, I’m still very, very enthusiastic about this approach. If you ever want to talk about the possibilities or ideas, please don’t hesitate to contact me. I’d love to come by or invite you over to the Van Nelle factory to talk about it and show you what we’re doing. Of course I am equally interested in how other companies solve problems like ours. Let me know via the contact form.
It’s the small things that easily make me a happy boy. Adding a unit test to a test project is easier via the context menu. Also the class that is generated from the template is very clean and doesn’t contain the TestContext and commented-out functions anymore. Using those functions is a bad practice anyway. But about a minute after installing Visual Studio 11 I’m already happy to work with it.


This blogpost is part of a series
- Template Method Pattern explanation
- Template Method Pattern example
- 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 MessageSender originally used.
- 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.

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.
This blogpost is part of a series
- Template Method Pattern explanation
- Template Method Pattern example
- 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.
This blogpost is part of a series
- Template Method Pattern explanation
- Template Method Pattern example
- 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:
Define 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.
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 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.
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.

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.
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.
In 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. 
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.
- One class library (a .dll) that will contain the message.
- One console application for the publisher.
- 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
- NServiceBus.dll
- NServiceBus.Core.dll
- log4net.dll
- 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.
- Did you add a using statement for NServiceBus?
If not, the extension methods for DefaultBuilder, XmlSerializer, etc. won’t be visible
- 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.
- InputQueue is the queue where our publisher will be accepting subscription requests on. Our subscriber will post an initial message here.
- 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.

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.
- 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.
- Logging is turned down and only shows warning messages.
- The UnicastBusConfig configuration has two important options.
- Messages is set to PubSubTutorialMessages.
This tells nServiceBus that all messages in the PubSubTutorialMessages.dll assembly should be routed to this subscriber.
- 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.
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
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.

<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>

Now this is nice. What’s happening here?
- We removed the DisplayMemberPath attribute, as we are going to very specifically define how we want to see the data.
- We’ve added a DataTemplate, which describes the visual structure of a data object, according to MSDN :-)
- 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>
And 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.
More Posts
Next page »