Changing the default naming convention for foriegn keys when using Fluent NHibernate

By default, NHibernate will assume that foreign keys should be named using the convention ReferencedTableName_id (e.g. Person_id). I personally don’t like this conversion and would prefer ReferencedTableNameId (e.g. PersonId).

Fortunately, this is pretty easy to achieve by extending the ForeignKeyConvention class in Fluent NHibernate:

using System;
using FluentNHibernate;
using FluentNHibernate.Conventions;

namespace NHibernate.Helpers.Conventions
{
    public class CustomForeignKeyConvention : ForeignKeyConvention
    {
        protected override string GetKeyName(Member property, System.Type type)
        {
            if (property != null)
            {
                return property.Name + "Id";
            }

            if (type != null)
            {
                return type.Name + "Id";
            }

            // If both are null, we throw an exception:
            throw new ArgumentNullException("property", "The property and type parameters cannot both be null");
        }
    }
}

This needs to be wired into your SessionFactory creation code as follows:

sessionFactory = Fluently.Configure()
    .Database(DatabaseConfiguration)
    .Mappings(x => x.FluentMappings.AddFromAssembly(MappingsAssembly))
    .Mappings(x => x.FluentMappings.Conventions.Add(new CustomForeignKeyConvention()))
    .ExposeConfiguration(x => new SchemaUpdate(x).Execute(false, true))
    .BuildSessionFactory();

Note that the example above will also update the database schema.

Once you’ve done that, all foreign keys will use the desired naming convention.

Testing Windows Services with dependency injection

Last year I wrote a post on Testing Windows Services. I pointed out that recompiling and installing your Windows Service following each change is a really inefficient way to develop and test a service. Instead, I suggest that you can run and debug your service in Visual Studio simply by wrapping the service up in a test console application.

I said that I would revisit the post for services using dependency injection, so here goes. Note that the code in this article follows on directly from the code in the previous article, so you’ll need to read the previous article in order for this to make sense!

First, a quick discussion as to how you could add dependency injection to a Windows Service:

I believe the easiest way to use dependency injection in a .NET Windows Service application is to use the dependency injection engine to inject required services into the ServiceBase.Run() method in the Program class for the service:

using System.ServiceProcess;

namespace MyService
{
    public static class Program
    {
        public static void Main()
        {
            var servicesToRun = new[] { (ServiceBase)Injector.Instance.Resolve() };
            ServiceBase.Run(servicesToRun);
        }
    }
}

In order to do this, you simply need to create an empty interface for your service, which the service implements:

namespace MyService
{
    public interface IService
    {
        // No implementation
    }
}
using System.IO;
using System.ServiceProcess;

namespace MyService
{
    public partial class Service : ServiceBase, IService
    {
        public Service()
        {
            InitializeComponent();
        }

        // Service implementation...
    }
}

My original article gave an example of a service which creates and deletes a file when it starts and stops. To complete the example, let’s extract the file interaction code out as a dependency. Here’s the interface:

namespace MyService
{
    public interface IFileCreator
    {
        void Create();
        void Delete();
    }
}

…and here’s the implementation:

using System.IO;

namespace MyService
{
    public class FileCreator : IFileCreator
    {
        public void Create()
        {
            using (var stream = new FileStream("Running", FileMode.Create, FileAccess.ReadWrite, FileShare.ReadWrite))
            {
                using (var writer = new StreamWriter(stream))
                {
                    writer.WriteLine("Running");
                    writer.Flush();
                }
            }
        }

        public void Delete()
        {
            var fileInfo = new FileInfo("Running");
            if (fileInfo.Exists)
            {
                fileInfo.Delete();
            }
        }
    }
}

The injector class for the service would then look something like this:

using Castle.MicroKernel.Registration;
using Castle.Windsor;
using Castle.Windsor.Installer;

namespace MyService
{
    public static class Injector
    {
        private static readonly object InstanceLock = new object();

        private static IWindsorContainer instance;

