Calculate an average using NHibernate

Yesterday I was writing a dashboard application to summarise data held in a SQL Server database. Part of the dashboard involves showing the average of a certain value in rows added in the last hour, day, week and month. In the good old days this would have been easy; I would have written a stored procedure involing the AVG function. However, as I was using NHibernate I thought I would try and do this without writing any SQL (or indeed HQL). While I am a big fan of NHibernate this was much less straightforward than writing some simple SQL.

Here is the code I came up with:

public double GetAverage(DateTime dateFrom, DateTime dateTo)
{
	var query = Session.QueryOver().SelectList(list => list.SelectAvg(item => item.Value))
		.Where(x => x.Date >= dateFrom && x.Date <= dateTo);

	try
	{
		return query.List().First();
	}
	catch (GenericADOException exception)
	{
		// Note that if there are no results for the period (and the average is null) then we will
		// get a specific error back from NHibernate. We filter this out and return 0:
		if (exception.Message.StartsWith("Unable to perform find[SQL: SQL not available]", StringComparison.OrdinalIgnoreCase) && 
		    exception.InnerException != null && 
		    exception.InnerException.Message.StartsWith("Value cannot be null", StringComparison.OrdinalIgnoreCase))
		{
		    return 0;
		}

		// In all other cases we re-throw:
		throw;
	}
}

I discovered that if the query is ran over a period containing no data NHibernate throws an exception, hence the error trapping which returns 0 if the exact error referring to zero records is encountered.

Interestingly, when I turned on Log4Net SQL logging I found that NHibernate generates exactly the same SQL I would have written myself in the good old days:

SELECT avg(cast(this_.Value as DOUBLE PRECISION)) as y0_ 
FROM [Item] this_ 
WHERE 
	(this_.Date >= @p0 and this_.Date <= @p1);
@p0 = 28/03/2013 20:17:04 [Type: DateTime (0)], 
@p1 = 28/03/2013 21:17:04 [Type: DateTime (0)]

Nice work NHibernate!

Registering many like types in Castle Windsor

Castle Windsor is an awesome dependency injection framework available for use with .NET. While a full explanation of dependency injection is beyond the scope of this post, two key reasons to use a dependency injection framework are:

1) Code using dependency injection is less “tightly-coupled” and thus less brittle.
2) Dependency injection is vital in order to achieve true test driven development (incorporating unit-testing and mocking).

Anyone familiar with Castle Windsor will know that individual types can be registered as follows:

container.Register(
                Component.For<IUserRepository>()
                .ImplementedBy(typeof(UserRepository))
                .LifeStyle.Transient);

However, it is often the case that we have many “like” classes in an application, all providing similar functionality and having a similar naming convention. A good example would be respository classes, particularly when using ORM frameworks. Rather than manually adding each repository to the dependency container, Castle Windsor has a neat shortcut for registering multiple classes:

container.Register(Classes.FromAssemblyContaining(typeof(UserRepository))
                .Where(type => type.Name.EndsWith("Repository"))
                .If(type => type.Namespace.StartsWith("MyApplication.Api.Data.Repositories"))
                .WithService.FromInterface(typeof(IRepository))
                .Configure(c => c.LifestyleTransient()));

The code above will find all classes implementing the interace IRepository in the namespace MyApplication.Api.Data.Repositories (and its children) that have Repository at the end of their name. These can then be accessed at runtime using:

var userRepository = injector.Resolve<IUserRepository>();
var productRepository = injector.Resolve<IProductRepository>();

Very cool!

Encapsulated and strongly-typed access to .NET configuration files

.NET is a strongly-typed object-oriented language, and it is my firm belief that everything we do within it should be strongly-typed and object-oriented in design. A trivial example would be to use the Uri class when dealing with URLs rather than simply passing strings around.

A central theme in object-orientation is encapsulation, which, in layman’s terms, I take to mean “when modelling a particular type of granular thing, the code for that thing should be contained in a single place”. There are a whole host of reasons why encapsulation is good practice, not least that it makes it really easy to change the way an aspect of the code works if changes only have to be made in one place. Better still, if things are encapsulated and strongly-typed, code changes that break other functionality can be found simply by recompiling, rather than having to execute the entire codebase looking for runtime errors.

