On Procrastination

Writing about procrastination seems like a good a way as any to pick up after a 7 year gap.

A lecture from Dr. Tim Pychyl was posted to Reddit recently, in which he discusses procrastination, its causes, and some strategies for change.

The lecture highlights some of the ways in which we deceive ourselves, mechanisms we use to give our brains those little dopamine hits to feel good now (writing to-do lists, distracting ourselves with something unrelated), whilst avoiding what we should really be doing (finishing that blog post).

Dealing with Procrastination

The main take away from the lecture for me was a very straight forward mechanism for dealing with it:

In situation X, I will do behaviour Y, to achieve subgoal Z.

By defining a task in terms a of a concrete start time, a well defined achievable task, and a reminder of why you are doing it in the first place, you remove a lot of the thinking involved in getting started in the first place.

Simply: The When, the What and the Why.

Agile

I like that this isn't a million miles away from what we try to achieve as good agile practitioners; planning work as a series of small, well defined increments:

As a <person in a situation>
I want <a defined behaviour>
So that <sub-goal is achieved>

This is also not a million miles away from defining acceptance criteria in the Given / When / Then format.

Original Video

Compact CSS And Javascript With MVC And SquishIt

SquishIt

SquishIt is a library for ASP .Net implemented by Justin Etheredge of CodeThinked that will take several separate javascript or CSS files and produce a single compacted file as ouput which is then returned to the client, rather than the several individual source files.

This is great as it saves bandwidth by both reducing the number of requests that need to be made, as well as compacting the files by removing excess white space and comments.

Less

One of the additional benefits of using SquishIt is built in support for dotLess. dotLess is a .Net port of the CSS extension Less, which was originally implemented for Ruby. This adds a number of neat features such as variables and mixins, which makes it easier to create well structured and maintainable CSS.

@brand_color: #4D926F;

#header {
h2 {
color: @brand_color;
}
}

Compacted

To make use of Squishit, all we need to do is change how we reference our CSS and javascript files. Instead of including tags in our <head> element, we make a call to Bundle.Css() or Bundle.Javascript() instead:

@MvcHtmlString.Create(Bundle.Css()
.Add("~/Content/style.less")
.Add("~/Content/jq.datatable.css")
.Add("~/Content/jquery-ui-1.8.14.custom.css")
.Add("~/Content/colorbox.css")
.Render("~/Content/Site.min.css"))

@MvcHtmlString.Create(Bundle.JavaScript()
.Add("~/scripts/jquery-1.6.2.min.js")
.Add("~/scripts/jquery.dataTables.min.js")
.Add("~/scripts/jquery-ui-1.8.14.custom.min.js")
.Add("~/scripts/jquery.colorbox-min.js")
.Render("~/Content/Site.min.js"))

In release mode this will combine the separate files into a single file with the specified name, as well as performing minification.

When running with debug on in your web.config (<compilation debug="true">), the files are not combined by default. You can alter this behaviour by chaining a call to ForceRelease() before the call to Render(). Likewise, a call to ForceDebug() can be made to keep everything seperate when doing a release build with debug off.

Using Multiple Layouts

It's not uncommon to have multiple layouts when developing a production web site with MVC3. There is a consideration to be made here, as if you wish to include different CSS / Javascript depending on the current layout, if you use the same output filenames for each layout, it could cause SquishIt to re-minify the files if going from a layout that uses one set of files, to one that uses a different set.

There are two ways round this:
1) Include all CSS and all Javascript for the entire site when bundling. You could extract this to a partial view that is included by each layout so that it only needs updating in one place.
2) Change the name of the output files depending on the view. This will ensure that re-minification only occurs when there are actual changes to the source files.

Permissions

One thing to note is that when using a release build, SquishIt may require write access to the directory containing the target files, which in our case is ~/Content. This is because should any of the source files be updated, SquishIt will want to output a new 'squished' version.

Summary

SquishIt takes all of your javascript, all or your CSS and squishes them into the smallest size it can. This is great in a world of heavily interactive web sites where the weight of scripts and CSS can add significant time to the loading of a page.

Dependancy Injection With RemObjects SDK

RemObjects SDK is a comprehensive remoting framework which I've used in a number of projects over the years. It has support for a number of platforms, including .Net and Delphi among others, and provides a comprehensive feature set from encryption to load balancing.

Injection Points

There are a few points we could use to do dependancy injection when using RemObjects; I have highlighted a couple below

Overriding Activate

Each service implemented in RemObjects inherits from RemObjects.SDK.Server.Service which has a method called Activate. This is called before a call is pushed through a service in order to carry out any initialization required.
using System.Collections.Generic;

