Profiling LocalDb

I have become quite enamoured with LocalDb and find myself preferring to use it over SQL Server or SQL Server Express. It was created for developers, so it kinda makes sense that I’d adopt it.

My first hitch came when I tried to use SQL Server Profiler to profile LocalDb. The tricky bit was connecting. A bit of Googling sorted me out and here are the steps:

  1. open the Visual Studio Command Prompt and enter Sqllocaldb info MSSQLLocalDB
  2. one of the details returned will be Instance pipe name. Copy that value to clipboard. For me it was np:\\.\pipe\LOCALDB#3B4A343D\tsql\query
  3. Open SQL Server Profiler and start a new trace. In the Server Name textbox of the Connect To Server dialog which launches, paste the pipe name.

And that’s it!

Note: if you have version 11.0 on your machine, the command to enter is Sqllocaldb info v11.0

Visual Studio Tips – By Video

I just wanted to share with the world some productivity tips which I use when using Visual Studio 2013. I’ve confined the tips to Visual Studio 2013, which is not running Resharper. The tips are conveyed in this video:
YouTube Preview Image

If you have particular thing that you use, please share it in the comments!

ExceptionAssert.Throws instead of ExpectedException

Jimmy Bogard has already written about the perils of using the ExpectedException attribute in unit testing (MS Test and NUnit have that attribute). NUnit has dealt with this by including an Assert.Throws<T> method (it also has an Assert.Catch<T> method).

My testing framework of choice (MS Test) does not have an equivalent (disappointing). So, I set about writing one. The implementation looks like this:

public static class ExceptionAssert
{
        public static void Throws<T>(Action code, string exceptionMessage = null, string message = null, params object[] args) where T : Exception
        {
            try
            {
                code.Invoke();

                Assert.Fail("No exception was thrown by the code under test.");
            }
            catch (Exception exception)
            {
                if (string.IsNullOrWhiteSpace(exceptionMessage))
                {
                    Assert.AreEqual(exception.GetType(), typeof(T), message, args);
                }
                else
                {
                    Assert.AreEqual(exception.GetType(), typeof(T), message, args);
                    Assert.IsTrue(exception.Message.StartsWith(exceptionMessage, StringComparison.OrdinalIgnoreCase));
                }
            }
        }
}

And using it in a unit test as so:

[TestMethod]
[TestCategory(TestCategories.MembershipIntegration)]
public void CreateUserAccountWithNoTenantThrowsException()
{
	var membershipService = new MembershipService();

	ExceptionAssert.Throws<ArgumentNullException>(
		() =>
			membershipService.CreateUser(null, 
			TestFirstName, 
			TestLastName, 
			TestFirstName + " " + TestLastName,
			TestPassword, TestEmail
			));
}

Now, we won’t get the false negative in the event that the exception is thrown in the constructor of the MembershipService class, rather than in the method under test, membershipService.CreateUser.

If you want to verify the text of the exception message, you can do that too:

[TestMethod]
[TestCategory(TestCategories.MembershipIntegration)]
public void CreateUserAccountWithNoTenantThrowsException()
{
	var membershipService = new MembershipService();

	ExceptionAssert.Throws<ArgumentNullException>(
		() =>
			membershipService.CreateUser(null, 
			TestFirstName, 
			TestLastName, 
			TestFirstName + " " + TestLastName,
			TestPassword, TestEmail
			),
			"The argument was null"
			);
}

I’ve also included parameters for a failure message and formatting of that message (which is a normal overload of the Assert methods).

Selenium and Hovering Over Page Elements

Many webpages use mouse-hovering as part of their user experience. This is despite the fact that those pages may be loaded using mobile devices (which quite often employ a touch-hold gesture to get the same effect as a mouse-hover). Quite often, a menu will require a mouse to hover over it before it expands to reveal submenu items. And quite often, the submenu items are not even in the dom until that hover is effected.

It is not possible to truly hover using Selenium. However, it is possible to simulate hovering.

