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:  

My customized Son of Obsidian Visual Studio color scheme for ReSharper

Sunday, 20 May 2012 20:41 by Rickard Nilsson

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:

son-of-obsidian

 
Download Son Of Obsidian scheme for Visual Studio 2012 (NEW!)
Download Son Of Obsidian scheme for Visual Studio 2010

Enable enhanced syntax highlighting

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.

rsharper_settings

 

See how to change Visual Studio color scheme

Tags:   visual studio, resharper, vs2010, styles, theme, dark side
Categories:   Software development
Actions:  

ReSharper templates from the Code Kata Cast

Tuesday, 17 November 2009 15:15 by Rickard Nilsson

After I posted my Code Kata Cast I received some feedback regarding the ReSharper templates I use to speed up my coding. I decided to share them with the public (like so many before me) in hope that others may benefit from them, as I do.


rickardn-resharper-templates.zip (1,44 kb)


After you’ve downloaded the zip-file and unpacked it, open Visual Studio and the ReSharper Templates Explorer: Menu –> ReSharper –> Live Templates…

Click on Import… as the screen shot below shows, and find the file “rickardn-resharper-live-templates.xml”

resharper_import_template

 Then click the “File Templates” tab and repeat the procedure for the “rickardn-resharper-file-templates.xml” file.

 Good luck with your katas!

 

Tags:   resharper, live template, c#, tdd, unit test, code kata
Categories:   Agile | C# 3.0 | TDD
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:  

The Humble dialog v.2

Tuesday, 15 July 2008 20:41 by Rickard Nilsson
Update! Download source: TheHumbleDialog2.zip (29,96 kb)

I've been working to get my head around the Model-View-Presenter pattern and I've focused primarily on a Winforms scenario. As it turns out there are numerous sources out there on MVP, some of which are focused on Winforms, e.g. [2, 8] and some which are not focused on Winforms but highly valuable just the same, e.g. [1, 4].


Figure A. Screen mock up 

However, none of the referenced sources discusses the issue of communication between MVP triads. All of them thoroughly discusses the ins and outs when you have a single presenter talking to a single view and a single model, but nothing about communicating with other MVP sets. I've also found that other people are also struggling with this problem and how to best solve it but no really good solution has presented itself.

The problem

Well, we start with an example to formulate the problem. If we look at the example of the humble dialog [8] this only covers a single triad so we make it slightly more complicated. We have two views, a parent view and a dialog view, and each view has an associated presenter, i.e. parent presenter and dialog presenter. Now, the requirement is that when a user clicks a button on the main view the dialog should pop up modally giving the user the possibility to change a property value. The value change should then be reflected in the parent view. Sounds simple enough, right?

The problem is to implement this leveraging the MVP pattern to achieve a loosely coupled, highly cohesive, and test friendly solution. Some of the questions are; who has the responsibility to create the dialog view, who has the responsibility to show the view, what is the result from the dialog view and who should act on it.

MVP Solution

There are many different ways we can go about doing this but since I'm into Test-Driven Development I'm gonna do it test first. I also like to do UI up front so I create a Winforms project in Visual Studio and start dragging and dropping. The simplest possible screens are shown in figure A.

OK, now let's start with our first test. We want the dialog to appear when the "Edit user name" button is clicked and following MVP the view should simply pass on control to its presenter. The parent presenter should then have the dialog view popping up. This is the first test using Rhino Mocks [3]:

[Test]
public void ParentPresenter_EditUsername_should_open_a_dialog() {
    var view = mockery.DynamicMock<IParentView>();
    var dialogPresenter = mockery.CreateMock<IDialogPresenter>();
   
    using (mockery.Record()) {
        dialogPresenter.Load();
    }

    using (mockery.Playback()) {
        var presenter = new ParentPresenter(view)
                            {
                                DialogPresenter = dialogPresenter
                            };
        presenter.EditValue();
    }
}

The parent presenter should simply pass the control to the presenter of the dialog. Thus, the parent presenter has a dependency on the presenter of the dialog and the dependency is injected through a property:

var presenter = new ParentPresenter(view)
                    {
                        DialogPresenter = dialogPresenter
                    };

Now, these interfaces and classes doesn't exists so first we have to create them. But before we do I see some code that has no test, namely dialogPresenter.Load(), so let's write another test:

[Test]
public void DialogPresenter_Load_should_call_show_on_view() {
    var view = mockery.DynamicMock<IDialogView>();

    using (mockery.Record()) {
        view.Show();
    }

    using (mockery.Playback()) {
        var presenter = new DialogPresenter(view);
        presenter.Load();
    }
}

So, the presenter simply tells the view to show itself. Remember that we're talking to an interface and that the view in the test is not the real implementation. We're only driving out the behavior of the presenter at this point but we're doing it in such a way that the view implementation should be as thin a possible.

Code generation

I'm using ReSharper [7] to generate the interfaces and classes that I dreamed up in the tests.