namespace TestService
{
using System;
using RemObjects.SDK;
using RemObjects.SDK.Types;
using RemObjects.SDK.Server;
using RemObjects.SDK.Server.ClassFactories;

[RemObjects.SDK.Server.ClassFactories.StandardClassFactory()]
[RemObjects.SDK.Server.Service(Name = "TestService", InvokerClass = typeof(TestService_Invoker), ActivatorClass = typeof(TestService_Activator))]
public class TestService : RemObjects.SDK.Server.Service, ITestService
{
private System.ComponentModel.Container components = null;
private ILogger logger;
public PingService() :
base()
{
this.InitializeComponent();
}
private void InitializeComponent()
{
}
protected override void Dispose(bool aDisposing)
{
if (aDisposing)
{
if ((this.components != null))
{
this.components.Dispose();
}
}
base.Dispose(aDisposing);
}
public override void Activate(Guid aClientID)
{
base.Activate(aClientID);
//inject here...
logger = App.Get();
}
public override void Deactivate(Guid aClientID)
{
base.Deactivate(aClientID);
//deinit here...
}
public virtual bool DoSomething(string msg)
{
try
{
//service implementation
}
catch (Exception ex)
{
logger.Log(LogLevel.ERROR, "Error in DoSomething: " + ex.Message);
return false;
}
}
}
}

Service Activator

In order to instantiate a service, RemObjects uses generated activator classes. This is the perfect point at which to inject whatever you need to as this is where the instance of the service is first created.
[RemObjects.SDK.Activator()]
[System.Reflection.ObfuscationAttribute(Exclude = true, ApplyToMembers = false)]
public class TestService_Activator : RemObjects.SDK.Server.ServiceActivator
{
public TestService_Activator() :
base()
{
}
public override RemObjects.SDK.IROService CreateInstance()
{
//call to our service locator
return App.Get();
}
}

The big downside to this is that this code gets generated every time you edit the service in the Service Builder application.

The App object above simply provides us with access to our chosen method of handling dependency resolution. In this case it would be wrapping access to the Ninject kernel configured for the application.

Decisions, Decisions

My preference is to do the injection in the Service Activator as this allows you to clearly define what dependencies a service has by listing them as part of its constructor.

If instead you were to override the Activation method, it becomes less clear what objects the service depends on as the details are lost in a method call, rather than being part of the class declaration.

Razor And HtmlHelper Extensions

HTML helpers can be fantastically useful when working on an ASP .Net MVC project, and they're dead simple. They boil down to methods which are used to encapsulate functionality to help reduce the amount of logic we end up with in a view.

For example there are helpers available to create labels and form fields, taking a property as input, and generating the relevant HTML for it.

Writing your own HTML helpers is easy and achieved by writing an extension method for the HtmlHelper class. I often hit a stumbling block when writing an extension which manifests itself in the following way:

Compiler Error Message: CS1061: 'System.Web.Mvc.HtmlHelper' does not contain a definition for 'TestMethod' and no extension method 'TestMethod' accepting a first argument of type 'String' could be found (are you missing a using directive or an assembly reference?)

An Example Extension Method

To demonstrate how to fix this, we need a quick example of an HTML helper extension method:
namespace MVC3Test.Helpers
{
public static class HtmlExtensions
{
public static MvcHtmlString TestMethod(this HtmlHelper htmlHelper, string input)
{
return MvcHtmlString.Create(input.Trim());
}
}
}

Make it work

The problem is caused by the fact that we don't have a reference to the namespace where the extension method lives. We have two options for fixing this:

Add a using directive to the view

The first thing we could do is just add a @using directive to the top of the view specifying our helper namespace:
@using MVC3Test.Helpers

Update View Folder Web.config

Adding using directives to each view that uses our helpers will quickly become tiresome. An easier way to apply this throughout the project is to update the web.config to reference the namespace.

This can happen at either the view folder level, or application folder. Either way, you need to update the web.config to add a new namespace entry, which should look something like this:


...

...

Summary

Html Helpers are a great way to reduce the complexity of your views and reuse code that is often repeated.

Just remember that when writing your own, it must be referenced from either the view, or web.config!

Fluent NHibernate, Counting Entries In A Related Table

I have a simple Fluent NHibernate mapping setup where a parent table has a 'HasMany' relationship to the child table.

As part of the parent table, I want to include a property that indicates how many child entries there are, without having to map the child relationship. This is mainly because I don't want the additional overhead of bringing back each child record, but is also useful for being able to sort by the count.

Turns out this can be achieved quite easily by using the 'Formula' function on a mapped property:

Map(c => c.ChildCount).Formula("(select count(*) from childTable where childTable.parentId = id)");

Simple when you know how!

System.Data.SQLite And 64 Bit Operating Systems

An old customer surfaced recently, wondering why a new installation of an old .Net WinForms application I wrote wouldn't work on their shiny new 64 bit system.

As it turns out, I used SQLite for this particular project as the data storage engine. Because this is a managed .Net wrapper around the native sqlite library, it was causing problems when trying to load the 32 bit version of the library on a 64 bit system.

A Quick Fix

Fortunately it's quite straight forward to force an assembly to run in a 32 bit version of .Net, regardless of the host platform as there is a flag in the assembly that will define this.

In Visual Studio this can be found on the project properties page under the 'Build' tab.

Platform Target

Setting 'Platform Target' to x86 will force the assembly to be run under the 32 bit .Net framework.

This can also be set using the command line corflags utility:
corflags /32BIT+ dotnetapp.exe

The Correct Fix

Obviously the correct thing to do would be to detect the OS version on install and use the correct version of the SQLite wrapper, but the above serves as a quick fix to get them up and running.