September 13th, 2012

When .FirstOrDefault() doesn’t return null

I ran into an interesting bit of code recently that made use of the FirstOrDefault() method. The original developer had the intention of handling the case where the collection didn’t have a value, but made an incorrect assumption about the return value of FirstOrDefault().

Here’s an example of what was being done:

DateTime? theDate = listOfDates.FirstOrDefault();

if (theDate != null)
{
    //somecode
}

While not immediately obvious, the //somecode block is never reached. I didn’t even realize it at first, at least until I got some strange data on the other end of the method.

So, I learned a little something about nullable types and the default value return by FirstOrDefault().

The default value for FirstOrDefault() does indeed return null for reference types, but nullable types are not reference types; they are structs. For non-reference types (i.e. value types), FirstOrDefault() will return the default value for the type.

In the above example, FirstOrDefault() will return either the first date from the collection, or DateTime.MinValue, which evaluates to 1/1/0001 12:00:00 AM. Since theDate will never be null, the intended block is never reached, and the case is never handled.

Note also that ReSharper will not catch this. The first line is a legal statement (since the value is implicitly converted to a nullable DateTime). But theDate doesn’t even need to be nullable. That line is also valid with a non-nullable DateTime parameter:

DateTime theDate = listOfDates.FirstOrDefault();

Of course, once you change this, ReSharper picks up on the fact that (theDate != null) is always true.

But I still want to handle the intended case, or at least what I assume to be the intended case. The way to do this (while still using FirstOrDefault()) is as follows:

DateTime theDate = listOfDates.FirstOrDefault();

if (theDate != default(DateTime))
{
    //somecode
}

August 30th, 2012

Why you get code sprawl

I’m working on a project right now, and I need to fetch a particular object from the database. Unfortunately, the method I need doesn’t exactly exist, despite the fact that the object is stored in the database and has a strongly-typed class that defines it.

I have to sit here and figure out exactly how to use the existing code to fetch the object I need and use it the way I want. Realistically, I’m going to have to either a) modify the existing code to make it generic enough to satisfy its existing purpose as well as my own, or b) write new code to fetch the object in the way I need it.

The fact that I’m facing this decision is exactly the kind of scenario that leads to code sprawl. In fact, I’m sure that this has already happened in our current code base, for this exact reason. I see stored procedures and methods all over the place that perform similar  — but not identical — retrievals of the same information.

So, how do you get out of this pattern?

Well, the answer is pretty straightforward: when you realize you’re about to write code that does something very similar to another piece of code, find a way to combine those functions into a single unit of code. Of course, this is downright scary to do if your code isn’t well-covered by tests. You know, because Murphy’s Law.

But, if you want your codebase to improve and be easier to work with, then it’s worth finding the time to make these kinds of changes. Furthermore, it’s best to make those changes right when you find the issue, because the same reason the earlier developer didn’t make the code generic enough at the outset is the same reason you won’t come back and do it later: you won’t have enough time or clarity to do it in the future.

Over time, these small changes improve the codebase and make it easier to work with, thereby improving the team’s productivity. It just takes a little bravery — and a little brevity — to accomplish it.


May 7th, 2010

Debug Windows services in C# using reflection

[This example is for .NET 3.5 and Visual Studio 2008]

I recently had to fix a bug in a Windows service written in C#. Unfortunately, Windows services are not straightforward to run in debug mode. This led me to try two solutions that I found lacking. I ended up using a relatively simple and flexible method involving reflection. I will provide some sample code below to help you use this in your own projects.

Option 1: the Microsoft way (inconvenient)

Microsoft’s official recommendation is to install the service and then attach the debugger to the service. While this is the best way to monitor a live service, it has two drawbacks when it comes to development: 1) you need to reinstall the service each time you want to debug, and 2) “you cannot debug the code in the service’s OnStart method this way”. Note that Microsoft does offer a workaround for the latter problem, though I find it to be rather inconvenient:

[...] create a temporary second service in your service application that exists only to aid in debugging. You can install both services, and then start this “dummy” service to load the service process. Once the temporary service has started the process, you can then [...] attach to the service process.

After trying this method, I ended up getting frustrated by the extra work involved and chose a simpler, but less maintainable, solution.

Option 2: run the service as an application (unmaintainable)

What ended up working for me (for a while, at least) was converting the project into a console application, with the service code being called from Main(). I successfully used this method to find the cause of the error and test my fix. I also used this method to make enhancements to the service.

However, it was only when I was making frequent check-ins that I spotted my problem: it took effort to make sure that I kept the repository’s version as a service and my own version as an application. It shouldn’t take that much effort to keep code synchronized.

So, while this method allows you to debug a service without first installing it, as well as debug the OnStart method, it doesn’t make for a maintainable solution. After learning about reflection, I found a better way.

Option 3: writing a test application using reflection

This method is based on reflection’s ability to invoke non-public members from outside of the target application. The basic idea is to create a second application that initiates the service.

Here’s how you can set this up for yourself.

First, create a Windows Service project. Visual Studio will automatically generate some code for you. Note the OnStart and OnStop methods, inherited from ServiceBase. These get called by Windows when the service is started and stopped, respectively; you will need to call these methods when you simulate running the service.

