Taming dictionaries to strongly-typed interfaces with Castle DictionaryAdapter

So Castle is one of those projects that seems to sit behind a lot of technologies (Moq, NHibernate) but which maybe people don’t look at directly. Which is a shame, because it’s pretty special. Here’s one block of code with a really interesting effect;

// Let's define an interface...

public interface ICustomerProfile
{
    string UserName { get; set; }
    int NumberOfTimesSiteAccessed { get; set; }
}

// now let's have Castle give us a 
// strongly-typed wrapper onto a 
// simple dictionary object;
class Program
{
    static void Main(string[] args)
    {
        var dictionary = new Dictionary<string, object>();
        var factory = new Castle.Components.DictionaryAdapter
            .DictionaryAdapterFactory(); 
        ICustomerProfile proxy = factory.GetAdapter<ICustomerProfile>(dictionary);
        proxy.UserName = "John Appleseed";
        Console.WriteLine(proxy.UserName);
        Console.WriteLine(proxy.NumberOfTimesSiteAccessed);
    }
}

This uses Castle’s DictionaryAdapter to create a strongly-typed interface to a dictionary. Castle is implementing ICustomerProfile for us, and intercepting any calls, translating them into calls to a dictionary. Those two lines in red do all the interesting work.

What we’ve done is taken something that feels dynamically typed and ‘frameworky’ (the dictionary) and make it a proper, strongly-typed domain object again.

As the docs point out, this is really useful when dealing with ASP.NET, where there are all kinds of dictionaries, like ViewState, Session state, and HttpRequest.Form contents flying about.

You could do this by writing your own adapter class, get and set accessors for each property, but why bother?

Advertisements

T4MVC for removing magic strings from Razor views.

If you haven’t used T4MVC before, it’s a very nice NuGet package that helps remove some of the ‘magic strings’ from MVC views. Normally, you would create a link to a controller action in razor like this;

@Html.ActionLink("Link Text",
    "Development", "ChangeConnectionString", new { connectionString= "DataSource=foo" })

Which assumes there is a DevelopmentController with an action method like;

ActionResult ChangeConnectionString(string connectionString) 
{
 ...
}

T4MVC is a T4 (text templating) file which scans all your controllers and makes strongly-typed methods for specifying the controlller, actions, and parameters, which you use like this;

@Html.ActionLink("Link Text", 
    MVC.Development.ChangeConnectionString("DataSource=foo"))

Notice how we’ve removed the magic strings for the controller name and method name, and made the parameters more compact. If an action method name changes, or the parameter signature changes, T4MVC’s methods now stop compiling, and you get compile-time errors in your views, rather than runtime errors.

T4MVC needs to be run whenever a controller is added or an action method signature changes. This can be easy to forget, so I recommend the AutoT4MVC extension.

NCrunch; background running of unit tests in Visual Studio.

I’ve recently started trying NCrunch. It’s commercial software with a 60-day trial which helps you make sure you are getting good code coverage and you’re not breaking tests.

What it does is fairly straightforward. It’s a test runner, like VS’s Test Explorer, except that it automatically builds your tests and runs them, optionally on many threads, in the background. It then reports on the health of those tests, so if you start breaking tests, you know about it quickly.

It also shows you, in the VS document editor, which lines are covered by unit tests. So you can see where you need to write more tests.

There’s a nice writeup on Olav Nybø‘s blog.

It reminded me of using jasmine-node, which is also a really nice way to automatically run your tests and have them re-run when a file is saved, although that works for JavaScript tests.

 

 

Poor Man’s T-SQL Formatter Addin: Useful for devs!

A bit of love for the Poor Man’s T-SQL Formatter addin to MSSQL Management Studio. Allows you to reformat any query window in Management Studio to apply a consistent format. Really nice ‘starter for ten’, letting you clean up a batch of SQL after a hacking session. Why not look just that little bit more professional, for free?

insert into dbo.ItemBase ([Id],[Name] ,[Modified] ,[Created] ,[EntityStatus]) 
select [Id] ,[Name] ,[Modified] ,[Created] ,[EntityStatus]
from dbo.MyTable

to this;

INSERT INTO dbo.ItemBase (
[Id]
,[Name]
,[Modified]
,[Created]
,[EntityStatus]
)
SELECT [Id]
,[Name]
,[Modified]
,[Created]
,[EntityStatus]
FROM dbo.MyTable

NB: I’ve not tried the Visual Studio addin, just the MSSQL one. I just thought I’d keep things a bit cleaner. It might work brilliantly, but I’ve not tried it.

Pluralsight – a short review

Down at DevWeek 2013, I was given a card for one month on Pluralsight; they do video courses for all manner of programming and technology courses. 

I activated it this weekend, and drank from the firehose. I’ve gone through several courses in a really short time. In that time, I’ve also been able to cut some working code in the new tech, and shore up some existing knowledge. Here’s what I’ve figured out;

  • Sometimes, video is much faster to absorb than books. If you learn that way, give them a look.
  • The courses are comprehensive. By that I mean that I feel more ‘armed’ than than the ‘thirty minutes of tutorials and short how-to videos’ approach to learning. In that, they are like a book.
  • They seem to have courses for every buzzword; 3 on node.js, 5 on nosql, 2 on OData, 16 on Azure. And loads on the staples; 33 on SQL Server, 28 on JavaScript,  12 on iOS, 38 on ASP.NET. And 73 on SharePoint (shudder. It must need a lot of explaining…)

I’ve stuck in my credit card details because I think I’m going to benefit greatly. 

I know this is a terribly positive review. I’m not affiliated in any way. 🙂

LiveReload; tightening the loop of web development

A lovely little discovery for me recently is LiveReload. It’s an file watcher app, and associated browser plugins, that will look over your HTML, CSS, and JavaScript files. When they change, the page you are developing reloads. 

What that means is that in a two-monitor system,  you can have your text editor in one window, and the browser in the other, and a simple save in the text editor reloads the page in the browser;

Image

This helps development, especially things like developing layouts or d3 visualizations because as soon as you save, you see the effects of your change. This means you don’t need to grab the mouse, select the browser, and refresh the page; you just keep on typing.

This also works really nicely when you’re looking at a jasmine spec runner; you can hack on your JavaScript without having to go to the browser at all; the browser now becomes a kind of status monitor, constantly telling you about the health of your code. 

Basic operation;

1. Install the chrome plugin;

Image

2. Install LiveReload. It looks like this;

Image

3) Use the ‘+ add’ button to start monitoring a folder

4) Copy the code snippet in the box marked ‘2’ above into the <head> tag of your web page.

5) Load the page in chrome, and click the LiveReload button that now sits at the right-hand-side of the addressbar.

That’s it! LiveReload will now refresh your pages for you as you save.