Poor man’s KVM

I have two PCs but one keyboard and monitor. Rather than shell out for a KVM, I plugged each PC into a different port on the monitor, and use the menu to switch between them.

For the keyboard I put a USB extension lying on the floor near the main PC, and I just get on my knees to swop the keyboard between it and the back of the main PC.

I don’t need to do this too often, so it works quite well enough for me. 🙂

Unit testing with DateTime.Now

Unit testing time sensitive code can be tricky because unit tests should be 100% repeatable, and the same each time.  The system clock will never be the same each time the test is run, so it’s difficult to assert time-dependant values.

This has been talked about before.  Probably most notably by Ayende on “Dealing with time in tests”.  However I have a slightly different take on the situation.

Sometimes you have code that depends on the time moving on, so a static clock with a fixed time value is of no use (say for example generating some unique key values based partly on the current time).

What I want is at the top of a test to “start the clock” once, where it will then continue to act like a clock from then on.  I solved this problem as many people do – by providing a layer of abstraction from the system clock:

public interface IDateTimeProvider
{
    DateTime Now { get; }
}

The default implementation is as follows:

public class DefaultDateTimeProvider : IDateTimeProvider
{
    public DateTime Now
    {
        get { return DateTime.Now; }
    }
}

This allows classes such as this (I use Castle Windsor to wire the dependencies up when not in unit tests):

public class MyTimeDependentService
{
    public IDateTimeProvider DateTimeProvider { get; set; }

    public MyTimeDependentService()
        : this(new DefaultDateTimeProvider())
    {
    }

    public MyTimeDependentService(IDateTimeProvider dateTimeProvider)
    {
        DateTimeProvider = dateTimeProvider;
    }

    public void MyTimeDependentMethod()
    {
        var now = DateTimeProvider.Now;
        // Do stuff with the current time.
    }
\

It’s a bit more heavy-handed than Ayende’s solution, but the treacle is in the implementation of the test datetime provider:

public class TestDateTimeProvider : IDateTimeProvider
{
    private readonly DateTime initial;
    private readonly DateTime created = DateTime.Now;

    public TestDateTimeProvider(DateTime initial)
    {
        this.initial = initial;
    }

    public DateTime Now
    {
        get { return initial + (DateTime.Now – created); }
    }
}

The big win here is that you can set the “start time” of the test.  As long as you assert the current values of the datetime provider etc against the results of the method calls, you should be okay.  I realise there could be inconsistencies depending on how long the tests take to run etc, but a lot of that can be mitigated by being careful obtaining the time only once at the top of a method and referring back to it each time as in my example.

HTH. 🙂

Rounding a Date/Time to the nearest 15 minutes in Microsoft Office Excel

So this is an easy trick that’s hard to actually remember the details for if you have a non-mathematical brain like mine.  If you have to do a bit of analysis and turn to Excel for help (which I seriously recommend), then this formula is very useful to round date/times to the nearest quarter hour for aggregation/pivottable purposes:

Given that a date/time of “19/01/2010 15:57” exists in cell B5:

=DATE(YEAR(B5), MONTH(B5), DAY(B5)) + TIME(HOUR(B5), ROUND(MINUTE(B5) / 15, 0) * 15, 0)

Will give you “19/01/2010 16:00:00”.

Of course you can do the same in C#:

using System;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            var unrounded = new DateTime(2010, 05, 07, 15, 23, 0);

            Console.WriteLine(“{0} rounds to {1}”, unrounded, unrounded.ToNearestQuarterHour());

            Console.ReadLine();
        }
    }

    public static class DateTimeExtensions
    {
        public static DateTime ToNearestQuarterHour(this DateTime input)
        {
            return new DateTime(input.Year, input.Month, input.Day, input.Hour, (int)(Math.Round(input.Minute / 15D) * 15), 0);
        }
    }
}

And yes, I know that isn’t clever enough to take seconds and milliseconds into account with the rounding, but it did what I needed so let’s say that’s an exercise for the reader, eh?

Recovering deleted branches in Subversion

If, like me, you delete a branch in Subversion (SVN) that later on you realise you actually still need, you don’t need to panic.

