Thursday, March 6, 2014

Avoid querying stale data when running integration tests against the database

A common pitfall in doing persistence tests occurs when entities are loaded into memory, persisted, then immediately queried back from the repository.
The default behavior of ORMs is to load the entity from the in-memory cache to spare a query to the database.
This behavior is fine overall but does not fully test the persistence of the entity. Therefore, it's important to evict the entity from the cache in order to force the ORM to re-load the entity from the db. This is the case for ORMs in either Java or .Net environments.

In Spring, if you have properly configured the JPA, you evict entities from the cache by doing the following:


You can access the entityManager by getting it from the container as follows:

private EntityManager entityManager;

Below you may find a simple, yet complete example of a persistence integration test with this technique applied:

Thursday, February 27, 2014

Handling multiple jQuery Deferred calls regardless of resolution

This post discusses a mechanism jQuery.whenAll() for making multiple Ajax calls (or really, any jQuery Deferred calls, since that is what the Ajax object is, and getting a resolution for all calls.

This is an alternative to jQuery's built-in Deferred.when(), which short-circuits on rejected resolutions (for example, jQuery Ajax failures resulting from a 400 or 500 level HTTP status) and will not give you subsequent responses.

So, for example a call such as: jQuery.when(jQuery.get('resource/404', 'resource/200')) will not give you a resolution for both requests, only the resolution of the rejected request (the 404 one).

Therefore, a mechanism like jQuery.whenAll() is very useful for situations when you may want the resolution to all of the requests.

The fiddle:

Wednesday, September 18, 2013

Integrating FluentValidation with ASP.NET Web API

In short, we dislike the Validation that comes with MVC and, now, Web Api. No need to go into why here, but things like Attribute dependencies and its clunky API are bad …. m’kay.
Fluent Validation is a popular, open-source, fluent-API based validation engine for .Net that we prefer over the default validation. There are several ways of integrating Web Api with Fluent Validations. 

Some of those are explained here and here.

Initially, we went with a custom implementation of the latter since it hooks right into the Model property of ActionContext of an ActionFilter. This is nice because the Validation action filter would only need to verify that the ModelState.IsValid is true, or else, return an HTTP Bad Request Response (400) with the error messages.

However, we cringed at bringing a custom implementation of this library that includes a lot of extra artifacts and seems to no longer be active.

At one point, we realized that we could hook right into the ArgumentsProperty of the ActionContext. In this case, we can ask the Dependency Injection Container (we use StrucutreMap) for the validator for the type, then execute the validation.
Although we lose the nice ModelState.IsValid hook, we make it up by having a less-magical, more explicit implementation for validation that is easier to maintain and debug.

In order to get the container to get us the right Validator for the type, we need to register all types that Implement the “AbstractValidator<>” interface.

By the way, these Validators are also easily unit testable.

All the necessary, simplified code is found below:

Thursday, November 8, 2012

Simple Dual Combo Box With Knockout JS

A very common web UI task that we are tasked with are dual combo boxes. These are very good if you want to manipulate or assign several items at once.

Below is a working sample of a Knockout JS way of doing one of these. I really like the result of using an MVVM framework to do these because the whole select -> option DOM manipuation is completely removed from us, Knockout takes care of that part. As a result, we are no longer using tons of jQuery magic; instead, we are dealing with the actual objects that will ultimately be sent over the wire.


Monday, November 5, 2012

Simple Strongly Typed Application Settings using StructureMap (à la Fubu MVC)

In this post, I will describe a simple method of achieving strongly typed application settings from your app config source (app.config, web.config, appSettings.config). There are many ways out there to achieve this, but having dived into Fubu MVC for over a year, I grew fond of the way they handle application settings through a class instead of using ConfigurationManager or a custom config section. In addition, even though the code below is not what you would find in the Fubu source, it is inspired and based on it. So, the credit for the idea and the basic implementation belongs to the folks who actively contribute to it. Finally, this post is based on StructureMap but I am sure that you can achieve the same effect using your favorite DI tool.

Purpose: To rid your code of the soup of ConfigurationManager calls and Magic Strings that is all too common in code.

The composition of this feature is very simple and is exclusively handled by StructureMap.

By inspecting the console code, we see a bootstrapping call.  In this call, we see the initialization block for StructureMap, with an additional custom convention called SettingsScanner.

SettingsScanner registers all the types in the assembly that end with name ‘Settings,’ setting all of its public properties with their matching appSettings values.

Get the entire code from GitHub

Food for thought

One important feature missing from this simple implementation is support for addional types; specifically, integers. Currently, this will only support string types which is what we get by default from .Net.

Thursday, July 5, 2012

Global Error Handler For ASP.NET MVC 3

After having posted Html Conventions for FubuMVC, this post will definitely serve as a contrast as it will be about ASP.NET MVC. This time, I hope to help those looking to handle HTTP errors globally in either the Global.aspx file or through and Http Module. There are a myriad of posts online about performing this very task and I, personally, spent considerable time looking at the different the different options that we have.

  • The first and most popular option if you're familiar with classic ASP.NET Web Forms development is the config section. Let me encourage you not to waste your time with this option. When using you're encouraged to redirect when the web stack encounters an exception. This is wrong because the original HTTP code should be preserved instead of the HTTP 302 redirect code. Also, the original Url should also be preserved. For instance, if you go to the original Url and 404 code is preserved while the not found message is displayed. This is the desirable result.
  • The second and also correct way is to use the config section through the web.config file or the IIS Http Errors option page. This options does handle the errors correctly, keeping the original Url with the Http error code. However, with IIS 7.5, it's awkward to configure and is also difficult to render custom error information that you may want to render in the page.
  • The third option, and the one that I will discuss in detail, lets you handle Http errors globally through the Global.asax file or an Http Module. This method does have several advantages over the others, specially that you will be in full control of how the errors are handled and error pages rendered. In the Global.asax, you can have a simple error handling code like the following:
You may also wish to put in logging or any other general exception handling features. Alternatively, you can write that same code within an Http Module, circumventing the Global.asax file altogether.

The actual magic is all contained in the HttpContextBase extension, specifically RenderViewToHttpContextResponse. This extension method takes in the view name to render, and optionally, the controller name plus any ViewData that we may wish to pass in.

The last remaining dependent code is the ExceptionExtensions for detecting whether an exception is an HTTP 404 Not Found. That is simply the following:

It is important to note that if any part of the code within the Application_Exception method fails, you will need to resort to a custom IIS Error, but hopefully, the code within that method is virtually fail safe.

Saturday, June 2, 2012

Example FubuMVC Html Conventions

This code oriented, first post of my blog hopes to give an example of the FubuMVC Html Conventions I've developed for our customer facing portal at iS3. Inc. These conventions came as a result of iS3's efforts to make a single customer facing portal for all our brands. So, we took this opportunity to migrate all of our Spark Engine views and hardcoded styles and Html to Razor Views, utilizing FubuMVC's InputFor(), LabelFor(), etc. to take advantage of Html Conventions. While writing these conventions, I found it difficult to find many code samples online, so I hope these help those that wish to do the same. Below you can find the Gist for our Html Conventions as they stand: