Rickard Nilsson

  • Blog
  • Archive
  • About
  • Contact

Welcome to rickardnilsson.net

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.

Follow @rickardn

Top Posts

  • Applying stylesheets dynamically with jQuery
  • My customized Son of Obsidian Visual Studio color scheme for ReSharper
  • .NET Development with Visual Studio on MacBook Pro
  • Code Kata Cast
  • ReSharper User tip #2: Refactor rename namespace
  • Combining and minifying JavaScript and CSS files with Ajax Minifier
  • Dependency injection in ASP.NET MVC with Unity IoC Container
  • C# REPL and Interactive interpreter

Categories

  • .NET
  • Agile
  • ASP.NET 2.0
  • ASP.NET 3.5
  • ASP.NET 4
  • ASP.NET MVC
  • BlogEngine.NET
  • C# 2.0
  • C# 3.0
  • C# 4.0
  • Continuous Integration
  • CSS
  • Design by Contract
  • Design Patterns
  • iPhone
  • JavaScript
  • Kata
  • Moles
  • Open source
  • Personal
  • Review
  • Social media
  • Software development
  • TDD
  • Testing
  • Umbraco
  • Unit testing
  • Unity
  • User tip
  • Web development

Five most recent posts

  • How to unit test your database code when using ServiceStack OrmLite
  • Extract class - ReSharper Ninja tricks
  • ASP.NET MVC 3 Template with built in JavaScript and CSS merging and minification
  • ReSharper Ninja tricks - Generate code from usage
  • Unit testing continuously

Tag cloud

  • agile
  • blogengine.net
  • c#
  • code kata
  • codegarden11
  • continuous integration
  • css
  • dependency injection
  • fakes
  • iso 8601
  • javascript
  • jquery
  • refactoring
  • resharper
  • resharper usertip
  • tdd
  • testing
  • umbraco
  • unit test
  • unit testing
  • visual studio

Recent comments

Extract class - ReSharper Ninja tricks

Thursday, 6 September 2012 06:46 by Rickard Nilsson

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.

Extract class

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.

Whats new in ReSharper 7

Checkout Hadi Hariri’s presentation on Extract Class at 07:28

Tags:   resharper, resharper usertip, refactoring
Categories:   User tip | Software development
Actions:  

ReSharper Ninja tricks - Generate code from usage

Tuesday, 28 August 2012 19:52 by Rickard Nilsson

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 

Generate code from usage + Move to folder

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.

 

Create class from usage
Place the marker on the class name in red and hit Alt+Enter

Create method from usage

Place the marker on the method name in red and hit Alt+Enter

Move to folder

Place the marker on the class name and hit Ctrl+R, O. Then pick the folder you want the class to move to.

Tags:   resharper, resharper usertip, code generation, refactoring, tdd, unit testing, user tip
Categories:   Software development | User tip
Actions:  

TDD Kata 2 - Interaction based testing

Tuesday, 19 July 2011 19:53 by Rickard Nilsson

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 Kata Cast

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

The code and Visual Studio solution for the finished Kata can be downloaded from GitHub:

Download source

Discussion

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.

The Kata

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;
    }
}


Figure 1. Output aspect


Which, at most, leaves the mark of a custom attribute in the Calculator class:

public class Calculator {
    [Output]
    public int Add(string value)
    { 
        ...
    }
}


Figure 2. Calculator class with Output aspect applied


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

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.

Tags:   code kata, kata cast, tdd, refactoring, agile, craftmanship
Categories:   Kata | TDD | Unit testing | Agile
Actions:  

Prime Factors Kata in C#

Wednesday, 21 July 2010 22:10 by Rickard Nilsson

Are you new to the concept of code katas? Read my previous blog post and watch me perform the String Calculator Kata.

In my never ending goal of self improvement in the techniques and tools I use I’ve been practicing a version of the Prime Factors Kata for a while.

The Prime Factors Kata, initially sparked by the infamous Uncle Bob Martin, is about finding an arbitrary number’s prime factors. In the cast I show how my TDD practice has evolved into a flavor of BDD, mainly to reduce duplication in the unit tests. I also show off the awesome power of my current toolset which includes the Visual Studio 2010 and the latest versions of ReSharper, TestDriven.NET, NUnit and NBehave.

Though my performance is not yet perfected I want to put it out there because I feel there are no C# version that can really match the Ruby version in elegance and wit. This is my attempt to show what you can do with the C# language when you know the frameworks really well.

Please leave comments and/or suggestions below or record your own kata session in response.

 

Prime Factors Kata in C# from Rickard Nilsson on Vimeo.

 

If you are new to the Prime Factors Kata, code katas in general, or TDD for that matter, you may find the steps I take unnecessary or weird. You may want to watch the annotated version in which Uncle Bob explains why each step is taken and why they are taken in that order.

  • Uncle Bob’s annotated version