In my opinion, interactions with standard .NET configuration files should be encapsulated and strongly-typed. Sure, it is possible to access configuration settings by littering code with calls to AppSettingsReader or ConfigurationManager, but this is neither encapsulated nor strongly-typed. If the return type for a setting appearing in many places in the code needed to change and AppSettingsReader/ConfigurationManager had been used throughout the code, this change would break existing code, and worst still, broken code would only be found at runtime. “Find and replace” could be used to find every instance of the setting in the code, but this is hardly ideal and may not find all instances if another coder had been clever and used constants for the key names. Similarly, if the way that configuration values were served needed to be changed, for instance by switching from the standard .NET configuration model to some other type of configuration provider such as a database you’d have to make changes throughout the code-base.

Keeping code to access the configuration file in one place feels like a much more elegant solution. So, how do I normally do this? Well, let’s assume an application with two UIs (User Interfaces) and an API layer (Application Programming Interface) as follows:

Encapsulated Configuration 01

Note that the example solution in this post has been included on GitHub here:

https://github.com/stevebarker333/Encapsulated-Strongly-Typed-Configuration-Files

In this example, both UIs are console applications, although in reailty these could be anything, including Windows Services, websites or Windows Applications. (Beware the .NET Framework 4 Client Profile issue if you are going to follow this example yourself!)

As configuration is owned at the level of the executing assembly, classes to encapsulate configuration settings should exist in the UI projects. However, these classes will share underlying functionality to interact with the configuration files, and so we create a base class in the API project from which all executable-level configuration file classes inherit:

using System;
using System.Configuration;

namespace API.Configuration
{
    public abstract class ConfigurationFile
    {
        private readonly AppSettingsReader appSettingsReader = new AppSettingsReader();

        protected string ReadString(string key)
        {
            try
            {
                return (string)appSettingsReader.GetValue(key, typeof(string));
            }
            catch (Exception exception)
            {
                var message = string.Format("Could not read key {0} from configuration file", key);
                throw new ConfigurationErrorsException(message, exception);
            }
        }

        protected int ReadInt(string key)
        {
            try
            {
                var value = this.ReadString(key);
                return int.Parse(value);
            }
            catch (Exception exception)
            {
                var message = string.Format("Could not read an int from key {0} in the configuration file", key);
                throw new ConfigurationErrorsException(message, exception);
            }
        }

        protected Uri ReadUri(string key)
        {
            try
            {
                var value = this.ReadString(key);
                return new Uri(value);
            }
            catch (Exception exception)
            {
                var message = string.Format("Could not read a Uri from key {0} in the configuration file", key);
                throw new ConfigurationErrorsException(message, exception);
            }
        }
    }
}

Note that all settings are first read as strings using the ReadString method. Other strongly-typed values are then derived from this method. I’ve included ReadInt and ReadUri functionality. More methods can be added to the base class as they are needed, but by the laws of YAGNI, don’t try and second guess every type your application will need up-front!

This class should be placed in a folder called Configuration to get the namespace shown. Additionally, a reference to System.Configuration will need to be added to access the exception classes from within our new base class:

Encapsulated Configuration 02

We can now start adding configuration at UI level. Here is my configuration file in UI1:

<?xml version="1.0"?>
<configuration>	
	<appSettings>
		<!-- UI1 Specific Settings -->
		<add key="UI1String" value="UI1.String"/>
		<add key="UI1Int" value="1"/>
		<add key="UI1Uri" value="http://www.ui1.com"/>
		<!-- Settings Required By API -->
		<add key="CoreString" value="Core.String"/>
		<add key="CoreInt" value="0"/>
		<add key="CoreUri" value="http://www.core.com"/>
	</appSettings>	
</configuration>

…and for UI2:

<?xml version="1.0"?>
<configuration>
	<appSettings>
		<!-- UI2 Specific Settings -->
		<add key="UI2String" value="UI2.String"/>
		<add key="UI2Int" value="2"/>
		<add key="UI2Uri" value="http://www.ui2.com"/>
		<!-- Settings Required By API -->
		<add key="CoreString" value="Core.String"/>
		<add key="CoreInt" value="0"/>
		<add key="CoreUri" value="http://www.core.com"/>
	</appSettings>
</configuration>

In order to simulate the kinds of scenarios that occur in enterprise solutions, I’ve included settings specific to the executing assembly and shared settings that are required by the API in each configuration file. An example of this would be a web-UI that needs a configuration setting as to how many search results to show on each page of paged search results, with an API responsible for performing the search which needs a configuration setting containing the database connection string to search against.

We can now write our strongly-typed encapsulated configuration file classes in each of the UIs. They have been added to each UI project as follows, along with references to the API project:

Encapsulated Configuration 03

Here is the class for UI1:

using System;

namespace UI1.Configuration
{
    public class ConfigurationFile : API.Configuration.ConfigurationFile
    {
        public string UI1String
        {
            get
            {
                return this.ReadString("UI1String");
            }
        }

        public int UI1Int
        {
            get
            {
                return this.ReadInt("UI1Int");
            }
        }

        public Uri UI1Uri
        {
            get
            {
                return this.ReadUri("UI1Uri");
            }
        }

        public string CoreString
        {
            get
            {
                return this.ReadString("CoreString");
            }
        }

        public int CoreInt
        {
            get
            {
                return this.ReadInt("CoreInt");
            }
        }

        public Uri CoreUri
        {
            get
            {
                return this.ReadUri("CoreUri");
            }
        }
    }
}

…and for UI2:

using System;

namespace UI2.Configuration
{
    public class ConfigurationFile : API.Configuration.ConfigurationFile
    {
        public string UI2String
        {
            get
            {
                return this.ReadString("UI2String");
            }
        }

        public int UI2Int
        {
            get
            {
                return this.ReadInt("UI2Int");
            }
        }

        public Uri UI2Uri
        {
            get
            {
                return this.ReadUri("UI2Uri");
            }
        }

        public string CoreString
        {
            get
            {
                return this.ReadString("CoreString");
            }
        }

        public int CoreInt
        {
            get
            {
                return this.ReadInt("CoreInt");
            }
        }

        public Uri CoreUri
        {
            get
            {
                return this.ReadUri("CoreUri");
            }
        }
    }
}

Note that each configuration file inherits from our shared base class so that it can access the ReadString (and similar) methods defined earlier. As the core/shared settings are shared with the API, then there is an argument for putting the property getters for these properties in the base configuration file class. However, I would argue against this approach as it means the API is dictating how the UI must organise its configuration file. If you’re comfortable with this approach then that’s fine; however I prefer to use an interface in the API to enforce the existence of shared settings in each UI. This allows the UI developer free choice to use any key names they deem fit for core settings. Let’s create this now in the following location:

Encapsulated Configuration 04

The interface is as follows:

using System;

namespace API.Configuration
{
    public interface ICoreConfiguration
    {
        string CoreString { get; }

        int CoreInt { get; }

        Uri CoreUri { get; }
    }
}

This interface is then applied to each of the configuration file classes in the UI:

using System;

namespace UI1.Configuration
{
    public class ConfigurationFile : API.Configuration.ConfigurationFile, API.Configuration.ICoreConfiguration
    {
	...        
    }
}
using System;

namespace UI2.Configuration
{
    public class ConfigurationFile : API.Configuration.ConfigurationFile, API.Configuration.ICoreConfiguration
    {
	...        
    }
}

The ground work has now all been done. All that remains is to put some example code into the UIs and API to demonstrate how our configuration classes and used, and that they do indeed pick up the correct settings.

I’ve added a class to the API to access the core settings:

Encapsulated Configuration 05

…which looks as follows:

using API.Configuration;

namespace API
{
    using System;

    public class Widget
    {
        private readonly ICoreConfiguration configuration;

        public Widget(ICoreConfiguration configuration)
        {
            this.configuration = configuration;    
        }

        public void DoSomething()
        {
            Console.WriteLine(configuration.CoreString);
            Console.WriteLine(configuration.CoreInt);
            Console.WriteLine(configuration.CoreUri);
        }
    }
}

Note that it is constructed with the type ICoreConfiguration so that it can use the core configuration settings without caring how they’ve be implemented. (Note also that this approach is still valid when using Dependency Injection, which I’ll cover in a future post.)

I’ve also included the following code in the Program class of UI1:

using System;
using UI1.Configuration;
using API;

namespace UI1
{
    public static class Program
    {
        public static void Main()
        {
            var configurationFile = new ConfigurationFile();

            Console.WriteLine(configurationFile.UI1String);
            Console.WriteLine(configurationFile.UI1Int);
            Console.WriteLine(configurationFile.UI1Uri);

            var widget = new Widget(configurationFile);
            widget.DoSomething();

            Console.ReadLine();
        }
    }
}

…and the following code in the Program class of UI2:

using System;
using UI2.Configuration;
using API;

namespace UI2
{
    public static class Program
    {
        public static void Main()
        {
            var configurationFile = new ConfigurationFile();

            Console.WriteLine(configurationFile.UI2String);
            Console.WriteLine(configurationFile.UI2Int);
            Console.WriteLine(configurationFile.UI2Uri);

            var widget = new Widget(configurationFile);
            widget.DoSomething();

            Console.ReadLine();
        }
    }
}

Running UI1 yields:

Encapsulated Configuration 06

…and running UI2 yields:

Encapsulated Configuration 07

…both as expected.

So, that concludes my exploration of strongly-typed encapsulated configuration files. Although it’s a bit more effort to implement than directly accessing the .NET configuration classes throughout code, it is more logical and far less brittle.

A final note: the .NET Framework automatically caches configuration file values in memory so there is no performance gain from storing configuration values in local class variables within each of our strongly-typed configuration file classes.

Update: As mentioned above, I’ve now extended the above by incorporating dependency injection. See my new post entitled Encapsulated and strongly-typed access to .NET configuration files with dependency injection.

Testing Windows Services

Windows Services should be part of any .NET developer’s arsenal as most enterprise solutions involve at least one Windows Service. Writing Windows Services is simple, and there are plenty of articles online to tell you how to do this. Testing Windows Services on the other hand, is a totally different story!

Of course, you could keep registering and running your service each time you make a change in order to test it, but this approach quickly becomes frustrating. A better technique that I use is to create a service wrapper console application project in the same solution as the service and run that each time I make a change. Here’s how…

Create a Windows Service. Your Solution Explorer should look a little something like this:

Testing Windows Services 1

Note that I’ve renamed Service1 to Service due to my OCD tendencies when it comes to naming conventions. I’ve created a simple test service with the following code in the Service.cs file:

using System.IO;
using System.ServiceProcess;

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

        protected override void OnStart(string[] args)
        {
            using (var stream = new FileStream("Running", FileMode.Create, FileAccess.ReadWrite, FileShare.ReadWrite))
            {
                using (var writer = new StreamWriter(stream))
                {
                    writer.WriteLine("Running");
                    writer.Flush();
                }
            }
        }

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

This just creates a file in the same directory as the service when the thing starts up, and deletes the file when it stops.

The service wrapper is just a console application, so add one of these to your solution. (Please note my post on the “.NET Framework 4 Client Profile” default setting for target framework when creating console applications as this may cause issues.) You will also need to reference your service project in the console application, along with a reference to System.ServiceProcess. The wrapper should then be set as the start up project:

Testing Windows Services 2

Add a class called ServiceWrapper to the console application as follows:

namespace MyService.Wrapper
{
    public class ServiceWrapper : Service
    {
        public void TestStart()
        {
            base.OnStart(new string[] { });
        }

        public void TestStop()
        {
            base.OnStop();
        }
    }
}

Notice that the wrapper inherits from my actual service, and exposes the OnStart and OnStop methods publically. This is a simple implementation of the facade pattern, and allows the console application to call service methods.

Then add the following code to the Program class in the console application:

using System;

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

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

When the console application is run, the wrapper simulates the service starting up and then waits for a key press in the console window. The service will then execute as though it had been installed and ran. If you follow this example, you’ll see the file called “Running” appear and disappear. I recommend putting a breakpoint in the catch block of the Program class to help diagnose any issues you may encounter.

This approach can still be used if you use dependency injection, although you will need to manually inject any required dependencies into the service via the Program class in your wrapper. I’ll cover that in a future article.

