Test your constructors to be simple

In the previous blog post I wrote how it is important to have a simple constructor that only accepts dependencies. And violation of this rule cost me at least 12 hours of debugging and blocking issue for some developers in the team. Now I have a unit test to prevent this kind of problem in the future.

One of the suggestions in the comments was to use strict mocks and inject them into a controller. And don’t set up any kind of expectations on mocks. This way if dependencies are doing anything in the controller, they will fail the test.

Continue reading

Constructors should be simple

Whole day of yesterday I’ve spent debugging some “random” error that came up third time during this week. The issue did go away after some tribal dances around the code, but two other instances did not get resolved easier. The biggest problem was that only one of the developers on the team did get the issue, and everybody else were not affected. And the same happened in the new deployment. And the issue was quite major – the whole site did not load. Nothing beyond the login screen. And it was impossible to hook in the debugger, it was bypassing all the breakpoints.

I would’ve gone through the issue and try debugging it, by my machine was not affected by the problem. I could not reproduce the issue locally. But on my home machine the issue came up. Strange I through, but was glad it came up – means I can dig my teeth deep in the problem and debug it.

Continue reading

Upload files to Azure Blob Storage with using Shared Access Keys

I had a task of uploading files from command line client to a private container in Azure Blob Storage. And as part of the overall infrastructure I also has MVC4 and WebApi sites running on my Azure Web-Site installation.

The problem with uploading files was that the container was private. Before, every time I used the container, I used private key to access it, but all the operations were contained on the server: user submits a file in a form in a browser, file is passed through MVC web-site, where it is uploaded into Azure blob storage. And in MVC there is a very easy way to manage multiple uploaded files.

Now my task was similar, but as a client I had command line application and server side was WebApi. In WebApi it is not so easy to manage uploaded files, especially if you had multiple files for upload. You could not (or I could not find a way to do that) simply redirect the upload stream from controller into Azure Blob. You had to store file somewhere and then copy that to Azure storage. And there are a few problems with that:

Continue reading

Find all descendants of a type

Quite often for DI auto-wiring I need to find all classes that implement a certain interface or inherit from some base abstract class. And reflection for that is brilliant. But I can never remember how to find these types, so every time I need to look up my old code. So I’ll record that in this blog. Here you go:

var profiles = Assembly.GetExecutingAssembly()
    .GetTypes()
    .Where(x => x != typeof(Profile) && typeof(Profile).IsAssignableFrom(x))
    .ToList();

This will give a list of types that all inherit from class Profile, but actually excludes the Profile class itself.

Ignore test categories in TFS build server using DefaultTemplate.xaml

At the moment I’m using excellent service from Microsoft: hosted TFS. The service is still in the preview (15 July 2013) and some features are in beta, but it works pretty smoothly already. One of the things I had to learn is how to use TFS as a build server. I’ve used to nice TeamCity with almost drag-and-drop build steps and simple configuration management. TFS is using XAML definition file to drive the build process. The default template that comes with any project is pretty much covers everything you might need when you start, but it is very complex and when you try looking on the XAML diagram, you might want to run away – it’s that big and complex. That’s what I did first time I looked on the XAML processes. Run away and installed TeamCity.

Now I’ve decided to give it another go. I’ve started from enabling nUnit tests on build server. By default TFS only works with MSTest. To enable nUnit, you need to add nUnit assemblies and nUnit to MSTest adapter to your source control. The process is perfectly described in this post by Ajay Majgaonkar. I’ve also seen the description of the process in some Microsoft documentation, but have lost the link.

Continue reading

Quartz.Net in Azure with Autofac. Smoothness.

Quartz.Net is an awesome scheduler for .Net world. It is a copy-cat from Java brother. The documentation is pretty useless, as it has not been updated for a while. The docs are useful to understand the general principals of operation, but examples of code usually don’t work. Instead the download provided on the site has a lot of examples. Use them as a guidance. Read the code, documentation sucks.

Anyway, I’ve spent couple days trying to get Quartz.Net to work inside of Azure and with Autofac dependency injection. And there are a few lessons that I’ve learned that I would like to share.

Continue reading

DRY for lambda expressions

I’m working with Entity Framework a lot and sometimes you can get yourself tied into a knot so hard, you can’t figure out wtf is happening and why simple looking LINQ query leads to about 1K actual SQL requests. This is not good, so be careful with what you are doing there.

Today I had to untie one of these knots: a simple looking LINQ was producing horrible SQL requests and made many of them. Mostly due to poor legacy structure of the DB we have to battle at the moment. Anyway, it turned out that instead one massive LINQ to Objects, it was more performant to make 3 similar request to 3 similar tables in SQL Server. And all those requests were with similar .Where() conditions. And it looked like this:

var holidayMovements = this.HolidayMovements
    .Where (m => (startDate <= m.Start && m.Start <= endDate)
        || (startDate <= m.End && m.End <= endDate)     
        || (m.Start <= startDate && endDate <= m.End));

