CQRS In Phases: Phase 2 - Commands, Events And Handlers

(please read my Introduction post in this series for an explanation of what I'm trying to do with this blog series)

In my last post, I talked about separating your reads from your writes in your applications. Once you've done that - you've already applied CQRS... you've separated the responsibility of reading your data from writing your data.  You're done and your app will b be better for it :)

But if you want to take things further, the next step in applying CQRS as you commonly read about it is to unify the way that data flows through the write side of your application.

Before that though, a quick note on the read side - it's done.  Once you've separated it out, that's really all that needs to be done.  It can now change indepdently of the write side and it should be very simple.  All you're looking to do on the read side is get some data and display it. You can tweak queries and tweak code, but the code should be very simple.  So once you've done step 1 as I outlined in my last post, you're pretty much done the "radical" changes on the read side.

On the write side, the way to unify the data flow through it is to issue commands from your client and have them handled by a command handler.  In the command handler, you load the business object that the command relates to, call a method that performs the command on the business object and, if necessary, have the business object fire off events which can be handled by event handlers.

Whoa. That was a pretty dense amount of information wrapped up in one paragraph. There's a lot of interesting information about what commands and events are and how they should be named, but rather than re-hash it, I'll just share a few links.

For more on commands, read this. For more on events, look here. And if you want to see a sample application that shows the most simple implementation of commands, events and how they're both handled, check out this project written by Greg Young.

If you don't feel like reading all that other stuff (shame on you), just understand that commands are telling the system to do something and should be named as such - i.e. UpdateCustomerInfoCommand. Commands should be in the imperative to imply that they are telling the system to do something.  Events are telling the system that something has occurred in the past.  That's the distinction.  So after you handled the UpdateCustomerInfoCommand, you might issue a CustomerInfoUpdatedEvent event to let other parts of the system know what happened in case they are interested.  And handlers are just functions that handle the commands/events when they're raised.

If you start following these guidelines of having your client issue commands that are handled and then having your business objects, as part of that handling fire events, you'll see some benefits over your standard architecture, including:

Consolidation of business logic into the business objects
I can't count the number of times I've seen an application that touted their business object layer, only to see all of the actual business logic in code-behind files or in MVC actions or elsewhere.  The business objects were really just DTOs with some data access methods and maybe a bit of validation logic. The actual changes to the object were occurring elsewhere, breaking encapsulation.  When you begin issuing commands, it becomes very natural that all of your business logic is inside your business objects.

A more human way to understand the system
Telling a system what to do and then having the system notify other systems what happened is a very easy thing to understand in human terms, because it models how humans work.  This makes it easy on the developer's brain to understand how data flows through the system and even more important, it makes it easy on the non-developer's brain to understand how the system works as well.  Instead of talking in terms of objects, you can talk in very real world terms which makes sense to non-developers that are part of building a system.  Which brings me to my next point...

You head in the direction of domain-driven design
I'm not a DDD expert, but I've read the big blue book and a lot of what it discusses is handled by moving into commands and events on the write side.  Most CQRS proponents suggest a full blown domain model behind the command handlers and it does make sense.  But you can almost get to a domain model just by consolidating your logic and issuing commands this way.

Your client apps become simpler and more focused
Your client apps, whether they be MVC apps, WebForms or desktop apps can go back to being more focused on what they're good at which is displaying data to a user and handling input from a user.  No longer will they be burdened with also housing business logic as part of their job. You're getting better SRP and SOC.  That's always a good thing.

This change is a little more involved than step 1.  In a larger app, it can take considerable effort to pull your business logic together when its currently spread all over your current system.  But you also get bigger bang for your buck with this step.  Even though refactoring your app to issue commands and raise events make take more effort, you're actually simplifying your system and making it easier to understand for the future.

In the next post, I'll talk about going even further with CQRS by using event sourcing.  This is probably where a lot of developers start to feel uneasy about CQRS.  Not that they don't see the benefits, but it's quite a leap from how they're used to developing that we become unsure if its the right way to go.

As I mentioned in my introduction post, if something here sounds wrong, or if I'm missing something - please let me know in the comments.  Feedback is very much appreciated.

  1. Introduction
  2. Step 1: Separating Your Reads From Your Writes
  3. Step 2: Commands, Events And Handlers

CQRS In Phases: Introduction

Lately, I've been a bit obsessed with Command-Query Responsibility Segregation (CQRS). I'm not quite sure if I'm late to the party or jumping on the bandwagon because I remember seeing a lot of noise around CQRS in my RSS feed a few months ago but didn't really bother with it at the time.  I'm not sure if it's still a hot topic or was a passing fad, but the more I read about it, the more interested I become.  I agree with a lot of the architectural principles, but I'm not going to re-hash those.

For anyone that wants to learn more about CQRS, http://cqrsinfo.com/ is a great starting place.  There are also great blogs out there maintained by Greg Young, Rinat Abdullin, Mark Nijhof, Jonathan Oliver and Udi Dahan - all of whom are far more knowledgeable on the subject than I am.

When you read about CQRS, you usually see what I call the full monty which includes using event sourcing (capturing all changes to an application state as a sequence of events), using separate databases for the read side and the write side and even distributing the application in the cloud.  There are very compelling benefits to using the full monty, but at the same time, I think there are benefits to using bits of the CQRS architecture without going all out.  So what I hoped to write about in these next few blog posts is dissecting some of the steps you can take in your code to achieve some of the benefits of CQRS without necessarily making it all or nothing proposition.

