Creating a Generic Base Fake Repository Class

In many enterprise level transactional applications, it is common to make use of a either a two or a three tier architecture, with one of the layers a data access layer. It is useful to have the data access layer loosely coupled, preferably via an IoC tool, in order to be able to “swap out” the real components with fake or stub versions.

For unit testing purposes this can be done using a mocking framework such as Rhino Mocks. It can also be useful to include hard-coded fake repository objects, not only for unit testing but also for prototyping either the front end or the service layer of the application, without requiring a real database and data access layer.

The IRepository Interface

In one of the applications I have been working on, my data access layer objects, implement (at a minimum), the following interface:

public interface IRepository<T> where T: class
    {
        T Get(int id);
        IList<T> GetAll();
        IList<T> GetBy(string find, string property, bool exactMatch);
        T Add(T item);
        T Update(T item);
        T Save(T item);
        IList<T> Save(IList<T> items);
        bool Delete(int id);
        bool DeleteAll();
    }

Creating Fake Repositories

Inspired partly by Gabriel Schenker’s article on the repository pattern, I created a set of fake repository objects to represent a set of hard-coded, fixed data along with dummy “working” operations. I soon realized that it would be beneficial to make use of a base class for my fake repositories, which provides generic implementations of all the required base methods, i.e.:

public class BaseFakeRepository<T> : IRepository<T> where T :class
{
protected Dictionary<int, T> _dictionary;
protected Expression<Func<T, int>> _identityExpression;

public BaseFakeRepository(Expression<Func<T, int>> identityExpression,
Dictionary<int, T> dictionary)
{
_identityExpression = identityExpression;
_dictionary = dictionary;
}

public BaseFakeRepository(Expression<Func<T, int>> identityExpression)
{
_identityExpression = identityExpression;
_dictionary = new Dictionary<int, T>();
}

public virtual T Get(int id)
{
return !_dictionary.ContainsKey(id) ? null : _dictionary[id];
}

public virtual IList<T> GetAll()
{
return _dictionary.Values.ToList();
}

public virtual IList<T> GetBy(string find, string property, bool exactMatch)
{
return _dictionary.Values.ToList().FindAll(x=>(exactMatch && x.GetType()
.GetProperty(property)
.GetValue(x, null).ToString().Equals(find)
|| (!exactMatch && (x.GetType().GetProperty(property).GetValue(x, null))
.ToString().Contains(find))));
}

public virtual T Add(T item)
{
var newKey = _dictionary.Count == 0 ? 1 : _dictionary.Keys.Max() + 1;
SetIdentityValue(item, newKey);
_dictionary.Add(newKey, item);
return item;
}

public virtual T Update(T item)
{
var identityValue = GetIdentityValue(item);

if (!_dictionary.ContainsKey(identityValue))
{
throw new Exception(“Cannot update”);

             }
            _dictionary[identityValue] = item;
            return item;
        }

        public virtual T Save(T item)
        {
            var identityValue = GetIdentityValue(item);
            return identityValue == 0 || !_dictionary.Keys.Contains(identityValue)
                ? Add(item) : Update(item);
        }

        public virtual IList<T> Save(IList<T> items)
        {
            var savedItems = new List<T>();
            items.ToList().ForEach(x => savedItems.Add(Save(x)));
            return savedItems;
        }

        public virtual bool Delete(int id)
        {
            _dictionary.Remove(id);
            return true;
        }

        public virtual bool DeleteAll()
        {
            _dictionary = new Dictionary<int, T>();
            return true;
        }

        protected virtual string GetIdentityName()
        {
            return ((MemberExpression)_identityExpression.Body).Member.Name;
        }

        protected virtual int GetIdentityValue(T item)
        {
            return (int) item.GetType().GetProperty(GetIdentityName()).GetValue(item, null);
        }

        protected virtual void SetIdentityValue(T item, object value)
        {
            item.GetType().GetProperty(GetIdentityName()).SetValue(item, value, null);
        }
    }

An Example of Usage

When using the base repository, we need some way to tell it which property will be used as the identity (key) on the entity object. The way I have provided is to specify a lambda expression, so that this is strongly typed. For example, if “Id” is the name of the identity property on the Account entity, then in AccountFakeRepository, you can provide a constructor like this:

