Fluent Validation – Separate Main Business Logic from Validation Logic

We all have nice business objects at the beginning. However, the codes become bloated, hard to read and maintain after we put in numerous complex business validation logic. We always hope that we can separate main business logic from validation logic, and reuse the validation logic to some degrees.

For example, we use IValidatableObject as the main validation mechanism (self-validating models) in MVC applications.  The validate method will be called after the model binder has assigned values to each of the model properties. There are a few variations. Some use abstract methods, and some use events inside Validate method of the base class to achieve some kinds of separation of main business logic from validation logic.

I came across the small library at github recently, Fluent Validation. This library is the best library that can separate the main business logic from validation logic I can find so far.

The following codes show how to add validation logic  to a customized validator using the popular fluent syntax.

public class CustomerValidator: AbstractValidator<Customer> {
  public CustomerValidator() {
    RuleFor(customer => customer.Surname).NotEmpty();
    RuleFor(customer => customer.Forename).NotEmpty().WithMessage("Please specify a first name");
    RuleFor(customer => customer.Discount).NotEqual(0).When(customer => customer.HasDiscount);
    RuleFor(customer => customer.Address).Length(20, 250);
    RuleFor(customer => customer.Postcode).Must(BeAValidPostcode).WithMessage("Please specify a valid postcode");

  private bool BeAValidPostcode(string postcode) {
    // custom postcode validating logic goes here

The following codes show how to call the validation method.

Customer customer = new Customer();
CustomerValidator validator = new CustomerValidator();
ValidationResult results = validator.Validate(customer);



Fluent Validation





Google Analytics API – 5 Minutes Crash Course

Google Analytics is very popular for measuring how users interact with your website. Most of the times, simply follow the instructions, and copy the following codes to every page you intend to track. It just magically works.

<!-- Google Analytics -->

(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),

ga('create', 'UA-XXXXX-Y', 'auto');
ga('send', 'pageview');

<!-- End Google Analytics -->

However, sometimes we have to dig deeper to achieve our goals. For example, how do we track each virtual page in Single Page Application (SPA)?

In order to answer this question, we have to understand how the script above works. From the reference, as quoted: “The above code does four main things:

  1. Creates a element that starts asynchronously downloading the analytics.js JavaScript library from https://www.google-analytics.com/analytics.js
  2. Initializes a global ga function (called the ga() command queue) that allows you to schedule commands to be run once the analytics.js library is loaded and ready to go.
  3. Adds a command to the ga() command queue to create a new tracker object for the property specified via the 'UA-XXXXX-Y' parameter.
  4. Adds another command to the ga() command queue to send a pageview to Google Analytics for the current page.”

The reference also points out, as quoted: “Custom implementations may require modifying the last two lines of the JavaScript tracking snippet (the create and send commands) or adding additional code to track more interactions. ”

Back to our tracking each virtual page of SPA question. I will use an example here. There are six menu items, ‘Home’, ‘About’, ‘Services’, ‘Projects’, ‘Qualifications’, and ‘Contact’ in this website, http://www.hdsoftwareconsulting.com, which is a SPA. Under normal circumstance, if we simply insert the script above to the page, it only logs “/home” to tracking. However, we do want to know the users browser navigation to other menu items as well.

Luckily, Google Analytics API is flexible and powerful. We can create a solution like this:

  1. Insert the following script to the page.

(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),

ga('create', 'UA-XXXXX-Y', 'auto');

<!-- End Google Analytics -->

2. Attach an onclick event handler to each menu item. For example, we attach the following script to ‘About’ menu item, and will do the same for the other menu items.

ga('set', 'page', '/about'); 
ga('send', 'pageview');

In this 5-minute crash course, we introduce Google Analytics API, and show how to apply it to a SPA.


  1. Look at network tab of Chrome to inspect what’s going between your browser and Google Analytics API
  2. The API exposes an object ‘ga’ as mentioned above. We can also inspect its internals.
ga(function() {
  // Logs an array of all tracker objects.
ga(function(tracker) {
  // Logs the trackers name.





Design Pattern – Chain of Responsibility

Design pattern Chain of Responsibility (COR) belongs to the general design concept Divide-and-Conquer.

Imagine that we have a complex business logic with inputs and outputs, and its content is filled with numerous statements.

One of Divide-and-Conquer techniques is to apply COR in the form of a single pipeline and multiple handlers. For example, each handler implements one or multiple statements as a logical unit. The inputs are implemented as requests, and the outputs are implemented as response. The requests are passed through the pipeline and each handler is given a chance to process the requests and add something to responses. In the end, one of the handlers or end of chain handler will return the responses back to the caller.

The real life analogy will be a car assembly line (pipeline). Each worker (handler) only knows how to work on the item on hand, and pass the item down the line to next worker (handler)…

The immediate observations are:

  1. Each worker (handler) is very good at the item that he/she is assigned to.
  2. Each worker (handler) really doesn’t care who the worker up the pipeline. They just work on the item passed to them, and make sure to pass the item on hand to next worker (handler)
  3. Each worker (handler) can be easily to be replaced with another worker (handler)
  4. The quality of the item that each worker (handler) works on can be easily verified.
  5. The workflow is efficient and easy to understand and be maintained



Chain of Responsibility at Wikipedia







Is the HttpContext.Current.Cache shared among different user sessions?

During one of discussion about caching, one senior developer pointed out that the HttpContext.Current.Cache is NOT shared among different user sessions.

I felt very shocked because I thought HttpContext.Current.Cache is shared among different user sessions. I quickly did research over internet, and confirmed that HttpContext.Current.Cache is shared among different user sessions.

MSDN – HttpContext.Cache: “There is one instance of the Cache class per application domain. As a result, the Cache object that is returned by the Cache property is the Cache object for all requests in the application domain.”




StackOverflow – Is the HttpContext.Current.Cache available to all sessions



MVC ModelState De-Confused!

I used to confuse about ModelState in MVC. I begin to realize that there are two ModelState concepts often referenced in MVC discussion.

Most people know the first concept of ModelState, Controller.ModelState, which is a property of System.Web.Mvc.Controller. I am going to use Controller.ModelState property here to avoid any confusion.  Controller.ModelState property represents the model state dictionary object  (ModelStateDictionary) that contains the state of the model and of model-binding. The important properties of ModelStateDictionary  are:

  • Count. Gets the number of key/value pairs in the collection.
  • IsValid. Gets a value that indicates whether this instance of the model-state dictionary is valid.
  • Keys. Gets a collection that contains the keys in the dictionary.
  • Values. Gets a collection that contains the values in the dictionary.
One of ModelStateDictionary properties, Values, is particularly interesting. It basically is a collection that contains the values of the model-state dictionary.
public ICollection Values { get; }

Type: System.Collections.Generic.ICollection<ModelState>

You are right. ModelState is the type of objects in the collection, not the property of controller. It confused me years ago, and most people like me might never pay attention to.

Here comes the second concept of ModelState, which is from System.Web.Mvc.ModelState. There are only two properties in this class, Errors and Value.

  • Errors. Returns a ModelErrorCollection object that contains any errors that occurred during model binding.
  • Value. Returns a ValueProviderResult object that encapsulates the value that was being bound during model binding.

If we organize our thinking a little bit, here is the structure for easy memorization.









Microsoft Small Basic – Robotic Programming for Kids 10+

While looked for robotic programming languages for kids 10+, I tumbled upon Microsoft Small Basic. It is a surprising simple language with only 14 keywords, simple data types, conditional branching, and looping. It also comes with a beautiful Integrated Development Environment with intellisense and in-editor documentation access on the sidebar.

If we trace the origin, it is a simplified and  trimmed version of BASIC. Small Basic also includes a few libraries such as Turtle, Flickr, etc., so that beginners can jump start.

When we add the extension EV3 Basic, Small Basic can program against Lego MindStorm EV3 robot.

I strongly recommend Small Basic for kids 10+ to learn programming.


  1. Microsoft Small Basic
  2. https://en.wikipedia.org/wiki/Microsoft_Small_Basic


Let’s look at SOAP vs REST.

First, the technology stacks of SOAP and REST are quite different.

Communication Protocol Quite complex. Simple,  reuse HTTP verbs
XML Yes  No
HTTP Yes Yes

Second, let’s look at what problems SOAP and REST try to solve. I will use Microsoft’s implementation as examples. Microsoft’s implementation of SOAP is ASP.NET web service, and REST is Web API.

ASP.NET web service (SOAP) was designed to solve complex business problems around 2000. The architecture was similar to remote procedure call (RPC) style, and based on complex protocol. The protocol can be described using XML. Visual studio makes programming ASP.NET web service a breeze and hide most of the complexity. Visual Studio creates a local proxy to program against, and make the RPC seamless and effortless. In addition, WSDL, a web service description language, was created behind the scene to make all these possible. However, it is very cumbersome to create the HTTP posts manually without Visual Studio because we have to know the protocol instead, which is not an easy task.

Around 2006, WCF was created. WCF is a superset of ASP.NET web service. So use WCF unless you maintain legacy applications.

With the coming of mobile devices and single page applications, etc., the business requirements shift. We don’t just solve complex business problems, and we need to solve simple business requests as well and more efficient. More developers from other technology stacks other than Microsoft find communication through short and simple message exchange more appealing. WCF including ASP.NET web service cannot solve the new business requirements naturally and efficiently. The overhead came with WCF and ASP.NET web service was too much.

JSON emerges as the default communication protocol on top of HTTP. Web API takes advantage of HTTP Verbs and the popular MVC style, and provide a solid foundation for REST. The business requirements are exposed as resources, and HTTP verbs are the actions again these resources. We can think about the resources as objects, and these objects offer implicit methods such as GET, POST, DELETE, PUT, etc. So we can say the programming paradigm changes. Although less descriptive, REST and JSON is easy  to learn, flexible, and have a light footprint.



C# Granularity of Abstraction – Class vs Interface vs Delegate

In C#, the language designers use constructs to model real-world objects or things.

One of these constructs is class. The class has instance variables and methods modeling the real-world object with states and behaviors, respectively.

Another construct is interface. Interface is used to model an abstract contract, and can not exist by itself. There must be a class that implements it. In the end, interface must exist in the forms of objects. Interface is also used to get around lack of support for multiple inheritance.

Delegate is special, and used to model a real-world behavior. Note that it cannot model an object. That is the reason I say delegate is the lowest granularity of abstraction.

So the granularity of abstraction from high to low is class, interface, and then delegate.

Design Principle – Favor Composition Over Inheritance



Reviewed a project with legacy code base of more than a quarter million lines of code. This legacy project was under re-writing proposal phase.

Designed a proposal with high-level UML activity, component, and class diagrams. And the proposal was adopted later.

After a few days of implementing a C# prototype, I slowly felt the pains of designing domain models without totally understanding the domain first. I used inheritance heavily. The levels of object hierarchies were increased to 5 or 6 or even more, , and the design structure began to show signs of fragile.  I had to spend tons of time to decide where an object belonged to this hierarchical tree, and I began to lose track of what was going on.

I realized I had to change. To model the complexity of domain objects and their hierarchies and relationships, I had to use a different strategy. Here came the design principle – favor composition over inheritance.

In this project, I was able to use this design principle to model the domain objects and finish the prototype successfully.


Composition over Inheritance in wikipedia


Evaluated a Bootstrap-Combobox Library

Evaluated a bootstrap-combobox library from GitHub. The setup was quite easy in Plunker, and I just need to copied two files, bootstrap-combobox.js and bootstrap-combobox.css.

The evaluation at http://plnkr.co/edit/XMzzoo?p=preview

I used $(‘#combobox1’).combobox() instead of $(‘.combobox’).combobox() to initialize the combobox.