        public static IWindsorContainer Instance
        {
            get
            {
                lock (InstanceLock)
                {
                    return instance ?? (instance = GetInjector());
                }
            }
        }

        private static IWindsorContainer GetInjector()
        {
            var container = new WindsorContainer();

            container.Install(FromAssembly.This());

            RegisterInjector(container);
            RegisterService(container);
            RegisterFileCreator(container);

            return container;
        }

        private static void RegisterInjector(WindsorContainer container)
        {
            container.Register(
                Component.For()
                .Instance(container));
        }

        private static void RegisterService(WindsorContainer container)
        {
            container.Register(
                Component.For()
                    .ImplementedBy(typeof(Service)));
        }

        private static void RegisterFileCreator(WindsorContainer container)
        {
            container.Register(
                Component.For()
                    .ImplementedBy(typeof(FileCreator)));
        }
    }
}

Note that I’ve wired up both the service (using IService) and my new FileCreator class.

The ServiceWrapper class would be exactly as in the previous example. The only change to the wrapper console application would be to change the Program, as follows:

using System;
using MyService;

namespace MyServiceWrapper
{
    public class Program
    {
        public static void Main(string[] args)
        {
            var serviceWrapper = new ServiceWrapper();

            // Wire up service dependencies here:
            serviceWrapper.FileCreator = Injector.Instance.Resolve();

            try
            {
                serviceWrapper.TestStart();
                Console.ReadLine();
                serviceWrapper.TestStop();
            }
            catch (Exception exception)
            {
                Console.WriteLine("Error: " + exception.Message);
                Console.ReadLine();
            }
        }
    }
}

Unfortunately, in this class I’ve had to wire up all the dependencies in the ServiceWrapper manually as I haven’t found a way to do this automatically. However, this one small pain point is a significant improvement compared to compiling and installing your service each time you make a change!

Removing duplicates with LINQ in C#

Here are a couple of tricks to remove duplication using LINQ.

Firstly, for simple lists:

var numbersWithDuplicates = new[] { "One", "Two", "Two", "Three", "Four" };
var numbers = numbersWithDuplicates.GroupBy(x => x).Select(group => group.First());

…and secondly for more complex objects:

public class Person
{
    public int Id { get; set; }
    public string Name { get; set; }
    public int Age { get; set; }
}

…you can de-duplicate using any property you like:

var peopleWithDuplicates = new[]
{
    new Person { Id = 2, Name = "Alice", Age = 29 },
    new Person { Id = 1, Name = "Bob", Age = 30 },
    new Person { Id = 3, Name = "Claire", Age = 31 },
    new Person { Id = 4, Name = "Bob", Age = 50 },
};
var people = peopleWithDuplicates.GroupBy(x => x.Name).Select(group => group.First());

The Problem Steps Recorder

On a Windows machine, if you try to run PSR.exe (by using CTRL+R, or by searching for a program called Steps Recorder), a rather inconspicuous tool with a record button appears:

Problem Steps Recorder

Clicking Start Record, performing some actions with the mouse or keyboard and then hitting Stop Record produces a step-by-step log of all user input, along with some very useful screenshots showing what was on the screen at the time.

How cool is that? So, next time you ask a tester to give you a bug re-pro, suggest they use the Problem Steps Recorder.

Apparently it’s been around since Windows 7, so hopefully most people will have it on their work computers.

Prevent malicious image uploads

If you allow users to upload images to your site, you may be opening up your site to malicious use. This is because particularly cunning hackers can hide commands to do just about anything in the data that makes up the image.

For a great example of an infected image file, see the following page:

http://www.eicar.org/86-0-Intended-use.html

Note that you’ll need to disable your anti-virus if you want to create this file on your computer.

If you allow users to upload this file, it will produce some interesting results!

