Luke Smith

Write today, wrong tomorrow

Sharing configuration across visual studio projects

Whenever creating a new visual studio project I always go through the pain of ensuring certain properties are setup and StyleCop is enabled. It’s manual and boring, and not to mention the repetition of the settings not exactly being DRY.

I can’t believe I didn’t think of this sooner but one way to get around this is to create a single target file, containing all of the properties and bits you want to run as part of building the project, then all you have to add to each project file is a single import of the target.

<Import Project="$(SolutionDir)\build\common.target" />

My common.target can be found on github.

Next task is to create a simple script to run through all .csproj files in a directory tree and add/update the import element if it’s missing.

Updating a pointhq dns record from amazon ec2 instances

If you’re using Amazon EC2 for any reason, but not running the instance 24/7 (I have an instance with TeamCity that I only want to run on the evenings/weekends when I’m doing any work) you may not want to spend the extra on an Elastic IP to get a static IP address.

Unless you use Elastic IP however, everytime you start your EC2 instance you get allocated a new dynamic address, annoying if you want to use a friendly hostname. So how can you  get your dns server updated when your instance starts?

My dns host of choice is PointHQ, they give 10 free domains and provide a useful api for managing the zones and records. Theres even a ruby gem.

Step 1 – Create an A record in PointHQ

First of all we need to create the record in Point. For my TeamCity instance i’ve created a A record for teamcity.example.com and put a temporary IP address as the records data.

Step 2 – Create a ruby script

The next step is to create a script that can be run to get the machines current public IP address and then to call the Point api. For this you will need to get your api key from the Point website.

To get the current IP address of the EC2 instance you need to make a GET request

ip = open('http://169.254.169.254/latest/meta-data/public-ipv4').read

Using the Point ruby gem we now need to get hold of the zone record hosted by Point and update the data with the instances public IP address.

zone = Point::Zone.find(<ZoneId>) # example.com
record = zone.record(<RecordId>) # teamcity.example.com
record.data = ip
record.save

Run the ruby script now and check PointHQ. The data field of the A record created in step 1 should now be updated with the public IP address of the EC2 instance.

Step 3 – AutoRun the script

We’ve got the script working updating Point, but it’s pretty useless if we still need to remote into the server and run it manually. As I’m running on Windows I’ve used the Task Scheduler to automatically run the ruby script. I couldn’t find a way to be notified when the EC2 instance starts so used the following triggers which update Point fairly quickly after starting the instance.

  • At system startup
  • At log on of any user <- I have a feeling only this one is required
  • One time – repeat every 10 minutes

The only problem I’ve had is dns caching, which you can flush locally easily. I use opendns which gets updated incredibly quickly and if not theres a handy cachecheck + refresh tool.

Now with hosted YouTrack from JetBrains, and GitHub, I have a fixed url that I can point to for integrating with TeamCity.

IIS Application Pool “randomly” stopping

This issue has just sent me crazy for the past day. On my development machine the application pool hosting one of our webservices would randomly stop with nothing more than the following error in the System Windows Log

Application pool ‘xx’ is being automatically disabled due to a series of failures in the process(es) serving that application pool.

Which resulted in subsequent calls to the service returning

HTTP Error 503. The service is unavailable.

Any attempt to attach a debugger to the service was no help, with the debugger becoming detached every 10 seconds when w3wp.exe died.

The automatic disabling of the app pool turned out to be due to the Rapid-Fail Protection that will stop the application pool after a default of 5 worker process failures. Several suggestions say to just disable Rapid-Fail protection, but this just masks the problem to stop the 503 from occurring.

With some help from Chris Forster I dived into the world of Windows Debugging, looking for any kind of IIS exception that could be causing the worker process to keep failing, which turned up nothing.

The culprit – NServiceBus

To cut a long and boring debugging story short, NServiceBus was the culprit. Or rather the user account of the application pool not having the permission to Read or Peek messages from the message queue. On application startup NServiceBus attempts to send a message and read it from the message queue in the background, killing the process after 10 seconds if it is not able to read it back from the queue.