var absenceMovements = this.AbsenceMovements
    .Where (m => (startDate <= m.Start && m.Start <= endDate)   
        || (startDate <= m.End && m.End <= endDate)             
        || (m.Start <= startDate && endDate <= m.End));         

notice that in both cases .Where() clauses are identical? And I have 3 of these. I could live with 2 instances of the same condition, as later down the line it might turn up that 2 of the conditions are not really the same and you need to change one of them.. and if you DRY-it out into a method, you might end up with more crutches than you need without DRYing. But 3 instances are prime candidate for refactoring this out into a function/variable.

But how can you separate lambda expression into a separate variable? Like this:

Expression<Func<PersonnelMovementBase, bool>> timeBoundaryCondition = 
    m => (startDate <= m.Start && m.Start <= endDate)   
            || (startDate <= m.End && m.End <= endDate) 
            || (m.Start <= startDate && endDate <= m.End);

var holidayMovements = this.HolidayMovements
    .Where (timeBoundaryCondition);

var absenceMovements = this.AbsenceMovements
    .Where (timeBoundaryCondition);         

Now condition is the same in the separate queries and the LINQ query looks much more sane now. Quite simple to my mind, but it took me more than 3 minutes to figure out how to create a lambda expression outside of the .Where(), so here you go. Just don’t forget to look this up when you need similar thing again.

Mocking Dependency Injection.

All the cool kids do write their own dependency injection container at some point. Today I had to come up with one for testing purposes:

public class MockDependencyResolver : IDependencyResolver
{
    private readonly Dictionary<Type, object> collection;

    public MockDependencyResolver()
    {
        collection = new Dictionary<Type, object>();
    }

    public void Freeze<T>(object mockedObject)
    {
        collection.Add(typeof(T), mockedObject);
    }

    public object GetService(Type serviceType)
    {
        if (collection.ContainsKey(serviceType))
        {
            return collection[serviceType];
        }
        var message = String.Format("No object is registered for type {0}", serviceType.Name);
        throw new ArgumentException(message);
    }

    public IEnumerable<object> GetServices(Type serviceType)
    {
        throw new NotImplementedException();
    }

Pretty simple, really. Very simple. And here how I use it in tests:

[TestFixture]
public class SomeClassTests
{
    private MockDependencyResolver dependencyResolver;

    public void Initialize_GenericInstance_IsValid(String forkName)
    {
        var dependencyResolver = new MockDependencyResolver();

        // this is a part of MVC project, hence MVC internal static reference
        System.Web.MVC.DependencyResolver.SetResolver(dependencyResolver);

        // I'm using Moq framework
        var someService = new Mock<ISomeService>();
        dependencyResolver.Freeze<ISomeService>(someService.Object);
        someService.Setup(c => c.SomeDepenentOperation()).Verifiable();

        // do you tests with someService as a dependency
        // inside of the class under test somewhere I have 
        //  DependencyResolver.Current.GetService<ISomeService>(); that would return null
        //  without mocking of DI

        someService.VerifyAll();
    }
}

Autofixture and Moq to test Entity Framework project

In the past month I have been using brilliant tool from Mark Seemann called Autofixture. The tool is aiming unit tests and shall help you create objects with some data filled in.

Usually for unit tests you need to create your objects manually and give them some kind of data inside of the objects, so you don’t get NullReferenceExceptions. And that sometimes takes a while and not always pleasant:

        var person = new Person
        {
            FirstName = "Dilbert",
            MiddleName = "Wall-E",
            Surname = "Smith",
            KnownAs = "Pointy Haired Boss",
            DateOfBirth = new DateTime(1975, 12, 31),
            Gender = Gender.Male,
            MaritalStatus = MaritalStatus.Single,
        };

Continue reading

Rollback attribute for NUnit and Entity framework

For integration testing it is very useful to wrap the tests in database transaction, and at the end of the test you just rollback the transaction, so any changes happened inside of the test are not persisted. And the next test run will be running on untouched data.

This is how the attribute looks:

using System;
using System.Transactions;
using NUnit.Framework;

/// <summary>
/// Rollback Attribute wraps test execution into a transaction and cancels the transaction once the test is finished.
/// You can use this attribute on single test methods or test classes/suites
/// </summary>
public class RollbackAttribute : Attribute, ITestAction
{
    private TransactionScope transaction;

    public void BeforeTest(TestDetails testDetails)
    {
        transaction = new TransactionScope();
    }

    public void AfterTest(TestDetails testDetails)
    {
        transaction.Dispose();
    }

    public ActionTargets Targets
    {
        get { return ActionTargets.Test; }
    }
}

Nothing fancy, just used NUnit’s ability to create custom attributes.

The tests will look like

[Test, Rollback]
public void YourTest() {
    // test method body
}

Alternatively you can apply Rollback attribute on the test suite and every test will be wrapped into a transaction automatically. Save you littering Rollback attribute on all the test methods.

[TestFixture, Rollback]
public class ClassUnderTestTests{
   // Test methods
}

Enjoy!