Customer Profile
CB Richard Ellis (CBRE) is one of the world’s premier full-service real estate companies, with 349 offices in 42 countries and over 44,000 employees. The company’s $223 billion in transactions span sales and leasing, loan originations, property and corporate facilities management and much more, making CBRE the global leader in real estate services and investment.

Business Situation
CBRE has over 100 mobile apps–some public facing–but most are unique to the company internal operations. However, disparate development platforms scattered around the world made it difficult to maximize economies of scale. The company needed a framework to deliver application portability to a spectrum of devices and operating systems, while at the same time, providing the “wow” factor field agents needed to close real estate deals.

Solution
When CBRE application development shifted increasingly to HTML5 and CSS3, the development team conducted a thorough review of the competitive landscape and after an exhaustive research they chose the Telerik Kendo UI® framework.

Benefits

Less resources needed to develop, test and keep things consistent for a wide array of machines, browsers and versions

Validation Framework will support reusable validations so that we can reuse them across the enterprise.

Validation Framework will support ad-hoc validations, meaning validations, that potentially will only be used once, that are not common validations, and very specific to a given entity with a unique use case.

Validation Framework can easily be plugged in e.g such as the MVC 4 run-time, not requiring developer’s to do anything different than they are today to validate their models.

We have a lot to cover so let’s dive right into the Validation project and its’ code!

Keeping track which property of the entity it’s its validation is for.

Setting the appropriate validation result and message.

Now really this is really all you need to start validating your entities/models. Although, there are some other classes that are in the Validation project, they are really not needed to start validating. They are there to help us later wire up our Validation Framework to MVC 4. With that being said let’s wire up our first validation, all you need to do is implement the the Validator class.

I’ve added a UnitTest project with two test class, one is simply a dummy model with fictitious property names, the property names are named after the type of validation we are performing on the property so that we can easily understand what type of validation is happening on each of them. The second class MyValidator is where are validations actually reside for validating MyModel.cs.

Notice all the validations are stored in the MyValidator.cs class and that our MyModel.cs knows nothing about any validation business. More importantly our validation is completely decoupled from our entities, giving us nice separation of concerns.

Validation.Tests.MyModel.cs

Note: Again, The property names here are named so that we can easily see what types of validations are happening for each of them. Obviously in the real world they would be named FirstName, LastName, Age, versus Compare1, Compare2, Regex, etc. :p

Here we have some simple validation implemented and wired up for our MyModel.cs entity. Here we are using some of the out of the box validations I’ve coded up, and some ad-hoc validations we are able to add to our Validator that the Validation Framework provides e.g. validating and Id, length, range, using Regex, required, IP address, email, etc.. Obviously you can easily add your own reusable validation, and again add ad-hoc (lines 34-37) validations that will probably only be specific to a given entity.

If we run our unit test, we can see that MyModel.cs was nicely validated…!

Now, this is great, but how do we seamlessly wire this up to MVC 4..?! Good question, let’s get started. To wire up our new Validation Framework with the MVC 4 run-time there are a couple of things we need to do.

When implementing the ModeValidatorProvider we see that we do need a factory of some sort to new up an instance of the right Validator to validate our model. We accomplish this with the ValidatorFactory. This class is responsible for discovering the ValidatorAttribute that the MVC model should be decorated with has the Validator type to be activated to validate the model.

