The Most Important Layer Of Them All

By Mike on 17 April 2014

If you tell a dev about 3 tier architecture 99.99% (s)he will reply "I know that, I'm using it in my Mvc app". And indeed, pretty much anyone is using a 2-3 tiers architecture , at least in theory. Even in practice an app seems to be structured that way, but in a lot of cases I see that only lip service is paid to Separation of Concerns (that's why you're layering your app in the first place). You can see db access or business logic in the controller, because it's simpler to implement that way, you can see the business model almost designed to represent a rdbms relationship (or to make things easier with the ORM or data serializer etc). Simply put, we have the layers, we know about them, but their spirit and purpose is not respected.

If you bothered to structure the app in a way, at least think why you did it. You decided that a layer should handle a certain responsibility, all code belonging to that layer should honour that. But it's hard to see things that decoupled, after all, the layers are just different point of views of the same thing. But which layer is the most important i.e which defines the thing?

Usually, you can see something like this: the DAL/Persistence at base, Business Layer/Domain in the middle and UI on top. It's no wonder that a lot of devs are starting with the database schema. After all the DAL is the base layer right? We need a strong foundation.

But you can see another approach, like in the Onion Architecture . It looks quite different right? Damn layers!

The good news is that there's always a hierarchy which should be respected in every app. I don't care about top or bottom, I do care about the leading, the master layer that every other layer serves. It's the Business/Domain layer. It's the center of the app, the master of them all. And you know why? Because the Domain encapsulates the reason you are building the app. An UI is similar in every app (get input from user, show some view to user), the persistence is about db access (we put/query data regardless on its structure), you might have an infrastructure layer which holds utilitarian behaviour, but these are not the primary purpose of the app being built.

The app should solve (at least) a problem for its users, and the problem and solutions are defined in the Domain. The other layers just provide the support for it. The UI presents a nice way for the user to interact with the app, which for complex app is quite different from how the Domain is structured, the DAL deals with storing data required by the Domain and so on.

The Domain Layer (DL) is the sun and everything else revolves around it. That's why the DL doesn't take a dependency on other layers, other layers take DL as a dependency.  That's why you should design the Domain objects ignoring everything else (how will it be presented or stored? who cares!). For a maintainable app things must be kept clear and decoupled. You want the domain objects focused on the problem or solution. You don't want bits of problem/solution scattered everywhere in the app. When the app evolves, because business rules change, the Domain should be easily changeable while the other layer would change as well (they follow the master). But when you change something in a support layer, the Domain shouldn't be touched. It's the Master, don't bother him with a problem a servant has.

It's easier to use this analogy: the DL is the King, everything else are its subjects. The King deals with (app) important matters, it's the ruler of the domain (sic) he decides what and how it will change. The King doesn't care about what's beneath him and dictates the changes everybody else must implement. And you don't tell the King to change its diet (encapsulating a filed in a property with a public getter or making things virtual) because a cook can't easily find an ingredient (the ORM has trouble persisting/restoring a domain object or the UI wants some total displayed).

In conclusion, the Domain is your spoiled precioussss and you should treat it like such. You don't implement domain concepts, behaviour or use cases outside the DL and you don't change domain objects because other layer needs it. Having the discipline to really respect the Separation of Concerns means your code is decoupled and maintainable i.e it's easier to change it often.

MvcPowerTools Preview: Html Conventions

By Mike on 11 April 2014

The moment we'll all be waiting for. Well, at least I was... I know this is (was) a Fubu feature that people used with asp.net mvc, but it was simply hat a developer extracted from Fubu then glued with the asp.net mvc. Html Conventions in MvcPowerTools (MvcPT) are a first class citizen, deeply integrated with Asp.Net Mvc. So, now you can use HtmlConventions like in Fubu (well the syntax resemble but it's not 100% identical) as a 'native' asp.net mvc feature.

If you don't know what's the deal with html conventions, let me make you a very short presentation. .Net Mvc templated helpers are great but they're a bit cumbersome if you just want something more of a widget, a mini-template that can be customized in more than 1 step. And sadly the mvc's behaviour is an all or nothing affair: you either use display templates for all properties in your model and you get away with _Html.EditorForModel_ or you have to write manually for every property _Html.EditorFor(m=>m.Property)_ just to have control for one property you want to be rendered differently.

The point of html conventions is to define html rendering 'rules' that will apply to all model matching a criteria. This means you can make bulk changes just changing a few lines of code in a convention. As I've said before, it works at a widget level. It's possible but not recommended to generate ALL the html via conventions. Among the best use cases are form fields (input controls). If you're dealing with many forms and fields, html conventions are a productivity saver. Add/change a convention and all targeted controls are automatically updated. A note about testing, the deep integration with asp.net mvc is both a blessing and a curse, in order to test the conventions you have to mock at least ViewContext (which requires a ControllerContext and so on). For now it's like this, maybe in a future version I can avoid this tight coupling (I wonder if 'integrated' and 'decoupled' are compatible).

