Razor View Interfaces

By using interfaces rather than classes for Razor models you can decouple them and make them more flexible.

Atomic Design

After reading Brad Frost’s awesome blog post on atomic design I got to thinking how a similar approach could be taken with Razor views.

Here is a very brief introduction to some concepts from Atomic Design.

Atomic Design is based around creating design systems from reusable and composable parts. These are split in to five sections.

Atoms

Atoms are the smallest parts of the system. They can include the styles of a button or heading.

Molecules

When you start to gather several Atoms together you end up with a Molecule. An example would be a site search form. Consisting of an input atom, a label atom and a button atom. This molecule can then be used in different places on the site.

Organisms

Organisms are made by bringing together molecules to form parts of a UI. For example a navigation molecule and a site search molecule might make up a site’s header.

Templates

A template is the framework for a page and how it will look when the organisms are arranged.

Pages

Once the template is populated with final content the page is then complete.

I found this concept of breaking down designs brilliant and it really reminded me of the Don’t Repeat Yourself rule in development.

Razor views

I started thinking how the principles of Atomic Design could be applied to Razor views. After some experimenting I realised that you could use an interface as the model for a strongly typed view. This sounds like a small change but it was news to me and opened up several new possibilities.

Reusable Partials

By setting the model for a partial view to be an interface rather than a class they can be more reusable.

Partial view;

@model ViewInterfaces.Interfaces.ICanRenderTitleSection

<div>
    <h1>@Model.Title</h1>
    <h3>@Model.SubTitle</h3>
</div>

This partial then can be used by any model that implements that interface.

Calling view;

@model ViewInterfaces.Models.HomeViewModel

@{
    ViewBag.Title = "Home Page";
}

@Html.Partial("/Views/Partials/_TitleSection.cshtml", Model)

Since the main view model is implementing all of the small interfaces required for the small partials, the partials are easily composable. As with Atomic Design the partials can reflect the organisms, molecules and atoms.

Interface;

namespace ViewInterfaces.Interfaces
{
    public interface ICanRenderTitleSection
    {
        string Title { get; set; }
        string SubTitle { get; set; }
    }
}

Small Interfaces

It is better to have your main view model to implement many small interfaces rather than one large one to help your model will be more flexible.

By following the Interface Segregation principle from the SOLID principles you are giving clear instructions on what partials the model can be used for and showing clear intent.

I’ve also found that it can help when it comes to using the model in the partial. Any properties on the view model that aren’t needed for that partial won’t be accessible due to using the interface.

Example

You can check out my MVC example on GitHub

Visual Studio Code File Icons

It’s the little things in life that make me happy and the new file icons available for Visual Studio Code make me very happy.

The new icons

For the August Visual Studio Code release there is now the option to show file and folder icons.

This may sound like just a small visual tweak but I’ve found it to be really useful in finding files I need faster.

visual studio code file icons
An example of some of the new icons

How to enable

Enabling the icons is easy and the update comes with two icon sets.

To enable just go to File > Preferences > File Icon Theme and select one.

how to enable the new icons
How to enable the new icons

More icons!

If you feel the need for more icons, there are already more icon sets available in the marketplace

Cucumber Style Tests Debate

Recently I had the opportunity to take part in a debate around Cucumber style tests. Luckily I was arguing for Cucumber tests as I’m actually quite a big fan of them.

What is Cucumber?

A Cucumber test follows the Given, When, Then style. For example;

Given there is a name field
When I enter a number
Then an error message is displayed

Cucumber tests are a very useful way of running automated tests, especially user based acceptance tests. However they are much more than that.

Check out cucumber.io to get a much more detailed explanation.

My points for Cucumber

Single source of truth

They provide a single source of truth of the software being created. Creating a single set of requirements/tests that can follow the software through the entire development life cycle.

Living documentation

Living documentation is another benefit that comes from using Cucumber tests. If the requirements change, you will then have to change the software. Since you will have breaking tests you are forced to keep them (and you documentation) up to date.

Avoiding regression

Since these tests can be automated and be part of a build pipeline, rework can be avoided when new features are added.

Collaboration

This I think is probably one of the main benefits of this style of test. Getting the correct Given, When, and Then isn’t easy. However, whenever I have seen Cucumber used, it has always been a great conversation starter. It provides a common language for technical and non-technical to come together and focus on the behavior of the software.