Allow me to reiterate - no CQRS information I've read has ever said that you need to do all the steps to see benefits in your application.  As a matter of fact, some things I've read have discussed the benefits as being independent.  I've just rarely seen the steps you can take broken out into logical pieces and the benefits of each discussed.  That's what I hope to do with this blog series.

Lastly, I hope to get some feedback from people with far more CQRS experience than I have.  If something I say sounds completely wrong, I'd love to know about it.  I'm just trying to distill the large amount of information I've digested into something that makes sense to me.  So I may have gotten something confused in all of my reading and I don't claim to be an expert.

My next post will talk through the first step I see towards CQRS - which is the most straightforward one... separating your reads from your writes.

  1. Introduction
  2. Step 1: Separating Your Reads From Your Writes
  3. Step 2: Commands, Events And Handlers

CQRS In Phases: Phase 1 - Separate Your Reads From Your Writes

(please read my Introduction post in this series for an explanation of what I'm trying to do)

The first "phase" in Command-Query Responsibility Segregation (CQRS) is probably the most straightforward and obvious - separating your reads (queries) from your writes (commands).  In a typical application (sorry, no samples), this basically means separating the queries that display data on the screen from the ones that perform inserts, updates and deletes on your database.

I should probably take a minute to explain the type of architecture I'm envisioning for this blog post, although benefits of the steps can be seen no matter your architecture.  For the phases, I'm imagining you have a domain model or at least a business logic layer which has business objects for each of the main entities in your system. In all likelihood, these business objects are being hydated from the database and also save their state back to the database.  Again, this isn't the only type of system that can benefit from some of the concepts of CQRS, but its what I have in mind mostly because it's what I deal with at work that I'm trying to improve :)

What do I mean by separate the reads from the writes?  Most them into different objects.  That's it.  If you use business objects, move the functions that read data from the database out of them and into another read-specific object.  If you just use a straight object for data access like a repository, break it up into two repositories - one for reading methods and one for writing methods.  Just separate the methods in your app that read data from the ones that write data.

With even just this simple step, you will see some benefits, including:

Your code, especially if you have business objects, will become simpler.
This may not be as applicable if you're not using business objects, but if you are - you have removed an entire responsibility from them.  The responsibility of hydrating themselves to display on the screen.  This means your business objects become more focused on what they're intended to do - validate things before they get created, updated, deleted, etc.

Increased ability to optimize your read query performance.
There are a few reasons for this.  The big one is that in most cases, your business object represents a row in a database table.  Even if you're using an ORM, you're mapping objects to database table rows. As such, you're usually querying entire rows, using lazy loading to get related child objects and other techniques in order to get the data you need to show a screen.

Once you've removed the concern of reading from business objects and put it into its own class, you're now able to use any techniques in order to get the performance you want.  You can write custom SQL queries to bring back just the data you need because you're not beholden to the business object definition.  If a stored procedure makes more sense here, use that.  If you only need two columns from a row instead of the entire row, just write a query that only returns those two values.  You have much more wiggle room this way.

So with just this simple change you've cleaned up your business objects and given yourself some leeway when it comes to optimizing your queries.  Not bad.

In the next post, I'll talk about the 2nd step as I see it - unifying the way data flows through the write side via the use of commands, events and handlers.

As I mentioned in my introduction post, if something here sounds wrong, or if I'm missing something - please let me know in the comments.  Feedback is very much appreciated.

  1. Introduction
  2. Step 1: Separating Your Reads From Your Writes
  3. Step 2: Commands, Events And Handlers

Book Review: ASP.NET MVC 2 In Action

I was looking for a good book to get started with the ASP.NET MVC framework now that I've found the time to actually sit down and play with it.  I'd used Castle MonoRail pretty extensively in the past on a few client projects and I've played with Ruby On Rails quite a bit too, so the idea of MVC wasn't new to me.  I was really looking for a book that talked about using Microsoft's MVC framework and one that explained some of the best practices, rather than just a primer or reference since I already had the MVC idea down pat.  In that regard, I think ASP.NET MVC 2 In Acton really shined.

ASP.NET MVC 2 In Action is laid out into four sections.  The first section is called High Speed Fundamentals and it focuses on a quick overview of what the Model-View-Controller paradigm is all about and then a chapter delves into each of the layers individually as a primer.  There's also a chapter which explains what things from the WebForms world are still usable in the MVC world.  There's a good amount of valuable info in this section, but it is, as the name, implies - high speed. I think it may even be a bit too high speed if you have no experience with MVC architecture and you're coming over from the WebForms paradigm.  It can be confusing and there's not much info here to really iron out that confusion.  It wasn't a problem for me, but I could see how someone new to the MVC paradigm might still be a little uncomfortable by the time they reach the end of the first section.

The second section, Journeyman Techniques, is where the book really starts to shine.  This is where the authors get into topics like domain modeling, extending the controllers and views and using Ajax.  IoC is covered briefly in this section as well.  The reason I find this so valuable is that I like reading books that are less a reference about the tool and more a real-world guide for usage.  That's exactly what this section of the book does.  Instead of just covering the features of MVC, this book gets into how developers should leverage the ASP.NET MVC framework in their own applications.  The chapter on custom model binding and value providers was very useful, as was the chapter on using IoC to create a custom controller factory - these are things that Microsoft might not tell you to do, but will quickly prove valuable if you work on a real-world, large ASP.NET MVC project.

The third section, Mastering ASP.NET MVC, takes things even further with chapters on routing and making your controllers lightweight.  There are also chapters on doing mapping with AutoMapper (Jimmy Bogard, who created AutoMapper, is an author of the book) and data access with NHibernate.  I could see some people being put off that tools are being suggested as part of the book, but again, I find this refreshing.  The book becomes more valuable than just as a reference of ASP.NET MVC features.  This is where the real value of the book is.  You get information on not just how to build an ASP.NET MVC application, but how to build a rock solid, well-factored ASP.NET MVC application.  Even if you don't choose the specific tooling and stuff they suggest, the ideas behind them are sound - such as keeping your controllers lightweight for easier maintainability and testability.

The final section, Cross-Cutting Advanced Topics, closes the book with some information about testing your applications and customizing Visual Studio for ASP.NET MVC work.  There's also a final chapter that's a short example of tying everything together which I felt was a little TOO short to be of any value.  But the chapter on testing is good as is the route debugging chapter.

Besides the quick introduction to the MVC pattern, I think this book really shines.  There is a lot of helpful information and it's great to see a book on the framework that gets into how developers can and should use it in their projects, rather than just being a reference.  I like that the book is opinionated and lets you know how real programmers are working with the framework, including how they're working around some of the weaker parts of the framework's default implementation.

I'd suggest this book to someone who understands the MVC architecture, but wants to work on an ASP.NET MVC project and is wondering what the best practices in the field are.

A Code Sample Is Worth A Thousand Words: Ruby Is Pretty Cool

Let me make this disclaimer first before anything else - I'm not jumping off the .NET boat or anything.  But I definitely see value in opening up and seeing how people do things on the other side of the fence.

So I've been reading this book online - Programming Ruby - The Pragmatic Programmer's Guide.  In the chapter on Standard Types, they showed this really short code sample.  Even though it's short in lines, it displays a bunch of things about Ruby that I think are really cool.  And things that are awesome in comparison to the way .NET handles things.

Here is the code and the output in Ruby:

num = 9
7.times do
     print num.class, " ", num, "\n"
     num *= num
end

# OUTPUT
# Fixnum 9
# Fixnum 81
# Fixnum 6561
# Fixnum 43046721
# Fixnum 1853020188851841
# Bignum 3433683820292512484657849089281
# Bignum 11790184577738583171520872861412518665678211592275841109096961

Here is the code to do the same thing in C# and its output:

private static void WithoutExtensionMethods()
{
     int num = 9;
     for (int i = 0; i < 7; i++)
     {
          Console.WriteLine("{0} {1}", num.GetType(), num);
          num = num * num;
     }
     Console.ReadLine();
}

// OUTPUT
// System.Int32 9
// System.Int32 81
// System.Int32 6561
// System.Int32 43046721
// System.Int32 -501334399
// System.Int32 2038349057
// System.Int32 -1970898431

Now, to be a completist, I also wrote a version that actually allows you to do something like 7.Times() in C# - it used an extension method on the int type and you had to pass the number you wanted to multiply (the 'num' variable) as well as a Func<int, int> telling it what exactly you wanted to do inside the loop.  I didn't show that example because I figured it was extra work and this is probably more likely how someone would do the code in the Ruby example in C#.  Ruby does have a for loop construct, but most Rubyists prefer using times, or upto or other methods as they're more clear to the programmer.

I'm going to cover the things that I think make the Ruby example cooler than the C# from the lighter "not that big a deal" stuff to the stuff that really IS that big a deal.  So without further ado.

1.  The Ruby code reads better.

That's pretty subjective, but in my opinion it does.  Your brain doesn't have to parse the for loop and figure out "ok, its starting at zero and running to less than 7 (meaning 6) so its going to run 0-6, so 7 times".  The loop construct in Ruby is "run this 7.times".  Another cool thing I found out about Ruby is that you can actually initialize big values using an underscore to break them up.  So "123_456_789" would just become "123456789" to the processor.  But its easier for another programmer to read that value with the underscores - this is the same thing that commas do in math - allow our brains to process the number easier.  Same thing that dashes do in phone numbers, etc.  The phone company doesn't need us to enter dashes in... it just needs 10 numbers to know what to call.  The dashes are for our brains.  And that's a lot of what programming is about.  The computer understands complexity.  You're not going to over-complex the computer.  So we write stuff cleanly and simply so that other programmers can read and understand your code.

2. The Ruby code block passed into the times function is actually aware of the context in which its running.

Again, I didn't show the C# version of the Times() function that you could write, but you do have to pass in the num variable so that the Func<int, int> knows what to work with.  Not the case with Ruby.  To further illustrate this point, scroll down to the LAST example at the BOTTOM of this page of the Ruby book I mentioned earlier.

With Ruby, that part between do and end is a block of code, similar to a function pointer.  It doesn't run immediately when its called, but rather waits until its called, just like Func<> or a delegate.  Only, with Ruby, it remembers the context when it was called - the local variables, the current object, and so on - so its able to work with those values inside the block.

3. Ruby is dynamic.

The first listing in the output for both types is the class or type of the variable.  Notice how in the Ruby example, when the value gets large enough, the variable changes to type Bignum instead of Fixnum and keeps on chugging.  In C#, that's not the case.  If you defined it as an Int32, that's what it's going to stay.  And that's deceptive and brings me to my last point.

4. Ruby gives you the right answer.

Because its dynamic, Ruby can compute values this big and store them in the correct type on the fly.

I'll be honest... when I coded this example in C#, I was expecting an OverflowException to be thrown once the number got too big.  The actual results scared me a little.  It runs just fine, but the results are incorrect.  In the 5th line, it's gone into negative numbers as we've overflowed the number of bytes that an Int32 can hold (for the record, I ran this and used an explicitly type Int64 and it overflowed as well).

I tried running this again and wrapped the computation in a try-catch block to catch the OverflowException explicitly.  It still ran just fine.  You have wrap that try-catch block in ANOTHER block called the checked block to get your program to check the exception.  And then your program will crash and die when you overflow the Int32 type.  That's good and bad.  It lets you know you've used a type that isn't big enough for the value you're computing... but it also doesn't get you the right answer or allow your program to continue to running .

Of course there are tradeoffs.  Because just like you had this num variable change from a Fixnum to a Bignum, you could set it to a String and it'll just chug along and not complain.  It's up to you to watch that stuff.  You could argue whether that's good or bad (I tend to think that it's not that bad... you oughta know your code well enough to know what its doing).  But either way... it's a different perspective.  Static languages aren't the only way of the world.