Videos on CQRS

This is more a future reference to me, but here’s a couple of excellent videos on Command Query Responsibility Segregation.

  1. Command Query Responsibility Segregation– Udi Dahan
  2. CQRS and Event Sourcing – the Business Perspective– Greg Young
  3. CQRS: Why, What and How– Ian Cooper
  4. CQRS Pattern, Event Sourcing and Their Real World Applications– Neil Robbins

When is an email address not an email address?

When it’s a string.

How many systems have you worked on where you pass strings/integers etc about for email addresses and passwords among other things.

Edit: I knew there was a real term for this, which Rob has reminded me - Business Primitives

What’s wrong with this?

You’re adding a lot more work to any methods that deal with email addresses. If your methods accept a string, even if the parameter name is “emailAddress”, what is stopping me from passing a value that doesn’t represent a valid address. The answer nothing. This puts the responsibility of validating the input on the called method, likely raising an exception if it doesn’t agree with what you’ve passed it.

Extension methods get used, and abused, for checking whether a string is a valid email address. The fact you are doing this with an extension method should indicate that a string is probably the wrong type.

So what can we do instead?

I believe a better approach is to represent the value with its own type. Create an EmailAddress type and have this do the validating and parsing of the actual value and have methods accept parameters of this type. No longer will you have conditions spread throughout your codebase and no more will you have to trace to find out how and where the incorrect value entered the system. You get instant feedback as soon as you try treating an invalid value as an email address, stopping it moving deeper into the system.

Passwords *should* be encrypted so generally you store the encrypted value as well as a Salt. value. Why treat these two values separate (a string for the encrypted value and a string for the salt), bring them together under a Password type. You then have a logical place to create passwords from plain text and compare whether a plain text string is the same as an encrypted password.

But what about my ORM?

Any decent ORM, such as NHibernate, will allow you to map a custom type. NHibernate enables this via the IUserType interface.

Show me the code

I have posted both my implementations for the EmailAddress and Password types over on github. I’ve also added gists for the associated NHibernate user types.

Another thing to think about is to not use integers to represent Age. Age generally cannot be negative, unless you have some complex domain, so using a type which allows this may not be the right solution if you are putting conditional checks throughout the system.

The When, What and Why of auditing

One of the things I’ve come across in most systems is the requirement for auditing.

As i see it there are 3 approaches to auditing

  1. When – Keeping track of when something changed. e.g Product A was changed by Bob on 1st April 2009.
  2. What – Keeping track of what changed – e.g Product A’s price was changed from £15 to £20 by bob on 1st April 2009
  3. Why – Keeping track of why something changed – e.g Product A’s price changed from £15 to £20 by bob on 1st April 2009 because it was wrongly priced originally.

Number 3, why, provides the most value. Not only does it allow the users of the system to be able to see the intent of changes (providing an extra dimension to reports) but it also provides some valuable information to any developer tasked with fixing an issue in the system. If a developer can see what the users intent was then it can help in providing a possible diagnoses.

As a more detailed example imagine you own an online shop that allows users to be able to cancel orders before they are actually shipped from the warehouse. You could provide a big button that says “cancel order”. Simple, but this would not give a reason behind the user cancelling their order.

A better option would be to give the customer a set of options as to why they want to cancel, is it because they’ve since found it cheaper elsewhere, decided they don’t want it anymore, have heard “the next big thing” is due out in a week and are waiting for that or that it is taking too long to dispatch? Capturing this information allows audit reports to be run in the future about why customers are cancelling their orders.

Once you know the intent behind the customer cancelling the order you can then initiate different business processes, if it is because they’ve found it cheaper elsewhere then this could invoke a process for the sales team to contact them to match the offer. If its because its taking too long to dispatch then send them a voucher for free delivery on their next order. Keeping the customer happy is more likely to make them return.