public AccountFakeRepository() :  base(x=>x.Id)

This then tells the base fake repository to use the property “Id” as the identity or key.

Looking Closer at how the Identity is Resolved

Looking at the method “GetIdentityName” you can see that the identity property is retrieved from the right hand side of the lambda expression, i.e.:

return ((MemberExpression)_identityExpression.Body).Member.Name;

The methods “GetIdentityValue”, and “SetIdentityValue” are then used to get and set, repectively, the identity values using reflection, i.e.:

Get:

return (int) item.GetType().GetProperty(GetIdentityName()).GetValue(item, null);

Set:

item.GetType().GetProperty(GetIdentityName()).SetValue(item,
 value, null);

How to Test the Base Fake Repository Class

You may notice that the class is not marked as abstract, and there is a second constructor which has the dictionary as an additional parameter. Strictly speaking this should be an abstract class. However, I have written it this way in order toallow easy unit testing of the class. For example, in your unit test “SetUp” method, you can do something like this:

var accounts = GetFakeAccounts();
_baseFakeRepository = new BaseFakeRepository<Account>(x => x.Id, accounts);

You can then write a whole suite of tests against the BaseFakeRepository if you feel the need to prove that the fake methods work correctly.

Submitting forms via Ajax using jQuery and ASP.NET MVC 2 extensions

In a previous post I talked about a neat way to submit forms via Ajax using jQuery. In another, more recent post I talked about some extension methods that you could add to the Html Helpers that will allow you to map properties of a Request Model to the “name” attributes of Input elements.

I want to reiterate that I think it’s important to distinguish between View Models and Request Models. For example, many pages in the  app I am currently working on contain, among other things, “Add New” forms. These forms will be submitted via Ajax in order to avoid unnecessary full page refreshes. As none of the fields in these forms are ever populated when the page loads, it seems messy to me if I had to include these properties along with the View Model, just in order to map the “name” properties of the fields (which I would have to do with the MVC version 2 Html Helpers out-of-the-box functionality). It seems more appropriate to me to have more than one set of models – one for rendering the page (the “View Models”), and another, different set for submitting (“Request Models”).

I’d now like to dig a little deeper and put it all together with an example. Say you have an page for managing employees, which includes a form to add an employee. The Request Model might look something like this:

    public class EmployeeMaintenanceRequestModel
    {
        public Employee Employee { get; set; }
    }

Where the Employee class looks something like this:

    public class Employee
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string PhoneNumber { get; set; }
        public string EmailAddress { get; set; }
    }

These property names can then be mapped to the names of Input elements in the form on the page:

image


The form will be submitted via Ajax, which I can do using jQuery:

image

A Closer Look at the “serializeArray()” magic

Let’s take a look closer at the data that will be posted, and note that I am using jQuery’s “serializeArray()” magic trick to automatically build an array from the values of the input elements in the form:

image

The object that gets submitted will look like this:image

Then when the request hits the MVC Controller action, the data will automatically get bound to an Employee object:

image

One Step Further – Binding to a Request Model

Automatically binding to an Employee object is nice, but what if there were some other business objects forming part of the request? It would be nice to automatically bind to the RequestModel object, i.e.:

image

To achieve that, one way would be to set up Model Binders. However, another alternative would be to modify the Html Helper extensions to output HTML like this:

<input id=”anything” name=”requestModel.Employee.FirstName” type=”text” value=”" />

That can be done, for example, by changing the TextBoxFor method like this:

image

image

This will then output the “name” attribute of Input Elements including the entire text of the right-hand-side of the lambda expression, in other words allowing for this syntax:

image

This will then be packaged up in a suitable array again using jQuery’s serializeArray() magic:

image

Which will then be passed to the Controller action method like this:

image

Conclusion

I have tried to demonstrate that by using a combination of extensions to the Asp.NET MVC 2 Html Helpers, jQuery, and a separation of View and Request Models, the asynchronous posting of form data using the Asp.Net MVC framework can be made cleaner, simpler, and more organized than with the out-of-the-box functionality. Almost all other guides don’t differentiate between View and Request Models, and the majority of examples are for full-page refreshes rather than Ajax calls. It might not suit everyone, but for me this fits very well to the type of business applications I will be building with Asp.NET MVC.