Book Review: Microsoft .NET: Architecting Applications For The Enterprise

I was recommended this book by a co-worker who had read it.  I did my due diligence and read reviews on Amazon.com that all spoke of it favorably and checking out the table of contents and such, it seemed to cover things I was interested in learning about.  Put simply, it seemed to be a book that would dive a little deeper into some of that patterns that Martin Fowler exposed in his Patterns Of Enterprise Application Architecture book.

I'll get to the point - I was severely disappointed by this book.  While it did continually reference Fowler's PoEAA book, it didn't really elaborate any of them moreso than the original PoEAA book does.  The rare, short example that was given was always in C#, but other than that, it doesn't do much than rehash the intent of the patterns.

For example, in the Business Logic Layer section of Microsoft .NET: Architecting Applications For The Enterprise, they briefly explain what should be a part of the business logic layer and then proceed to explain four types of model for the BLL - the transaction script, the table module, the active record and the domain model.  These are all gleaned right from Fowler's book and do little to elaborate on Fowler's explanations.

Furthermore, the first section of the book is a bunch of excerpts from IEEE whitepapers and a rehash of good design principles (favoring composition over inheritance, the single responsibility principle, etc.)

I think my biggest disappointment out of the book was that I didn't learn anything.  Everything in the book was stuff I already knew.  And as I always say... I'm far from a master programmer.  It's just that much of the book is built on ideas that are covered in so many books (such as the design principles) and the part of the book that I had the most interest in - the part that dealt with organizing and writing code for enterprise systems, was really light on examples and there was no depth.

