That tomorrow was today

What was going to be yet another lazy day turned out to be the “tomorrow” I promised to restart my running, and yesterday affirmed to someone.

And so, on a bit gloomy day nearly a month after my last run, I ended up running almost 10K today.


The “almost” came about since my trusted Bluetooth thingy decided to ditch me midway. The experience was a bit surreal. I don’t remember the last time I ran without music and distance and timings every 5 mins and every kilometre respectively about how I’m doing.


I honestly can’t say which one is better – the silence makes me appreciate the run a lot better and be in tune with my physical self, but my mind does tend to wander more nothing to listen to; plus it’s difficult to push myself if I can’t get (hear?) the results in short durations.

So I was fairly upbeat when I started my 40 mins drive for work. Then came Apple intervention (for want of a better phrase) in the form of “I’ll meet you at midnight” as the first song of my drive.

A peppy but melancholy song, it was followed by a remix of “Tu hi meri shab hai“, another (Hindi) one in the same vein, and one which has memories of a close relative no longer with us attached to it. (auto correct nearly drove me crazy respelling the Hindi song as “Tu hi mere stab hai”)

The contemplative mood that set in led me to remember some forgotten losses and continuation of some wanderings my mind went to during the “silent” part of my run.

Aah! An emotional wringer, and the day had just about begun.


Friday frivolities – the Perspective Man strikes

Winding down hours last Friday, I was thankful to have my head down coding after days of analysis. I noticed Chris, the senior-most infrastructure guy, lurking around suspiciously long on Nick’s (the dev team leader who sits diagonally behind me) empty desk. I briefly considered challenging him but was having way too much fun coding my way to the first (jubilatory) end to end working call of a service I was working on.


A while later, my euphoria was cut short by Nick’s growl: “Who’s been messing with my desk, I can’t move my $%@*%£# mouse?” Turns out the mouse had been very firmly glued to the desk by the aforementioned Chris. Cue general hilarity while Nick and others, including me, tried to move the mouse. The mouse was firm in its Corbyn/Trump-esque refusal to yield to increasing amount of force. After a frustrating amount of time (& swearing), Nick bit the bullet and employed a careful but firm kick (yes, believe it: it was an actual boot to the mouse kick) to get it unstuck.

So far so good; comments ranged the usual spectrum and threats of retribution abound. Picking up about Chris’ dog, I proffered a waking-up-with-dog’s-head solution, which was met with the standard hilarity: till the Perspective Man stepped in.

A word about Andy: a proficient & extremely helpful senior developer, he also has deep pockets of knowledge of a wide range of non software related subject. I’m talking about a level/range from sub-atomic forces to effect of types of soils on growing orchids. Yup: it’s about areas no-one knows they (definitely) don’t care about till they hear about them. That hasn’t stopped him from providing out-of-the-blue perspectives on situations leaving gobsmacked listeners in his wake.

So the situation: retaliation against a guy, a dog and maybe a horse thrown in metaphorically.

Andy’s take: “You know, there’s not much meat in a dog’s head. With a horse’s head I could feed my family for a week probably.

That brought the house down. The earlier raucousness, dying down to the end of the working week gentle hubbub, was re-energised. So the horse’s dead, and they may be coming after you next but the family food is sorted for the week – overall a mixed day! How’s that for a fresh perspective?

As is usual, the Prospective Man was not finished – providing us with something not featured in Jamie’s kitchen:


Dinner is served!

First look: NancyFx

To get a better idea about NancyFx framework, I followed the journey in the book Instant Nancy Web Development. The code I’ve put together is available in GitHub. It showcases some aspects of the framework, like its lightweight nature, no frills setup, dependency injection and quite elegant Domain Specific Language. The framework also allows easy addition of extra capabilities like unit testing, Razor support etc using the number of Nuget packages available for it.

The site created by the code, a WIP at the moment, is a very limited Todos list manager which currently just allows adding items to the todo list and viewing them, as given in the book mentioned above.