In my case, I deleted a couple of feature branches I thought had been merged into the release candidate but hadn’t.  Thanks to my friend and colleague Damian, I managed to get them back without waiting for hours of checking out the parent folder full of other feature branches.  Here’s how I did it using TortoiseSVN:

  1. Perform a sparse checkout of HEAD revision of the folder that used to contain your branch(es).  I.e. for svn://svn.mycompany.com/branches/features/case4321 you should checkout svn://svn.mycompany.com/branches/features.  To make it sparse, in the Checkout Dialog you should select “Immediate children, including folders” from the Checkout Depth dropdown.
  2. Use the Revision Log to find the revision immediately before the one where you deleted the branch.  Repeat step 1, but instead of HEAD, sparse checkout that revision.  For this example let’s call it revision 1024 because that’s a nice round number.
  3. In Windows Explorer you should now have two sparse working copies for same URL but different revisions.  One will contain the deleted branch (r1024), the other will not (HEAD).
  4. Right-click and drag the folders representing the branches you want back from the r1024 working copy to the HEAD one. You’ll get a context menu, from which you should choose SVN Copy Versioned Item(s) Here.
  5. Now commit the HEAD working copy and review in the Repository Browser.  All should be well!

Thanks again to Damian for sorting this out!

Getting data from a WinForms DataGridView

Now, I know this is out-of-date tech these days, but there’s a lot of it about (indeed, I’m working on it right now), so this may be of some use.

It’s tempting when getting data from a DataGridView to get the data from the cells, like so:

if (dataGridView1.SelectedRows.Count == 0) return;
string employeeName = (string)dataGridView1.SelectedRows[0].Cells[4].Value;

However, it’s far better to work with the data that is bound to the grid instead, like so:

if (dataGridView1.SelectedRows.Count == 0) return;
CrmDataSet.EmployeeRow selectedEmployeeRow = (CrmDataSet.EmployeeRow)((DataRowView)dataGridView1.SelectedRows[0].DataBoundItem).Row;
string employeeName = selectedEmployeeRow.EmployeeName;

Now you get the benefit of refactoring tools like Resharper, and you don’t need to worry about future layout changes (like adding/removing/rearranging columns) from breaking your code.

In fact, I’ve written this up as a little extension method, since it’s fairly common.  Let me know what you think in the comments:

using System.Data;

namespace System.Windows.Forms
{
    public static class DataGridViewExtensions
    {
        public static TRow GetSelectedRow<TRow>(this DataGridView grid, int index)
            where TRow : DataRow
        {
            var selectedRow = grid.SelectedRows[index];
            var selectedTypedRow = (TRow)((DataRowView)selectedRow.DataBoundItem).Row;
            return selectedTypedRow;
        }
    }
}

You’d use it like this:

var selectedEmployee = dataGridView1.GetSelectedRow<CrmDataSet.EmployeeRow>(0);

Resharper + INotifyPropertyChanged

I’ve created a handy Resharper Live Template to make creating a class that implements INotifyPropertyChanged a little easier.  To implement it, do the following:

1.  Create the live template

  1. Click Resharper->Live Templates….
  2. On the Template Explorer dialog Live Templates tab, click New Template.
  3. Enter “nprop” as the Shortcut and “INotifyPropertyChanged property” as the Description.
  4. Copy/paste the following into the template:

    private $TYPE$ $FIELDNAME$;
    public $TYPE$ $PROPERTYNAME$
    {
        get { return $FIELDNAME$; }
        set
        {
            bool changed = value != $FIELDNAME$;
            $FIELDNAME$ = value;
            if (changed) InvokePropertyChanged(new PropertyChangedEventArgs(“$PROPERTYNAME$”));
        }
    }

  5. In the macro settings, leave “TYPE” as “choose macro”, set “FIELDNAME” to “Suggest name for a variable” and “PROPERTYNAME” to “Value of FIELDNAME with the first character in uppercase” and “not editable”.
  6. Save settings and close Live Templates windows.

2.  Using the live template

  1. Create a class that implements INotifyPropertyChanged:
  2. public class Employee : INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;
    }

  3. Put the cursor on the PropertyChanged event name, and use the Resharper Actions List (ALT+ENTER) to generate an event invocator:
  4. public class Employee : INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;

        private void InvokePropertyChanged(PropertyChangedEventArgs e)
        {
            PropertyChangedEventHandler changed = PropertyChanged;
            if (changed != null) changed(this, e);
        }
    }

  5. Inside the class, rather than manually typing in a property by hand, invoke the live template by typing “nprop”, then pressing TAB.
  6. The live template will create a property with a backing field for you, and the code necessary to invoke the event:
  7. Type the TypeName of the property, press TAB, then type the field name of the property.
  8. Press ENTER when you are done, rinse, and repeat as necessary.