Some well made points against Cucumber

So this was a debate and did have some good arguments againt the use of Cucumber tests.

It’s another tool we need to learn

Yes, it is another tool that people would need to learn. However if you can get it part of your workflow, the benefits should outweigh that effort. Although I do agree that you don’t need Cucumber to get the benefits. If you can get the benefits using your current tooling then why would you add another layer of complexity. But I have found that Cucumber is a great way to start realising those benefits.

They are brittle

Yes, Cucumber can tests can become extremely brittle. Especially if they are tightly coupled to a UI. However I feel that can be said about a lot of code. Tests should be treated like the code that it is. The same care will need to be taken when writing the tests as any code would need, such as following the 4 simple rules of code and refactoring techniques.

The debate

Here are my great slides from the debate;

And here is the debate itself;

And the following discussions;

TL;DR

Cucumber tests can be very useful and are more than just automated tests. However, as with many tools, they are not a silver bullet. They need to be thought about carefully and weigh up are the advantages greater than the cost.

Planet proto solution

Continuing to work through the awesome nodeschool.io tutorials I decided I needed to know more about the javscript object model, so here are my solutions to the Planet Proto workshop.

This was a really useful set of tutorials, it felt like it filled in a big gap in my javscript knowledge.

Planet proto lessons
The lessons available in Planet Proto.

Each lesson in this tutorial comes with a handy boilerplate file that explains what is required and you need to fill in the results in the test assertions.

Simple Objects

Lesson one explains the easiest way to create an object in javascript; using object literals.

// -> Create an object called 'robot' using an object literal
// -> robot should have a property 'smart' with value true
var robot =  {
    smart: true
}

// -> Claim the result robot.smart
claim(robot.smart, true);

// ------------------------------------------------
// Common JS exports for verification, don't modify
module.exports = {
    robot: robot
}

Proto

Lesson two goes on to explain about the __proto__ object. While usually supported, its behaviour has only been standardised in ECMAScript 6 as a legacy feature and changing an objects prototype is a very slow operation. So while its not advised to use, its good place to start learning about the object model.

One object can be set as the prototype of another. This allows for the properties of the prototype to be available on the parent object.

You can check the prototype of an object with the .isPrototypeOf() function which returns true/false.

/* global claim */
// -> Create a machine object
//    with a property motors = 4
var machine = {
    motors: 4
}

// -> Create a robot object
//    with a property friendly = true
var robot = {
    friendly: true
}

// -> Create a robby object
var robby ={}

// -> Make machine the prototype of robot
robot.__proto__ = machine;

// -> Make robot the prototype of robby
robby.__proto__ = robot;

// -> What is `robby.motors`?
claim(robby.motors, 4);

// -> What is `robby.friendly`?
claim(robby.friendly, true);


// ------------------------------------------------
// Common JS exports for verification, don't modify
module.exports = {
    machine: machine,
    robot:   robot,
    robby:   robby
}

Dynamic Lookups

Properties can be added to the prototype at any time and those properties will be available on the parent object.

// -> Let's define three objects: 'machine' 'vehicle' and 'robot'
var machine = {}
var vehicle = {}
var robot = {}

// -> Make machine the prototype of vehicle
// -> Make machine the prototype of robot
vehicle.__proto__ = machine;
robot.__proto__ = machine;

// -> What is `vehicle.motors`?
claim(vehicle.motors, undefined);

// -> What is `robot.motors`?
claim(robot.motors, undefined);

// -> Define a 'motors' property on machine, set this to 4
machine.motors = 4;

// -> What is `vehicle.motors` now?
claim(vehicle.motors, 4);

// -> What is `robot.motors`?
claim(robot.motors, 4);


// ------------------------------------------------
// Common JS exports for verification, don't modify
module.exports = {
    machine: machine,
    vehicle: vehicle,
    robot:   robot
}

Property assignments

Properties that are updated on the parent object are assigned to the object and don’t update the prototype.

// -> Define three objects: 'machine', 'robot' and 'vehicle'
//    In the definition of machine add a property 'motors' set to null.
var machine = {
    motors: null
}
var robot = {}
var vehicle = {}

// -> Let's make machine the prototype of robot and vehicle
vehicle.__proto__ = machine;
robot.__proto__ = machine;

// -> What are `machine.motors`, `robot.motors` and `vehicle.motors`?
claim(machine.motors, null);
claim(robot.motors, null);
claim(vehicle.motors, null);