In this post I'll show you some interesting examples to show you the possibilities, it's not really meant to be a tutorial. Let's begin!

I happen to use angularjs for my mvc javscript needs and I'm using it when editing a form. So I want that every model that I annotate with [NgModel] to generate html inputs supporting anuglarjs i.e having the _ng-model_ and _ng-init_ attributes set. To define the conventions I recommend the following directory structure (each .cs file is a HtmlConventionsModule)

App_Start - Html - Display - Build.cs
				          - Modify.cs
					  - Ignore.cs		
							
			   - Editors - Build.cs
			                 - Modify.cs
					 - Ignore.cs					
							
			   - Labels  - Build.cs
				          - Modify.cs
					  - Ignore.cs					
                  

				  
     public class NgModelAttribute:Attribute
    {
         
    }
	
	//namespace App_Start.Html.Editors
	
	 public class Modify:HtmlConventionsModule
    {
       
        public override void Configure(HtmlConventionsManager conventions)
        {
            var e = conventions.Editors;
			
			 e.If(m =>
                (!m.IsRootModel && m.ParentType.HasCustomAttribute<NgModelAttribute>() &&
                 !m.HasAttribute<NoAngularAttribute>()) || m.HasAttribute<NgModelAttribute>()
                )
                .Modify((tag, m) =>
                {
                    var input = tag.FirstInputTag();
                    if (input == null) return tag;
                    var ngName = "res." + input.Attr("name").ToLower();

                    input.Attr("ng-model", ngName);

                    if (!m.ValueAsString.IsNullOrEmpty() && !m.Type.IsUserDefinedClass())
                    {
                        if (m.Type.Is<bool>())
                        {
                            input.NgInit("{0}={1}".ToFormat(ngName, m.ValueAsString.ToLower()));
                        }
                        else
                        {
                            input.NgInit("{0}='{1}'".ToFormat(ngName, m.ValueAsString.AddSlashes()));
                        }
                    }
                    return tag;
                });
				
			e.Always.Modify((tag, i) =>
            {
                var input = tag.FirstInputTag(t => t.IsHiddenInput());
                if (input == null) return tag;
                if (input.HasAttr("ng-model"))
                {
                    input.Angular("update-hidden");
                }
                return tag;
            });
        }
	}

	//Setup the conventions
	 public class ConfigTask_HtmlConventions
    {
        public static void Run()
        {
			//predefined modifiers which mimic default asp.net mvc templating behaviour
			HtmlConventionsManager.LoadModule(new DataAnnotationModifiers(), new CommonEditorModifiers(), new SemanticModifiers(), new CommonDisplayModifiers());
					
			//load all conventions defined in the assembly
			HtmlConventionsManager.LoadModules(typeof (ConfigTask_HtmlConventions).Assembly);
			
			//predefined builders for use with model annotations
			HtmlConventionsManager.LoadModule(new DataAnnotationBuilders(),new CommonHtmlBuilders());            
		}
	}