The major deviation from the book has been implementing the data store as XML store, something I’d always wanted to give a try. For unit testing I’ve used NUnit framework instead of xUnit used in the book code samples. The unit and integration tests have been separated into different projects in the solution and mocking using the Moq framework has been added where possible.

The usage of XML store has necessitated injection of file path provider for the file to store the XML data in, set for App Data folder. The path is currently hard coded but can be easily moved to config. One file will be created for each object. For integration tests the location is changed to temp path folder. This implementation is suitable only for small projects or POCs and is unlikely to fulfil the needs of anything more demanding.

Modules are the workhorses for NancyFx and the one implemented for this project: TodosModule allows deletion, listing, adding and amending to do items by the following lines in its constructor. The binding and content negotiation used by this is automatic.


The above shows the sheer simplicity of coding using NancyFx. Sticking to the REST principles facilitates creation of modules that don’t do too much. What also helps is the access to pipelines that helps keep most cross cutting concerns out of the modules. For example, the following code in the PipelineExtensions class logs all requests and all response codes. This is in contrast to having logging calls peppered in all the methods.


Methods similar to above log unhanded exceptions and set the current user on the context being passed to the modules. These are all called in the Bootstrapper class, that overrides a default class provided by NancyFx to setup application wide concerns like logging, dependency injection, conventions etc.

This finishes a brief first look at NancyFx, more in later posts.



Coding tactics: .Net MVC

The following are some of the general guidelines I follow while coding to get a better code structure and easier test driven development. IMHO, these also make code easier to understand and debug.

  1. Do not use regions – these only hide information and are probably an indication your class is too big.
  2. Put the fields, properties and methods in alphabetical order and similarly the tests in the unit tests.
  3. Name the unit tests starting with the method name so the ones relating to same methods can be grouped together.
  4. A recommended format for naming tests is MethodName_Input_ExpectedResult. This differentiates method name, input and desired result, something other formats usually don’t. Also, all the tests for the same method are grouped together when searched for by using Resharper (Alt + \) or Visual Studio (the methods drop down on top). If the tests are put alphabetically, they will reside next to each other for the same method.
  5. Start writing unit tests with the all green (positive) condition first. This fleshes out all dependencies so the hard work is done. Now the unit test can be copied and things changed for other conditions – so work is completed quickest.
  6. Limit unit tests to assert one or two things, unless maybe if these are related to the same object.
  7. The unit tests should be guiding responsibilities of classes – Test Driven Design is a more appropriate expansion for TDD. Whenever testing a method takes too much setup and too many assertions, it’s doing too much and some if it needs to be done by another class, to be injected into the method.
  8. Do not hard code data in unit test expectations. If needed, variables should be used to check the right string/int etc is being returned. The System.Random class can be used to create random integers, doubles, or strings by using ToString() on the integer generated. The same can be extended to create random decimals if needed.
  9. Use Dependency Injection effectively – never create new instances of dependencies in methods/properties, inject them where possible.
  10. Any method which needs scrolling to read is probably too big to grok easily. An object should always tells others to do work, instead of asking for their properties and doing it.
  11. Smaller classes and methods, with less responsibilities, are usually easier to debug, especially if every class’ method validate input independently.
  12. Do not use abbreviations, name variables as per their class or utility. The class names should be per business terminology where possible, otherwise as per their utility.
  13. Private/internal methods should be avoided as their usage encourages keeping too much responsibility in a class since the method calling it is smaller. Most likely, these should be part of a new class tasked with the responsibility of what the method does. Moreover these cannot be mocked so every class calling them has to cater for what they do.
  14. ViewBag usage should be minimised/eliminated. The biggest disadvantage being no name or type safety checks, it also encourages unplanned hacks which are best avoided.
  15. Use models for all method parameters – the more specific the better. This is useful for MVC actions too. In the vast majority of cases, MVC binds them without any problem. The signature of method calls doesn’t change if the model changes and the method/action is easier to test or mock out. A whole bunch of logic can be pushed to the model which the calling class doesn’t need to know of – it can tell the model to do stuff, even passing it repositories/services etc to do work.
  16. The size of models should be an indication of complexity of the calling method/class. Too many properties/methods indicate a need to split it (and possibly the calling class/method) into multiples.
  17. At a more advanced level, the use of models allows use of custom model binders, which can add a whole level of logic before the controller is involved, like redirecting based on model properties – I’m looking at you Multi-Tenancy. The result, the controller is cleaner and more specific.
  18. Still need more reason to use models? For MVC controller actions FluentValidation validators can be attached to models and it’s integration with MVC can make sure that the validator is called automatically by the controller before the action. So the validation logic can be pulled into different classes, another responsibility off the controller! Tie this up with Dependency Injection and your custom validator can have services injected to do the validation.
  19. MVC controllers and their actions should be smallest possible. New view/condition? Create a new action or even new controller, making the calls as RESTful as possible.
  20. MVC filters provide a helpful way to take repeated pre/post action work out of controllers. Besides authorisation and exception handling, these can also allow setting of controller properties if that can be done using injected services. Coupled with well implemented Dependency Injection to provide constructor parameters, these can keep the controllers as lean as possible.
  21. Use AutoMapper to take care of converting classes to one another. For all its drawbacks, it provides a really nice way to separate concerns and take out a whole lot of distracting code responsibilities out of the controllers/service classes.
  22. When using AutoMapper, don’t utilise it’s Mapper class static methods – instead inject IMappingEngine for using the mappings and create them in profiles (classes extending AutoMapper’s Profile class) which can be automatically picked up & added on application start if DI is used well. In the profiles, use the CreateMap method available in the class instead of calling the Mapper.CreateMap static method. A good setup will also allow injecting other services into custom resolvers/converters when required for mapping.