// -> Set `robot.motors` to 4 by direct assignment
robot.motors = 4

// -> What are `machine.motors`, `robot.motors` and `vehicle.motors` now?
claim(machine.motors, null);
claim(robot.motors, 4);
claim(vehicle.motors, null);


// ------------------------------------------------
// Common JS exports for verification, don't modify
module.exports = {
    machine:  machine,
    vehicle:  vehicle,
    robot:    robot
}

Arrays and Objects

Strangely arrays and objects don’t behave in the same way. If you update an array or object property on a parent object they are updated on the prototype.

// -> Create three objects: 'machine', 'robot' and 'vehicle'
// -> In the definition of machine set a property 'parts', set it to an 
//    empty array `[]`
// -> In the definition of machine set a property 'capabilities', set it to 
//    an empty object `{}`
var machine = {
    parts: [],
    capabilities: {}
}
var robot = {}
var vehicle = {}

// -> Let's set the prototype of both robot and vehicle to machine
robot.__proto__ = machine;
vehicle.__proto__ = machine;

// -> What is `robot.parts`?
claim(robot.parts, []);

// -> What is `vehicle.parts`?
claim(vehicle.parts, []);

// -> What is `robot.capabilities`?
claim(robot.capabilities, {});

// -> What is `vehicle.capabilities`?
claim(vehicle.capabilities, {});

// -> Let's add a 'core' part to robot
robot.parts.push('core');

// -> What is `robot.parts` now?
claim(robot.parts, ['core']);

// -> What is `vehicle.parts` now?
claim(vehicle.parts, ['core']);

// -> Let's set an ability to vehicle
vehicle.capabilities.fly = true;

// -> What is `robot.capabilities` now?
claim(robot.capabilities, {fly:true});

// -> What is `vehicle.capabilities` now?
claim(vehicle.capabilities, {fly:true});


// ------------------------------------------------
// Common JS exports for verification, don't modify
module.exports = {
    machine: machine,
    vehicle:    vehicle,
    robot:    robot
}

Object Create

So by setting __proto__ directly it has easier to see how it behaves, however it is not yet fully supported. A more supported method is to pass the prototype to Object.create().

// -> Let's create an object called 'machine'
var machine = {}

// -> Use Object.create to create another object called 'robot' with 'machine' 
//    set as the prototype
var robot = Object.create(machine)

// -> Use Object.create to create another object called 'robby' with 'robot' 
//    as the prototype
var robby = Object.create(robot)

// -> What is the result of `machine.isPrototypeOf(robby)`?
claim(machine.isPrototypeOf(robby), true);

// -> What is the result of `robot.isPrototypeOf(robby)`?
claim(robot.isPrototypeOf(robby), true);

// -> Which object is the direct prototype of robby?
claim.same(Object.getPrototypeOf(robby), robot);


// ------------------------------------------------
// Common JS exports for verification, don't modify
module.exports = {
    machine:  machine,
    robot:    robot,
    robby:    robby
}

Dot new

A nice way of using Object.create() is to create a function on an object called new(). When new() is called return Object.create(this).

// -> Define an object called 'Robot'
// -> Define a method called 'new' in Robot
// -> When Robot.new is called it should return a new object with Robot as its prototype 
//    e.g. var robby = Robot.new();
//    Robot should be the prototype of robby

var Robot = {}

Robot.new = function(){
    return Object.create(this)
}

var robby = Robot.new()


// ------------------------------------------------
// Common JS exports for verification, don't modify
module.exports = {
    Robot: Robot
}

Constructor functions

A popular way of creating prototype chains is to use constructor functions. This works by creating a function that has statements like this.{propertyName} = x. Then you call the function with new. The return object is linked to the function by its prototype.

// -> Define a 'Robot' constructor function
// -> Inside the Robot constructor assign a property 'motors' on 'this',
//    set motors to 2
// -> Create an instance of Robot called 'robby'

function Robot(){
    this.motors = 2
}

var robby = new Robot()

// -> What is the result of `(robby instanceof Robot)`?
claim((robby instanceof Robot), true);

// -> What is `robby.motors`?
claim(robby.motors, 2);


// ------------------------------------------------
// Common JS exports for verification, don't modify
module.exports = {
    Robot:  Robot,
    robby:  robby
}

Implicit This