This book is really just PoEAA where the examples are specific to .NET.  The only people I could possibly recommend this book to are people who haven't heard of, or read, the PoEAA book and are looking for it's NET-specific counterpart.  Almost everything you find in it can be found elsewhere, covered more thoroughly.

Using ASP.NET MVC for cleaner Ajax handling in a WebForms app

ASP.NET WebForms And Ajax Go Together Like Oil And Water

In the past few months, I've seen some of the pretty ugly ways in which ASP.NET WebForms works with Ajax.

I've seen the Microsoft Ajax Toolkit which is just embarrassing.  Once again, Microsoft tries to lock you in to their stuff rather than the industry standard (jQuery/Prototype) and also provides limited functionality in the form of Ajax web controls and other proprietary stuff.  Very nice, but we're big boys now.  We don't need the coddling and MS telling us to use their stuff and everything will be OK.

I've seen using a .NET web service and having your Ajax requests call it to get the data they need.  It's better than the Microsoft Ajax Toolkit, but it still leaves something to be desired.  As far as I can tell, you still have to reference the web service in your page with an <asp:ScriptManager> tag and it also seems like you're making a poor technology choice by building out a web service just to get some data back to your system without the full post back.

Slightly better, but still crummy, is marking methods in your code-behind with the [WebMethod] attribute and making them static so you can get at them in aspx/ascx pages via ajax calls.  This is nice because now you can start to use jQuery instead of relying on Microsoft's Ajax implementation, but I see two problems with it.  First, the methods have to be static and attributed as WebMethods.  The static methods don't let you use instance variables of the class without a lot of ugly and odd workarounds.  Second - as is the case with a lot of WebForms code, since it's code-behinds you either have your Ajax methods duplicated across code-behinds or you have different WebMethods scattered in different code-behinds which is pretty messy.  It's the same sort of spaghetti code and coupling of responsibilities that a lot of people see as a big problem with the WebForm/code-behind model.

Plus - with all these solutions, I'm pretty sure you need to use a third-party (or write your own) solution to serialize your returned objects as JSON.

So what's the solution?

ASP.NET MVC Works Cleanly With Ajax Out Of The Box

Finally, with ASP.NET MVC, jQuery and Ajax are finally given the attention they deserve.  When you create a new ASP.NET MVC project in Visual Studio, it creates a Scripts folder with jquery.js already in it!  But their support for jQuery and Ajax goes way beyond that.