To prevent the vulnerability (at least when using C#) you simply need to try and load the image data into an Image object. This will throw an exception if the image contains anything nasty. Here is an example:

var image = Image.FromStream(imageDataStream);
using (var memoryStream = new MemoryStream())
{
    image.Save(memoryStream, ImageFormat.Png);
}

Note that you’ll need to load the uploaded data into a stream (imageDataStream in the example above) to get this to work.

Using the Return key with Back and Next buttons on web-sites

When it boils down to it, most sites on the web are just gloried data crunchers. Users enter information, which the system churns up and splits out again at some point in the future, potentially to a different user.

If a site requires a lot of information, it is common to see multistage wizards, with each stage asking for a small portion of the information. Each stage usually has a Back button and a Next button. Convention and common sense dictate that the Back button should be on the left, and the Next button on the right as in the following example:

Type something here:
… and here:

NB: The onclick events return false to prevent the page from actually submitting.

This all seems to works fantastically, and even uses tabindex to ensure that the user tabs onto the Next button before the Back button… until someone comes along that prefers to use the Return key to submit the form, instead of using the mouse or tabbing to the Next button. In this case, the Return key will call the first submit button it can find, which in this case is the Back button. This is not the expected behaviour! Put the cursor in one of the input fields and click Return to see this in action.

One solution to correct this would be to use floats and/or JavaScript to try and reverse the order the buttons are displayed in while still having the Next button placed highest in the HTML to ensure that it would respond to the Return key. However, if a user disables CSS and/or JavaScript this solution will fail. A simpler option is to create a hidden submit button as the first element within the form, which performs the desired Return key operation. The order of any other (visible) buttons on the form is then irrelevant.

The following form demonstrates this:

Type something here:
… and here:

Again, put the cursor in one of the input fields and click Return to see this in action. The only downside to this is that the user will see another submit button if they disable CSS, but in most cases I think it is still the best solution.

Basic fluent interface

Fluent interfaces seem to be everywhere these days, probably because they can be used to produce highly readable code. They use method cascading/chaining to achieve this, whereby method calls are made one after another on the same object reference.

Good examples are the LINQ component in .NET and Fluent NHibernate, obviously!

Here is a really simple example to demonstrate how you would go about writing a fluent API, in which values can be added to or subtracted from a numeric value. This is encapsulated in a Number class:

public class Number
{
    private int currentValue;

    public Number(int value = 0)
    {
        currentValue = value;
    }

    public int Value
    {
        get
        {
            return currentValue;
        }
    }

    public Number Add(int value)
    {
        currentValue += value;
        return this;
    }

    public Number Subtract(int value)
    {
        currentValue -= value;
        return this;
    }
}

Note that each of the chained methods returns the current instance, via the this keyword.

The Number class can be used as follows:

public static class Program
{
    public static void Main()
    {
        var number = new Number();
        
        number.Add(1).Add(2).Add(3);
        Console.WriteLine(number.Value);

        number.Subtract(4).Subtract(1).Add(2);
        Console.WriteLine(number.Value);

        Console.ReadLine();
    }
}

As an aside, adding the ability to multiply and divide would significantly increase the complexity of this class, since the order of operations would need to be taken into account.

However, hopefully my example shows how fluent APIs are put together.

Simple trick to help prevent click-jacking

Click-jacking is a technique used by hackers to get you to interact with websites without your consent or knowledge. An example would be to get you to click a Like button on a Facebook page without you realising it. The trick with click-jacking is misdirection. One way to achieve this is to show you a friendly looking site, preferably a site which you are already familiar with, but where the buttons perform actions other than those you expect. This can be achieved by hosting the friendly site in an iframe, with fake buttons floated over the top of the real buttons. These fake buttons can then perform unintended actions, such as submitting a Like to Facebook.

You can test whether your website is vulnerable using the following HTML snippet:

<html>
<head>
<title>Clickjack test page</title>
</head>
<body>
<p>Website is vulnerable to clickjacking!</p>
<iframe src="http://www.mywebsite.com" width="1000" height="1000"></iframe>
</body>
</html>

If you can see the text Website is vulnerable to clickjacking! when you look at the code in a browser your site could be used as a target for click-jacking.

A simple way to prevent this kind of attack is to include the following JavaScript at the top of your site:

<script type="text/javascript">
// Prevent the page from being vulnerable to click jacking
if (self == top) {
var theBody = document.getElementsByTagName('body')[0];
theBody.style.display = "block";
} else {
top.location = self.location;
}
</script>

The JavaScript checks to see if the containing page is the top-most entity in the HTML served to the user. If not, then the whole browser is re-directed to the address of the containing page, thus removing the iframe.

Obviously this won’t work if users don’t have JavaScript enabled, but for the sake of a few lines of trivial JavaScript it’s worth adding this to your site.

Ignore SSL errors when calling web-services in C#

Often when developing .NET systems that call secure web-services, I find myself running code against development and test servers with invalid SSL certificates. This causes service calls to fail and prevents me from making progress. To get round this potential blocker, I include the following snippet somewhere in the code before the service call is made:

ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };

This code only needs to appear once, and it is not good practice to leave it in production code as it means that data sent over HTTPS isn’t actually secure. Consider making the inclusion of this code configurable, or wrap it up in #DEBUG statements so that it is not compiled into production code.

Classic web-page layout with HTML and CSS

I met up with a great friend of mine the other week for our monthly “tech-talk” session, in which we share things we’ve learned or heard about in the IT world. We hold these sessions in order to give ourselves the illusion that we are actually managing to keep up with the ever-changing world of IT, and of course to enjoy some good banter and real ale.

We started talking about the layout of web-pages, and why using tables for anything other than an actual table is a bad idea. (If you don’t know why it’s a bad idea, ask someone with a visual impairment for their thoughts on the matter…)

I promised to share with my mate how I would go about creating a classic header/columns/footer web-site using only divs and CSS. Here is the result:

<html>
    <head>
        <title>Class Page Layout</title>
        <style type="text/css">
            body {
                font-family:'Courier New';
                font-size:1em;
                background-color:gray;
            }

            ul {
                margin:0px;
            }

            #container {
                width:800px;
                margin-left:auto;
                margin-right:auto;
            }

            #header {
                height:50px;
                padding:10px;
                margin:0px;
                background-color:#FFFF66;
            }

            #mainContent {
                height:400px;
            }

            #leftSection {
                background-color:#99FFFF;
                width:25%;
                float:left;
                height:100%;
            }

            #centreSection {
                background-color:#00FF00;
                width:50%;
                float:left;
                height:100%;
            }

            #rightSection {
                background-color:#99FFFF;
                width:25%;
                float:left;
                height:100%;
            }

            #footer {
                clear:both;
                height:50px;
                padding:10px;
                margin:0px;
                background-color:#FFFF66;
            }

            #footerLeft {
                float:left;
            }

            #footerRight  {
                float:right;
            }
        </style>
    </head>
    <body>
        <div id="container">
            <div id="header">Header</div>
            <div id="mainContent">
                <div id="leftSection">
                    <ul>
                        <li>One</li>
                        <li>Two</li>
                    </ul>
                </div>
                <div id="centreSection">
                    <h1>Heading</h1>
                    <div>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</div>
                </div>
                <div id="rightSection">
                    <ul>
                        <li>One</li>
                        <li>Two</li>
                    </ul>
                </div>
            </div>            
            <div id="footer">
                <div id="footerLeft">Footer</div>
                <div id="footerRight">Copyleft 2013</div>
            </div>
        </div>
    </body>
</html>

You can view the actual page here.

Although you’d probably use something like Bootstrap to achieve this kind layout these days, especially if you wanted it to render nicely on mobiles, it’s good to be able to build this kind of layout from scratch as well. The secret to getting it working is in the floats, and if you use the Web Developer toolbar by Chris Pederick to turn off CSS as I mentioned in a recent post about Firefox add-ons, you can see that the underlying HTML is a simple set of divs, one after the other.

I’ve tested this layout in the following browsers and all looks good:

  • Firefox
  • Chrome
  • IE10
  • IE9
  • IE8
  • IE7
  • Opera
  • Safari (for Windows)