Hope you find it useful.  Here’s a short video of it in use: INotifyPropertyChanged Resharper Live Template video.

Keeping an empty email inbox

You may have heard of Getting Things Done (GTD).  I don’t know it well, but I’ve tried to apply a bit of it to the way I deal with emails.  Once upon a time I had deep, complex folder structures in Outlook to keep my email “tidy”.  Since starting to use Gmail for personal emails though, I’ve decided I want to avoid the time spent “filing”, and process emails in one of three categories:

  1. “Do something”.
  2. “Be aware of/remember something”.
  3. “Not needed”.

I’ve recently been asked by a colleague what my actual process is, so I thought I’d share it here in case it’s useful for anyone else that would like to simplify the way they deal with their emails.

Aim

  • Quickly deal with incoming emails.
  • No time spent on "filing" – be more like Gmail.
  • Make it easy to see what you have outstanding actions for, and hard to lose them and forget.
  • Make it easier to find things by using searching, sorting, filtering rather than rummaging through a complicated folder hierarchy.

Setup

  • Enable and increase the delay on Outlook desktop toast notifications.
    This means the toast popup will stay on the screen for longer, letting you at least finish the sentence you’re writing without worrying about it disappearing before you get to it.
  • Create "Inbox Archive" folder in the root “Mailbox – [Username]” folder.
    This is where all emails that you do decide to keep will end up.

Getting Started

This is the bit you won’t like, where I make you undo years of hard filing work.  Do it though; you’ll feel better for it as you loosen the email filing shackles!

  • Move any and all emails that are "helpfully" sorted into various folders into the Inbox Archive folder and delete the folders they were in.
  • Go through the Inbox previewing every email and clicking the flag column on anything that needs something doing by you.  Don’t cheat – this shouldn’t take long because you’re just going down the list quickly.
  • Sort by "flagged" and move anything that’s not flagged to the Inbox Archive folder.
  • Re-sort by "Arranged by date".

You should now only have things in that require you to perform an action or compose a reply.  Lovely!

New Email Workflow

The aim here is to try and deal with emails from the “toast” popup in Outlook as they arrive in the same way you might approach an exam paper – do the quick ones first, knowing you’ll come back to the harder ones later.  The toast window contains useful buttons: Flag and Delete, as well as the ability to click on the popup to see the message in full.  All without actually opening the main Outlook window (something I try to avoid doing).

  • If you can immediately tell you don’t need it (e.g. spam or webinar adverts you don’t have time for), click the delete button.
  • If you immediately know it will take more than two minutes to deal with, click the flag button and go back to what you were doing.
  • Otherwise, click the “toast” popup to see the message in full.
  • If you can deal with it in less than two minutes, do what’s necessary then use the “move to folder…” toolbar button to move it to the “Inbox Archive” folder when you’re done.
  • If you don’t need it, click the delete button.
  • If you need longer than two minutes to deal with it, click the flag button on the toolbar and go back to what you were doing.

Periodically

  • Check there are no un-flagged emails in Inbox – flag or archive as necessary.
  • Deal with some flagged emails, then flag as complete (click the flag column again).

Archiving

Archiving can be done in a few ways:

Drag and drop

You can literally drag and drop emails from your Inbox to the Inbox Archive folder.  I don’t recommend it because it’s easy to accidentally drop them in the wrong place, and you can only do this with the main Outlook window open.

The “Move to Folder” toolbar button

This is available in the Outlook main window, and also in the email window you get when you view an email directly.

A macro

I personally have an “Archive” toolbar button the main Outlook window that I pointed to a customised version of this Outlook VBA macro to move items from one folder to another.  It only saves one mouseclick over the "”Move to folder” button, but does earn me some geek points so if you’re a geek this is what I’d expect you to do.

Going on holiday/long term sick leave