Without catching the intent (whether for auditing or not) this would not be possible.

Write today, wrong tomorrow

My blogs been without a subtitle for as long as I can remember, I just couldn’t think of anything “catchy”. But now I have come up with something that I think fits “Write today. Wrong tomorrow”.

This refers to the constant learning that occurs in the development world. I’m a huge believer that if you look back at code written 6 months ago and think “wow, that was amazing – I wouldn’t do anything differently” then you haven’t learnt anything new since.

So take whatever I say on this blog with a pinch of salt, I might not necessarily agree with it in 6 months time – that includes the subtitle ;)

Creating website installer using WiX

I’m currently working on a new project and one of the things I want is an easy deployment process. Rather than wait till I actually want to deploy the site to production to put something in place I’ve decided to build it early and use the same process as part of my CI process. Testing the process early and often will mean any issues will be solved sooner rather than on the day of the release.

I decided to go with an msi installer, so had 2 choices. Either using a Setup Project, that’s included in Visual Studio, or WiX. WiX is far more powerful, and also doesn’t require Visual Studio being installed on the build machine (Setup Projects aren’t supported by MSBuild and so you have to use devenv.exe to build them…urgh).

WiX is a Windows Installer toolset and you write your installation packages using XML. It’s a Microsoft project and hosted on sourceforge.

The following uses wix3.0.5419 and requires Visual Studio 2008.

Step 1: Download WiX

Download WiX from sourceforge. Make sure you also install Votive (included in the WiX installer) which will give you support for creating WiX projects inside Visual Studio with full intellisense.

Step 2: Create a new WiX project

Simple, just as you would any other Visual Studio project.

Step 3: Adding the WixIIsExtension

WiX provides a template to work with when creating a new project, which is useful. The first thing we need to do is reference to WiXIIsExtension, which provides us with the tasks needed to create websites and virtual directories from the installer. References are added in the same way as any other project reference, via the Solution Explorer.

 

You then need to add a new xml namespace to the Wix root element in your Product.wxs file. If you don’t do this then I’ve found you cannot make use of the tasks provided by the extension library and will get the error “The Component element contains an unexpected child element ‘WebSite’.”

Add the namespace xmlns:iis=”http://schemas.microsoft.com/wix/IIsExtension”.

Step 4: Creating the website

In the Product.wxs file you can now add a task to create a website in IIS within a Component.

 

Update the ComponentRef under the Feature Id=”ProductFeature” to point to the Website component, Ctrl+Shift+B and you’ve created an installer that creates a website under IIS.

Step 5: Run the installer and view the result

Find the installer that is produced in the bin directory and run it. There is no UI for the user to interact with, and a new website is created pointing to C:\Project Files (x86)\WixSampleProject

 

We’ve not included any files in our installer, for that I use heat which I’ll blog about in a future post.

Hope you’ve found this helpful

Technorati Tags: ,,,

Reading Geek Night Presentation slides

I recently gave a 15minute presentation covering the SOLID Principles at the Reading Geek Night, not enough time to go into each principle but hopefully enough that people went away with some understanding of the principles and were encouraged to learn more about them.

I highly recommend watching this video of “UncleBob” at the Norwegian Developers Conference 2009 on SOLID Principles of OO class design

I’ve also uploaded my slides of my presentation to slideshare.

Now using github

I’ve decided to move my open source projects over to github, rather than hosting them on a private subversion server where they aren’t very accessible.

From what I’ve seen, and heard, github is a great source control repository, I only hope there is a visual studio addin as good as visualsvn in the pipeline.

Currently my 2 JavaScript libraries have been moved over

  • linq2js is a JavaScript library providing an api similar to that of linq in the .net framework. It features a near complete method for method implementation of those found on the IEnumerable interface as well as lazy evaluation of queries.
  • vegeojson is a helper utility i wrote for drawing shapes on a virtual earth (now bing) map given an object in the geojson format.
Follow

Get every new post delivered to your Inbox.