I was just typing this…
…when ReSharper 5 suggested its “Loop can be converted into LINQ-expression”:
You gotta love this!
I have been working in the IT for over 13 years, I'm Principal Consultant at Aviva Solutions, and I'm well-known for my pragmatic approach and my knowledge on software factories, automated testing, design patterns, architecture, Agile practices and TFS. I've has also published Coding Guidelines for C# 3.0 and C# 4.0 (www.csharpcodingguidelines.com), and an open-source framework for verifying specifications in unit tests called Fluent Assertions (fluentassertions.codeplex.com).
I was just typing this…
…when ReSharper 5 suggested its “Loop can be converted into LINQ-expression”:
You gotta love this!
After a week of testing in some of our projects, it is time to remove the beta marker from release 1.2.3 of our fluent assertion framework, Fluent Assertions. It’s just a small release, as was the previous one, but it still adds some nice additions requested by the community. This is the official list of changes:
As usual, you can download Fluent Assertions 1.2.3 from its resident CodePlex site.
What is it?
Using Team Foundation Server’s User Story, Task and Bug work item types as the central unit of work for all the activities done within a project.
Why would you do it?
What’s the usual thing to do?
How do you do that?
What is it?
The Ubiquitous Language is a unified language consisting of verbs and nouns from the business domain of an enterprise system and should be used by all team members, stakeholders and other involved persons.
Why would you do it?
What’s the usual thing to do?
How do you do that?
What is it?
An automatic build is a fully automated compilation of a specific version of your source code repository and which runs at regular intervals. More often than not, such a build includes additional steps such as running a static code analysis and code coverage, executing all automatic unit and integration tests, and possibly even a full-blown deployment of the product and the database to a test server. Continuous Integration, or CI, is just a fancy name for saying that a build runs whenever a developer checks-in his changes into the source code repository. This essentially forces all developers to continuously integrate their changes into a working product. However, since these kind of builds are run very frequently, extra steps are usually limited to unit tests and code coverage.
Why would you do it?
<Target Name="AfterBuild" Condition="('$(Configuration)' != 'Debug') and ('$(Configuration)' != 'Release')">
<!-- If a configuration-specific web.config exists, replace the default web.config with it –> <Copy Condition="Exists('$(DeploymentFolder)\web.$(Configuration).config')" SourceFiles="$(DeploymentFolder)\web.$(Configuration).config" DestinationFiles="$(DeploymentFolder)\web.config" />
<Delete Files="$(DeploymentFolder)\web.$(Configuration).config" />
<!-- If a configuration-specific enterpriselibrary.config exists, replace the default enterpriselibrary.config with it –> <Copy Condition="Exists('$(DeploymentFolder)\enterpriselibrary.$(Configuration).config')" SourceFiles="$(DeploymentFolder)\enterpriselibrary.$(Configuration).config" DestinationFiles="$(DeploymentFolder)\enterpriselibrary.config" />
<Delete Files="$(DeploymentFolder)\enterpriselibrary.$(Configuration).config" />
</Target>
<Target Name="AfterBuild" Condition="('$(Configuration)' != 'Debug') and ('$(Configuration)' != 'Release')">
<Message Text="Deploying Web Site to '$(DeploymentFolder)'." Importance="high" />
<!-- Create the _PublishedWebsites\app\bin folder –> <MakeDir Directories="$(DeploymentFolder)\bin" />
<!-- Copy build outputs to $(DeploymentFolder)\bin folder. –> <Copy SourceFiles="@(IntermediateAssembly)" DestinationFolder="$(DeploymentFolder)\bin" SkipUnchangedFiles="true" />
<Copy SourceFiles="@(AddModules)" DestinationFolder="$(DeploymentFolder)\bin" SkipUnchangedFiles="true" />
<Copy SourceFiles="$(IntermediateOutputPath)$(_SGenDllName)" DestinationFolder="$(DeploymentFolder)\%(Content.SubFolder)%(Content.RecursiveDir)" SkipUnchangedFiles="true" Condition="'$(_SGenDllCreated)'=='true'" />
<Copy SourceFiles="$(IntermediateOutputPath)$(TargetName).pdb" DestinationFolder="$(DeploymentFolder)\bin" SkipUnchangedFiles="true" Condition="'$(_DebugSymbolsProduced)'=='true'" />
<Copy SourceFiles="@(DocFileItem)" DestinationFolder="$(DeploymentFolder)\bin" SkipUnchangedFiles="true" Condition="'$(_DocumentationFileProduced)'=='true'" />
<Copy SourceFiles="@(IntermediateSatelliteAssembliesWithTargetPath)" DestinationFolder="$(DeploymentFolder)\bin" SkipUnchangedFiles="true" />
<Copy SourceFiles="@(ReferenceComWrappersToCopyLocal); @(ResolvedIsolatedComModules); @(_DeploymentLooseManifestFile); @(NativeReferenceFile)" DestinationFolder="$(DeploymentFolder)\bin" SkipUnchangedFiles="true" />
<!-- copy any referenced assemblies to $(DeploymentFolder)\bin folder –> <Copy SourceFiles="@(ReferenceCopyLocalPaths)" DestinationFolder="$(DeploymentFolder)\bin" SkipUnchangedFiles="true" />
<!-- Copy content files recursively to $(DeploymentFolder)\bin folder –> <Copy SourceFiles="@(Content)" DestinationFolder="$(DeploymentFolder)\%(Content.RelativeDir)" />
</Target>
<Target Name="AfterDropBuild">
<MSBuild Projects="$(SolutionRoot)\Main\Source\ConstructIT\Database\Database.dbproj" Properties=" OutDir=$(OutDir)" Targets="Deploy"/>
</Target>
What is it?
A mindset and practice that requires you to continuously reevaluate a region of code each time you make a change. In essence, you need to look at the code related to your changes and reconsider whether the original solution is still the best solution accounting for the information you currently have (and did not have at that time). Refactoring is a core practice of the Test Driven Development.
Why would you do it?
What’s the bare minimum you need to do?
What’s the usual thing to do?
How do you do that?
As promised earlier, you can now download the concept version of my new Coding Guidelines for C# 3.0 and C# 4.0 from a dedicated CodePlex site at www.csharpcodinguidelines.com. The list of changes is quite big, and includes new guidelines covering object-oriented design, design principles, C# 4.0 and the smells and heuristics from Robert C. Martin’s book Clean Code. I’ve also removed many guidelines that have become obsolete or deal with situations that rarely occur. And the entire document has become much easier to read because I’ve changed to a less formal writing style.
A common question I receive regularly is how to introduce coding guidelines or coding standards into a team or organization, so I’ve adapted my April post on Coding Guidelines and included it into the document. Another question I get asked commonly is what to do if something is not covered by the document. For this, I’ve included my most favorite design principles that should help you determine when something is valid or not.
Similarly to the quick reference guide for the C# 3.0 version of the document, I’ve included a two-page A4-sized cheat sheet with the most important guidelines and some handy tables on naming, ordering and layout.
And finally, Jonne Kats and I started creating a set of FxCop and StyleCop rules that verify your code against some of the guidelines in this document. It’s a side project, so it may take a while before a first release will be made available. In the mean time, check out the source code repository regularly.
And last but not least, this document has not been cut in stone. So if you have remarks, comments, additions or complaints, just let me know. I’ve already received valuable feedback from the community and will continue to update the document whenever something useful comes to my attention.
Now that my CQRS/Event Sourcing talk for DotNED is done, the pressure on the free hours between work and family has been reduced significantly. That doesn’t mean I’m going to sit back and relax. Oh no, I’m full of ideas. so let’s see some of my plans.
Yesterday evening I did a talk on building a .NET-based system using Command Query Responsibility Segregation and Event Sourcing. We had a lot of awesome discussions on its applicability, and as usual, I ran out of time again. I could have easily spend a full day on this subject, but unfortunately, I only had about 1 hour and 45 minutes to my disposal.
All code is available as a CodePlex project and I’ll be continuing development on the demo application so that it includes all major and all corner cases. I’m going to try to make it a great reference for anybody whose intention is to start building CQRS-based systems.
Most of us will be familiar with the standard 3- or 4-layer architecture you often see in larger enterprise systems. Some are already practicing Domain Driven Design and work together with the business to clarify the domain concepts. Perhaps you’ve noticed that is difficult to get the intention of the 'verbs' from that domain into this standard architecture. If performance is an important requirement as well, then you might have discovered that an Object-Relational Mapper and a relational database are not always the best solution.
One of the main reasons for this is the fact that the interests of a consistent domain that takes into account the many business rules, and those of data reporting and presentation are conflicting. That’s why Betrand Meyer introduced the Command Query Separation principle.
An architecture based on this principle combined with the Event Sourcing concept provides the ideal architecture for building high-performance systems designed using DDD. Well-known bloggers like Udi Dahan and Greg Young have already spent quite a lot of of posts on this, and this year’s Developer Days had some coverage as well.
But how do you build such a system with the. NET framework? Is it really as complex as some claim, or is just different work? If you want an answer to this, sign up for this evening and come see how I've built a concrete Silverlight demo app.
Subjects that I’ll cover:
You can find the latest details on this evening and the registration info here.
I've recently finished the book The Inmates Are Running The Asylum by Alan Cooper, a well known proponent for interaction design. To be honest, I never really saw the purpose of interaction design in our projects. But after reading this book, I now know I didn't really understand what it was about and why it is so important. 
One of my colleagues, Stefan Bookholt, has mentioned the need for some good interaction design many times, but his persistence was often met by laughter. This post is not really a review of the book, but rather my public apologies to him for not listening earlier.
First of all, this book is really worth its money and very easy to read. It's so full of real life cases and anecdotes, it really helps you to gain a solid understanding of why interaction design is so important.
Some highlights you should remember the next time you have a discussion about the functional design of your application.
It has been only 6 weeks since I first released Fluent Assertions to the public, followed by version 1.1 a week later. In the weeks thereafter, I received some nice ideas from the community which caused me to start working on the next version.
But it was not easy. I found that designing a small framework like this really requires you to carefully design the syntax you want to offer. For instance, I underestimated the limits of the current version of C# and had to make some tough decisions along the way. But I'm done now, so get version 1.2 from CodePlex. However, please read this post before you start introducing it in your project. Those tough decisions will cause some minor inconvenience.
The collection assertion methods now include a BeNull() and NotBeNull() to ensure that a collection is initialized or not. I’ve also made sure that the Contains() method of a generic collection takes an object of the right type instead of System.Object (this breaks existing usages though). And if that is not enough, you can also pass in a lambda expression to specify that the collection should contain a specific instance. Something like this:
dtoCollection.Should().Contain(dto => dto.Id != null);
Similarly, you can also use a lambda when asserting the count of a collection:
collection.Should().HaveCount(c => c >= 3);
If the subject-under-test does not comply with the expression, it will include the actual expression of the lambda in the error message. As a matter of fact, this applies to all assertion methods that take a lambda expression.
I’ve added the possibility to assert the equality of entire objects by comparing their properties by name. This even works if the types of the properties differ but a built-in conversion exists (through the Convert class). As an example, consider a Customer entity from some arbitrary domain model and its DTO counterpart CustomerDto. You can assert that the DTO has the same values as the entity using this syntax:
dto.ShouldHave().AllProperties().EqualTo(customer);
As long as all properties of dto are also available on customer, and their value is equal or convertible, the assertion succeeds. You can, however, exclude a specific property using a lambda, such as for instance the ID property:
dto.ShouldHave().AllPropertiesBut(d => d.Id).EqualTo(customer);
The other way around is also possible. So if you only want to include two specific properties, use this syntax.
dto.ShouldHave().Properties(d => d.Name, d => d.Address).EqualTo(customer);
In addition to simple assertions between two DateTime objects, I’ve added a whole bunch of methods for asserting that two dates or times differ a specific amount of time (specified using a TimeSpan). With these you can do things like:
dt1.Should().BeWithin(TimeSpan.FromHours(50)).Before(dt2);
dt2.Should().BeLessThan(TimeSpan.FromDays(1).After(dt2);
It supports BeMoreThan(), BeAtLeast(), BeExactly(), BeWithin() and BeLessThan() before or after a specific date and/or time.
In addition to fixing several minor bugs reported by the community, I have spend a considerable amount of time in making sure the assertion failure messages clearly explain why it failed. For instance, a date/time assertion might return the following (lengthy) exception message:
”Expected date and/or time <2010-04-08 09:59:59> to be within 2d and 2h before <2010-04-10 12:00:00> because 50 hours is enough, but it differs 2d, 2h and 1s.”.
The part after the because is the part that you need to add using one of the many overloads. It really helps to keep the developer from the need to start the debugger.
One particular bug I fixed was when asserting that a collection of strings contained a particular string, it was interpreted as an IEnumerable of Char. Obviously it never succeeded, regardless of the fact that the original string was part of the collection.
I also looked at extensibility a bit more by making classes public and ensuring you can override an assertion class at the right spots. I still have to do some work here, but whenever somebody has a problem, I’ll fix it soon enough.
As a result of some important feedback from the community, my desire to remove a lot of noise from the syntax, and limitations of the language I ran into, I decided to introduce some changes that will break existing code. Fortunately, it is just a cosmetic change, so some smart search/replace should get you back on track easily.
First of all, I’ve renamed almost all Equal() methods to Be(). So instead of myString.Should().Equal(“hello”) you now have to write myString.Should().Be(“hello”). The only exception to this is the one for comparing two collections for equality, since it’s purpose to see if they have the same items.
Also, I’ve renamed the Satisfy() method for asserting an arbitrary object against a lambda expression to Match(). Apparently, the word satisfy was a bit to technical. On the flipside, you now get multiple overloads which allows you to do the following.
o.Should().Match(obj => obj == null)
o.Should().Match<CustomerDto>(d => d.Name.Length > 0);
o.Should().Match((CustomerDto d) => d.Name.Length > 0);
The whole exception throwing assertion syntax was way too noisy, so I removed some unnecessary parts and changed the overall syntax. For instance
someObject.ShouldThrow(x => x.SomeMethod()).Exception<SomeException>();
has been changed into
someObject.Invoking(x => x.SomeMethod()).ShouldThrow<SomeException>();
Which doesn’t really remove noise, but feels more natural to me when invoking a lambda expression. When using an Action<T>, the syntax has changed as well. Consider a class with a method Foo() that should throw an instance of SomeException:
Action act = () => someObject.Foo();
In 1.1 asserting that Foo() really threw that specific exception with specific values for its Message and a custom property SomeParam had to be done like this:
act.ShouldThrow().Exception<SomeException>().
And.WithMessage(“Something went wrong”).
And.ValueOf.SomeParam.Should().Equal(23);
In 1.2 I’ve changed it into:
act.ShouldThrow<SomeException>().
WithMessage(“Something went wrong”).
And.SomeParams.Should().Equal(23);
You can download version 1.2 from here.
This morning, on the Developer Days 2010, I did a talk on the current state of affairs of the 4.0 version of the Entity Framework, including a rough comparison with NHibernate 2.1. Apparently this is something that’s on the mind of many people. The room was supposed to accommodate a maximum of 80 attendees, but at least 30 people were standing in the back or sitting on the ground and 10-20 more were refused access. I think that counts as a success… Anyway, you can find the slides here and download the demo code from here.
During the day many attendees asked me about the final conclusion. So, is Entity Framework 4.0 ready for the real work?
Yes…because the designers are excellent for rapid application development and suitable enough for simple domain models that provide a one-to-one mapping to the database. Moreover, you don’t need to struggle with big bundles of documentation to quickly get started.
But…the Code First functionality in CTP3 is still too limited for serious Domain Driven Design. It simply misses too much concepts very common in mature OR/Ms like NHibernate and its fluent add-on Fluent NHibernate. Worse, there is no Go-Live yet, so you can’t use it in production systems yet.
Nevertheless, the choice between NHibernate and EF4 is not trivial and depends entirely on the context of your project. NHibernate is still my first choice, but looking at the progress Microsoft has made the last year or so, I’m confident EF will gain some ground soon…
Some of you who have been visiting the Dutch Developer Days 2010 in The Hague today may have noticed the flyers and banners for promoting the new online version of the .NET Magazine. Those who already know me may have noticed that it’s me on those banners.
Since the photographer spent a considerable amount of time setting up his photo studio at Aviva Solution, and the fact that he shot almost 100 pictures, I wanted to give him Marco Hofste, the photographer, some credits. You can find his portfolio over here.
As part of my effort to improve the type-safety of Fluent Assertions, I’ve been investigating the possibility to use C# extension methods all the way. Unfortunately I think I’ve ran into the limitations of C# 3.0 (and C# 4.0 since it doesn’t add anything useful for this). Essentially, I’d like to do the following things.
var someList = new List<string> {"hello world"};
someList.Should().HaveCount(1);
someList.Should().Contain(s => s.Length > 0);
The first one is easy because it does not require any type-specific extensions and can be implemented by the following piece of code:
static class Extensions
{
public static EnumerableConstraints Should(this IEnumerable subject)
{
return new EnumerableConstraints();
}
}
public class EnumerableConstraints
{
public ShouldConstraint(IEnumerable subject) { }
public void HaveCount(int expectedCount) { }
}
The second one is more tricky. In order for the Contain() method to take a lambda expression on a List<string>, it needs to know the actual type of items in the IEnumerable collection. We can fix that by changing the type of the subject parameter to IEnumerable<T> and pass the <T> type parameter to the class that exposes the actual assertion methods:
static class Extensions
{
public static EnumerableConstraints<T> Should<T>(this IEnumerable<T> subject)
{
return new EnumerableConstraints<T>(subject);
}
}
public class EnumerableConstraints<T>
{
public void HaveCount(int expectedCount) { }
public void Contain(Func<T, bool> predicate) { }
}
That solves our initial two requirements, so let’s add another one. I’d like to be able to use a lambda expression on any possible type. Something like this:
var dto = new FindOrdersDto { CustomerName = “blah”, MaxItems = 10 };
dto.Should().Match(d => d.MaxItems < 100);
The first idea that pops up in my mind is to add an overload of Should<T> to the Extensions class, like this:
static class Extensions
{
public static EnumerableConstraints<T> Should<T>(this IEnumerable<T> subject) { }
public static BasicConstraints Should<T>(this T subject) { }
}
Unfortunately, this overload takes precedence over the overload taking an IEnumerable<T> and breaks the first working example. That’s a real bummer. If only I could use a where constraint stating that the <T> does not comply with a specific constraint. For instance
public static BasicConstraints Should<T>(this T subject) where not T : IEnumerable
I’ve also tried to change the HaveCount(), Contain() and Match() methods into extension methods on a single generic class ShouldConstraints<T> like this:
static class Extensions
{
public static ShouldConstraints<T> Should<T>(this T subject)
{
return new ShouldConstraints<T>(subject);
}
public static ShouldConstraints<T> HaveCount<T, TItem>(
this ShouldConstraints<T> constraints, int expectedCount) where T : IEnumerable<TItem> { }
public static ShouldConstraints<T> Contain<T, TItem>(
this ShouldConstraints<T> constraints, Func<TItem, bool> predicate) { }
public static ShouldConstraints<T> Match<T, TItem>(
this ShouldConstraints<T> constraints, Func<TItem, bool> predicate) { }
}
class ShouldConstraints<T>
{
public ShouldConstraints(T subject)
{
Subject = subject;
}
protected T Subject { get; set; }
}
This compiles fine, but causes the compiler to complain about missing type parameters because it is unable to infer these from the usage. This forces us to use this rather ugly syntax:
var someList = new List<string> {"hello world"};
someList.Should().HaveCount<List<string>, string>(1);
someList.Should().Contain<List<string>, string>(s => s.Length > 0);
Other solutions that crossed my mind included testing the ability to define two extension methods with the same name and the same parameters but having different constraints such as:
public static EnumerableConstraints Should<T>(this T subject) where T : IEnumerable
public static ComparableConstraints Should<T>(this T subject) where T : IComparable
But this is, as I expected, not supported by C#.
The conclusion? Well, as far as I can tell, my problem is currently unsolvable…
In response to my posts on Peer Reviews, Unit Testing & TDD, and Common Code Layout, someone noticed that all these posts were part of my Team Foundation Server Development Practices series, but not every post actually mentioned TFS. Obviously, he was right. The reason for using the TFS prefix is that our company is heavily using TFS as a platform for supporting Application Lifecycle Management. Most of the practices I talk about include a lot of practical advice on how to get the most out of the TFS product suite. Nevertheless, I’ve renamed the series to ALM Practices to better emphasis the real purpose of it. So what’s planned?
What is it?
A collection of rules stating what a block of code should look like. These may include rules on where line breaks are required, how to place parentheses, how much whitespace to put before and after those parentheses, how many spaces to use when indenting and where to insert empty lines.
Why would you do it?
What’s the bare minimum you need to do?
What’s the usual thing to do?
How do you do that?