The Big Rewrite

I know the big rewrite is almost never the right answer, but in the case of a stalled hobby project that started a year ago with Linq to SQL, ASP.NET MVC 1.0, then maybe it’s okay. 🙂

I’ve decided to start again totally from scratch. This is for a few reasons:

  • I want to start again using ASP.NET MVC 3 with Razor view engine, and make use of the many other improvements.
  • I want to use EF code first, rather than Linq to SQL.
  • I attended DDD9 today, and saw a session with a lot of useful information about CQRS that I want to try and apply here.
  • I want to remove the product name from the code. I think I’ll still be branding it as “Workflo”, but since I have this overall idea of a project called “Genrsis” that’ll include other products, the root namespace for this particular product will probably be something more abstract like “Genrsis.WorkItemTracking”.
  • I want to host this project on codeplex.
  • There is a lot of stuff I can reuse from the old code: my custom ASP.NET MembershipProvider, logo, CSS etc.

So I’m going to get started on this now. The sooner I can start dogfooding the better. 🙂

Yet Another Bug Tracking System

Other titles I thought of included “If you build it, they will come” and “Building a better mousetrap”.  What can I say, SEO isn’t a skill of mine.

I needed a hobby project that was a thought experiment (which is my caveat for all my bad architectural decisions) that could go somewhere.  That wasn’t just a name and a few lines of half-finished code.  Something that I could take on a laptop to job interviews in the future and say “No, I can’t actually work out an algorithm on the spot that calculates the distance in yards from London to Calais, but look at this neat thing I’ve done…”.  Not that I’m looking for work right now, but it’s good to have something to show for one’s skills that one owns the IPR to.

Amongst other things, I wanted to try ASP.NET MVC (which was v1 at the time), jQuery and Linq to SQL (I know it’s out of date now, but I have my reasons…).

I decided to be different, and write a bug-tracking system.  My motivation came in the form of difficulties using FogBugz at work.  FogBugz is very capable, but only if you use it the way the guys at Fog Creek expect you to – which means conforming to the way they think bug tracking should be done.  We’re trying to use it in a different process than it was designed for, and it’s caused friction.  Being the jumped-up know-it-all that I am, I thought I could do better (well, different) so, full of Great Ideas, I started planning.

This was many months ago.  I’ve put quite a few hours in here and there.  Probably a few weeks FTE.

Then yesterday I deleted much of the code I’ve written.  I’ve kept infrastructure stuff (like ASP.NET Membership providers – yuck!), but basically this is a re-write of what little I’d actually managed to create.

I’ve learnt much with my tinkering over the last year, but now I’m going to give it a proper go.  Hopefully this may even end up as something we can use at work.  It’s called “Workflo”.  Yes, I know that name exists but I have a project codename to put it under and “Buggr” just didn’t seem appropriate.  It has few key features:

  1. A fully-customisable workflow.  Not using MS Workflow Foundation, but something home-grown (it’s a thought-experiment, see).
  2. Estimates and time-tracking per status.  So developers estimate the development, testers estimate the testing, etc etc.  Then you see how long those things actually took and do amazing reports like how good people are at estimating, either for themselves or on behalf of others, and break down how much effort goes into testing vs. actual coding.

That’s kind of it, for now.  I have lots of wonderful ideas floating around, and the plan is to use this blog to chronicle the various design decisions and implementation tribulations as they happen.  Hopefully I will learn something, even better would be to teach something.  We’ll see.  I’ve got a little more re-jigging to do, and then I’ll be posting the code on Codeplex.

Wish me luck!

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 🙂