In browsers apart from Internet Explorer, the following code represents how you would hover over a menu and then click on one of its sub-menu items:

var firefoxBinary = new FirefoxBinary("PathToFirefox.exe");
var firefoxProfile = new FirefoxProfile();
IWebDriver webDriver = new FirefoxDriver(firefoxBinary, firefoxProfile);

//  Now for the hover magic
var elementToHoverOver = webDriver.findElement(By.Id("elementId"));    
var action = new Actions(webDriver);  
// Move to the Main Menu Element  
action.MoveToElement(elementToHoverOver).Perform();  

// Wait for the SubMenu to reveal  
var elementWait = new WebDriverWait(webDriver, TimeSpan.FromSeconds(WaitTimeout));
var subMenuItem = elementWait.Until(ExpectedConditions.ElementIsVisible(By.Id("subMenuItemId")));
subMenuItem.Click();

I’m not sure why you need to make the call to Perform() on the Actions object returned by MoveToElement. But that’s how you hover.

Now for Internet Explorer. In a nutshell, you execute some JavaScript via Selenium which would invoke a mouseenter event. So, you first cast the webDriver to IJavaScriptExecutorand call ExecuteScript to execute some JavaScript like the following:

var internetExplorerDriverService = InternetExplorerDriverService.CreateDefaultService(DriverPath);
var internetExplorerOptions = new InternetExplorerOptions();

IWebDriver webDriver = new InternetExplorerDriver(internetExplorerDriverService, internetExplorerOptions);

((IJavaScriptExecutor)webDriver).ExecuteScript("$('#main_menu ul li.parent:eq(1) a').mouseenter();");

The code for finding and executing a sub-menu item is the same as above.

Querying in the Home Library

An index for these Home Library posts can be found here. The code in this post can be viewed in full at this tag of the repository.

In this post, I’m going to reference a fair bit of code to go through the approach I’ve taken to retrieving data in my application. With this application, I am employing something known as Command Query Separation. Note that I am not going crazy with this and having separate databases for queries and commands. There is only a single database. I’ve tagged the current state of the code and it can be viewed/downloaded from this tag reference on Github.

I have adopted an implementation of this by Steven Van Deursen which he writes about in this blog post. So you can reference that for more details, as I won’t be going into that level of granularity for my explanation. On to the code.

The use case that I created for myself was to retrieve a collection of Lendings, to be displayed in a grid. Being that a query is required, I created a Query object called GetLendingsPagedSortedQuery:

public class GetLendingsPagedSortedQuery : IQuery<IList<Lending>>
{
	public int PageNr { get; set; }
	public int PageSize { get; set; }
}

The interface which that implements is as follows:

public interface IQuery<out TResult>
{

}

You may find an empty interface a little underwhelming. However, it does have an important role to play and gives us plenty!

The query object itself is a little misleading in its nomenclature, as it is really just a carrier of meta-data for the query. You can include all sorts of properties which inform the kind of search that is required. But it doesn’t actually perform the querying of the database. That is done by the query handler (coming up). So what we have is a separation of data and behaviour (which seems to transgress the principles of object-oriented programming). But that separation is actually important, as the modern approaches for decoupling components and using dependency injection make working with complex objects more difficult. Separating out the data and behaviour gives us the flexibility we strive for in maintainable/scalable applications.

The handler for that query is contained in a class where I am storing all of the handlers (all of the handlers for Lendings anyway):