Second, we need to implement the ModelValidator (http://msdn.microsoft.com/en-us/library/system.web.mvc.modelvalidator(v=vs.108).aspx), this will provide the MVC 4 runtime to call into our Validation Framework and execute our Validator.Validate(object model) method and return a set of ValidationResults. Once our ValidationResult payload is returned we will then need to map it back to MVC’s ModelValidationResult so that it can display our validation messages correctly.

Now let’s start off by validating one of our existing entities Entites.Customer.cs. You can really place your validation objects anywhere you’d like, for simplicity sake I’ll go ahead and place them in the same project as our Entities under a folder named Validations.

Notice how we are calling the MVC ModelState.IsValid, and when we debugging this, we see that the MVC run-time will invoke our custom Validation Framework.

Our error message from Entities.Validation.CustomerValidator.cs.

All of the out of the box Validators that are included in the example download, follow the described pattern listed below, this is also how you would extend or add your own reusable validations to the framework.

Extend the Validator, by writing an Extension method

Instantiating a fluent helper class for the validation

Setting the property to be validated

Setting the validation logic

Adding the the validation to stack of validations to the Validator instance

Let’s take a quick look at one of the out of the box validations e.g. ValidateLength.

Support for Ad-Hoc Validations with Generic Funcs using AddValidation() Fluent Method

Finally, let’s quickly go over adding ad-hoc validations by adding in-line Lambda’s or Generic Funcs, all you hvae to do is call AddValidation() and using the fluent API, and make sure your generic func accepts a TModel (could be of any object type) and returns a Boolean. In the sample code below we are doing a simple ad-hoc validation for the property Email, validating if there’s a value or not and returning an validation message.

Update: 02/24/2014 – v3.2 released, improved API and reusable queries with the variation of the Query Object Pattern. Breaking change: Framework now ships returning all things TEntity or IEnumberable for compartmentalization, you will need to change the Repository.cs (see below, what methods signatures to change) if IQueryable is preferred over IEnumerable, IEnumerable is preferred as a best practice (http://genericunitofworkandrepositories.codeplex.com/documentation).

First off let’s elegantly setup our solution, and prep it for real world development. We have our solution broken up into four different projects, now let’s talk about the “why?”.

Data Project (Data Access Layer)

This is where all of our ORM tooling related objects reside. In our case the EF (Entity Framework 6.0 Alpha 3) DataContext, Mappings, Migrations, etc. This give is nice separation, control and isolation of where any persistence related objects live. If ever, one day we need to change the tool of choice, or even upgrade, there’s only one layer or project to do this in, the Data project.

Entities Project (Domain Layer)
The Entities project is where all of our POCO (Plan Old C# Objects) objects will live. POCO’s should be very ignorant objects that pretty much have nothing in them but the structure of your data. With that being said, typically anything outside our Repository layer e.g. presentation layer (MVC), services layer (will cover in next post) should be completely ignorant to any persistence tool or technology e.g. NHibernate, eXpressPersistent, OpenAccess, EF (our case), etc.

Repository (Layer)
This is where our UoW (Unit of Work) pattern will be implemented as well as our Repository implementation. Our UoW implementation will handle most of our usual CRUD activities.

Two important objectives we will try to with our UoW pattern implementation are:

Abstract away the ORM tool, in our case EF.

Ensuring that all interactions with the database are happening under one DbContext instance per page request.

Obviously there are many other benefits, such giving us the ability to implement different variations of our UoW, potentially wire up to different types of repositories. For purposes of this article, we’ll stake focus on our two primary objectives, and I’ll cover the other benefits in later posts.

Web Project (Presentation Layer)
This is our presentation layer, for the purposes of the blog, we will use MVC (ASP.NET MVC 4). Again, this project should not have any dependent code on EF assembly, therefore that should not be any references to the EF assembly, it should only reference our Repository project for data access.

Refactoring the NorthwindContext for an Abstracted and Cleaner Implementation

Now that we’ve gone over the solution and it’s projects, let’s do a little bit of refactoring and cleaning up with our EF code.

We can see that our DbContext is now much cleaner, and that it implements IDbContext. IDbContext will be the abstraction we will be working with when interacting with it’s concrete implementation, NorthwindContext.

Best Practice, Coding Against Abstractions or Interfaces

Abstractions serve as a nice flexibility point later, allowing us to implement different variations of the abstraction (interface). This will be very useful later when we implement DI (Dependency Injection and IoC (Inverse of Control) patterns. Coding to an abstraction will also help us easily create unit test, allowing us to inject faked or mocked instances as well. If your a bit unclear on how this helps set stage for DI, IoC and Unit Testing, no worries, I’ll cover these topics in the next post.

Let’s take a look at our IRepository Repository() method here in our UnitOfWork implementation. Here we are storing all the activated instances of repositories for each and every requests. One there is a request for a given repository we will first check to see if our Hashtable (container to hold all of our activated repository instances) has been created, if not, will go ahead and create our container. Next, we’ll scan our container to see if the requested repository instance has already been created, if it has, then will return it, if it hasn’t, we will activate the requested repository instance, store it in our container, and then return it. If it helps, you can think of this as lazy loading our repository instances, meaning we are only creating repository instances on demand, this allows us to only create the repository instances needed for a given web request. Last but not least, notice here how we are following best practices mentioned earlier, we are not return the concrete implementation for the Repository, but the abstraction, IRepository.

Our generic implementation for Repository allows us to have have all our basic heavy lifting of a Repository out of the box for any one of our Entities. All we have to do is request for the Repository of interest by passing in the Entity e.g.

UnitOfWork.Repository<Customer>

will give us the Customer Repository with all our out of the box plumbing available.

Let’s take a quick look at our Get method in the Repository implementation.

The Get method here, handles fetching data. It handles querying the data supporting a filtering, ordering, paging, and eager loading of child types, so that we can make one round trip and eager load the entity graph.

We notice here that the method is marked “internal”, this is because we only want the Get method here to be accessible to objects with the same assembly, Repository.dll. We will expose the Get method via the Query method and return the RepositoryQuery object to provide a fluent “ish” api, so that’s its a bit more easy and intuitive for our developers when querying with our Repository layer. Note, only methods in our RepositoryQuery will actually invoke the internal Get method, again, which is why we went ahead and marked the Get method internal.

Well, what happens if we need extra methods a specific Repository? Meaning, how do we address “extensiblility” in our Repository? No problem, we have a couple of options here, we can simply inherit a Repository and add your own methods to it, or what I prefer, create extension methods e.g. extending IRepository (with some pseudo code for validating an address with UPS).

Great, now that we have our project nicely structured with the our generic implementation of the Unit of Work and Repository Pattern, let’s see how we can leverage this by wiring up a simple controller to show a list of customers.

To help us with this go ahead and NuGet the PagedList for MVC so we easily create a view with a paged grid.

Let’s create a CustomerController Index Action load a paged list of customers to hydrate a grid.

Another item I wanted to go over was insert and updating graphs with our Repository pattern. There are four use cases for inserting graphs, they are as follows.

To abstract the complexity and EF experience required, and how the DbContext manages graphs e.g to know to set the root entity state and how it affects other entities in the graph (e.g. updating the root entity in the graph, and existing entities in the graph are to be updated or deleted) we added a interface IOjectState that all of our entities will implement.

These two classes will allow our development team to explicitly set the state of each of the entities in the graph when inserting or updating a graph. To make use of the classes we’ll need to extend the DbContext with a few methods, we’ll do this by creating extension methods.

Now we will override the SaveChanges in our NorthwindContext to invoke the ApplyStateChanges method to synchronize our ObjectSate with EF’s EntityState, so that the context will know how to deal with each and every entity when dealing with entity graphs.

Now when inserting, updating you can explicitly set the entities state, especially useful when dealing with graphs. This abstracts the skill-set of a developer using our Repository of having to know the what, when and how to set the state of entities in the graph in order for the context to update the graph and persist the graph correctly. Let’s take a look at an example of updating an existing Order and adding an OrderDetail item with an entity graph. Both these actions, are will be executed on the same graph, however notice that the action is different for both of the entity’s, one is updating and the other is adding, however we will only be invoking one method (IRepository.Update(TEntity entity) from our IRepository in one transaction.

So we’ll demonstrate and prove out updating an entity graph with our UnitOfWork implementation in these steps.

Code Snippet from LinqPad, notice how we are explicitly setting each of the entities state in the entity graph.

Query the OrderDetail table, make not there are only three (3) items, that belong to the same Order.

Update the ShipName value in the Order.

Add an OrderDetail to the Order.

(click image to enlarge)

Presto, we were able to successfully update an existing Order and add a new OrderDetail via an entity graph with one transaction using one method. Now, we can absolutely do this using EF out of the box, however, our goal here is was to abstract the complexity and skill set required from a developer in regards to EF specially how do deal with the DbContext in order to make this happen as well as obviously still support working with graphs through our IRepository implementation.

There you have it, and extensible genericized implementation of the UoW and Repository pattern with EF in MVC. In the next blog post, we’ll add DI & IoC to this solution and introduce the Services layer, this layer will house all of our business logic and rules. We will also implement the Services layer in a way, where we don’t violate our Unit of Work pattern, meaning all the work done in our Repository and Services are executed under one single instance the DbContext per page request.