I'm not going to get too into the nitty gritty details on ASP.NET MVC - if you want that, there are plenty of resources on the web.  But on a high level, the things that make Ajax with ASP.NET MVC so nice are:

  • URLs are just routes to resources, in this case a controller and an action.  Your URL is not pointing directly to a physical ASPX file.  This means you can just point your Ajax request to a controller action and have access to whatever data the controller action returns when its done processing.  And since the URL points to the function where the data is coming from, you're less likely to have duplicated code.  No matter where you need the same data, you can always just point to that controller action as a URL.
  • ASP.NET MVC comes with a JSON serializer.  You simply return a JsonResult from your controller action and the objects are converted to JSON for you.  This means that you also don't have to mark your methods as WebMethods, or make them static or anything like that.  They're just regular methods that return JSON and they're easily called via the controller/action URL.

Here's an insanely simple example to show just how simplified the code can be:

First, the javascript:

   1:  <script type="text/javascript">
   2:   
   3:          $(document).ready(function() {
   4:              $('#ajaxBtn').click(function() {
   5:                  $.ajax({
   6:                      type: 'POST',
   7:                      url: '/Home/GetFakeObjects',
   8:                      success: function(data) { updateDocument(data) },
   9:                      error: updateDocument
  10:                  });
  11:              });
  12:          });
  13:          
  14:          function updateDocument(data) {
  15:              $.each(data, function(key, value) {
  16:                  $('#results').append('<li>' + value +'</li>');
  17:              });
  18:          }
  19:          
  20:  </script>

And now, the ASP.NET Controller and Action:

   1:  [HandleError]
   2:  public class HomeController : Controller
   3:  {
   4:       public JsonResult GetFakeObjects()
   5:       {
   6:            var returnedObjects = new List<string>();
   7:            returnedObjects.Add("Dan Donahue");
   8:            returnedObjects.Add("Somebody Else");
   9:            returnedObjects.Add("Another Person");
  10:   
  11:            return Json(returnedObjects);
  12:       }
  13:  }

 

I don't think the code needs much explanation if you've played with jQuery and Ajax before, but as you can see in the javascript, the url that we're posting to via Ajax is "Home/GetFakeObjects" which ASP.NET MVC routes to new HomeController().GetFakeObjects()  and that method returns a JsonResult with that list of people's names.  This data is then available in the successMethod of the ajax request.  Simple as cake.

But My App Isn't Built With ASP.NET MVC

Never fear... it doesn't have to be.  You can actually mix ASP.NET MVC with ASP.NET WebForms in the same project.  This is great if you want to start moving your project to ASP.NET MVC piece by piece, or if you want to just take advantage of the Ajax benefits that I described above without converting your entire web app to ASP.NET MVC.

Hit the links below for information on mixing the two technologies in your app.

http://www.hanselman.com/blog/PlugInHybridsASPNETWebFormsAndASPMVCAndASPNETDynamicDataSideBySide.aspx

http://www.packtpub.com/article/mixing-asp.net-webforms-and-asp.net-mvc

 

Wrap Up

There is only so much finagling you should put up with to solve a problem.  This is especially true in code when "finagling" typically means using hacks or generally degrading the quality of the code you're writing in order to work around a problem.  When that happens, sometimes it's best to just look into bringing in a better technology that has already solved the problem nicely, rather than desperately looking for the next "quick fix" which will ultimately cause more problems down the line that will need additional "quick fixes".  As the Pragmatic Programmer says... quick fixes are quick sand.

So if you have a WebForms app that you're jumping through hoops to add jQuery too, maybe bringing in ASP.NET MVC to, at the very least, handle the Ajax portions, is a good alternative.

MVCommand - Hello World

I recently decided to pull down MVCommand, which is a front controller implementation built on top of ASP.NET MVC that uses individual Command objects (or a set of Command objects) to process requests.  It was created by an old co-worker of mine, Erik Peterson.  You can read more about his implementation here and here.

I was interested in the project because I am of the opinion that a controller handling multiple actions seems like its doing too much and this solution addresses that issue.  It also seems like a shorter tail solution than picking up FubuMVC, while accomplishing many of the same things that FubuMVC is trying to accomplish.

I wanted to see how easy it was to use MVCommand and I was impressed at how simple it was to get it going.  The app I created is about as simple as simple gets... but I really just wanted to see how much effort was involved in getting something set up to use MVCommand.

Getting MVCommand:

The first thing I did was pull down MVCommand from Erik's github profile.  There is a version specific to ASP.NET MVC 2, so I grabbed that.  But there's also a version that plays with the 1st version of ASP.NET MVC, so if you're still using that version, you can download the MVCommand trunk and you'll be set.  Compile it into a DLL, or just open the solution and follow the steps below.

Creating A New Project:

The next thing I did was create a new ASP.NET MVC, since MVCommand still uses the same project structure - views are stored in the Views folder, Models in the Model folder, etc.  Add a new reference either to MVCommand project if it's in your solution, or the DLL you compiled from the previous step.

Setting Up Your Front Controller:

Instead of having many controllers that relate to different routes in your MVC application, MVCommand handles all requests through a single controller.  That controller determines which command, or set of commands, to run based on the route and executes them.

Setting up the controller used to handle this is a cinch.


   1:      [HandleError]
   2:      public class ConfigController : CommandController
   3:      {
   4:          public override Type[] CommandTypes
   5:          {
   6:              get
   7:              {
   8:                  var temp = typeof (ConfigController).Assembly.GetTypes().Where(x => typeof (ICommand).IsAssignableFrom(x) && !x.IsInterface).ToArray();
   9:                  return temp;
  10:              }
  11:          }
  12:   
  13:          public override Type BindableCommandType
  14:          {
  15:              get { throw new NotImplementedException(); }
  16:          }
  17:      }