Of course, if you’re going to be away from your email for any significant amount of time (you know what this is based on your current email throughput), then your inbox can overflow while you’re away.  To avoid this, try this tip: create a rule that deletes all incoming email, regardless of sender or content.  Then, setup an out of office reply that tells senders that your emails are being deleted, that you won’t respond, but that you’ll be back on xyz date and they may try again then.  Be sure to offer an alternative contact though, for urgent queries.  There’s a Lifehacker article on creating effective, professional “out of office” replies that I recommend you take a look at.

 

I hope this is useful to someone other than me.  Let me know if it works for you!

Resharper Ninja Tip

If you find a method with deep nested if statements, use a combination of "Invert ‘if’" and "Remove redundant else" from Resharper’s Quick-Fix menu (ALT+ENTER) to flatten it all out nicely. Makes it much easier to "return early" and means you don’t have to worry you’ve screwed up the actual logic too much in the process because R# deals with swopping the boolean logic in the if statements for you.

Here’s a super-contrived example:

Before:

public void MyMethod(string parameter)
{
    if (parameter.Substring(0, 1) == “A”)
    {
        if (parameter.Substring(0, 2) == “B”)
        {
            if (parameter.Substring(0, 3) == “C”)
            {
                if (parameter.Substring(0, 4) == “D”)
                {
                    if (parameter.Substring(0, 5) == “E”)
                    {
                        DoSomethingCool(parameter);
                    }
                    else
                    {
                        throw new ArgumentException(“Parameter[4] is invalid”);
                    }
                }
                else
                {
                    throw new ArgumentException(“Parameter[3] is invalid”);
                }
            }
            else
            {
                throw new ArgumentException(“Parameter[2] is invalid”);
            }
        }
        else
        {
            throw new ArgumentException(“Parameter[1] is invalid”);
        }
    }
    else
    {
        throw new ArgumentException(“Parameter[0] is invalid”);
    }
}

After:

public void MyMethod2(string parameter)
{
    if (parameter.Substring(0, 1) != “A”) throw new ArgumentException(“Parameter[0] is invalid”);
    if (parameter.Substring(0, 2) != “B”) throw new ArgumentException(“Parameter[1] is invalid”);
    if (parameter.Substring(0, 3) != “C”) throw new ArgumentException(“Parameter[2] is invalid”);
    if (parameter.Substring(0, 4) != “D”) throw new ArgumentException(“Parameter[3] is invalid”);
    if (parameter.Substring(0, 5) != “E”) throw new ArgumentException(“Parameter[4] is invalid”);

    DoSomethingCool(parameter);
}

Hope this helps 🙂

TortoiseSVN tip for “blaming” on historical versions

I found this today, and I’m sure the last to realise, but it is helpful.

Most people already know about TortoiseSVN’s blame feature, which gives you a view of the code, with the revision/author against each line:

Example (taken from the TSVN Blame page linked above):

Blame

However, what you might not have known, is that you can right-click in the Revision/Author area for a given line of code, and select Blame Previous Revision.

This will open another TSVN Blame window, with the selected revision’s changes.  You can keep doing this, going back in time to see a picture of the updates that have been layered on a code file.

Of course, this could get a little unwieldy, but if you’re only checking the last few commits, it could prove useful.

Strongly-typed ints

Weird title, no? I couldn’t think of a snappier one, I’m afraid.

I’ve been thinking of a way to ensure that this sort of subtle bug/typo doesn’t happen:

public void MyMethod(int useCaseId)
{
    // Do something with the useCaseId
}

public void SomeOtherMethod()
{
    int userId = 12;
    int useCaseId = 15;
    MyMethod(userId); // Ooops! Used the wrong value!
}

This bug would be hard to find because there’s no compile-time error, and you wouldn’t necessarily even get an exception at run-time. You’d just get "unexpected results".

To resolve this in a simple way, I’ve experimented with using empty enum definitions. Effectively making a user id a data type (without going quite as far as a class or a struct):

public enum UseCaseId { // Empty… }
public enum UserId { // Empty… }

public void MyMethod(UseCaseId useCaseId)
{
   // Do something with the useCaseId
}

public void SomeOtherMethod()
{
   UserId userId = (UserId)12;
   UseCaseId useCaseId = (UseCaseId)15;
   MyMethod(userId); // Compile error!!
}

What d’you think?