Double figures run (finally)

Run on 05 Apr 2015

My 10 miles run on 05 Apr 15

For last Sunday’s run, recorded here, the route was simple, run 5 miles, run back!

It went so well I finished with nearly the exact pace I was aiming for:

Timing for my 05 Apr 15 run

My last long(er) run was half a decade ago – 14 Feb 2010 to be exact, when I managed to stumble across the finish of Liversedge half marathon:

Timing 2010 Liversedge half marathon

The timing, as mentioned in the picture, was after hitting the wall at around 8 miles mark. For the last 5 miles, it took all my will power to continue “running” (i.e. not walk) – fun times! Things didn’t get better after that. I hadn’t started recording my runs so… a few longer runs later I pulled my leg muscle, a week or two before the marathon I was supposed to run.

Distances runLong story short, I’ve not had a really long satisfying run after that, for whatever reason, as can be witnessed on my Runtastic statistics page, shown here.

This 10 miles run may not be noteworthy, but running that distance easily has given me more confidence than I ever imagined. Suddenly running a marathon is not so damn daunting.

As the pace was not taxing, even with just one energy gel I didn’t hit the wall thingy, but now I have the option to do so. If you’re not aware, energy gels are used to provide immediate energy to the body and stave of hitting the wall for as long as possible. I wasn’t aware of these when I ran at Liversedge, after all I’d run 8 miles without any problem – what could possibly go wrong!

I tried out faster paces in the gym yesterday – till 4 mins/km for a short while. It does seem I can handle a bit more this Sunday, when I run the Sheffield half marathon – hopefully a better performance to talk about.

Visual Studio project templates: a (possible) boon for micro services

During my talk on micro services at Leeds Sharp recently, it dawned on me that Visual Studio project templates are not something very well known. So here’s a quick primer on them, which can be useful for a large number of similar projects – a usual requirement for micro services. For our implementation of micro service we went down the route of using shared libraries to control their structure and make them easier to setup. This needed some custom code e.g. base repository for Entity Framework classes, wrapper for API calls etc; which was repeated for every micro service – hence a need for project templates.

Any Visual Studio project can be converted to a template by clicking File –> Export Template… This will get a pop up like the one shown below:

Project Template Wizard Start

Micro Services Project

