Rickard Nilsson is a software architect, developer, craftsman, agile enthusiast, and father of three... More
Rickard blogs about crafting software using .NET tooling and solid, development practices.
I’ve been working extensively with ServiceStack lately and I really like what they’ve done. As it contains the full stack for building HTTP based services from text serializers to development tools to a micro ORM it’s very easy to fall into the pit of success. I don’t mind picking and choosing these things for my self, however it’s nice that is doesn’t require any brain power making choices. Plus you can always be assured that the tools you get in the box is quick to get started with, and has all the performance you’ll ever need. They might be too simplistic four your needs but then it’s nice to know that its usually very simple to replace them with something else.
Let me tell you a story.
I was cruising along doing my thing, test-driving my code and was feeling pretty good about myself. I was hitting a very high code coverage as I was only writing a little bit of test code, a little bit of production code, and refactored as I went along. Now, I hit a pain point which showed itself to be very difficult to get under test. It was the few lines where I actually called the database through OrmLite’s extension methods.
OrmLite is a micro ORM and is part of the basic ServiceStack package. It is a set of extension methods on top of System.Data.IDbConnection which makes it very easy to use at the same time giving you direct access to the underlying APIs. It consists of operations like Insert<T>, Update<T>, Select<T> etc. and is really easy to get started with.
Anyway, as OrmLite is only extension methods on IDbConnection I though it’d be simple as cake to fake it out such that I could get my database calls under test as well.
Turns out it was way more difficult than I had anticipated. After a little while I gave up and left a total of four lines uncovered (one line per entity).
The other day I was looking through the ServiceStack documentation after something totally unrelated and stopped at a couple of lines that caught my attention.
// Use in-memory Sqlite DB instead
var dbFactory = new OrmLiteConnectionFactory(
":memory:", false, SqliteOrmLiteDialectProvider.Instance);
So, it was possible to use an in memory database instance instead of the SQL Server provider I was using in production. Very interesting. Could I utilize this in my unit tests to get that last mile?
Lets see. I quickly wrote a little unit test to try it out.
1: [TestClass]
2: public class EntityRepositoryTests
3: {
4: Entity expectedEntity;
5:
6: [TestMethod]
7: public void GetAll_All_ReturnsAllFromDatabase()
8: {
9: var dbFactory = new OrmLiteConnectionFactory(
10: connectionString: ":memory:",
11: autoDisposeConnection: false,
12: dialectProvider: SqliteOrmLiteDialectProvider.Instance);
13:
14: using (var db = dbFactory.OpenDbConnection())
15: {
16: db.CreateTable<Entity>();
17: expectedEntity = new Entity
18: {
19: Id = 1,
20: Name = "foo"
21: };
22: db.Insert(expectedEntity);
23: }
24:
25: var repository = new EntityRepository(dbFactory);
26:
27: var result = repository.GetAll().ToList();
28:
29: Assert.That(result, Is.EqualTo(new [] { expectedEntity }));
30: }
31: }
Sqlite is not included in the standard ServiceStack package, however it’s simply a matter of running a command in the Nuget Package Manager Console:
1: PM> Install-Package ServiceStack.OrmLite.Sqlite32
for the test project and SqliteOrmLiteDialectProvider lights up.
When this was done NCrunch automagically picked it up and everything turned green immediately. Nice!
Running the test with MSTest was a little trickier as it turned out. Sqlite drops an interop dll in the test project as a resource which MSTest couldn’t pick up. To get that to work I needed to add the dll as a deployment file in the local test settings. When I did that, the whole thing even ran in the continuous integration build in TeamCity.
Awesome day at work. Hope you’ve found this tip useful. Cheers!
This is part of a series of ReSharper Ninja ticks and workflows which I’ve picked up over the years. This particular one is brand new in ReSharper 7.
Category: Refactoring
This is a new feature in ReSharper 7 and one that I and many with me has been missing for a long time. Previously when you had a class with too many responsibilities, you had to go through a lot of hoops with ReSharper to refactor the code into cohesive units, and it usually involved a few manual steps.
Now, in version 7, we have an option on the refactoring menu called Extract class which automate the procedure. You place the marker on a class member and hit Ctrl+Shift+R to bring up the refactoring menu, and choose Extract class. This gives you a dialog where you can pick which members should be extracted and ReSharper analyses dependencies between different members such that the code won’t brake after the refactoring.
Checkout Hadi Hariri’s presentation on Extract Class at 07:28
In a previous post I described the importance of optimizing your web site resources and how you can do it using the open source tool Ajax Minifier. I’ve received a few questions about how to automate this process and now I want to share a ASP.NET MVC 3 template with the combining and minification built in as a post compile step.
Since my last post Ajax Minifier is now available as a NuGet package and is easily installed in your solution either via NuGet Package Manager or using the NuGet Package Manager Console command:
PM> Install-Package AjaxMin
However, to get the AjaxMin.exe you’ll have to download it manually from Codeplex. My MVC 3 template is build on a simple Internet Application MVC 3 template with Razor and HTML5 semantic markup. My additions to automate resource optimizations consists of the following:
After the web project is built a custom target is called:
<Import Project="$(MSBuildProjectDirectory)\AfterBuild.tasks" />
<Target Name="AfterBuild">
<CallTarget Targets="Minify"></CallTarget>
</Target>
The after build target executes the AjaxMin executable:
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<BuildLibPath>$(MSBuildProjectDirectory)\..\packages</BuildLibPath>
<Ajaxmin>$(BuildLibPath)\AjaxMin.4.62.4618.15628\bin\Ajaxmin.exe</Ajaxmin>
</PropertyGroup>
<Target Name="Minify">
<Exec Command='"$(Ajaxmin)" -js -xml minify.js.xml -clobber' Condition="'$(Configuration)' == 'Release'" />
<Exec Command='"$(Ajaxmin) -css -xml minify.css.xml -clobber' Condition="'$(Configuration)' == 'Release'" />
</Project>
The xml files minify.js.xml and minify.css.xml are used to define which resources should be merged together, minified and where to output the result.
<root>
<output path="Scripts/Mvc3Application.min.js">
<input path="Scripts/myplugin.js"/>
<input path="Scripts/viewModel.js"/>
<input path="Scripts/foobar.js"/>
</output>
</root>
Download ASP.NET MVC 3 Template
Target: .NET 4.0
I’ve been a heavy ReSharper user, fan, and addict since I first tried it back in 2007. Over the years I’ve developed the way I code leveraging the powerful productivity features of ReSharper and Visual Studio.
I present a series of my favorite Ninja tricks and workflows to inspire others to improve their skills and I encourage you to do the same, either in the comments section or elsewhere.
You can find this and other power tips with the ReSharper user tip tag
Category: Workflow
Following test-driven development I often define my unwritten classes by first using it in a unit test. I then use Create class and Create method or property to generate the code from usage. As the class gets created in the same file as the unit test I use Move to folder to put the class in the production code assembly. Namespaces and using statements are fixed automatically.
Place the marker on the class name in red and hit Alt+Enter
Place the marker on the method name in red and hit Alt+Enter
Place the marker on the class name and hit Ctrl+R, O. Then pick the folder you want the class to move to.
The foundation for all solid professional software development in my opinion is good craftsmanship practices and the most important of them is unit testing. It used to be great debate and controversy about weather unit testing was worth it or not but the fact is, the jury is back and the verdict is final. Unit testing is a core software development practice which can be ignored no longer, for any reason.
Unit testing is a relatively old practice and what has become the definition of a good unit test through decades of practice is the following:
Given this definition there are many ways to produce these unit tests that are so important, but what has proven to be the most efficient way to get them done is to iteratively write a test before you write the production code which should make the test pass. Thus, using test-driven development, not only do you get unit tests written such that you can prove that the application is working as expected, but with test-driven development you get so many other benefits. It’s really about thinking through what your application should do and designing it to be testable which inherently forces you to make it more decoupled and cohesive, two of the oldest software metrics of good design.
With a suite of unit tests in which you trust, you are much more comfortable doing can do ruthless refactoring. Without tests you can’t. Refactoring is one of the core practices of test-driven development, and it’s all about making changes to the code to keep it flexible in order to make it easier to change and maintain.
When we’re doing test-driven development properly we’re working in very short cycles of writing a little bit of test code, a little bit of production code, and then cleaning up after our selves as we go along. When you do this you want to make sure that all your old tests passes for every change you make as well as only the test case you’re working on is failing as expected. This leads to lots of overhead of clicking buttons in the IDE or pressing short cut keys over and over again. What you really want is a way to run all the tests automatically when ever anything changes. This is where continuous testing comes into play.
Continuous testing as a practice is actually what you do when you’re doing test-driven development properly, however the term has been claimed by a range of tools which was sprung out of the Ruby community. It provides tool support for automatically detecting when you save a code file and then running the entire unit test suite and report the result back to you. Consequently it somewhat changes the way you do test-driven development because you never need to think about running your tests again. You simply keep on coding, adding another test, implementing it and meanwhile the red light has lit up and switched to green again as you’ve made it pass.
It might seem like a subtle change but I’ve found that it really changes and improves the flow when I code, plus using a tool like NCrunch, as a side effect, I get so many other cool features like code coverage and pass or fail status next to every line of code (see the image at the top of the post). NCrunch takes advantage of all the cores in my machine and uses parallel execution to run the entire suite of tests every time. It optimizes the build such that only the modules that are impacted by the change are built and run first so I get immediate feedback plus the rest of the test suite is running behind the scenes for safety.
Continuous testing tools for .NET:
Disclaimer: This is my view on how software development should be practiced in a professional environment. It is my own opinion and do not represent my employer’s view in any way.
I’ve previously blogged about how we practice Continuous Integration with TeamCity at Ninetech but some time has passed and now it is time for an update.
After an upgrade to TFS2010 we started to use its build system for some of our development projects but since many of them lacked automated testing the usage didn’t really take off. To change this, an internship project was started where students from Karlstad’s university would create some way to highlight the opportunity to get immediate feedback for team members as well as stake holders and other interested at our company.
The result of the project can be seen below. It is our TFS TV placed on the wall of our developer room such that all developers, as well as any one who passes by, can see the current status of our projects. It is a WPF app which cycles through all of our TFS build configurations, gathers the latest test data, goes to our web site and fetches the photo of the latest committer, and displays it all on the 42” plasma screen.
The effect we’re after is to raise the level of awareness and usage of continuous integration and automated testing by providing immediate feedback to all teams when something fails and as well as a quick way of keeping track of a project through some of its metrics.
As seen below no one can miss if a build is failing which makes everybody who commits to a project on the screen extra careful not to commit code which is untested or brakes the build in any way.
What’s next? As we’re using a mix of source control systems (TFS, Git, Hg, SVN) and continuous integration platforms (TFS, TeamCity) the plan is to support TeamCity as well and maybe find a way to release it into the wild. We’ll se what happens.
Update! Download for Visual Studio 2012 and ReSharper 7!
Since I switched to the dark side I’ve made several tweeks and customizations to the Son of Obsidian scheme. I’m a heavy ReSharper user (i.e. addict) and ReSharper on its own extends and overrides some of the the highlighting and what not in Visual Studio, hence the original scheme looks a bit broken when turning on all the ReSharper features.
I’ve finally decided that is was time to publish my changes so if you’re into Son of Obsidian and ReSharper, this is for you:
Download Son Of Obsidian scheme for Visual Studio 2012 (NEW!)Download Son Of Obsidian scheme for Visual Studio 2010
To enable the enhanced syntax highlighting and color identifiers in ReSharper, go to the Options dialog and check both Color identifiers and Highlight color usages.
See how to change Visual Studio color scheme
I brought my son to work the other day and was suppose to show him what I do for a living. I wanted to introduce him to programing but he is only eleven years old and his native language is Swedish, unlike most programming languages.
To introduce him to the idea of programming, i.e. the way to think in terms of logic and structure, I searched for a visual programing language and found Kodu from Microsoft Research, which is made for creating games on PCs and the XBox 360.
Using Kodu I was able to introduce the basic concepts of sequence and flow of control in a very concrete way where the child with a click of a button could run the game and see the consequences of his programing.
Where as my son is only eleven this was maybe a little too early, or he simply lacked interest, however I was thinking what the next step would be? I found a couple of options.
SmallBasic has a user friendly development environment, event for children, and easy to understand guidance to get going.
Finally I thought of VB.NET with Visual Studio Express, which is kind of the way I started out myself, however, then it was Visual Basic 3 and the Internet wasn’t invented yet (well, almost).
This blog post introduces CSRepl, the C# REPL and interactive interpreter which I have founded on BitBucket. REPL stands for Read-eval-print loop and is a simple, interactive computer programming environment. It can be used to evaluate C# expressions and statements on the flight as well as creating types (classes, stucts, enums).
CSRepl can conveniently be used to quickly explore .NET Framework classes and APIs as well as third party assemblies.
Download
Download installer | Wiki | Source | Report an Issue
CSRepl is implemented as a windows console application and to use it when installed, you simply start it with the csrepl command from the command line:
C:\Program Files (x86)\CSRepl\>csrepl
CSRepl 1.0 Interactive build 1.0.4383.22797
Copyright (c) trycsharp.org. All Rights Reserved.
For help type Help
>
Support includes, but does not stop at:
Literal expressions:
> 1 + 2
3
> 2 * 4
8
> "hello, world"
"hello, world"
Semicolon is optional:
> 1 + 2;
Sequence of statements:
> var x = 1
> x
1
> x = 2
2
Collections:
> new[] {1,2,3}
[1,2,3]
> var list = new List<int> {1,2,3}
> list
> var map = new Dictionary<int, string> {{1,"foo"},{2,"bar"}}
> map
[[1, "foo"],[2, "bar"]]
Method declarations:
> int Foo() { return 1; }
> Foo()
Type declarations:
> class Foo { public string Bar() { return "Bar"; } }
> var foo = new Foo()
> foo.Bar()
"Bar"
Multi line statements:
> class Foo
> {
> public int AddOne(int v)
> return v + 1;
> }
> foo.AddOne(1)
Using statements:
> new ArrayList {1}
The type or namespace name 'ArrayList' could not be found
> using System.Collections
[1]
Formatting of complex types:
> class Foo { public string Bar { get; set; } }
> var foo = new Foo { Bar = "Hello" }
> foo
Foo { Bar = "Hello" }
> var anonymous = new { X = 1, Y = "foo" }
> anonymous
{ X = 1, Y = foo }
> var xml = new XmlDocument();
> xml.LoadXml("<foo bar=\"baz\" />")
> xml
<foo bar="baz" />
Load external assemlies:
> LoadAssembly("ICSharpCode.SharpZipLib.dll")
> using ICSharpCode.SharpZipLib.Zip
> new FastZip()
FastZip { CreateEmptyDirectories = False, Password = null,
NameTransform = ZipNameTransform { TrimPrefix = null },
EntryFactory = ZipEntryFactory {
Setting = LastWriteTime, FixedDateTime = 2012-01-01 12:36:13,
GetAttributes = -1, SetAttributes = 0, IsUnicodeText = False },
UseZip64 = Dynamic, RestoreDateTimeOnExtract = False,
RestoreAttributesOnExtract = False }
TDD Katas has become very popular in a small segment of the development community and we call our selves software craftsmen. We are passionate about software development as a craft and engage in different activities to better our selves and our peers.
My first kata cast, for instance, has been viewed close to 10k times on Vimeo since its publication. Much of the attention is of course due to Roy Osherove linking to my blog post from his TDD Kata 1 page. This time Roy initiated a sequel, meant to introduce interaction based testing using mocks and possibly stubs, and continue the teaching process of TDD and unit testing practices.
The following screen cast covers the entire kata in .NET, complete with Osherove’s three steps as well as manual UI testing at the end.
For best viewing experience I recommend watching it on Vimeo.com in HD
String Calculator TDD Kata 2 - Interactions from Rickard Nilsson on Vimeo.
The tools I use are Visual Studio, ReSharper, TestDriven.NET, Moq for mocking, and NUnit.
The code and Visual Studio solution for the finished Kata can be downloaded from GitHub:
Download source
As Osherove mentions in his instructions, this kata is not as simple as the first part, nor as simple as most katas out there. The reason is the element of interaction based unit testing involved, which is quite difficult to wrap you mind around, and it took quite a while to get the steps right. I thought I should share my path to the kata in its present form for others to learn from and comment on.
Step 1. Everytime you call Add(string) it also outputs the number result of the calculation in a new line to the terminal or console. (remember to try and do this test first!)
As I did this test first I started out pretty much as how it ended up in the cast. However, after a while I tried to take a step back and see if there were any smells in the code I had not yet discovered.
I found that I didn’t really like the mixed responsibilities that the Calculator class got when I introduced writing to the console. This could be seen as a logging feature and thus a perfect candidate to become an aspect (in AOP). I started playing around with PostSharp and ended up with the following solution which is quite clean.
[Serializable] public class OutputAttribute : OnMethodBoundaryAspect { [NonSerialized] private IContainer container;
public override void OnExit(MethodExecutionArgs args) { var console = container.Resolve<IConsole>(); console.WriteLine(args.ReturnValue.ToString()); }
[OnDeserialized] public void OnDeserialized(StreamingContext context) { container = ContainerFactory.Current; } }
Which, at most, leaves the mark of a custom attribute in the Calculator class:
public class Calculator { [Output] public int Add(string value) { ... } }
The problem with this solution is the way PostSharp works. It does all its magic as a post compilation step so everything is pretty much static. This is a problem in a testing scenario when we need to inject the mocked console in this case, hence the smelly ContainerFactory.Current stuff.
Another problem with this solution is that in part three, the console app, we need to disable or override what is outputed. This ends up becoming a static mess which did not feel right at all. If you have another view on this please leave a comment.
Step 2. Create a program (test first)that uses string calculator, which the user can invoke through the terminal/console by calling “scalc ‘1,2,3’” and will output the following line before exiting: “The result is 6”
For step 2 and 3 I thought a bit about refactoring to a UI design pattern like MVP, MVC or MVVM but finally decided to drop it, mainly because I didn’t know any framework like that for console applications. If the application grows I think this is the right way to go, but for the known requirements it’s an overkill, especially considering how small the solution is.
Step 3. Instead of exiting after the first result, the program will ask the user for“another input please” and print the result of the new user input out as well, until the user gives no input and just presses enter. in that case it will exit.
I played around a bit with SpecFlow, which has ha free form Given/When/Then specification syntax, on the later part of the kata. However, I felt that I lost velocity so I dropped it as well. Maybe, if I had some way of conducting complete acceptance testing through a real console, I would have pursued this further. It was simply too much to write, for example:
Scenario: Prompt user for another input Given a new string calculator And the user has entered: a valid input When the program has outputed The result is 1 Then the user is prompted for another input Scenario: Quit on empty input Given a new string calculator And the user is prompted for another input When the user hits enter Then the program should exit
Scenario: Prompt user for another input
Given a new string calculator
And the user has entered: a valid input
When the program has outputed The result is 1
Then the user is prompted for another input
Scenario: Quit on empty input
And the user is prompted for another input
When the user hits enter
Then the program should exit
Figure 3. SpecFlow Feature specification for the console app If you have any thoughts, comments, suggestions, or any other feedback please leave them below or ping me on twitter.