More testing

When the initial tests are passing let's move on. The next thing that should happen is the user providing a new user name in the dialog and clicks on OK. So lets write a test for the OK event. I realize that some refactoring is also in place:

[Test]
public void DialogPresenter_ChangeName_should_change_value_and_close_dialog() {
    var model = mockery.CreateMock<User>();
    var callBack = mockery.CreateMock<Action>();
    var expectedName = "foo";

    using (mockery.Record()) {
        Expect.Call(dialogView.Username).Return(expectedName);
        dialogView.Close();
        callBack();
    }

    using (mockery.Playback()) {
        IDialogPresenter presenter = new DialogPresenter(dialogView)
                                         {
                                             Model = model
                                         };
        presenter.NameChanged += callBack;
        presenter.EditName();

        Assert.That(model.Name, Is.EqualTo(expectedName));
    }
}

Passive view and Observer synchronization

The last requirement states that the user name change should be reflected in the parent view. There are a couple of ways to do this but in this example I'm gonna go with the Observer synchronization [6] strategy because it provides a nice separation of concerns and is easy enough to mock. Note, however, that it is the presenter which acts as the Observable, not the domain object itself (User in this case). This is because I do not want to polute the domain model with event code. The previous test verified that a callback method is called whenever the name in the dialog is changed. Now, the parent presenter only has to hook up an event handler to the dialog presenter's event. Our next test shoes what should happen in the parent presenter when the event is triggered:

[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()) {
        var presenter = new ParentPresenter(parentView)
                            {
                                Model = model
                            };
        presenter.Update();
    }
}

So, the presenter explicitly tells the view what to do. The parent view is an example of a Passive view [5]. The presenter's code is included below for completeness:

// Parent Presenter
public class ParentPresenter {
    private readonly IParentView view;

    public ParentPresenter(IParentView view) {
        this.view = view;
        this.view.Presenter = this;
        Model = new User();
        DialogPresenter = new DialogPresenter(new DialogView())
                              {
                                  Model = Model
                              };
        DialogPresenter.NameChanged += Update;
    }

    public IDialogPresenter DialogPresenter { get; set; }
    public User Model { get; set; }

    public void Load() {
        view.Show();
    }

    public void EditValue() {
        DialogPresenter.Load();
    }

    public void Update() {
        view.Username = Model.Name;
    }
}

// Dialog Presenter
public class DialogPresenter : IDialogPresenter {
    public event Action NameChanged;
    private readonly IDialogView view;

    public DialogPresenter(IDialogView view) {
        this.view = view;
        this.view.Presenter = this;
    }

    public User Model { get; set; }

    public virtual void Load() {
        view.Show();
    }

    public void EditName() {
        Model.Name = view.Username;
        view.Close();

        if (NameChanged != null)
            NameChanged();
    }
}

And then the view implementation which is as minimalistic as possible:

// Parent View
public partial class ParentView : Form , IParentView {
    public ParentView() {
        InitializeComponent();
    }

    public ParentPresenter Presenter { private get; set; }

    public string Username {
        set { username.Text = value; }
    }

    void IParentView.Show() {
        Application.Run(this);
    }

    private void editValueButton_Click(object sender, EventArgs e) {
        Presenter.EditValue();
    }
}

// Dialog View
public partial class DialogView : Form , IDialogView {
    public DialogView() {
        InitializeComponent();
    }

    public IDialogPresenter Presenter { private get; set; }

    public string Username {
        get { return nameTextBox.Text; }
    }

    void IDialogView.Show() {
        ShowDialog();
    }

    void IDialogView.Close() {
        Close();
    }

    private void acceptButton_Click(object sender, EventArgs e) {
        Presenter.EditName();
    }
}

Conclusion

The way the MVP parts are separated makes a UI with allmost 100% test coverage but above all the UI logic is in a separate class which is not tied to a frame, thus enabling us to discover duplicated code and oportunities to refactor and keep the UI maintainable. I think that this is a great way of driving out a design since I start out with the client hat on and not the other way around were I first list a bunch of methods and properties on a class. IMO this kind of interaction based testing really lends itself to driving out interaction design, and tools like ReSharper really makes the developer experience pleasant and productive.

References

[1] Jean-Paul Boodhoo. Design Patterns: Model View Presenter
[2] Dan Bunea. Model View Presenter - is testing the presenter enough
[3] Oren Eini. Rhino Mocks - dynamic mocking framework
[4] Michael Feathers. The Humble Dialog Box
[5] Martin Fowler. Passive View
[6] Martin Fowler. Observer Synchronization
[7] JetBrains. ReSharper
[8] Jeremy Miller. A Simple Example of the "Humble Dialog Box"

Tags:   model-view-presenter, mvp, humble dialog box, tdd, rhino mocks, resharper
Categories:   C# 3.0 | Design Patterns | TDD
Actions:   | Ping backs (10)
 
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