A Slice Through the Layers

An index of the HomeLibrary application posts can be found here.

As I mentioned in my last Home Library post, I was eager to do a slice through the layers to test out any possible flaws or problems in my general architecture so far. To facilitate this, I fired up Balsamiq and created a View of roughly how I want one of the screens to look. The screen which manages people:
People

Note that all I want to implement here is the grid, not the whole screen. Also, I probably don’t need to explain the low fidelity nature of Balsamiq which ensures that we don’t get to choose one down by such things as colour selection.

The main things I want to verify in this exercise is:

  • whether I have configured Automapper correctly;
  • that my dependency injection is in order; and
  • that the data is making it from the database to the View as expected.

I created a separate branch to do this exercise, and as always with GIT, it’s very easy to make that available – LayersSlice Branch

Firstly, I I created a service which will feed data to a presenter:

public class HomeLibraryService : IHomeLibraryService, IDisposable
    {
        private readonly IUnitOfWork _unitOfWork;
        private readonly IUniversalMapper _mapper;


        public HomeLibraryService(IUnitOfWork unitOfWork, IUniversalMapper mapper)
        {
            _unitOfWork = unitOfWork;
            _mapper = mapper;
        }

        public BindingList<UiModel.Models.Person> GetAllPeople()
        {
            var peopleRepository = _unitOfWork.People;
            PaginatedList<Person> peoplePaginated = null;

            peoplePaginated = peopleRepository.Paginate(0, 3);

            var uiList = new BindingList<UiModel.Models.Person>();

            _mapper.Map(peoplePaginated.AsQueryable(), uiList);

            return uiList;
        }

        public void Dispose()
        {
            //  This will be properly done in final code.
        }
    }

2 of the main things I want to verify can be ascertained right here. You can see that the parameters to the constructor are facilitating constructor injection by my dependency injection container. That is configured in my composition root, a.k.a. Program.cs:

    static class Program
    {
        private static IUnityContainer _container;

        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main()
        {
            Database.SetInitializer(new HomeLibraryInitializer());
            new HomeLibraryContext().Database.Initialize(true);

            var autoMapperBootstrapper = new MapperBootstrapper();
            autoMapperBootstrapper.Initialize();

            ConfigureIoc();

            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new PersonView());
        }

        private static void ConfigureIoc()
        {
            _container = new UnityContainer();

            _container.RegisterInstance<IMappingEngine>(AutoMapper.Mapper.Engine)
                .RegisterType<IUniversalMapper, UniversalMapper>(new TransientLifetimeManager());

            _container.RegisterType<IRepositoryProvider, RepositoryProvider>(
                new TransientLifetimeManager(),
                new InjectionMember[] {new InjectionConstructor(new RepositoryFactories())}
                );

            _container.RegisterType<IUnitOfWork, UnitOfWork>(new TransientLifetimeManager());
            _container.RegisterType<IHomeLibraryService, HomeLibraryService>(new TransientLifetimeManager());

            PresenterBinder.Factory = new UnityPresenterFactory(_container);
        }
    }

The service also contains the code which I use to map a domain object to a Ui-model (objects which are more suited and shaped to the View for use in Viewmodels). With just two lines of code I’m able to map all of the properties from the domain’s PaginatedList to the Ui’s BindingList. Thank you Jimmy Bogard!

I’ve only created one View for this demonstration as I only needed to verify the slice through the layers. What you will see in the PersonView is that I have used the PresenterBinding attribute to bind the View to the PeoplePresenter:

[PresenterBinding(typeof(PeoplePresenter))]
public partial class PersonView : MvpForm, IPersonView
{
	public PersonView()
	{
		InitializeComponent();
	}

	private void PersonView_Load(object sender, EventArgs e)
	{
		dgvPersons.AllowUserToAddRows = false;



		dgvcDelete.Image = ImageResources.delete;
		dgvcEdit.Image = ImageResources.edit;

		dgvPersons.DataSource = ViewModel.People;
	}

	public event EventHandler ViewClosing;
	public event EventHandler EditPersonClicked;
	public PersonViewModel ViewModel { get; set; }

	private void dgvPersons_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
	{
		switch (dgvPersons.Columns[e.ColumnIndex].Name)
		{
			case "dgvcIsAuthor":
				bool isAuthor;

				if (bool.TryParse(dgvPersons.Rows[e.RowIndex].Cells["dgvcIsAuthor"].Value.ToString(),
					out isAuthor))
				{
					e.Value = isAuthor ? ImageResources.tick : ImageResources.cross;
				}
				break;
		}
	}
	
	public void ReleasePresenter(IPresenter presenter)
	{
		PresenterBinder.Factory.Release(presenter);
	}