public class LendingsHandlers : 
	IQueryHandler<GetLendingsPagedSortedQuery, IList<Lending>>,
	IQueryHandler<GetLendingByPkQuery, Lending>
{
	private readonly IUnitOfWork _unitOfWork;
	private readonly IUniversalMapper _mapper;

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

	public IList<Lending> Handle(GetLendingsPagedSortedQuery query)
	{
		 IList<Lending> lendings = new List<Lending>();

		 foreach (var lending in _unitOfWork.Lendings.Paginate(query.PageNr, query.PageSize, l => l.Id, l => true, l => l.Book.Authors, l => l.Borrower ))
		 {
			 var uiLending = new Lending();
			 lendings.Add(_mapper.Map(lending, uiLending));
		 }
		
		return lendings;
	}

	public Lending Handle(GetLendingByPkQuery queryObject)
	{
		var uiLending = new Lending();
		return _mapper.Map(_unitOfWork.Lendings.FindBy(l => l.Id == queryObject.Id).Single(), uiLending);
	}

	public void Dispose()
	{
		_unitOfWork.Dispose();
	}
}

All of the handlers implement the following interface:

public interface IQueryHandler<in TQuery, out TResult> : IDisposable 
	where TQuery : IQuery<TResult>
{
	TResult Handle(TQuery query);
}

Grouping them in the one class is not a problem as they all have different closed generic types. And it is just a design decision that I made. If you want, you can create a separate class for each handler. The UnitOfWork is responsible for data access operations and the mapper is just an abstraction of the Automapper mapper engine which maps my Domain objects to my Ui-flavoured Domain objects (refer to this post for elaboration, if required).

Now, we could just go right ahead and inject the relevant handler/s into our controllers. But Steven came up with a better way. He has implemented the Mediator design pattern and done it in a very clever way, as foreshadowed by my previous post which set the ground work for this aspect of this post.

Normally, when the Mediator pattern is implemented, the object which is the Mediator is a member of each of the Colleague objects. But with an innovative usage of the dynamic run-time, mixed in with some reflection and dependency injection, we can write a Mediator which does not need to be a member of its Colleagues. This reduces the infrastructure code we would need to write as the number of handlers grow. The Mediator which I am using in Home Library looks like this:

public sealed class QueryProcessor : IQueryProcessor
{
	private readonly IUnityContainer _container;

	public QueryProcessor(IUnityContainer container)
	{
		_container = container;
	}

	//[DebuggerStepThrough]
	public TResult Process<TResult>(IQuery<TResult> query)
	{
		var handlerType = typeof(IQueryHandler<,>).MakeGenericType(query.GetType(), typeof(TResult));

		dynamic handler = _container.Resolve(handlerType, "Queryor");

		return handler.Handle((dynamic)query);
	}
}

where the interface IQueryProcessor has just the one method:

public interface IQueryProcessor
{
    TResult Process<TResult>(IQuery<TResult> query);
}

I feel I can’t just leave you in the lurch and not explain how I configured the dependency injection for that, as it was a little challenging with Unity. In fact, I cheated and took the code from a StackOverflow question answered by Steven himself (which I converted to the expression-style of syntax, as I don’t like the SQL-style of syntax of LINQ):

/// <summary>
/// From http://stackoverflow.com/a/13859582/540156, as updated by me with expression-style syntax
/// </summary>
/// <param name="type"></param>
private void AutoRegisterType(Type type)
{
	const string Registration = "Registration";

	var handlerRegistrations = _serviceAssembly.GetExportedTypes()
		.Where(x => !x.IsAbstract)
		.Where(x => !x.ContainsGenericParameters)
		.SelectMany(x => x.GetInterfaces()
			.Where(i => i.IsGenericType)
			.Where(i => i.GetGenericTypeDefinition() == type)
			.Select(i => new { service = i, implementation = x })
			);

	foreach (var registration in handlerRegistrations)
	{
		_container.RegisterType(
			registration.service,
			registration.implementation,
			type.Name + Registration,
			new TransientLifetimeManager());
	}

	if (type == typeof(IQueryHandler<,>))
	{
		// Decorate each returned IQueryHandler<T> object with an
		// QueryHandlerValidatorDecorator<T>.
		_container.RegisterType(
			type,
			typeof(QueryHandlerValidatorDecorator<,>),
			"Queryor",
			new InjectionMember[] { new InjectionConstructor(new ResolvedParameter(type, type.Name + Registration)) }
			);
	}
	else if (type == typeof(ICommandHandler<>))
	{
            //... ommitted as not relevant here
	}
}