Adding Extension Methods to the ASP.NET MVC 2 Strongly Typed Html Helpers

In my last post I talked about what I felt was missing in version 2 of the ASP.NET MVC framework. Specifically, I’m talking about the ability to map the “name” attributes of input control to properties of Request Models. I mentioned that it would be achievable via writing some extension methods, and here are some concrete examples.

Let’s start by writing extension methods for the “TextBoxFor” method. Essentially, I need methods where you can define the type of model that you want to map to. For example, the syntax I am aiming for would be like this:

image

This is an appropriate example for me to use, because typically on a Log-In page the “Password” property’s text will never be rendered on the screen. It will, however, be sent as part of a request when the page is posted. Therefore, it doesn’t fit to include this property as part of the View Model, but it does make sense to have it part of the Request Model.

To achieve this, I can create a new static class, and add some extension methods, as follows:

image

Let’s take a closer look at the third method – note how the signature allows you to specify the type of model:

image

If I then reference the namespace of my static class in my page, I can then use the extension methods, for example:image

If for example I did want to populate this field with a value when rendering the page, I can do so by specifying a value for the “value” attribute, i.e.:

image

I can then use my newly defined syntax to render a control which has the following HTML output:

<input id=”Password” name=”Password” type=”text” value=”" />

Strongly Typed Html Helpers in ASP.NET MVC 2 and what they are missing

Something that is new in version 2 of the  ASP.NET MVC framework is the strongly typed Html Helper methods, for example:

image

These provide a lot of value over the version 1 “magic string” approach, as they help to avoid typos and earlier feedback should the properties on the model ever change without updating the view to match. More details can be found here: ASP.NET MVC2: Strongly Typed Html Helpers – ScottGu’s Blog

However, the way that this has been implemented doesn’t work for me. The MVC pages I work on use a lot of Ajax in order to boost performance. I could potentially have a number of different actions available on the page which do not cause the whole page to refresh. Instead, they post data from particular sub-areas of the page, and only portions of the pages are updated when the request comes back. With the MVC 2 implementation of the strongly typed Html Helpers, they assume that the Model you will be using to submit your action will be the same type of Model that is used to initially render the page. In my situation, this “Request” Model (as apposed to “View” Model) often does not fit:

ModelDoesNotFitForMe

To illustrate this with a concrete example, let’s suppose I have a page with both a grid containing a list of items, and an “Add New” form with a Submit button. The View Model to render the page would contain the list of items to be displayed in the grid. However, there would be no properties related to the Add New form because all fields would be blank when the page first loads. When the user enters some details in the Add New form and presses the Submit button, an Ajax request is made in order to post the new data. However, the Request Model for this now contains properties to represent data from fields in the Add New form. It does not need to contain a list of items in the grid, which it would include if I was forced to reuse the same type of Model, as with the MVC2 implementation.

Interestingly, the implementation they have used in the FubuMVC framework does allow you to specify the type of the model. This could be because Jeremy Miller understands the difference between a Request Model and a View Model. For example (taken from one of the FubuMVC unit tests for TextBoxExpression):

image

Similarly, the FluentHtml library in MVCContrib also allows you to define the model type, albeit a more clunky syntax than with FubuMVC, for example (taken from one of the unit tests for TextBox):

image

Of course I could write my own extension to the ASP.NET MVC Html helpers in order to give me this functionality, but I just feel like I should have to. I think that they have been a bit short-sighted with this one, particularly since the focus of the version 2 release is “Enterprise Ready”. Perhaps they are more focused on the non-Ajax / full page post-back, single-form web page like in the world of more traditional ASP.NET web forms. Maybe this will be available in version 3?

Caution: Asp.NET MVC Filters can be invoked in reverse order

In one of my current Asp.NET MVC web applications I use a number of custom filters to perform processes such as logging, compression, whitespace removal and so on. Some of these are designed only to be ran after actions or results have executed. In order words, they only override the “OnActionExecuted” or “OnResultExeuted” methods.

These filters also have explicit ordering. For example, I intended to remove whitespace first, and then compress, so for example I would have 2 filters explicitly ordered like this:

[WhitespaceFilter(Order=1)]

[CompressionFilter(Order=2)]

However, what I found out is that when executing, the order gets reversed. After digging into the source code of the Asp.NET MVC Framework, I realized that this is by design. Basically the OnActionExecuting and OnResultExecuting events were being fired in order, but the “ed” events were being reversed, which makes sense when you think about it. What this means is that you have to be careful to remember this when defining the order of filters which only respond to the “ing” events!

Using Wildcards with JQuery Selectors

I have been using some nifty JQuery tricks to provide a rich UI experience in the application I am currently working on. One of the things I have been using it for is for watermarks. I found a neat JQuery extension for adding watermarks here: Josh Bush’s watermarking.

However, I have many input elements on my page which require watermarks, and one nifty way I found was to use wildcards with JQuery selectors. Here is the section of the JQuery documentation that I found the most useful (taken from here:

Update made on 1/22/2010: As of jQuery 1.4, the @ symbol in the syntax has been removed (actually it was deprecated in 1.3). For jQuery 1.3 or later, the recommended approach is to leave out the @ symbol. Refer to the latest jQuery documentation for more details.

All attribute selectors are written like their XPath counter-parts (in that all attributes should begin with an @ symbol).

* E[@foo] an E element with a “foo” attribute
* E[@foo=bar] an E element whose “foo” attribute value is exactly equal to “bar”
* E[@foo^=bar] an E element whose “foo” attribute value begins exactly with the string “bar”
* E[@foo$=bar] an E element whose “foo” attribute value ends exactly with the string “bar”
* E[@foo*=bar] an E element whose “foo” attribute value contains the substring “bar”
* E[@foo=bar][@baz=bop] an E element whose “foo” attribute value is exactly equal to “bar” and whose “baz” attribute is exactly equal to “bop”

So, for example I can write:

$(‘input[id$=ExpirationDate]‘).Watermark(‘no expiration’);

This will add watermarks with the text ‘no expiration’ to all input elements which have an id ending with “ExpirationDate”. Nifty!

Similarly ^= means “starts with” and *= means “contains”.

Nifty!

A neat way to submit forms via Ajax using JQuery

I am currently working on a web application using Microsoft’s ASP.NET MVC framework. Most of the actions / page interactions are done via Ajax calls. When submitting a form, typically my JavaScript looked something like this:

// Get the values 
var company = { Name : $('input:name=companyName').val(),
Address1 : $('input:name=companyAddress1').val(),
Address2 : $('input:name=companyAddress2').val(),
City : $('input:name=companyCity').val(),
State : $('input:name=companyState').val(),
ZipCode : $('input:name=companyZipCode').val() }

// Send request
$.post('/CompanyMaintenance/Add', company, function(data) {
$('#ResultDiv').html(data);
}, "html");

However, I came across the following useful article:

http://stackoverflow.com/questions/267707/how-to-pass-complex-type-using-json-to-asp-net-mvc-controller

Using this approach, I don’t need to manually pull out all the values from the input elements, I can automatically serialize all the elements in my form. Also, if I’m smart about naming the elements in my form, the object I get will be automatically recognized by my Controller at the .NET side. For example, if I name my elements like this:

<form id="CompanyAddForm">
<input type="Text" name="company.Name"/>
<input type="Text" name="company.Address1"/>
etc.

and then my JavaScript can be like this:

var company = $('#CompanyAddForm').serializeArray();

// Send request
$.post('/CompanyMaintenance/Add', company, function(data) {
$('#ResultDiv').html(data);
}, "html");

My controller action (at the .NET side) will then look like this:

public ActionResult(Company company)
{
    companyService.Add(company)
    ... etc.
}

Additionally I can also use the same kind of code to do this from ASP.NET WebForms using the Ajax Pro library for Ajax. The main difference in the page is that there is only one Form, so I’ll have to make clever use of JQuery here, but essentially I could do something like this:

<div id="CompanyAddDiv">
<input type="Text" name="company.Name"/>
<input type="Text" name="company.Address1"/>
etc.

// Seralize all input elements
// within the 'CompanyAddDiv' div
var company = $('#CompanyAddDiv input').serializeArray();

// Send request
var result = CompanyPage.Add(company);

$('#ResultDiv').html(result.value);

WatiN 1.3 is MUCH faster

I use the WatIN framework to run tests against the UI of our web application. After upgrading to version 1.3 (the October 2008 release) I see a tremendous improvement in speed, and our build time has changed from 8 minutes to 3! Thank you WatiN!

Why do organizations hire consultant .NET developers?

Consultants cost a lot more than full-time / permanent employees, that’s a fact. I’ve always wondered why a company would choose to hire a consultant over a cheaper regular full-time employee, particularly someone from a ’boutique’ consultancy, which is similar to the company I work for. I’ve not been working as a consultant for long, but I have began to notice some patterns among clients. I have a theory that I’m pretty sure holds true for the majority of organizations that hire .NET developers. Note that I am restricting this to .NET developers because for other technologies and skill-sets, the same may not apply.

When faced with the question “why do organizations hire consultant .NET developers?”, at first glance the answer is simple. It is because (a) the organization needs to get someone in quickly, (b) the organization has a project which is short-term, and will not have work for a full-time hire after the project is finished, and / or (c) the organization has work which requires someone who is more senior / experienced than a regular full-time candidate.

I thought that this was the answer too. However, after some experience in the field I have a theory that this is incorrect, and that the real reasons are different. (a) is wrong because if a company could organize itself then full-time hires can be quick and painless. (b) is wrong because when a company is hiring .NET developers the need is rarely short term – projects usually require ongoing maintenance, and if an organization has one .NET project it is likely to have many more.

My theory is that the reasons for hiring a consultant over a regular full-time are one or all of the following:

(a) Human Resources isn’t organized – they either take too long, are bad at, or simply unable to bring in suitable full-time staff. One phonecall to a consultancy is all it takes to get a consultant in the door and start working.

(b) There are problems with the interview process for full-time candidates – they exclude too many good people, or are not asking the right questions in order to be able to hire suitable full-time staff.

(c) The company can’t attract full-time candidates – the company has either a strong culture, does not advertise itself positively, is badly located, is not in an attractive enough industry, or does not pay enough to warrant interest from qualified full-time candidates.

(d) Management isn’t organized – this is actually the most common. Management is unable to structure teams and make things work with less experienced staff, and therefore has to resort to hiring only very experienced workers who are self-accountable and able to self-manage. If only organizations where this happens were able to recognize this problem, they would be able to bring in a mix of experienced and less experienced developers at lower costs.

Does anyone have any similar experiences?

What type of developer are you?

Over my relatively short career as a developer so far, I have been privileged to work with a lot of other developers with a wide variety of work styles. Here are some of the patterns that I have noticed so far:

Strive to Improve or Stay the Same

80% strive to better themselves by learning new coding styles, better patterns and practices, using cutting edge tools and technologies, and generally striving to be a better developer.

20% are happy to trudge along the same path, will rarely change their coding syle, continue to use “for i=0 to…” instead of the “foreach” loop, name variables with either single characters or highly abbreviated codewords, cram all of their business logic into stored procedures, shy away from unknown open source libraries, and will probably be in the same job in 10 years time.

Copy Existing Patterns or Write your Own

When working on an existing codebase:

60% for the most part stick to the same patterns and coding styles in the existing codebase.

30% attempt to improve the patterns and coding styles in some places were it most needs it and uses some of their own styles in brand new sections.

10% strive to rewrite as much as possible and completely ignore any current patterns or styles, perhaps also even introducing their own third party libraries, even if the same functionality already exists.

Leave No Comments or Write Noisy Code

20% write code with no comments whatsoever.

40% write code which is very sparsely commented, often inconsistently.

30% go overboard with comments and fill codebase with lots of noisy comments which add no additional value, for example commenting Getters and Setters with “Gets XXX” and “Sets XXX” etc., or mirroring method and/or variable names which already describe the functionality succinctly without the need for comments.

10% write just enough comments, that add value without adding too much noise.

Test Driven Development or Manual Testing

65% do not unit test their code.

30% use some kind of unit tests, but write them after the code.

5% practice Test Driven Development (TDD) and tend to have high (>50%) test coverage.

Follow

Get every new post delivered to your Inbox.