Many have recorded there own versions of the Prime Factors Kata which all inspired me in the way I practice it. The cast that inspired me the most is

  • Uncle Bob’s Ruby version

there are also a few other C# casts worth watching for comparison by:

  • Uri Lavi
  • Slatner
Tags:   agile, c#, code kata, refactoring, tdd, bdd
Categories:   Agile | Kata | TDD | Unit testing
Actions:  

Code Kata Cast

Tuesday, 27 October 2009 20:28 by Rickard Nilsson

Have you ever come across the concept of a Code Kata?

For me it really took off after reading blog posts (1, 2, 3) by Unce Bob Martin and Pragmatic Programmer Dave Thomas. The concept is really simple: how can we, as programmers, better our selves and improve our techniques and proficiency in using the tools and processes in our every day work?

The suggested solution is inspired by the martial arts kata. You learn how to implement a solution to a specific problem and you practice all the moves in the exact same order over and over again. The point is that you should know the moves so well that you forget about them and focus on improving your key strokes and the use of your tool set. The never ending goal is to perform the kata with the least amount of key strokes.

The promise is that practicing these kata's often and regularly makes you a better and more productive programmer in that you are trained to act instinctively in certain reoccurring situations.

Calculator kata cast

Anyway, I've been practicing a kata based on a problem initiated by Roy Osherove and I decied to record it to get some feedback and maybe spread some knowledge on how I practice Test-driven development using ReSharper.

 

Calculator Code Kata Cast 1 from Rickard Nilsson on Vimeo.

Tags:   unit test, refactoring, tdd, code kata, resharper
Categories:   C# 3.0 | TDD | User tip | Kata | Unit testing
Actions:   | Ping backs (11)

ReSharper User tip #2: Refactor rename namespace

Tuesday, 26 August 2008 10:30 by Rickard Nilsson

Update! You can now find more user tips with the ReSharper user tip tag.

Have you ever wanted to rename a namespace but you have too many classes in the namespace that it would be an infeasible hassle changing all of them individually. Even using a tool like ReSharper to refactor the namespaces class by class is a hassle. Here is how to rename a namespace for all of its classes in a couple of key strokes using ReSharper.

Example

Mechanics

  1. Open Class View (Ctrl + Shift + C)
  2. Choose the namespace you want to rename
  3. Press Ctrl + R, R*
    or right-click on the namespace an choose Refactor > Rename
  4. Pick another name
  5. Hit Next

Update! Alternate context menu option to rename namespaces. Tested with ReSharper 5.1.

rsharper_rename_namespace

and you're done!

Please leave a comment if you found this useful.

* Visual Studio scheme

Tags:   resharper, refactoring, resharper usertip
Categories:   .NET | User tip | Software development
Actions:  

ReSharper User tip: Refactor magical strings to variable

Thursday, 31 July 2008 00:28 by Rickard Nilsson

Update! You can now find more user tips with the ReSharper user tip tag.

I've been using Jetbrains ReSharper a while now and I love it. I can't even imagine going back to plain Visual Studio anymore because there are so many things in my daily work that involves ReSharper, even simple tasks like editing source code and navigating through code and source files, let alone creating files and running unit tests.

Now I want to share a user tip I found that isn't obvious to find nor part of any context menu. It's actually a refactoring and I call it Magical strings to variable. You can use it when you end up with multiple equal string literals in a piece of code. You would probably want to gather all of the string literals in a variable and reuse it through out the code. You can use ReSharper to do it for you in a couple of key strokes.

Example

[Test]
public void ParentPresenter_Update_should_update_view() {
    var model = new User {
                        Name = "foo"
                    };
    using (mockery.Record()) {
        Expect.Call(parentView.Username = "foo");
    }
    using (mockery.Playback()) {
        IParentPresenter presenter = new ParentPresenter(parentView) {
                                Model = model
                            };
        presenter.Update();
        Assert.That(presenter.Model.Name, Is.EqualTo("foo"));
    }
}

[Test]
public void ParentPresenter_Update_should_update_view() {
    var name = "foo";
    var model = new User {
                        Name = name
                    };
    using (mockery.Record()) {
        Expect.Call(parentView.Username = name);
    }
    using (mockery.Playback()) {
        IParentPresenter presenter = 
            new ParentPresenter(parentView) {Model = model};
        presenter.Update();
        Assert.That(presenter.Model.Name, Is.EqualTo(name));
    }
}

Mechanics

1. Highlight one of the string literals

2. Press Ctrl+R, V (Ctrl+Alt+V)* to introduce a variable

3. Select to replace all occurrences (default option)

4. Pick a name for the variable

..and you're done! Please leave a comment if you find this usefull.

* Visual Studio scheme (ReSharper 2.x / IDEA scheme)

Tags:   resharper, refactoring, resharper usertip
Categories:   C# 3.0 | User tip
Actions:  
 
Disclaimer: The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.
© 2008-2011 rickardnilsson.net
Creative Commons-licens