CommandController is an abstract class provided by MVCommand.  It forces you to implement two properties - CommandTypes and BindableCommandType.  BindableCommandType is too advanced for this post, but the CommandTypes array is just a collection of all the commands in your project.  You can set this up however you like, whether it be manually adding them, using an IoC tool, or just running through the assembly types and returning all of the Command objects, as I did above.  In the end, you just want to have a list of all the Types in the assembly that are Commands.

Setting Up Your Front Controller Factory:

After you've created your front controller, you have to create a new controller factory - the class responsible for returning the correct controller.  Again, since ASP.NET MVC's controller factory will return whatever controller corresponds to the request, we need to override that behavior and have our default controller used for every request.

Again, this is pretty simple.


   1:  public class ConfigControllerFactory : CommandControllerFactory
   2:  {
   3:       public override IController CreateController(RequestContext requestContext, string controllerName)
   4:       {
   5:            var commandController = new ConfigController();
   6:            return commandController;
   7:       }
   8:  }


CommandControllerFactory is an abstract class in the MVCommand project. Create your own controller factory class and inherit CommandControllerFactory.  The overridden method implementation should just create your front controller.

In order to let ASP.NET MVC know that you want to use your custom controller factory instead of the default one, you have to add this line to your global.asax file in the Application_Start method:

   1:  ControllerBuilder.Current.SetControllerFactory(typeof(ConfigControllerFactory));

Setting up an IoC Container for Service Location:

MVCommand uses Microsoft Patterns and Practices Service Location to create instances of the commands it executes.  The MS Service Locator is an abstract service location tool which lets you use any IoC container and service locator in your code without hardcoding references to the IoC in your code.

I used StructureMap as my IoC container in my application.  I'm not going to get into setting up the StructureMap container because you find that elsewhere.  But once you have the container, you do have to tell Microsoft's Service Locator how to use it to, well, locate your services :)

To do that, I created a class called StructureMapServiceLocator that overrides ServiceLocatorImplBase.  This base class is what MS Service Locator uses to find your classes, so you basically have to fill in the overriden methods with calls to your StructureMap container that retrieves instances of the requested type.  It looks like this:

   1:      public class StructureMapServiceLocator : ServiceLocatorImplBase
   2:      {
   3:          private readonly IContainer _container;
   4:   
   5:          public StructureMapServiceLocator(IContainer container)
   6:          {
   7:              _container = container;
   8:          }
   9:   
  10:          public IContainer Container { get { return _container; } }
  11:   
  12:          protected override object DoGetInstance(Type serviceType, string key)
  13:          {
  14:              return  string.IsNullOrEmpty(key)
  15:                         ? _container.GetInstance(serviceType)
  16:                         : _container.GetInstance(serviceType, key);
  17:          }
  18:   
  19:          protected override IEnumerable<object> DoGetAllInstances(Type serviceType)
  20:          {
  21:              return _container.GetAllInstances(serviceType).Cast<object>().AsEnumerable();
  22:          }
  23:   
  24:          public override TService GetInstance<TService>()
  25:          {
  26:              return _container.GetInstance<TService>();
  27:          }
  28:   
  29:          public override TService GetInstance<TService>(string key)
  30:          {
  31:              return _container.GetInstance<TService>(key);
  32:          }
  33:   
  34:          public override IEnumerable<TService> GetAllInstances<TService>()
  35:          {
  36:              return _container.GetAllInstances<TService>();
  37:          }
  38:      }

And just like with your overriden controller factory, you have to tell the MS Service Locator to use your StructureMap service locator in the global.asax file:

   1:  var serviceLocator = new StructureMapServiceLocator(container);
   2:  ServiceLocator.SetLocatorProvider(() => serviceLocator);

Creating Your First Command:

By default, MVCommand runs all of the commands in a namespace that relates to your route.  This behavior can be overriden by providing a dictionary that maps commands to a route, but that's beyond the scope of this post.

The main route is below:

   1:  routes.MapRoute(
   2:                  "Default", // Route name
   3:                  "{context}/{event}/{id}", // URL with parameters
   4:                  new {controller = "Command", action = "DefaultAction", id = ""}             // Parameter defaults
   5:                  );

(note that the second token of the url has been renamed from 'action' to 'event' - you will need to rename that token as well)

In the case of this route, MVCommand will run all the commands where the namespace ends with 'Context.Event'.  So for example, in my example, I called this url: http://localhost:1162/home/helloworld and the command whose namespace ends with *whatever*.Home.HelloWorld.  If there's multiple commands in that namespace, it'll run them all.

For my insanely simple example, I created a new Command simply called Command2 with hard-coded return value of my name and age.

   1:  namespace MVCommand.HelloWorld.Commands.Home.HelloWorld
   2:  {
   3:      public class Command2 : ICommand
   4:      {
   5:          public object Execute()
   6:          {
   7:              return new HelloWorldModel {Age = 31, Person = "Dan" };
   8:          }
   9:      }
  10:  }

