Generator pattern in C# .NET

Boo language has nice code pattern called Generator:

// Generator expressions are defined through the pattern:
<expression> for <declarations> in <iterator> [if|unless <condition>]

// Generator expressions can be used as return values:
def GetCompletedTasks():
      return t for t in _tasks if t.IsCompleted

// Generator expressions can be stored in variables:
oddNumbers = i for i in range(10) if i % 2

This pattern simply creates some IEnumerable object via the syntax transformation. We can not have this sugar in C# yet, but that’s how we can leverage the concept:

// Simple syntax
var customerList = new List<Customer>();
for (int i = 0; i < 40; i++)
{
	customerList.Add(new Customer
	{
		Name = "Customer_" + i
	});
}

// generator + LINQ syntax
var customers = Generator.For(40).Select(i => new Customer
{
	Name = "Customer_" + i
});

Continue reading ‘Generator pattern in C# .NET’

Linq queries with parameters for your ORM IRepository

Ricardo Cavalcanti has raised question on fluent passing of parameters into the queries encapsulated by the QueryFor (specification) pattern.

Let’s talk about the easiest option of passing parameters, first. It requires no new code at all and is just about chaining queries:

var list = customers
	.Find<ImportantCustomers>()
	.Where(c => c.City == "Ufa");

Where comes from the in line extension method provided by Linq.

However, in certain situations Linq might be not enough. This involves queries that encapsulate come complex business logic or require parameter pre-processing, that you want to hide away.

Continue reading ‘Linq queries with parameters for your ORM IRepository’

What is common between Autofac, Castle and MEF?

Ok, now it is official. The father of Autofac .NET IoC Container, Nicholas Blumhardt, has joined the team of Krzysztof Cwalina at Microsoft.

He will be the Program Manager in a team that’s building the Managed Extensibility Framework

Additionally Hamilton Verissimo (founder of the Castle project) will be joining the same team.

Congratulations and good luck, Nick! You can make the difference out there))

PS: Nick and Hamilton will still be able to spend as much time as they want on their pet projects. There’s the permission from Microsoft for that.

The power of simplicity

Answer to a comment by Jeremy Gray has started getting really long, so I’m putting the primary idea in a separate post.

As we all know, NUnit is one of the first unit testing frameworks for .NET. It is old, stable and quite conservative. At the same time, it’s feature set is inferior to the functionality provided by some newer frameworks (or even frameworks for handling unit testing frameworks, like Gallio).

However, I’m still trying to stick to NUnit in my projects. Reasons for that are:

  • It does not make reading tests challenging for new devs (unit tests are normally point of entry into the code, if they are present)
  • Unit tests are often considered to be usage samples for the code they test. We’d prefer to keep these simple, would not we?
  • The most important reason for me: simple unit testing framework forces developer to write unit tests that are easily testable (just like TDD forces some good logical separation between the components)

Imagine some really complex method that accepts quite a number of arguments and performs some black-box magic inside. If you have a data-driven unit testing framework at hand, you can simply create CSV file with valid entries and test this method against that. But if you do not have this functionality at hand, then you’d need to refactor the method to make it more simple and testable.

I like the last scenario. Even if it is not fun at the very start, it does pay off in the long term.

NUnit introduces the concept of row tests

Latest version of NUnit unit-testing framework for .NET has finally got support for the row tests. They are implemented by Andreas Schlapsi as an extension that now comes bundled with the NUnit 2.4.7.

Basically, row test is a test that could be run multiple times with different parameters (in other words, it is a simple data-driven test, where the data is provided by the attributes). Consider the following C# code snippet:

[TestFixture]
public sealed class Test_InterceptorCompiler : DslTests
{
	[RowTest]
	[Row("Chained Interceptions.boo")]
	[Row("ConsoleWriter.boo")]
	[Row("IWriter.boo")]
	[Row("Multiple Classes.boo")]
	[Row("Complex Writer.boo")]
	public void Interception_Dsl_Compiles(string name)
	{
		var step = new InterceptorCompilerStep()
			.Intercept<ComplexWriter>()
			.Intercept<ConsoleWriter>()
			.Intercept<IWriter>();

		CompileDslToMemory(step, name);
	}
}

Upon the execution in the NUnit GUI it will produce the following output:

Row tests in NUnit

Note, how every Row is treated as a separate unit test, and you can see which parameters have caused the failure.

Disadvantage of this new feature of NUnit is - JetBrains test runner (it comes with the R#) does not recognize them, yet. You would need to fire up NUnit GUI or use some other VS integration like TestDriven.NET in order to “run this test from the code”.

PS: there is an interesting podcast on the topic - The Past, Present and Future of .NET Unit Testing Frameworks.

Options of separating queries from the ORM Repository

Let’s get back to the discussion from XPO+ORM+IOC series on Implementing ORM-independent Linq queries.

As you can see from the previous post, there are 3 options to abstract away queries in a testable manner (and we will add one theoretical one for the Boo):

1. Put queries right into some domain-specific repository implementation (i.e.: CustomerRepository.FindImportantCustomers) and ask the container about it.

  • Pro: Simple and looks as if there is no logical separation between the repository and queries
  • Con: Low scalability
  • Con: Coupled code that would take some effort to test

2. Put queries into the extensions that use Repository[T].Find method.

  • Pro: A bit more abstraction and testability, than in the previous option
  • Con: Does not make a lot of sense

Continue reading ‘Options of separating queries from the ORM Repository’

Implementing ORM-independent Linq queries

We’ll get back from the Boo + Business + DSL to the XPO + ORM + IOC series for a little bit.

Nicholas Blumhardt has just written an interesting and extremely thorough article on Implementing the Specification Pattern via Linq. Let’s try to play with the idea and take it a one step down the road. Here we can:

1. Add ORM abstraction by implementing generic IRepository (of T) interface:

public interface IRepository<T>
{
	IQueryable<T> Find(QueryFor<T> query);
	IQueryable<T> Find(string criteria);
	IQueryable<T> Find<K>() where K : QueryFor<T>, new();
	IQueryable<T> Query();

	// ...
}

Continue reading ‘Implementing ORM-independent Linq queries’