using System;
using System.ServiceProcess;

namespace TestableWindowsService
{
  public partial class Service1 : ServiceBase
  {
    public Service1()
    {
      InitializeComponent();
    }

    protected override void OnStart(string[] args)
    {
    }

    protected override void OnStop()
    {
    }
  }
}

Once your service is set up, create a new Console Application in the same solution. You will need to add a reference to the service project, as well as a reference to System.ServiceProcess (available under the .NET tab in the Add Reference… screen).

There isn’t much code you have to write to simulate calling the service, but it’s worth explaining.

Service1 service = new Service1();

Initiate the service so we can call its methods.

Type service1Type = typeof (Service1);

This is the key to reflection. Once we have the Type for the class, we can use reflection to access its methods and properties at runtime.

MethodInfo onStart = service1Type.GetMethod("OnStart", BindingFlags.NonPublic | BindingFlags.Instance);

Here we use the GetMethod method to search for the method we want. The BindingFlags are important because OnStart is an instance method that is protected. Setting these flags ensures that these types of methods are included in the search. If the method isn’t found, null is returned.

onStart.Invoke(service, new object[] {null});

This is where we actually call the method. The method is called using the service object created above. The second argument to this method is the string[] parameter required by OnStart. Note that this cannot be set to null if there is a parameter in the method signature.

At this point, we have effectively started the service. If there is any code in your service’s Program.Main method that is supposed to run, you would call that now. Note that you can’t actually call the Program.Main method because it will try to start the service, which you can’t do from within Visual Studio.

MethodInfo onStop = service1Type.GetMethod("OnStop", BindingFlags.NonPublic | BindingFlags.Instance);
onStop.Invoke(service, null);

This code will stop the service. Since OnStop doesn’t have any parameters, null is used for the second argument. Depending on how your service is configured, you may not actually need to call this (since the TestApplication will kill the service anyway at this point).

using System;
using System.Reflection;

namespace TestableWindowsService
{
  class TestProgram
  {
    static void Main()
    {
      Service1 service = new Service1();

      Type service1Type = typeof (Service1);

      MethodInfo onStart = service1Type.GetMethod("OnStart", BindingFlags.NonPublic | BindingFlags.Instance);
      onStart.Invoke(service, new object[] {null});

      MethodInfo onStop = service1Type.GetMethod("OnStop", BindingFlags.NonPublic | BindingFlags.Instance);
      onStop.Invoke(service, null);
    }
  }
}

When you build and run the test application in debug mode, you will be able to step through your service code without going through the trouble of installing the service and attaching the debugger.


June 30th, 2009

How to close the last/only tab in Firefox 3.5

I recently downloaded the latest version of Firefox. I quickly discovered that one of my favourite features was gone: the ability to close a tab if it’s the only one open.

It’s turns out that the feature isn’t missing; it’s just no longer enabled by default. I figure this makes sense since a fresh install of Firefox doesn’t show the tab bar at all for a single tab.

Anyway, here’s how to do it, just so you don’t have to mess around with the options to figure it out (like I did):

  1. Open about:config.
  2. Set browser.tabs.closeWindowWithLastTab to false.

And that’s all! Back to “normal” browsing.

EDIT: Looks like I beat mozillaZine by about 4 minutes on this. They now have a longish thread discussing this exact topic.


June 15th, 2009

Trusting your users is hard for you, but good for them

Default options should handle the most common, most trustworthy case.

Gmail got this right when they stopped asking for confirmation for users’ actions and started allowing people to undo them instead. For example, most of the time, I am sure I want to trash that email, so asking for confirmation does nothing for me; my default action becomes to auto-confirm, since it’s what I do most often. Ben Bryant has a good post on how trust worked for Wikipedia. And to quote Neil Davidson on avoiding the real problems: “don’t create rules for the many based on the sins of the few”.

When I built the prototype for my cell phone bill analysis tool, I had an item pretty high up on my list of core features to have user accounts. When I got to it, I titled my head to the side and let out a nice long “Hehhhnh?”. I realized that it really didn’t make much sense. If people wanted to come and try the service, having to register is a pain. I can’t even list off the apps – free or paid – that I wanted to try out once but stopped when I had to register. Seriously, it’s really, really annoying.

So I asked myself: “Why would people want to register?” The only answer I could come up with was that they might want to save their bill data and come back at a later date. I figured most people wouldn’t be doing that to start, so user accounts dropped priority, and I instead implemented persistent temporary sessions.

Apparently, Jason Kester feels the same way:

Our stated goal with Twiddla is to get the hell out of your way so that you can get some work done. We’ve taken that idea so far that most of our users will never see a login screen of any description. Some might not ever know they’ve used Twiddla at all, since we keep our Logo hidden away in the corner where it’s not in your way.

That’s a great example of putting your users first. Registering for a service is a hassle for the user, and that’s something that’s true whether there’s a good reason for registration or not. Maybe capturing a user’s information helps you market to them down the line. Maybe capturing a user’s information makes it easier for you to personalize the user’s experience. It doesn’t matter though. It’s not your choice. It’s the user’s choice.

And respecting a user’s choice is a great way to get them to trust you with their money.