(note that the namespace ends with Home.HelloWorld')

This class implements the ICommand interface that is part of the MVCommand framework.  This is insanely simple, but you could do any processing necessary in this class, whether it be hitting a database or whatever the case may be.

The returned object is set in the ViewData dictionary.

Using The Returned Model In The View:

The last piece of the puzzle is getting the data that was returned from the Command and using it in your View.  I created a HelloWorld.aspx view and made it inherit from an MVCommand helper class ViewBasePage<T> where T is the model.  This just creates a property named Model with the object that is returned from your command.

   1:  <%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="MVCommand.Views.ViewBasePage<MVCommand.HelloWorld.Models.HelloWorldModel>" %>
   2:   
   3:  <asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
   4:      HelloWorld
   5:  </asp:Content>
   6:   
   7:  <asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
   8:   
   9:      <h2>HelloWorld</h2>
  10:   
  11:      <p>
  12:          Hello, <%: Model.Person%>.<br />
  13:          You are <%: Model.Age %> years old.<br />    
  14:      </p>
  15:      
  16:   
  17:  </asp:Content>


Wrapping It Up:

That's about it.  As you can see, it's pretty easy to get up and running with MVCommand.  Just set up a front controller and new controller factory to create instances of that controller.  Then, set up your IoC container and service location.  Then, start creating commands and views and go to town!

Hopefully that is enough to get you started with MVCommand. Download it and start playing around.

I hope to do more posts in the future about MVCommand.  I know there are other things to go over, such as using the Command dictionary instead of namespacing to determine which commands to run for a request.  And how to get and use form data and querystring values in your Commands.  Look for those posts at a later date.

Til then... don't hesitate to leave comments with questions, or if you noticed I royally screwed something up.   It wouldn't surprise me if I missed something, mis-typed something or otherwise had some sort of brain fart while writing this up.  So thanks in advance for the feedback.

Book Review: Code Complete

I've been trying to be constantly reading a book for about the past year and a half now.  And in addition, I started a dev book group where I work, where we pick a book and read it a certain amount each week and then meet for an hour to discuss that section - whether it be making decisions on whether this is something we want to do as a department, or how we can apply the topic to our projects, etc.

The latest book we just finished was Code Complete.  I feel like I was long overdue reading this one as I've heard a few times in the past that this was one of those required reading books on programming.  Actually, on more than one occasion, I've been asking during a job interview what books I've read and liked the most and after giving my list, the interviewer has said "all great books... the only one I'd add is Code Complete".  So I was pretty excited to finally read through this one.

I've broken up my review into a section of positives, negatives and then a summary.  I find that helpful because sometimes reviews get too verbose and will be filled with double speak such as "the paragraph on *whatever* was great, except ..." .  So I'm going to try to avoid that and just talk about what I liked, what I didn't.

POSITIVE:

I can't stress enough how much good information this book is packed with.  There's a ton of information to digest about a wide range of topics - from how to organize and comment your code to team dynamics, estimation tipis and even programmer human characteristics - this book does a great job of taking a good 1000ft.view of a lot of aspects of software development and also gives a lot of "read this next" resources for topics that you might want to delve deeper into.  McConnell (the author) does a pretty good of using case studies to back up his points.  And while some of the information is a little out of date in the book (happens often in these types of books... the software industry just moves too fast), a lot of the information is plenty applicable no matter what language you develop in, type of development you do, etc.

NEGATIVE:

First off - this book is long... REALLY long.  We actually skipped a few chapters early on during the book group and it still felt like the book would never end.  That's a bit nitpicky though as the Lord Of The Rings trilogy is long as hell, but it's a great read   I think the biggest disappointment to me was that a lot of the information put forth was stuff that you learn your first few years in professional software development and it just becomes common sense.  More often than not, I found myself (and I believe some of the others in the group) saying "these are great points - but I already knew this" or "these are great points - but this is common sense".  And then, of course, the problem with a 1000ft. view that I mentioned earlier is that if you find yourself interested in one of the ideas that he presents, you would love to learn more, but it's just not there.  That's not a problem with this book in particular... but I guess my preference is with more directed learning books.  Books that take a smaller array of topics and really delve into them in greater detail.

SUMMARY:

I'm not sure I'd ever read this one again.  Like I said, it just contains too much information that I already knew.. and I don't even pretend to be a software guru by any stretch of the imagination.

However, this book is far from worthless.  I think this book should be required reading in a college course on programming, or the first book a young developer reads before ever working on their first project.  This is type of stuff that you can either learn organically by being in the industry for a while and seeing it all come to life in both good and bad ways in your projects, or you can just read this book and enter the industry with this knowledge in hand.  It'll put you on level playing ground with people who take the long path.

I also think this is one of those books that would be a checkmark in the thumbs up column if a prospective new employee had mentioned reading it.  It would be a sign that the developer was equipped with knowledge of good programming practices and ideas (of course - whether they apply them is a different story, but you'd rarely get that out of an interview anyway).

Bottom line... new developers should be forced to read this book.  Older developers probably already know most of what it contains.  But it was nice to get some of this knowledge reiterated (much like how I re-read The Pragmatic Programmer every year or two just to get rejuvenated) and also have the case studies to back up the information with statistics.  It's one thing to do something a certain way because it works for you, and even better when it turns out that it works for the entire industry :)

Linq To Sql Web App Lifetime Management - Take 1

I was asked to help another project team at work to come up with a good way to manage Linq To Sql data contexts on their project.  Their current situation is that they open and use a datacontext wherever needed, but often run into problems where they're trying to save entities with expired contexts or opening too many connections to the database to grab the same record multiple times.  They're not fully utilizing the datacontext's features such as the Identity Map or Unit Of Work.

I haven't had much experience with Linq prior to being asked to help, but I knew the basics.  For the rest, I decided to do a bunch of blog reading on the subject to help out with my implementation.  My criteria for a good solution was the following:

Ease Of Use / Clean Syntax
I figured this one was self-explanatory.  First, I didn't want to get into a huge architecture if I didn't have to and furthermore, I figured that if it wasn't easy to implement and use, no one would want to do the work to implement it.

Unit Testable:
I like to do unit testing and wanted to be able to write tests that didn't actually hit the database.  I wanted to be able to write mock versions of the implementation instead for tests so I could control them during my tests.

Unit Of Work/Lifetime Management:
This was to solve the problem that they came to with me in the first place.  Microsoft, as well as common sense, indicate that you should really only have one datacontext around per request for web applications.  This seems to make sense since the datacontext already is built like a unit of work (it records all changes to entities, inserts and deletes and waits until SubmitChanges() to actually persist them to the database).

Validation Of Entities:
Another concern the team had was how to validate entities before saving them.  Their current implementation was to create partial classes for each entity and create custom attributes to perform validation.  I did not include my solution as part of the prototype I came up, but I actually suggested they pull the validation out into separate Specification objects - this way, they can keep the entity classes to solely what Microsoft provides them and the Specification objects can be reused, as well as making more explicit the business rules around a valid entity - something I learned from reading Eric Evans' DDD book.

What I came up with was pretty simple. I mostly just took a lot of what other bloggers were suggesting and stripped out a lot of stuff I didn't think was necessary at the moment.  Not that I felt others were over-complicating the matter, but they were showing examples of things they needed for their projects which may not necessarily be needed in this one.  And taking the YAGNI approach, I felt like I should keep it as simple as possible, knowing that I could add in the desired features later if necessary.

So, finally, here is the design I came up with...

   1:  public class UnitOfWork : IUnitOfWork
   2:  {
   3:       private readonly EntityClassesDataContext context;
   4:   
   5:       public UnitOfWork()
   6:       {
   7:            context = new EntityClassesDataContext();
   8:       }
   9:   
  10:       public Table<T> GetTable<T>() where T : class
  11:       {
  12:            return context.GetTable<T>();
  13:       }
  14:   
  15:       public void SubmitChanges()
  16:       {
  17:            context.SubmitChanges();
  18:       }
  19:  }

This UnitOfWork class just wraps the DataContext and implements an IUnitOfWork interface which can then be used in the rest of the system, so that we can mock it during tests.  It just provides the ability to get a table (which can then be queried, or inserted to/deleted from) and run SubmitChanges().  I considered having SubmitChanges() be run automatically at the end of each request, but I felt like that was dangerous as you may not want all changes submitted - I want to make it more explicit and require programmers to call that function when they wanted their changes persisted.

   1:  public class UnitOfWorkFactory
   2:  {
   3:       private const string HTTP_CONTEXT_KEY = "SFT.UnitOfWork.Factory.Context.Key";
   4:   
   5:       public static IUnitOfWork GetUnitOfWork()
   6:       {
   7:            if (HttpContext.Current != null)
   8:            {
   9:                 if (!HttpContext.Current.Items.Contains(HTTP_CONTEXT_KEY))
  10:                 {
  11:                      HttpContext.Current.Items.Add(HTTP_CONTEXT_KEY, Activator.CreateInstance(typeof(UnitOfWork)));
  12:                 }
  13:                 return (IUnitOfWork)HttpContext.Current.Items[HTTP_CONTEXT_KEY];
  14:            }
  15:            throw new Exception("No current HttpContext found.");
  16:       }
  17:  }

This factory is used to get the current UnitOfWork which is stored in HttpContext's Items collection.  It's pretty simple.  If you ask for the current UnitOfWork and it hasn't been created for the current request yet, it creates it and puts into the Items collection.  Then, it returns it.  Otherwise, if it already exists, it returns the one that's in the Item's collection already.  From what I read, this should guarantee that you always use the single, per-request DataContext which means you take advantage of the Identity Map (instead of loading the same entity from the db multiple times) and have all your changes in a request tracked.

   1:  public DefaultPresenter(IDefaultView view) : this(view, UnitOfWorkFactory.GetUnitOfWork(), new DebtorRepository())
   2:  {
   3:  }
   4:   
   5:  public DefaultPresenter(IDefaultView view, IUnitOfWork unitOfWork, IDebtorRepository repository)
   6:  {
   7:       this.view = view;
   8:       this.unitOfWork = unitOfWork;
   9:       this.repository = repository;
  10:  }

And this is how I used the factory in my prototype.  Dependency injection allows for unit testing because in the unit tests, I can use the 2nd constructor and pass in a mock of the IUnitOfWork, but in production, I can use the above constructor which calls on the UnitOfWork factory to get the concrete UnitOfWork class that wraps the Linq datacontext.

I know that IoC containers would get me down to one constructor, but for the purposes of the prototype, I didn't want to do the extra work.  However, itt's probably something I would suggest if this is used in an actual project.

The last thing which I won't post is that I use Repositories for getting data.  I do that cut down on the duplication of queries across the codebase and also to abstract out the Table classes that come with the datacontext since they're not easily mocked for testing.  I read about ways that you could mock them out and provide data from an in-memory data store during testing, but when I'm testing the presenters, I don't want to have to worry about all the overhead of setting that up in my test, so I'd rather just put it behind an IRepository interface.  When it comes time to test the Repository classes, I can focus on how to write the tables with an in-memory data collection.

And that's it.  I would love some feedback as this is my first time taking up something like this.  Is there any obvious, or not-so-obvious flaw in this design that I'm missing?  Are there any ways it could be improved?  Your comments would be greatly appreciated.