Update: Note that if your Windows Service uses a .NET configuration file, you’ll need to share this with the console application. The best way to do this (to avoid duplicating settings between two configuration files) is to add the Windows Service configuration file to the console application as a link file. That way the console application will always use the Windows Service’s version of the file.

Console application pitfalls: .NET Framework 4 Client Profile

Console applications are extremely useful for testing out bits of code before you’re ready to start writing production code. For instance, I use them when getting to grips with new third party components. These applications are supposed to be throw away and so coding standards are not usually adhered to!

One thing I often forget is that by default, console applications start with the target framework set to “.NET Framework 4 Client Profile”, as in the following properties window screenshot:

.NET Framework 4 Client Profile

Symptoms of this include references missing from the references dialog box, methods not being available in Intellisense and code generally not behaving as expected. I’m not exactly sure why “.NET Framework 4 Client Profile” is available in the first place or why it’s so restrictive. I’ve also not bothered to research this, although I suspect it’s probably to allow code to run in environments with low security permissions. However, for throw away code or code that is never going to leave your infrastructure I’d advise getting into the habit of changing the target framework to “.NET Framework 4” each time you make a new console application, otherwise you’re likely to end up scratching your end when simple stuff doesn’t work as expected.

Monitoring website up-time

Most web-hosting firms specify the level of “up-time” you can expect to get on your website. Typically this is given as a percentage (e.g. 99.99%, 99.999%, etc…), but how do you know if they’re really telling the truth? After all, you can’t measure this yourself.

I currently use Pingdom to measure up time for my sites. Pingdom constantly monitors websites and produces a monthly report stating the uptime. It also emails me to tell me each time my site does not respond for a period of time (i.e. it is down), and when it comes back up again. The basic package is totally free and perfectly adequate if all you want is to receive up-time statistics and site-down alerts.

WordPress and Google Analytics

Following on from my last post in which I describe how to include code snippets in WordPress posts, I also decided it would also be great to track visitors to my blog using Google Analytics. Fortunately, this was very easy to set up.

The first step is to create a Google Analytics account. This is easy and fully explained by Google so I won’t go into details here. Once you have created your account you should be able to see your tracking code, which for me looks like this:

<script type="text/javascript">// <![CDATA[

  var _gaq = _gaq || [];
  _gaq.push(['_setAccount', 'UA-39305296-1']);
  _gaq.push(['_trackPageview']);

  (function() {
    var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
    ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
    var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
  })();

// ]]></script>

To monitor your WordPress site using Google Analytics you simply need to open the editor under the ‘Appearance’ menu, select Footer (footer.php) and paste the entire tracking code block just before the closing body tag:

</body>

Once done, Google Analytics will monitor traffic to your site.

Addendum: Warning! Updating your WordPress theme will overwrite any customisations you have made to the files. So, if you run a WordPress auto-update, be prepared to have to re-paste the Google Analytics code in again.

Including code snippets in WordPress using Sunburst Code Prettify

I realised that if this blog is going to be effective I’m going to need to show code snippets in my posts. This is obviously something that WordPress doesn’t do out of the box. I experimented with a few options before settling on the Sunburst Code Prettify plugin. Unlike other alternatives that I tried, this plugin worked straight away with no extra configuration needed.

However, there was one annoying issue. When I entered the text below into a new post:

Prettify 1

…it rendered as:

Prettify 2

Notice that the quotes have been scrambled. A few minutes on Google later and I’d found the following great article that explained what was going on:

WordPress Stop Changing My Quotes

The solution for me was to add the following line of code to my “Theme Functions (functions.php)” file in the WordPress editor, right at the end of the file:

remove_filter(‘the_content’, ‘wptexturize’);

Doing this fixed the issue and my code renders correctly as follows:

using System;

namespace HelloWorld
{
    public static class Program
    {
        public static void Main(string[] args)
        {
            Console.WriteLine("Hello World");
            Console.ReadLine();
        }
    }
}

Update (3rd September 2013)
Having seen Scott Miller’s blog and had some great advice from him via email, I have since switched to using ‘pre’ tags to render my code snippets, so this article is now out of date. The ‘pre’ approach is simpler and results in cleaner looking cope snippets. Another benefit is that I haven’t found any character issues yet, although code containing tags (e.g. HTML and XML) does have to be encoded before it can be encased in the ‘pre’ tags.