While it looks a bit scary, it's pretty simple. We check that the model is a property and the parent or the property has [NgModel] and if that's the case, we modify the supplied HtmlTag: get the input element then add the ng-model attribute with the property name (made to be angularjs compatible). Then we handle some edge cases (these come out after you're using the app). In the end, we make sure that the hidden fields are updated, by adding the update-hidden directive.

In the view the code looks like this

@Html.EditModel()
<!-- or -->
@Html.Edit(m=>m.MyProperty)

Now, any view model decorated with [NgModel] is automatically angularjs ready.

You can freely mix .Net Mvc's Html.EditorFor() and Html.Edit(), any MvcPT helper which works with properties is compatible with the default html helpers.

Let's see some Twitter Bootstrap integration. This automatically adds the classes form-control and form-group when rendering html text inputs.

e.If(m => !m.IsRootModel)
	.Modify((tag, m) =>
	{
		var input = tag.FirstInputTag();
		if (input != null && input.IsHiddenInput()) return tag;
		var type = input.Attr("type");
		if (type != "checkbox" && input.TagName()!="textarea")
		{
			input.AddClass("form-control");
		}
		return tag;
	});

	e.If(m => 
	!m.IsRootModel && !m.Type.IsUserDefinedClass() && !m.PropertyOrParentHasAttribute<InlineAttribute>())
	.Modify((tag, m) =>

		new HtmlTag("div").AddClass("form-group").Append(tag)
	);

These are example when you want to render input fields, forms but the same thing can be applied when you just want to display things. Here's a simple convention that says to render any property having [Text] as a <pre>

var d=conventions.Displays;
	
	d.If(m => m.PropertyOrParentHasAttribute<TextAttribute>())
                .Build(m =>
                {
                    return new HtmlTag("pre").Text(m.ValueAsString);
                });

Here we're building a display date time widget. Automatically, any DateTime property will be rendered with the widget.

d.ForType<DateTime>()
                .Build(m =>
                {
                    var time = m.Value<DateTime>();
                    var tag = new HtmlTag("div")
                        .AddClass("last-update")
                        .Attr("title", time.ToLocalTime())
                        .Text(string.Format("Updated {0}", DateTime.UtcNow.Subtract(time).ToHuman()));
                    return tag;
                });

In views

@Html.DisplayModel()
	@Html.Display(m=>m.Property)
	
	//want to display a defined template like asp.net mvc does, but for ANY model
	@Html.DisplayTemplate(someModel)
	
	//Now you can do this
	@foreach(var item in Model.Items)
	{
		@Html.DisplayTemplate(item)
		//or if you want to use html conventions 
		@Html.Widget(item)
	}

The cool thing here is that you don't need to create a partial (template) view for List<Bla> just to be able to use the templated html helpers.

Whoa, that's a long post already and I've only scratched the surface of what you can do with html conventions. It's a pretty big and complex feature but it can give you a LOT of power and flexibility when building your views. To give you an idea, you have support for html conventions profiles that can be changed on every request and you can define your own conventions registries besides Editor, Displays or Label (but you need to implement your own html helpers for those).

MvcPowerTools Preview: View Engine Conventions

By Mike on 8 April 2014

What I like the most from FubuMvc (RIP) is the the paradigm of 'make the framework serve you, define your own conventions that suits your style'. Simply put, you decide the way you want to structure and code an app, not some framework. Frameworks are good but they shouldn't be in your way, you shouldn't force your app to comply with the framework, it should be the framework who should comply with your approach.

Asp.Net Mvc is a good, easy to use framework but it still suffers from some 'you have to do things this way' symptoms. One example, why should I always inherit from Controller, instead of using any class and have the dependencies I want (HttpRequest, HttpResponse etc) injected? There's a lot of coupling in asp.net mvc, but this is how it is for now. I'm doing my part with MvcPowerTools to provide SOLID options for some features for when you reach the stage when you begin to fight the framework. I've already written about Routing Conventions and ActionFilters Conventions , now it's time to tackle the view engines a bit.

I'm not really a fan of "~/Views/[controller]/[action].cshtml" . It's a way to structure things but it gets tedious with many controllers and actions. Also throwing everything in Shared is not a good idea either. I like the 'Handler' approach for my controllers (i.e the controller is the action, its methods represent handlers for each supported http method) so the view name is the controller name. And I want that at least for a group of controllers to have the view in the same place as the controller. For other parts of the site, I want the views grouped into a theme/skin with no controller in sight. In a nutshell, I want to name and put my views wherever I need and sometimes that's not a predefined location (think themes, you want the user to copy the theme into directory with whatever name and the app should be able to use it).

How to achieve that with the default aps.net mvc view engine? First of all, let me tell you a little trick: a view engine in asp.net mvc is actually a view locator. Then you have the templating engine (Razor for example) who does the real work. MS decided to couple these 2 so that's why there is an aspx view engine and a razor view engine. It should be one view engine (locator) supporting n template engines, but I digress.

Anyways, if you want to change the view location or even use a different view name convention (not the action name) you can do it by inheriting (yeah...) one provided view engine and then change the paths. What if you want to support themes i.e have another dynamic value (besides controller and action) in a path of a view? Well... you kinda have to rewrite a lot of what the view engine does, because it only provides 2 variables: controller and action name. What if you want (gasp!) different naming and path conventions for your views in the same application? Please, don't say:"Why would you want that? One convention to rule them all is the best". Yeah and one model for everything is also the best.

Long story short, if you truly want to be in control of your views, there's a lot of work and some pain with asp.net mvc. Let MvcPowerTools (MPT) ease that pain with the FlexibleViewEngine. Yeah, it's flexible because YOU decide the conventions it uses. And you can have as many conventions as you need. You can start with one, the add some more. The only effort is to write the convention class. Nothing else.

For this example, I want my views in the same folders with my controllers and the view has the controller name. Let's see how hard it is to implement it.

public class ViewsPolicy:BaseViewConvention
    {
        public override bool Match(ControllerContext context, string viewName)
        {
            return !viewName.StartsWith("_");
        }

               public override string GetViewPath(ControllerContext controllerContext, string viewName)
        {
            var ctrl = controllerContext.Controller.GetType();

            var path = ctrl.ToWebsiteRelativePath(GetType().Assembly);
            return path + ".cshtml";
        }
    }

	//let's enable all conventions defined in the assembly
	 FlexibleViewEngine.Enable(c =>
            {
                c.Conventions.Clear();
                c.RegisterConventions(typeof (ConfigTask_ViewEngines).Assembly);
            },removeOtherEngines:true);

Lots of complicated code here, let me help you understand it: first we decide when to apply the convention, in this case the view which isn't a partial (the underscore prefix designates a partial). Next, we need the path to the controller and we have a nice extension method (part of the tools) that takes a namespace and returns it as a path. We add the desired suffix and that's it.

Now, let's see the code for when I want to have views with the controller name directly in ~/Views but with theme support.

/// <summary>
    /// Used with Handler pattern controllers
    /// </summary>
    public class ViewIsControllerNameConvention:OneLayoutConvention
    {
        public override bool Match(ControllerContext context, string viewName)
        {
            return !viewName.StartsWith("_") && !FlexibleViewEngine.IsMvcTemplate(viewName);
        }

        public override string GetViewPath(ControllerContext controllerContext, string viewName)
        {
            var theme = controllerContext.HttpContext.GetThemeInfo();
            var controller = controllerContext.RouteData.GetRequiredString("controller");
            if (theme==null)
            {
                return "~/Views/{0}.cshtml".ToFormat(controller);
            }

            return "{0}/{1}.cshtml".ToFormat(theme.ViewsPath,controller);
        }
        
    }

I think only one thing needs to be explained: GetThemeInfo() . Theme support is provided by MPT via extension method and configurable structures. You only need a view engine capable to use them.

In conclusion, you get the power to control the view engine and writing a convention is as hard as you've seen above. A word of advice, make separate conventions for views and partials, it's easier this way.

P.S: I do understand if you don't find this feature useful, the point of MPT is to provide options for those who want them. Having alternatives is great, especially for those 1% edge cases asp.net mvc won't play nice with.

MvcPowerTools Preview: Query and Command Controllers

By Mike on 7 April 2014

MPT gives you a helping hand if you want to use Query or Command Handlers  . While not exactly the same implementation as Jimmy's, it's the same idea, only combined with the Handler Controller approach (in a nutshell, the Controller is the action and its methods handle GET/POST, very similar to WebApi or REST approach). It also makes use of the One Model In, One Model Out convention.

Note that these are opinionated choices, alternatives and not yet another silver bullet solution. Just another way to do things, that might suit your style. Enough said, let's see some code (pasted directly from an app I did recently, and yes, that's ALL the controller and handler code).

