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:

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

        // I'm using Moq framework
        var someService = new Mock<ISomeService>();
        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


Why you should write unit tests

One of the questions I have to answer frequently (mostly question myself) is “why should I write unit tests?”. One of the simplest answers it “They help you discover bugs”.

When you are writing unit test, you should not think about the internals of your methods, but rather about results you would like to get from that method. Kind of black-box testing. If you are not doing TDD, it also can help if you write tests the next day, when implementation details of your methods are not so fresh in your head.

Today I discovered yet another problem in the implementation of RavenDBMembershipProvider: most of the code is not mine there, but I’m writing tests and aim close to 100% coverage. Now in the main class only a few lines of code are not covered. When I started writing last few tests for these lines, I have discovered a problem. Without tests that would possibly be never discovered.. and possibly could lead to a security vulnerability.


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)

    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


Raven DB

I’ll probably start a series of posts related to RavenDB, since I’m learning to use it. And here is the first one.

I’ve been using SQL queries most of my programmers life and I’m so used to ask database things like this: show me all projects that user has access to.

Or Select * from project where ProjectId in (select ProjectId from UserPermissions where UserId=1)

When you try to use the same logic in RavenDB, it throws you NotSupportedException and no hints of how to do it. Luckily, RavenDb is popular enough to have a good hit score in Google and I managed to find the answer on the interwebs pretty quick.

Here is the way to search in a subset:

var locations = ravenSession
    .Where(l => l.ProjectId.In<string>(currentUser.ProjectIds))

And you’ll have to add using Raven.Client.Linq; to your class, so In<> becomes available.

Remove Server http header from ASP.NET MVC Application

There is an opinion in the online community that HTTP Headers in your application must not be giving out information about your site. But in every StackOverflow question about removing headers, there always will be someone saying “why bother?”. Well.. don’t bother if you don’t want to. You are quite right, there are ways to detect what server and technologies are used to serve the site. But I do not know any of these techniques, so I’ll keep removing headers from my applications.

Also it seemes that IIS insists on providing Server header with every request and there is no way to remove it via web.config. To get rid of this header I have seen people going out of their way with HTTP Modules and UrlScan. But in MVC4 (not sure about version 3 – never tried it there) and IIS 7.5 you can easily do that in you Glabal.asax.cs file.

In the application request life-cycle there is EndRequest() event that can do what we want:

    protected void Application_EndRequest()
        // removing excessive headers. They don't need to see this.

Much the same way you can remove any other header from the reply: X-Powered-By, X-AspNetMvc-Version and etc. But for these there are legit ways to do that through web.config.

Itenso TimePeriod library: change dates for TimePeriod

It took me a while to figure out how to change Start and End dates on an instance of TimePeriod. There are many functions to shrink and expand start and end dates, move the period by a certain time span, but I could not find anything that would just change .Start and .End.
Obviously you can do this:

timePeriod.Start = new DateTime(1999, 7, 9);
timePeriod.End = new DateTime(2012, 7, 9);

But this can lead to an exception if you are trying to move timeperiod to the future: Say start was on 1 Jan 2000, and on 1 Feb 2000. Then you give it .Start = 1 June 2000 and you get an exception saying “date out of range blah-blah”. That is because you are trying make start after end. You can swap assignment around, assign .End first then .Start. But you still can get an exception if you try to move the period to the past.

Instead, use .Setup method:

timePeriod.Setup(new DateTime(1999, 7, 9), new DateTime(2012, 7, 9));

And this should change your dates safely.

Disclaimer: I have not checked the source code, and not sure if that somehow ignores some internal mechanisms. So before blaming me that .Setup does not work, check with the author.

Set Validation error in ASP.Net MVC Controller

Every time I need to set a validation error in a controller, I need to look up how to do this. But it is very simple. So I’ll just write it down here, for future reference: In controller do:

ModelState.AddModelError("FieldName", "Error message for User");

If you leave FieldName blank, the error will come up in validation summary. In a view you’ll have to do this:

@Html.ValidationSummary(true) // for the whole model
@Html.ValidationMessageFor(m => m.UserName) // for individual model field

Unable to set break point for debugging in Visual Studio

Getting “The breakpoint will not currently be hit. No symbols have been loaded for this document.” in Visual studio whenever you try to debug?
There are a million solutions out there and every time it is a different issue.

Here is one way of sorting things out in VS2012:

Go to Tools -> Options -> Debugging -> Symbols.
Hit Empty Symbol Cache and select All Modules Unless Excluded.

Possibly will need to restart VS. And should work.