HTTP: the Other ESB
I presented this at Houston Tech Fest 2009 back in September. The attendees received the topic well, and I was pretty happy with it, considering I’m still learning a lot myself.
I presented this at Houston Tech Fest 2009 back in September. The attendees received the topic well, and I was pretty happy with it, considering I’m still learning a lot myself.
Anyone who has worked with INotifyPropertyChanged knows that this simple interface can be a royal pain in the ass.
To try and eliminate the pain, people have created some great solutions using AOP : IL weaving (PostSharp) and using a proxy (Castle Dynamic Proxy).
PostSharp has a little too much voodoo for me atm. I think I will warm up to it though and re-examine using PostSharp on my next solution. But for now, I wanted to use Castle Project’s Dynamic Proxy.
Naturally since Castle also has a very popular IoC container in Windsor, most examples marry Dynamic Proxy and Windsor to form an AOP INotifyPropertyChanged solution.
Since I am using StructureMap for this project, I endeavored to create my own solution using Dynamic Proxy.
My first attempt I shared at the Virtual Brown Bag look liked it worked but in reality I was constructing my objects twice.
Once with SM and once with the Proxy generator.
I had to go back to the drawing board and posted my problem at the SM google group. http://groups.google.com/group/structuremap-users/browse_thread/thread/1a6b19ce8152db1b?hl=en
I believe the syntax given to me was an older version of SM. For the record, I am using version 2.5.3.0
But it did direct me to the general idea on where I should start looking. I ended up needing to create an IBuildInterceptor.
public class MyBuildInterceptor : IBuildInterceptor { public MyBuildInterceptor(Type concreteType) { _ConcreteType = concreteType; } readonly Type _ConcreteType; public object Build(BuildSession buildSession, Type pluginType, Instance instance) { var constructorArgs = _ConcreteType .GetConstructors() .FirstOrDefault() .GetParameters() .Select(p => buildSession.CreateInstance(p.ParameterType)) .ToArray(); var interceptors = new List<IInterceptor> { new NotifyInterceptor() } .ToArray(); return new ProxyGenerator().CreateClassProxy(_ConcreteType, interceptors, constructorArgs); } public IBuildPolicy Clone() { return InnerPolicy.Clone(); } public void EjectAll() { InnerPolicy.EjectAll(); } public IBuildPolicy InnerPolicy { get; set; } }
To register my ViewModels I created a convention using a TypeScanner
public class MyNotifyConvention : ITypeScanner{ public void Process(Type type, PluginGraph graph) { if (type.GetInterface("IViewModel") == null) return; var interfaceType = type.GetInterfaces().FirstOrDefault(i => i.Name.Contains("ViewModel") && i.Name != "IViewModel"); if (interfaceType == null) return; graph.Configure(r => r.ForRequestedType(interfaceType) .InterceptConstructionWith(new MyBuildInterceptor(type)) .TheDefaultIsConcreteType(type)); }}
I then used a Dynamic Proxy Interceptor that I basically copy and pasted from Serial Seb’s example.
public class NotifyInterceptor : IInterceptor{ public void Intercept(IInvocation invocation) { // let the original call go through first, so we can notify *after* invocation.Proceed(); if (invocation.Method.Name.StartsWith("set_")) { string propertyName = invocation.Method.Name.Substring(4); RaisePropertyChangedEvent(invocation, propertyName, invocation.TargetType); } } void RaisePropertyChangedEvent(IInvocation invocation, string propertyName, Type type) { // get the field storing the delegate list that are stored by the event. var methodInfo = type.GetMethod("RaisePropertyChanged"); if (methodInfo == null) { if (type.BaseType != null) RaisePropertyChangedEvent(invocation, propertyName, type.BaseType); } else // info != null { methodInfo.Invoke(invocation.InvocationTarget, new object[] {propertyName}); } }}
Instead of looking for the PropertyChanged Handler, I create a RaisePropertyChanged method and use that. Although I could raise the event using the field method Seb was using, WPF wasn’t updating the binding. I didn’t really bother to investigate and just rolled with this solution.
So that’s my solution and I’ll start using it in my current solution. Naturally I will clean up the code some more etc. Feel free to use this for any of your own projects. You can also get the solution at my GitHub:
I presented this at Houston Tech Fest 2009 back in September.
Microsoft Research recently published the article “Exploding Software Engineering Myths,” by Janie Chang. For those who haven’t seen it, you will likely be surprised by some of the findings. Chang and his team worked with IBM and found that code coverage isn’t a terribly excellent metric, TDD may not necessarily speed development, Asserts (and by extension Code Contracts) greatly improve development code quality, and organization structure does matter though geographic proximity does not. The article includes links to the team’s published findings if you want more information.
I don’t really think the first finding is all that shocking, but I was surprised by the second. I’ve found TDD as useful as using Asserts–another unsurprising finding, at least to me. The authors do acknowledge that teams using TDD generally face far less post-production issues. So at worst, TDD likely keeps development time the same but allows the development team to catch the majority of the bugs as opposed to the end users. For my money, I would prefer my development team find the bugs and let the end users think we did an excellent job. In addition, you can never know when some bit of functionality just hasn’t been tested by an end user that might require a significant re-write to fix (heaven forbid).
That’s my two cents. What are your thoughts? Are you surprised at the findings?
For those interested in learning the principles of functional programming, Dr. Erik Meijer and Channel 9 started releasing a lecture series using Haskell as the primary language and exercises in C#. They provide a discount for Graham Hutton‘s Programming in Haskell, the text for the series, as well. Go check it out here!
If you are wondering what happened to my flame-war-instigating series on the problems with MVC, you’ll have to continue waiting (as will I for the flame war, apparently). I’ve been busy and haven’t had the time to finish typing and inserting links into the rest of the posts. Such is life.
In the meantime, I hope to start emphasizing the usefulness of developing with patterns. This post was inspired by Sean Chambers recent 31 Days of Refactoring (e-book) and my recent flub when trying to describe the Decorator pattern (ducks, really?).
On a recent project using WPF and Prism, we’ve built business layer objects to import and export text and Excel files in batches. These batch processes included importing data, transforming the data into something useful, and persisting the transformed data into our database. We needed to communicate progress back to the UI for each of these tasks to keep the user aware of progress, as these tasks can take quite a long time, especially with multiple files. The initial design was raw and messy with lots of code duplication to explicitly create a BackgroundWorker directly within each ViewModel to start the import/export process and listen for events fired directly from our business objects (which essentially follow the Transaction Script pattern, more or less).
Another co-worker, when he was tasked with building another importer, created a subclass of our base ViewModel class and added all the BackgroundWorker plumbing, then did the same for our base business object class. He also created a ProgressItem : INotifyPropertyChanged type with methods to Start(int items), StartAsIndeterminate, IncrementProgress, EndWithSuccess, and EndWithFailure. He also added a collection wrapper for ProgressItems to allow ease of registering and auto-subscribing (through the AutoNotify method) the owning business object to the PropertyChanged events of the ProgressItems. With this setup, the UI ViewModel could listen to the PropertyChanged events of the business object’s ProgressItems instead of having the business object fire its own events. As you can imagine, this made implementing a batch import / export process immensely easier.
I eventually went back and refactored all of our existing business objects and ViewModels to follow this approach. Not only are both the business objects and ViewModels easier to debug, they are also easier to test since we are no longer firing events, just updating the state of a given ProgressItem. Well, sort of….
I was recently tasked with creating a new batch import process to pull data from Excel. I started by following the pattern JB set up and had the initial steps of my batch import object ready to go. (I also confess to not having written any tests yet because, to date, we hadn’t figured out how to mock out the SpreadsheetDocument, Rows, etc. from the Open XML SDK we’re using to assist in our import / export tasks. I’ve now solved that problem and retro-fitted in unit tests. I’ll post that solution later.)
After taking a step back to look at what I had done, I quickly realized that I was violating SRP with the inclusion of the ProgressItems in each step. Some might think that’s not such a big deal; after all, calling start, increment, and end on a single object is only three lines, which doesn’t seem like a lot. However, multiply those three lines by the number of import/export objects and factor in the number of times we forget just one of the them, and you begin to appreciate removing the extraneous bits.
I’m quite certain I noticed this primarily because of my study of functional programming rather than any object-oriented pattern literature I’ve come across. Nevertheless, I considered only OO patterns for the solution simply because the alternative was likely a monad, and that just scares the pants off of most people. (And I like my co-workers.)
I needed something that could pull the ProgressItem out of my actual import procedure and allow me to focus that logic purely on the import. The two patterns that came to mind were the Decorator and the Visitor.
The Decorator is generally considered (well, at least by the people I know) the simpler of the two. It wraps and extends an object without changing the underlying object and still providing the same interface. Examples include “decorating” coffee with sugar, cream, etc. and returning an adjusted price for the additional “decorations.”
The Visitor, on the other hand, is passed into an object’s void Accept(Visitor visitor) method and provides some resulting side-effect through the visitor itself. Examples include pretty printing, which print a tree-structure with the appropriate indentation, or adding the appropriate tax to an order. Another example for those using the System.Expression namespace would be using the ExpressionVisitor to allow the use of POCO objects with Entity Framework v1, as JB demonstrated here. (For those familiar with monads, you’ll likely see some resemblance.)
In this case, I had the following interface:
For reference, the initial state of a Loader looked something like this, making adjustments to the method signatures for the addition of the ProgressItem, which initially was passed to each method:
Instead of muddying my interface with a void Accept(Visitor vistor) method, I chose to just decorate it. My resulting decorated class looked as follows:
The resulting base DetailLoader looked like so:
This made the loader much easier to reason about and test thoroughly, as the ProgressItem is completely removed. I no longer have to remember to add the calls to it or even bother with anything other than loading data. Again, I know some will probably call this an over-engineered example, but as a developer who has had to debug these things when they were initially one method directly on the business object not firing a particular event, the additional abstractions make this a breeze to create, debug, and test. To each his own.
As I mentioned, I figured out a way to test this against the Open XML SDK, but since this is already quite a long post, I’ll postpone that for later. I hope you find this a helpful explanation of how and when to refactor using the Decorator pattern. Please let me know if you have any feedback on the matter.

Dogs and Cats Living Together
You’ve probably read Joel’s post on The Duct Tape Programmer and several responses. I did not like Joel’s post at first, as I thought it far too general and easily taken in the context of “always do it this way.” For the record, I have no problems with the duct tape approach when trying something out, but I’ve been burned when having to work on someone else’s let-me-try-this project that then became a core, production system. That’s a formula for PAIN. That said, I think you can make a case for using a duct tape approach for some, small parts of your application.
This past week I put together a presentation on DDD for my office. I included some slides describing DDDD and CQS as Greg Young has discussed time and again. While I put together those slides and thinking about Bounded Contexts, I had a sudden realization that even within a single Bounded Context or Module, you could mix duct tape with quality when using CQS.

If you look at the diagram above, you can easily see where this is possible. If you split your module into read and write contexts, you can focus your greatest efforts for quality on the write side, where your domain lives, and leave the ever-changing read side to duct tape, RAD, etc. for displaying in the UI or reporting. The idea here is that you will often find that what you need to persist doesn’t change very much, but what you are asked to display changes nearly constantly. That’s at least my experience.
Another benefit to this approach is on the sales pipeline. Creating applications consists of these two parts: reading and writing. You may find that clients who have their own internal developers may not want to hire a consultant or contracting firm to build an entire app at their normal rates, but if you can provide them the write side and architecture guidance for the rest of the app, you may be able to sell more projects and keep your people happy working on quality code and quality projects. Of course, that’s just theory at this point.
So is this a case of “mass hysteria”? I don’t know. I like the idea, if not so much for the inclusion of duct tape as the possibility of limiting changes to the core domain models in an application architecture. I’m curious to know what others think or have done.