public class TagsListController : QueryController<PagedInput, TagsListModel>
    {
        public override ActionResult Get(PagedInput input)
        {
            return Handle(input);
        }
    }

 public class TagsListHandler : IHandleQuery<PagedInput, TagsListModel>
    {
        private readonly IQueryTaxonomyStats _stats;

        public TagsListHandler(IQueryTaxonomyStats stats)
        {
            _stats = stats;
        }

        public TagsListModel Handle(PagedInput input)
        {
            var model = new TagsListModel();
            model.Page = input.Page;
            model.Resources = _stats.GetTagList(input.ToPagination());            
            return model;
        }
    }

Let's see: you have an input model (PagedInput) received by the controller. The controller just asks the base QueryController to handle it, in essence, to return the view (output)model for that input. All that the query controller does is to use the Dependency Resolver to invoke the defined handler that accepts PagedInput and returns TagsListModel. In this specific scenario I'm using a repository, but I could have just used an ORM directly. The handler's job is to assemble the view model and here it's quite trivial.

You may ask yourself why should we bother with this when we could've put that handler behaviour directly in the controller. The answer is: decoupling. TagsListHandler is somewhere outside asp.net mvc, UI, in my app is part of the QueryModel project . Also, as you can see, it doesn't depend on asp.net, controllers, HttpContext etc. It's totally decoupled from the UI and this means it easy to test and it can be reused outside asp.net mvc.

So, TagsListController's job is simply to build the input model (in this case it doesn't have to do anything) that will be use by the query handler. And all controller handling queries look like this one. The important part is the query handler itself, which is just a class from a querying layer.

Now let's see a command controller.