And I call that method with a simple invocation AutoRegisterType(typeof(IQueryHandler<,>)); in my DiContainerConfigurer class, which is one of the classes that runs on start-up to wire up all the dependency injection. You can see in lines 33 and 34 references to a decorator. That’s coming up next.

But before we get to that, I mentioned earlier the important role that the empty IQuery<out TResult> interface plays. Take a look at the following code in my presenter:

public class AddLendingsPresenter : Presenter<IAddLendingsView>, IDisposable
{
	private readonly ICommandProcessor _commandProcessor;
	private readonly IQueryProcessor _queryProcessor;

	public AddLendingsPresenter(IAddLendingsView view, ICommandProcessor commandProcessor, IQueryProcessor queryProcessor) : base(view)
	{
		_commandProcessor = commandProcessor;
		_queryProcessor = queryProcessor;
		View.ViewClosing += View_ViewClosing;
		View.CloseControl += ViewCloseControl;
		View.Load += View_Load;
		View.AddNewLending += View_AddNewLending;
	}

	void View_Load(object sender, System.EventArgs e)
	{
		var getPeopleSortedQuery = new GetPeopleSortedQuery {SortBy = "id"};
		var getBooksSorted = new GetBooksSorted {SortBy = "id"};

		IList<Book> books = _queryProcessor.Process(getBooksSorted)
		IList<Person> people = _queryProcessor.Process(getPeopleSortedQuery)
		
		var addLendingViewModel = new AddLendingViewModel
		{
			Books = new BindingList<Book>(books),
			People = new BindingList<Person>(people)
		};
	}
	// ...
}

If you look closely at lines 21 and 22 where the _queryProcessor (our mediator) is put into play, no casting is required. Compile-time support is provided by our query architecture, and that seemingly underwhelming IQuery<out TResult> interface gives us that strong typing.

The other really cool aspect of this architecture is the use of decorators to implement cost-cutting concerns. The next piece of code which I am going to set out shows how we can use the Decorator pattern to wrap a query handler with a class that performs validation before the handler is invoked. If you are unfamiliar with the Decorator pattern, one of its hallmarks is that the class which is decorating another class implements the same interface that the decorated class implements. Below, QueryHandlerValidatorDecorator also implements IQueryHandler<TQuery, TResult>. So, inside the Handle method of our decorator, we perform some validation of our query object (in this case, using the Validator in the System.ComponentModel.DataAnnotations namespace) and then call the Handle method of our query handler, or decorated object:

public class QueryHandlerValidatorDecorator <TQuery, TResult> : IQueryHandler<TQuery, TResult>
	where TQuery : IQuery<TResult>
{
	private readonly IQueryHandler<TQuery, TResult> _queryHandler;

	public QueryHandlerValidatorDecorator(IQueryHandler<TQuery, TResult> queryHandler)
	{
		_queryHandler = queryHandler;
	}

	public TResult Handle(TQuery query)
	{
		var validationContext = new ValidationContext(query);

		try
		{
			Validator.ValidateObject(query, validationContext, true);
			return _queryHandler.Handle(query);
		}
		catch (ValidationException validationException)
		{
			throw;
		}
		catch (Exception exception)
		{
			throw;
		}
	}

	public void Dispose()
	{
		_queryHandler.Dispose();
	}
}

For the purposes of this post, I’ve added a very basic annotation to the GetLendingsPagedSortedQuery class, and it is that which gets validated by our decorator:

public class GetLendingsPagedSortedQuery : IQuery<IList<Lending>>
{
	[Range(0, 100, ErrorMessage = "The Page Number cannot be less than 1.")]
	public int PageNr { get; set; }
	public int PageSize { get; set; }
}

If you want to see the validation fail, just go to the LendingsPresenter and change the PageNr of the GetLendingsPagedSortedQuery to -1.

Again, you can check out the code for the content referred to in this post by going to this tag of the code.