When a constructor function is called with “new”, Javascript has an implicit reference to the new object being created with the “this” keyword. So it’s important to remember the “new”. To help remember to use “new” it is common to capitalise the first letter of the constructor function.

With my background in C# this is the method of creating instances of objects that is the most natural to me.

// -> Define two constructor functions: 'Robot' and 'Vehicle'
// -> When called with 'new', the Robot constructor function should return 
//    the implicit 'this'
// -> When called with 'new', the Vehicle constructor function should return 
//    an object of your own making, not the implicit 'this'.

function Robot(){
    
}

function Vehicle(){
    return {}
}


// ------------------------------------------------
// Common JS exports for verification, don't modify
module.exports = {
    Robot:    Robot,
    Vehicle:  Vehicle
}

The function prototype

So this one took a bit to get my head around.

Every function in Javascript has a property called prototype. This is not the same as __proto__. It is the object that an instance created by the function will have as its own __proto__.

So any property added to functionName.prototype will be available to all instances created by that function.

// -> Define a 'Robot' function constructor
// -> Create two instances of Robot: 'robby' and 'cranky'
// -> Both robby and cranky should respond to 'parts' and 'capabilities', these 
//    should be empty arrays at first

function Robot(){
    this.parts = []
}

Robot.prototype.capabilities = []

var robby = new Robot()
var cranky = new Robot()



// -> Claim the result of robby.parts
claim(robby.parts, []);
// -> Claim the result of cranky.parts
claim(cranky.parts, []);
// -> Claim the result of robby.capabilities
claim(robby.capabilities, []);
// -> Claim the result of cranky.capabilities
claim(cranky.capabilities, []);

// -> Add 'core' to robby.parts, cranky.parts should still be empty
// -> Add 'fly' to robby.capabilities, after doing that cranky.capabilities must 
//    also have 'fly' without adding to it directly, so this property has to be 
//    shared

robby.parts.push('core')
robby.capabilities.push('fly')

// -> Claim the result of robby.parts
claim(robby.parts, ['core']);
// -> Claim the result of cranky.parts
claim(cranky.parts, []);
// -> Claim the result of robby.capabilities
claim(robby.capabilities, ['fly']);
// -> Claim the result of cranky.capabilities
claim(cranky.capabilities, ['fly']);


// ------------------------------------------------
// Common JS exports for verification, don't modify
module.exports = {
    Robot:  Robot,
    robby:  robby,
    cranky: cranky
}

node-windows

Using node-windows was the first time I’ve tried to setup a Node application as a Windows service and I couldn’t believe how simple it was.

I needed to serve up a static html file, so installing and configuring IIS seemed like overkill. So for in order to get the file served as quickly as possible I made a very basic express.js app.

Setting up the express app

To initially set up the app and create the package.json I ran the below command and taking all of the defaults apart fron the entry point which I set to app.js

npm init

Once the package.json file is in place from running npm init, then I installed express itself.

npm install express --save

The app.js file itself was extremely basic. Listen on a port and just return the html file.

var express = require('express');
var app = express();
var path    = require("path");

app.get('/', function (req, res) {
res.sendFile(path.join(__dirname+'/index.html'));
});

app.listen(3000, function () {
console.log('Example app listening on port 3000!');
});

To make the app accessible I just needed to add a new firewall rule in for the port it was listening on.

Adding the app as a Windows service

Initially I ran the express app from the command line with

node app.js

Which worked great initially, however, unsurprisingly it wasn’t long until someone else logged on to the server and thought “I wonder why this command prompt is open, lets close it”.

I was told about node-windows and thought I’d give it a go.

First job was to install node-windows globally

npm install -g node-windows

Then at my project root

npm link node-windows

Finally, I ran the below script taken from the docs with updating the path to app.js

var Service = require('node-windows').Service;

// Create a new service object 
var svc = new Service({
    name:'Hello World',
    description: 'The nodejs.org example web server.',
    script: 'C:\\MyApp\\app.js'
});

// Listen for the "install" event, which indicates the 
// process is available as a service. 
svc.on('install',function(){
    svc.start();
});

svc.install();

and that was it! The express app was then accessible without having to run the app via the command line.

So this was just the basic setup of node-windows but it does have other features that are pretty cool. These include uninstalling services, killing processes by their PID and a clever wrapper around the node app for handling if the app crashes and needs restarting.