public class AddInformationsController : CommandController<AddInformationsModel,NoResult>
    {

        public ActionResult Get()
        {
            var model = new AddInformationsModel();
            return View(model);
        }

        public override ActionResult Post(AddInformationsModel model)
        {
            return Handle(model,
                d =>
                    this.RedirectToController<BrowseResourceController>(
                        c => c.Get(new BrowseResourceInput() {Type = ResourceType.Informations})));           
        }
	}
	
	 public class AddInformationsHandler:IHandleCommand<AddInformationsModel,NoResult>
    {
        private readonly IDispatchMessages _bus;

        public AddInformationsHandler(IDispatchMessages bus)
        {
            _bus = bus;
        }

        public NoResult Handle(AddInformationsModel model)
        {
            //map model to domain entity
			//add entity to storage
			//publish domain event
            return new NoResult();
        }
    }

 So, I want to add an information. The Get method returns a view with an empty view model. Then, the form is submitted and the Post method is invoked. The command controller will use the DependencyResolver to request and execute a handler which takes an AddInformationsModel input (command) and returns NoResult (if you want to return let's say an id, define a class SomethingId encapsulating the id and use that instead of NoResult). Please excuse the pseudocode comments, the actual code is irrelevant here. The controller's Handle method second argument is a lambda for what to do after the command is handled successfully, in this case a redirect. Again, the advantage is that we keep the command handler outside of UI, decoupled from asp.net mvc. In this example, the handler is part of the Domain (I don't have a Services layer).

As you can see, the controllers are as slim as they can get (1-2 lines of code) while the real logic is in the proper layer. And if you followed closely, you could see a convention at work here:  TagsListController, TagsListModel, TagsListHandler. If the input model had more then a 'page' property, I would have had a TagsListInput class as well. It's easy, even now, after a few good months to go directly to the class I need, when I want to change something.

A final note, this approach really require the use of a DI Container and of course, the handlers need to be registered with one.

Software Development Is A Marathon

By Mike on 5 April 2014

I really like productivity tools. I want to develop software faster, I want to work less, I want to release software fast.  Unfortunately, there is a mindset that cares only for (initial) speed and productivity at the expense of everything else. Those developers rush to finish fast and are very proud of it. They'll code in 2 days, what you code in 5. Sure, they don't have tests, the 'architecture' is at most MVC and the software 'just works' (well, you know... bugs but what software is perfect anyway?) Changes mean patching/hacking things together and it's all natural that everything will become a complicated mess, it's software development, it's expected to be hard and complicated (really?!).

But nevertheless, they 'ship' the first version so fast, they're that good. Too bad that a software product is finished only when it's at the end of life. Finished software is dead software (found that bit on twitter) and I wholly agree with it.

You see, developing software is like running a marathon. It's a long affair and it does matter to first finish (not to quit or die on the way) then to finish first. In software, to get to the finish is to win. The developers I was talking about before are not marathon runners, they are sprinters. How many sprinters won marathons? None, unless they become marathonists :) But why it that?

Sprinters are very good are running very fast on short distances. They train for that purpose. They simply can't run at that speed for 40Km, the human (animal) body isn't built for that. They might sprint for a time, take a break, sprint some more and so on, but in the mean time it's still the skinny jogging person that will finish the race.

When developers rush for first release or 'to finish' the software, they simply don't care about the long run. It's all now and that's it. Great for things you don't care about, but very bad choice for software you know it's gonna be used for some time, will change and worst of all, YOU'll be maintaining it.

You need to be a marathon athlete. You don't rush, you are going 'slow' (by sprinter standards) but steady. Your work needs to allow you to stay in the race, that is to allow you easy changes. Fewer bugs too, less bugs => less fixing => less breaking. And it's always more fun to code new things than fixing a bug variant for the 58th time. Going steady and not hurrying allows you to keep your sanity, to focus on producing higher quality code which means less boring work.

Fast and productive is cool but quality influences your future work and the question is: can you maintain your speed for all the product's lifetime? If you're fast only at the beginning then you slowdown to a crawl, how do you think you'll be perceived? I think lots of people will say that you are slower, not focused enough, you got older(!) or you don't care enough anymore. Few people will congratulate you for your 'old' productivity, they'll likely say that you were shallow and did a poor, rush out job and that's why you and your team struggle today

Managers and clients always want the work done yesterday, they'll praise you for being fast. They'll also forget instantly about it, when bugs appear or changes take long to implement. It's in your best interest to do a proper job from the start. Productivity is welcome, rushing is not. Design and code your app for the long haul, not just for tomorrow. It will be easier and faster for everyone, especially you, the one who actually has to do the job. Respect yourself and make your job easier, it matters the most to finish the marathon.

MvcPowerTools Preview: Action Filters Conventions

By Mike on 3 April 2014

Action filters are a great way to implement some aspect oriented programming and a powerful feature of Asp.Net Mvc. However, in a big application, it can become cumbersome to decorate controllers and methods with every filter you want. You can use global filters but those are .... global, they apply to everything. If you don't want to copy paste annotations every time, a workaround is to define a base class and make the controller inherit from it. But this is a workaround and on the long run, the solution isn't very clean at all. What if you need filters that are present in 2 base classes? Create a third with the common filters? Slowly the ball of mud gets bigger.

MPT gives you the tools to implement this functionality without inheritance or other duct tape solutions. All clean and SOLID. And easy to use. The point is you define conventions based on which filters are applied to actions. Plain and simple. No tower of annotations required.

As an example, I want that all my controllers from the Admin namespace to require authorization i.e use [Authorize] . Also, I want that all actions names prefixed with 'ajax' to accept only ajax requests. And all the POST actions (either prefixed with 'post' or having [HttpPost]) should be the subject of [ValidModelOnly].

public class MyFilterConventions : FiltersConventionsModule
        {
            public override void Configure(IConfigureFilters filters)
            {
                filters
                    .If(a => a.DeclaringType.StripNamespaceAssemblyName().StartsWith("Admin"))
                    .Use<AuthorizeAttribute>()
                    .If(a=>a.Name.StartsWith("ajax"))
                    .Use<AjaxRequestAttribute>() //part of MvcPowerTools
                    .If(a=>a.Name.StartsWith("post") || a.HasCustomAttribute<HttpPostAttribute>())
                    .Use(()=> new ValidModelOnlyAttribute()) //part of MvcPowerTools
                    ;

            }
        }
		
 FiltersConventions.Config.RegisterControllers(Assembly.GetCallingAssembly());
 FiltersConventions.Config.LoadModule(new MyFilterConventions());
 FiltersConventions.Config.BuildAndEnable();

That's all! Easier and clearly more maintainable than using inheritance, right? And your controllers stay clean. Now, one might argue that it is a good thing to have those annotations right on top of the action. Indeed, it's a visual help. However once you have more than 2 annotations, it becomes a clutter. In my opinion, it's much more clean to set up some conventions and respect those. But it's a matter of taste and this is an alternative to the 'standard' asp.net mvc approach. You can use both at the same time, it's a valid choice also.

A note, if using a DI Container. If you're not creating the action filter instance yourself (like in the final convention above), you need to make sure the DI Container knows how to instantiate the filters you want.

MvcPowerTools Preview: Routing Conventions

By Mike on 1 April 2014

MvcPowerTools (MPT) is a library aimed at the experienced asp.net mvc developer. It's meant to give you the power and flexibility when you find the standard asp.net mvc to be too rigid or just in your way. MPT it's deeply integrated with asp.net mvc (5+) and gives you alternate ways to accomplish things. It's heavily inspired from FubuMvc, so if you're familiar with Fubu, you'll find many similar things here.

Today's post is about Routing Conventions. More exactly, MPT allows you to define your very own routing conventions. One thing to note is that it doesn't replace the standard conventions, you can use both the 'old' style and conventions at the same time, because all the conventions do is to allow you to define how the routes are generated for controllers matching a criteria. Once again, it's a way to extend what asp.net mvc already offers.

So, you may not like to write all your routing by hand (for obvious reasons). Or you might want to use a certain routing approach for some controllers, some attribute base routing for others, namespace based hierarchy for some etc. Of course, you can do all this right now, but ... what if you need to change your routes based on the SEO flavour of the day or to accommodate internationalization  or versioning or.. you get the picture. Would you prefer to do it by hand, changing God knows how many routes or modifying tens or hundreds of controllers or you prefer to change a convention in ONE place and that's it?

The point with routing conventions is that allows you to decouple the route generation from the controllers in a very maintainable manner. You can have as many conventions you need for all the edge cases. You don't have to force everything into a one way of doing things.

Enough talk, let's see some code. Let's suppose I want a namespace based hierarchy for all controllers from the "Admin" namespace. And I want that all actions names starting with 'get' to be constrained as GET and what starts with "post" to be constrained as POST (yes, convention not attribute, less clutter). To keep things tidy, I'll define the convention inside a module (there are other ways)

public class AdminConvention : RoutingConventionsModule
        {
            public override void Configure(RoutingConventions conventions)
            {
                conventions.
                    If(action => action.Controller.StripNamespaceAssemblyName().StartsWith("Admin"))
                    .Build(action =>
                    {
                        var url =
                            action.Controller.ToWebsiteRelativePath(GetType().Assembly)
                                .TrimStart('~')
                                .TrimStart('/')
                                .ToLowerInvariant();
                        var rt = action.CreateRoute(url);
                        //todo if you want to add params to url


                        if (action.Method.Name.StartsWith("get", StringComparison.OrdinalIgnoreCase))
                        {
                            rt.ConstrainToGet();
                        }
                        else
                            if (action.Method.Name.StartsWith("post", StringComparison.OrdinalIgnoreCase))
                            {
                                rt.ConstrainToPost();

                            }
                                                       
                        return new[] {rt};

                    });

            }
        }

Next, in the routing config file (from App_Start)

RoutingConventions.Configure(cfg =>
           {
               cfg
                   .RegisterControllers(Assembly.GetCallingAssembly())
                   .HomeIs<SomeController>(c => c.Index(null,"something"));
               
               cfg.LoadModule(new AdminConvention());
           });

Now, just for fun, I want that all CamelCase controller names to be rewritten like "camel-case". I add a modifier.

cfg.Always().Modify((r, action) =>
		   {
			   var con = action.GetControllerName();
			   var i = 0;
			   var final = new List<char>();
			   foreach (var ch in con)
			   {
				   if (char.IsUpper(ch))
				   {
					   if (i > 0)
					   {
						   final.Add('-');
					   }
				   }
				   final.Add(char.ToLower(ch));
				   i++;
			   }
			   r.Url = r.Url.Replace(con, new string(final.ToArray()));
		   });

Now everytime I want to change something, I change it here. Anything else stays untouched. Btw, the register controllers part is required.  While this is only an example, you can create much more specific conventions each in its own class (SRP!).

MPT comes with 2 predefined conventions: HandlerRouteConvention  and OneModelInHandlerConvention. Personally, I prefer the latter one as it's easier to maintain.

OK, thats' it for now, but here's a taste of things to come: view engine conventions, html conventions, apply filters by conventions, command and query controllers. In the mean time you can check the GitHub repo

Domain Event Design Principles

By Mike on 27 March 2014

In theory it's pretty simple: a domain event notifies that something has happened in the domain i.e the domain has changed. But how do we design the event to capture the relevant information? That event can have many subscribers(handlers) and each handler should interpret the event properly. There's no recipe here and no single truth, but I'll try here to present the principles I'm using when I'm thinking about a domain event.

Let's consider this scenario: Customer changes its address. The obvious event would look like this

public class CustomerAddressChanged 
{
	public Guid CustomerId;
	//Address is a value object
	public Address Address;
}

or like this?

public class CustomerProfileChanged
{
   public Guid CustomerId;
   public string FirstName;
   public string LastName;
   public Address Address;
   //etc
}

I think the majority would choose the first option as it's more explicit. However, what if the customer can only change its profile as a whole? So basically, everytime he wants to update the address, the whole profile is loaded, address is changed, whole profile is submitted. You can detect the change and generate the corresponding event, but what if he changes 90% of its profile (unlikely but the important bit is that you have a form with many updated fields). Would you want to generate 10 events related to the same object? A single CustomerProfileChanged event might be more suitable.

But even with one event, what do the fields represent? The current state, you say? But did all the fields change? A null address can be a valid value or the 'fields has not changed' value. Clearly, one event is not the best solution if only some fields can change. So, back to our 10 events generation?

I think we should correlate the event content with the command fields (or service parameters if you're not using commands) and with the context. In our example, things like Address or Email can change (very rarely but more often than FirstName) and it makes sense to have specific events for that. But also it may make sense to have something like CustomerBasicProfileUpdated for many changes at once. We don't know how the UI looks and we can't guess how the UI might change in the future so we need to decide how to design relevant events: specific enough to convey proper information but not that specific that you end up generated 3 of them for every change (i.e don't automatically create an event for each object property that can change).

So I'd design a few events

public class CustomerBasicProfileChanged //I think there's a need for a better name though
	{
	   public Guid CustomerId;
	   public string FirstName;
	   public string LastName;
	   public PhoneNumber HomePhone;
	   public PhoneNumber MobilePhone;
	}
	
	public class CustomerAddressChanged
	{
	 public Guid CustomerId;
	 public Address Address;
	}
	
	public class CustomerEmailChanged
	{
		public Guid CustomerId;
		public Email Email;		
	}

Of course, these are a hypothetical solution in a hypothetical example. The relevant part is that you need to group the information based on a criteria. Here, I've chosen the "how often information is updated" criteria. Depending on the domain, the criteria may be obvious or you'll have to come up with one.

Another thing to keep in mind is an event is a DTO so it should be kept as simple as possible, as serializable as possible. That's why you shouldn't put a full domain object in an event, but mainly primitives or at most value objects. The important thing here is the event has to contain all the relevant information that can be easily transported. Serializing rich objects is a waste if not a technical pain and keep in mind that a domain object is valid (make sense) only within a bounded context, while the event handler can belong to a very different context. Don't reuse the rich object  for event messaging, it's not DRY, it's an excuse for laziness, leading to complications in the future.

A note about value objects. These are simple to serialize but might not have exactly the same meaning in all bounded contexts. In some situations it's better to just use the encapsulated values as primitives (string, int etc).

Most of the time you'll have the combo: ActionCreated/ActionChanged. It's important to maintain the different semantics even if they are technically identical (they contain the same fields). Just make one inherit the other.

There is a use case that might come up often: you want to notify that a status has changed. You have 2 options: make an event for each status or make an StatusChanged event containing the new status. In my experience, the second option is the more maintainable one. The downside is that an event handler has to check if it's the status it cares for. A small price to pay, in my opinion.

If you have tips about domain event design please share your experience with a comment.

Rich Domain Is SOLID , Anaemic Domain Is An Anti Pattern

By Mike on 26 March 2014

 Reading that The Anaemic Domain Model is no Anti-Pattern, it’s a SOLID design I couldn't help but to disagree with the author, hence this post.

I think the author misunderstood how a rich domain (or an anaemic domain) really looks like. It's not about putting everything in one class, not caring about proper layer separation, it's about modeling properly the business concepts and use cases.

 "In an RDM, the domain service layer is either extremely thin or non-existent [20], and all domain rules are implemented via domain models. The contention is that domain entities in a RDM are then entirely capable of enforcing their invariants, and therefore the system is sound from an Object-Oriented design perspective."

Yes, but it's about business rules that the concept needs in order to be valid. It's not about the business rules required by a use case. Those are treated at the use case level, that is the Application (Services) Layer which isn't that thin anymore. As an example of a rule that should be enforced by a domain concept, an order should not accept quantities or prices lower than 0 (well, to be more exact the Price object used by the Order shouldn't allow values < 0).

 Next, I simply can't agree with the rich domain example presented by the author. ActiveRecord pattern shouldn't be used in a rich domain context. Ever! You want to keep things decoupled so, no way a proper business object should contain db access code. The example is simply flawed. A DomainEntity base class containing CRUD methods is something belonging to persistence (ORM entity), a real domain base class doesn't care about database, even less about CRUD.

"A proponent of the RDM architecture might claim that the hypothetical example provided is not representative of an true RDM. It might be suggested that a well implemented Rich Domain Model would not mix persistence concerns with the domain entity, instead using Data Transfer Objects (DTO’s) [18, 17] to interface with the persistence layer."

 Actually, it will use a repository. The DTOs might work for querying purposes but that's it.

The anaemic domain example presented looks pretty SOLID if not a bit over engineered. However, that's a use case that's using the domain concepts. I get the feeling people think that rich domain object have to be big, complex objects with 20 public methods and 17 children and even more private methods. The richness of a domain stems from the number and complexity of concepts(with relevant behaviour) and use cases (business rules, business flows), it's not about fat objects.

"As the hypothetical RDM is refactored to apply the SOLID principles, more granular domain entities could be broken out; the Customer domain entity might be split into CustomerPurchase and CustomerRefund domain models. However, these new domain models may still depend on atomic domain rules which may change independently without otherwise affecting the domain entity, and might be depended on by multiple domain entities; to avoid duplication and coupling, these domain rules could then be further factored out into their own modules and accessed via an abstract interface. The result is that as the hypothetical RDM is refactored to apply the SOLID principles, the architecture tends towards the ADM! "

 No it doesn't! CustomerPurchase and CustomerRefund are use cases of the Customer concept (entity). If another bounded context sees the Customer a bit differently(structure or behaviour), then we're talking about a different concept (the model is valid only within the context boundaries, it shouldn't be reused under the pretext of DRY).

 Concepts interact with other concepts (behaviour) according to the use case. The behaviour is a part of the concept and cares only about the concept's limited subdomain. And that behaviour certainly isn't related to persistence or UI widgets or even other bounded context (outside the concept's context). You can say an use case encapsulates how a concept 'works' with other concepts given a certain context. But that behaviour is intrinsic to the domain object, the use case just uses it.

In a properly modelled rich domain, a service (implementing a use case) manages 1 or more domain concepts towards a goal. But the service doesn't define a (new) behaviour for the involved objects (the concepts don't change). In an anaemic domain, the 'domain' model is just data while the behaviour is defined in another place (a service), not only keeping the data separated from the behaviour but also mixing together (confusing) behaviour and use case, which leads to bad modelling hence it's an anti pattern. And improper modelling means poor maintainability, complicated codebase etc.

 When dealing with any domain (rich, simple) you should be in complete control over the code. You should know WHY you defined a class in a certain way, in what layer are you working, what is the responsibility of a certain class and if the class really models the proper business concept. It requires a lot of attention and analytic skill but it's not hard. The biggest mistakes you can make is to be superficial and to get bogged down by technical details. Remember that domain modelling is done at a high level, so the concern of lazy loading or the debate to use a List or an IQueryable don't belong here.

DRY Code, Rich Code

By Mike on 15 January 2014

The good part is that even junior devs know about DRY (Don't Repeat Yourself). The bad news is that a lot of devs believe that DRY is about avoiding repeating lines of code or properties names.

 But just like the Law of Demeter isn't about counting dots DRY isn't about avoiding having 2 classes with the same property. It's all about context and behaviour.

It's obvious that when you need the same behaviour implemented by a code block, you should refactor it to a function. This allows you to change the behaviour in one place only. This is the meaning of DRY, don't duplicate code which does the same thing. Reuse it. However...

 There is the issue of context. All model and behaviour happens within a context. You are structuring your app in layers(tiers) because you want each layer to handle one specific concern. Thus, the model for Persistence deals with databases, in Domain it's only about business concepts and use cases, in UI we care about User Interface and not about business logic or databases etc.

So there are multiple models, each specific to its own context (layer, tier,component, module, subdomain etc), minding only their specific concern. But those models can't be that different, after all there are just different aspects of the same things. And in simple apps you see that the view model is 99% identical to the business data structures and 99% identical to the persistence model.

 And you think: "DRY!" and try to reuse it. One model to rule them all. But this will be a problem on the long run, because now, you have one model reused for different purposes. This is not DRY, this is a confusing mess, hard to maintain code.

 Reusability is great and desired, but the separation of concerns should be the primary criteria when deciding if something is indeed a repeat or it can be reused. This means you have to be aware at any time in what context you're working on and you have to maintain the discipline to treat each model in that context.

It's normal human behaviour to look out for shortcuts, but if you want a highly maintainable application, don't use the same model outside its own context. If it's identical to other models, just define a new class inheriting the other or copy/paste directly the properties (not the methods though). The point is that the code in one context should be 'coupled' only to the model from that context (as much as possible) or a compatible context (part of the same responsibility).

 So don't reuse your business data structures as view models or as persistence entities. They serve different purposes and it's just a coincidence they look the same. Treat them like the separate models they are. It's important from an architectural point of view to maintain this separation, and the implementation details are yours to decide. And yes, copy/paste is a valid method and works great, but remember it's just a tool that can be easily abused.

In conclusion, DRY doesn't mean "make a mess under the illusion of reusability", it's just a simple principle that reminds you to keep relevant behaviour in one place.