The areas outlined in red are customisations in the above sample micro service project that are likely to be repeated in any new micro service. This includes a line that needs to be added to the NinjectWebCommon.cs file in Ninject MVC to make it work with a Web API project, the kind of project we used for micro services. These and any other customisations, including any Nuget packages etc will be included in the project template created. On clicking next we get to the final screen:

Project template wizard

This gives us the option of adding icon & preview image and some other details. The output location, outlined in red, is where Visual Studio looks for any such templates to show when getting us the new projects wizard. Click Finish and we are done. So the next time a new project is required, the new template (with the chosen icon) is visible:

Project template in action

Now we click OK after putting the name and location of our new micro service and we get the new project with the required custom items:

Micro Service Project template implemented

That’s about it, there’s the option to have multiple projects in a template – more like a solution template, but it’s not possible via a wizard and was too much effort for what we needed. A bit of googling will set you on the road if you need something along those line e.g. multiple custom projects per solution.

So there you have it, a way to ease initiation/propagation of something like micro services. There is the obvious pain of having to update all the previous projects for things missed out or implemented incorrectly, but that’s just something waiting to be learnt with or without templates.

Resharper Templates – supercharge your coding

Resharper_AltInsertResharper can help with a lot of repetitive tasks which can take a bit of time everyday. For example, the templates provided by Resharper are quickly available by using Alt+Insert when a project/folder/class are selected in the Solution Explorer, an example shown on the right. This will give you options as per the item selected on the solution explorer. In the example given here, the entries for “MS Test class” and “NUnit Test class” are custom file templates, which will not be available out of the box. Their creation is explained below.

The options provided here are the Resharper templates which can be edited by selecting the Resharper –> Templates Explorer… menu. This gives the Templates Explorer screen where the Live, Surround and File Templates can be selected, as shown below. The New/Edit Template Icon can be used to create/edit the respective type of template.


To add standard repeated items like copyright to a class/enum, click on File Templates sub-tab in the Templates Explorer tab, select C# in the Scopes column on the left, and double click the Class/Enum item, which should be at the top of the ‘In quicklist’ items on the right.

This should open up the edit template tab where anything that’s needed for all class definitions can be added. So if the copyright is added as shown, it will come up for each class created and would replace the class name where the $CLASS$ item has been added.



The $ enclosed words are parsed as macros by Resharper and can be selected by clicking the link for the respective macro shown on the right hand side of the edit template screen under Parameters sub-section, as in the picture above. Clicking on the link brings up the “Choose Macro” dialog box shown to the right.

The above process will have to be carried out for any other file templates e.g. enum to get the same copyright etc.

Live templates are templates available in the files and are used by typing their shortcut and pressing the tab key. This will print out the template with ‘hotspot’ (the place to type code) at the first of the macro location. The other locations can be accessed using the tab key.

To create a new live template, like for NUnit test class, select Live Templates tab in the Templates Explorer and click on the icon for New Template shown before. Here the Class template can be copied over and alterations made as needed for a NUnit test class. The macros will have to be selected under the Parameters sub-section above. The resulting dialog ‘Choose Macro’ dialog box is shown.

The $END$ is a Resharper macro where the cursor is placed after all the editable parts of the template are filled one by one by using the Tab key. This allows continuing the flow of typing while filling in a template.


Creating a template as explained above will create a new template as named under the ‘Not in quicklist’ section on the right when Templates Explorer is opened and C# selected. To show this template in the quicklist drag the template into the ‘In quicklist’ section. This will show the template when Alt+Insert is clicked after selecting an artefact in Solution Explorer.


Sharing the templates: To share the templates, select Resharper –> Manage Options… and click on Import/Export Settings –> ‘Export to File’ option highlighted on the right.

Then the relevant settings to export can be highlighted, select OK and provide an appropriate name for the file to share.

To import the settings select the ‘Import from File’ option from Resharper –> Manage Options… –> Import/Export Settings and choose the file required.

This will bring the appropriate templates in the C# section but only in ‘Not in quicklist’ section in the Templates Explorer. To see them on pressing Alt+Enter at the right location, drag the template into the ‘In quicklist’ section from Resharper –> Templates Explorer –> File Templates –> C#.