	protected override void OnClosing(CancelEventArgs e)
	{
		ViewClosing(this, EventArgs.Empty);
		base.OnClosing(e);
	}
}

WinformsMVP has 2 mechanisms for binding, that attribute and binding by convention. The reason I can’t use convention in my project is because my presenters will be located in a separate project which does not conform to the convention used by WinformsMVP to search for presenters. And that’s okay. It was a design choice I made. But if people prefer to bind by convention and to organise their projects in such a way that it conforms to that convention, then that’s okay too.

When the app is fired up, the following window loads:
PersonView

It’s not much to look at now, but this is just “proof of concept” time. The data is there and all is well for the plumbing, from top to bottom in the stack.

Note that a lot of the code in this post (in the branch referred above) will not look the same as I progress the project further. I have already moved forward and started putting in place the bootstrapping code in earnest.

Lookout for a another post in the near future which will talk about the query handling aspects of my architecture by virtue of the Mediator Pattern. Got to keep those presenters clean!

Underscore.js can Bind This!

underscore.js has a really neat method called bind that does something quite interesting. Let me first talk you through what that method is addressing.

One of the foibles in JavaScript is that the this pointer has a somewhat unusual behaviour in that it will point to the window object, when inside a nested function. Take the following example:

var car = {
	engine: 1,
	doorToWheelRatio: function (nrOfDoors){
		
		this.nrOfDoors = nrOfDoors;					
		
		return function (nrWheels) {
			//  'this' refers to window object in here
			return this.nrOfDoors / nrWheels;
		};
	}			
};

There are two instances of this. The second one being in the nested function. That function is not going to behave as expected because the this pointer is pointing to the window object. This is a known foible, especially in light of the fact that the previous this pointer points at the car object.

The historical way in which developers have overcome that is to assign the this pointer to another variable in the enclosing function (e.g. self), thus making it available in the nested function:

var car = {
	engine: 1,
	doorToWheelRatio: function(nrOfDoors) {
		this.nrOfDoors = nrOfDoors;
		var self = this;
		return function(nrWheels) {
		  return self.nrOfDoors / nrWheels;
		};
	}
};

Using underscore.js’ bind function, we can effortlessly bind the this pointer in that nested function to the car object:

var car = {
	engine: 1,
	doorToWheelRatio: function (nrOfDoors){
		this.nrOfDoors = nrOfDoors;

		return _.bind(function (nrWheels) {
			return this.nrOfDoors / nrWheels;
		}, car);
	}			
};

Now both instances of this are pointing at the same object, car.

When I say effortlessly, bear in mind it comes at substantial cost. Take a look at this benchmark which I have performed at perf.com which clearly shows that using bind is an expensive operation compared with using a local variable (as was historically done).

It would be remiss of me not to point out that jQuery also has an equivalent function called proxy. That code would look like the following if we were to use proxy:

var car = {
	engine: 1,
	doorToWheelRatio: function (nrOfDoors){
		
		this.nrOfDoors = nrOfDoors;					
		
		return $.proxy(function (nrWheels) {
			return this.nrOfDoors / nrWheels;
		}, car);
	}			
};

That is all.

Underscore.js Avails Interesting Possibilities with Reduce

Since I began playing around with Underscore.js, I have become obsessed with its reduce method. reduce takes a collection (or an object) and returns a single value. But it is the way in which it does that which makes it compelling. From the documentation, its signature is:

_.reduce(list, iterator, memo, [context])

I’ll start out with a simple example. Probably the kind of example you’ll see everywhere around the Internet:

var result = _.reduce([100, 25, 2], function(memo, num) {
	 return memo / num;
});
// result === 2

The iterator function is being applied to each of the elements of the list. But not only that, it is making available to each iteration the result of the previous iterator-function’s result.

  • In the first iteration, memo has the value 100 and num is 25.
  • In the second iteration, memo has the value 4 and num is 2.

As you can see, the value of memo in the second iteration is equal to the result of the iterator function from the first iteration. So we have this concept of a value which is travelling through the iterations. The parameter memo is short for memoization. This is an implementation detail which is not relevant to this post. As that parameter travels from function to function through the iterations, I am using the name traveller for the purposes of this post.

There are only 2 iterations in this example because the list has 3 items and we have not passed it a seed value as the 3rd possible parameter. If we change that function to the following, we will get 3 iterations and the value of traveller on the 1st iteration will be 10000, whilst the value of num will be 100.

var result = _.reduce([100, 25, 2], function(traveller, num) {
	 return traveller / num;
}, 10000);
// result === 2

When it comes to the iterator function, you are free to be very creative in there. But first, I just want to point out that it is not limited to integers. The following example creates a sentence out of a string array:

var words = ['Reduce', 'is', 'an', 'interesting', 'method'];

var sentence = _.reduce(words, function(traveller, current) {
	var collate = traveller + ' ' + current;
	return collate;
});
//	sentence === 'Reduce is an interesting method'

You can also pass an object as the first parameter. This is where you can do some interesting stuff, like the following example that creates an address object from a person object:

var person = {
	name: 'Dave',
	age: 39,
	address: '28 Scenic Road',
	suburb: 'Kenmore',
	postcode: 4069
};

var address = _.reduce(person, function(traveller, objectValue, objectMember) {
    switch (objectMember) {
		case 'address':
		case 'suburb':
		case 'postcode':
			traveller[objectMember] = objectValue; break;
		default : break;
    }
    return traveller;
}, {});

You can see that I have passed an empty object as the 3rd parameter to reduce, which will be the initial value of the traveller parameter.

Note that I’m not saying the last example is the best way to achieve that end. But that example does show that you can use the reduce function for a great many things beyond simple arithmetic and sentence construction.

Perhaps in a month or 2 I’ll have a really good example that solves a problem nice and elegantly.

Until then!

Git Alias for Resetting Web.config

In circumstances where the only thing that changes in the Web.config file is the connectionstrings element (my local machine v.s my collaborators’ machines), I found myself entering the following command before every commit:

git reset HEAD TheNameOfTheWebProject/Web.config

Well, I got sick of typing all that, so I decided to create a simple alias.

git config alias.rew 'reset HEAD TheNameOfTheWebProject/Web.config'

Now my workflow looks like this:

git add -u
git rew
git commit -m "Some message about changes"

Note, I did not make the alias global, as it only applies to the Web.config of that particular project.

Caching Dom Objects with jQuery

I learnt something interesting about JavaScript that I was not aware of this last week. I’ll elaborate by walking you through what I discovered. Basically, I was trying to come up with a pattern that stored a jQuery object, and if for some reason that object had become null at some point, then a failsafe re-query would occur. It looked like this:

  1. Declare a variable
  2. Add it to the pageObjects object, with a cascade to the jQuery selection call
  3. Prime the variable in the document.ready function
  4. All dom manipulations are via the pageObjects object
var someDiv; // step 1

// step 2
var pageObjects = {
  someDivOnPage: someDiv || $('#someDiv'), // different name not necessary, but illustrative
  otherProperty: // ... pageObjects has many properties 
};

//********* document.ready function ********* / 
$(function() {
    // step 3
    someDiv = $('#someDiv');
});

//  ... access object later in script ...
// step 4
pageObjects.someDivOnPage.css('color', #eeeeee);

I discovered, after a while, that this did not work. If that div in one operation was removed from the dom, and re-added in another operation, calling pageObjects.someDivOnPage was undefined. Apparently, the coalesce in that statement was a one-off. That is, the first time pageObjects.someDivOnPage is accessed, the statement coalesces to the jQuery query as planned. But that statement only runs once and the property of that object is stored in a memory location. Once the element underpinning that jQuery object is removed from the dom, that property no longer points to that jQuery object and it doesn’t coalesce to the re-query as it did upon first access.

The proper way to do it is as follows:

var someDiv;

var pageObjects = {
  someDivOnPage: function () {
	return someDiv || $('#someDiv'); // different name not necessary, but illustrative
  },
  otherProperty: // ... pageObjects has many properties 
};

//********* document.ready function ********* / 
$(function() {
    someDiv = $('#someDiv');
});

//  ... access object later in script ...
pageObjects.someDivOnPage().css('color', #eeeeee);

As you can see, I have changed the property in the pageObjects object to be a function. And later on, when I reference that property I call it as a function.

So, the conclusion is that when the interpreter first parses the pageObjects object, the properties are assigned in the way that an expression is executed. To use pseudo code, it would look like this:

// for my first flawed approach.
... {
  someDivOnPage = someDiv || $('#someDiv');
};

// for my corrected approach
... {
  someDivOnPage = function () {
	return someDiv || $('#someDiv'); // different name not necessary, but illustrative
  };
};

That assignment occurs once and the result of that expression is assigned to the property. Makes complete sense really. It’s just something I had not picked up on. Felt like a goose.

So you’re probably wondering about performance? Well, that was the whole idea. The project which I am working on had jQuery performing queries heaps of times for the same dom objects in different operations during the lifecycle of the page (button-clicks, mouse-overs etc.).

If you look at this benchmark which I created at jsperf.com, you will see that this approach is very performant.

The other advantage is that if you are using a good IDE, you get intellisense when you “dot through” to the relevant property on the pageObjects object. This makes maintenance a lot easier and reduces the opportunity for typos when writing out each and every jQuery selector.