Monthly Archives: December 2007

Easily Unit Testing Event Handlers

In C#, If you need to unit test a class that fires an event in certain circumstances (perhaps even asynchronously), you need to handle a little more than just running some code and doing the assertion. You have to make sure your unit test waits for the event to be fired. Here’s one naive way of doing it, a WRONG way:

   1: private bool statsUpdated = false;
   2: private ManualResetEvent statsUpdatedEvent = new ManualResetEvent(false);
   3:
   4: [Test]
   5: public void CheckStats()
   6: {
   7:     BrickDatabase db = new BrickDatabase(tempFolder, maxCacheAge);
   8:
   9:     statsUpdated = false;
  10:     statsUpdatedEvent.Reset();
  11:
  12:     db.InventoryStatsUpdated += new EventHandler(db_InventoryStatsUpdated);
  13:     db.DoSomethingThatFiresEvent();
  14:
  15:     statsUpdatedEvent.WaitOne();
  16:
  17:     Assert.IsTrue(statsUpdated);
  18: }
  19:
  20: void db_InventoryStatsUpdated(object sender, EventArgs e)
  21: {
  22:     statsUpdated = true;
  23:     statsUpdatedEvent.Set();
  24: }

There are a number of things wrong with this:

  1. The class variables. More complex unit test class. Have to coordinate these variables across multiple functions.
  2. Since they are class variables, you will want to reuse them, but you’d better remember to reset the event and the boolean every time!
  3. Have to have two functions to do something really, really simple.
  4. The WaitOne() does not have a timeout, so if the wait is ever satisfied then statsUpdated is guaranteed to be true.

Here’s a better way of doing it, using anonymous methods in C# 2.0:

   1: [Test]
   2: public void CheckStats()
   3: {
   4:     BrickDatabase db = new BrickDatabase(tempFolder, maxCacheAge);
   5:     bool statsUpdated = false;
   6:     ManualResetEvent statsUpdatedEvent = new ManualResetEvent(false);
   7:
   8:     db.InventoryStatsUpdated += delegate
   9:     {
  10:         statsUpdated = true;
  11:         statsUpdatedEvent.Set();
  12:     };
  13:
  14:     db.DoSomethingThatFiresEvent();
  15:
  16:     statsUpdatedEvent.WaitOne(5000,false);
  17:
  18:     Assert.IsTrue(statsUpdated);
  19: }

Improvements?

  1. The event is just part of the method. Since the event handler is an anonymous delegate, it can access the enclosing method’s local variables.
  2. Added 5,000ms timeout to the WaitOne() function to prevent hanging of unit tests.

Infinity – Infinite Energy

Power. Electricity. The Holy Grail of modern technology.

I say this because the information revolution completely depends on electricity, whether it’s batteries, hybrid motors, or the grid. Everything we do depends on converting some naturally occurring resource into power to drive our lives.

I was thinking about power recently while watching an episode of Star Trek: The Next Generation. Everything they do depends on an infinite (or nearly so) source of energy. Their warp core powers the ship for a 20-year mission. Each device they have is self-powered. From what? Do they need recharging? I imagine not, but it’s been a while since I’ve read the technical manual.

In any case, much of that world (and other Sci-Fi worlds) depends on powerful, long-lasting, disconnected energy sources. For one example, think of the energy required to power a laser-based weapon. And it has to fire more than once.

The truth is that having such a power source is more than world-changing. It has the potential to completely rebuild society from the ground up. If you think about it, much of the world’s conflict is over sources of energy. Authority and power is derived from who controls the resources. If energy was infinitely available, it would be infinitely cheap (at least in some sense). I almost think it would change society from being so focused on worldly gain, to more on pursuit of knowledge, enlightenment, and improvement. We wouldn’t have to worry about how to get from one place to another, or who has more oil, or what industries to invest energy resources in. So much would come free.

When I speak of “infinite” power, don’t take it literally. What I mean is “So much to be practically unlimited.”

Of course there are different types of infinities:

  1. Infinite magnitude – Can produce any amount of power you desire. Not very likely. Something like this would be dangerous. “Ok, now I want Death Star phasers. ok. Go.” Boom.
  2. Infinite supply – There’s a maximum magnitude in the amount of power it can generate, but it can continue “forever” (or at least a reasonable approximation of forever). This is the useful one.

And there are a few other requirements we should consider:

  1. Non-destructive. Environment. Mankind, etc.
  2. Highly-efficient.
  3. Contained and controlled. Obvious.
  4. Portable. Sometimes microscopically so.

It’s nice to dream about such things…

  • Cell phones and Laptops that never need recharged
  • Tiny devices everywhere that never need an external power source (GPS, sensors, communications devices, robots, etc.)
  • Cars that do not fuel. Ever. We’d probably keep them a lot longer. They could do more, be larger, more efficient, faster, safer.
  • Vehicles that can expand the boundaries of their current form. How big can you make an airplane if you don’t have to worry about using up all its fuel? (not to mention the weight)
  • Easier to get things into orbit–space program suddenly becomes much more interesting. Maybe we can develop engines that produce enough power to escape gravity, without using propellant (a truly ancient technology).
  • Devices that can act more intelligently, and just do more than current devices. Think if your iPod that turns itself off after a few minutes of not using it. That scenario would be a thing of the past.

With such a power source the energy economy of devices that we have to pay such close attention to now goes out the window. Who cares how much energy it uses if there’s an endless amount to go around (and since we’ve already established that the energy source is non-destructive and highly-efficient, environmental factors don’t enter in). There would be no need for efficiency until you started bumping up the boundaries of how much power you needed.

del.icio.us Tags: ,,

Infinity – Infinite Storage

Anybody who’s taken high school or college mathematics know how phenomenal exponential growth is. Even if the exponent is very, very small, it eventually adds up. With that in mind, look at this quick-and-dirty chart I made in Excel, plotting the growth in hard drive capacity over the years. [source: http://www.pcguide.com/ref/hdd/hist-c.html]

Hard Drive Capacity Graph

Ok. it’s ugly, but notice a few things:

  1. The pink denotes the data points from the source data or what I put in (I added 1000 GB in 2007).
  2. The scale is logarithmic, not linear. Each y-axis gridline represents a ten-fold increase in capacity.
  3. At the current rate of growth, by 2020, we’ll have 1,000,000 GB hard drives. That’s 1 petabyte (1PB). (by the way, petabyte is not in Live Writer’s spelling dictionary–get with the times Microsoft!)
  4. The formula, as calculated by Excel, says that the drive capacity should double roughly every 2 years.

Also, this doesn’t really take into account multiple-hard drive storage schemes like NAS, RAID, etc. Right now, it’s quite easy to lash individual storage units together into packages such as those for more space, redundancy, etc. I’ll ignore that ability for now.

So 2020: that’s 12 years from now. We can expect to have a petabyte in our computers. That’s a LOT of space. Imagine the amount of data that can be stored. How about every book ever written? How about all your music, high-def DVDs, ripped with no lossy compression?

Tools such as Live Desktop and Google Desktop take on a whole new level of importance when faced with the task of cataloging petabytes of information on your home PC. Because, let’s face it, you’ll never delete anything. You’ll take thousands of pictures with your digital camera and never delete any of them. You’ll take hours of high-def footage and never watch or edit them, but you’ll want to find something in them (with automated voice recognition and image analysis, of course). Every e-mail you get  over your entire lifetime can be permanently archived.

What if you could get a catalog of every song ever recorded? That would probably require more than a few petabytes, even compressed, but we’re heading that way. I don’t think the amount of music in the world is increasing exponentially, is it? Applications like iTunes and Window Media Player, not to mention things like iPods, would have to have a critically-designed interface to handle the organization and searching for desired music. I think Windows Media Player 11 is incredible, but I don’t think it could handle more than about 100,000 songs without choking–has anyone approached any practical limits with it?

What about the total information in the world–that probably is increasing exponentially.  Will we eventually have enough storage so that everyone can have their own local, easily searchable copy of the vast sum of human knowledge and experience? (Ignoring the question of why we would want to)

Let’s extrapolate this growth out 100 years to the year 2100. I won’t show the graph, but it approaches 1E+20 GB by the year 2100.

How do the economics of digital goods change when you can have an infinite number of them? It’s the opposite of real estate, an ever-diminishing good.

On my home PC, for  the first time, I do have a lot of storage that isn’t being used. I have about 1 TB of storage, and about 300 GB free. I suppose I could rip all my DVDs, rip all my music at lossless compression (it’s currently all WMA / 192Kbps).

The rules of the game can change quickly when that much storage is available. It will be interesting to see what happens in the coming decades. Of course, all this discussion is completely ignoring the increasingly connected, networked world we live in.

del.icio.us Tags: ,,,

20 Things to do when the Internet goes down

Even if the Internet connection goes out, your computer does not become a dumb brick. There were days these last few days where I didn’t bother turning it on. Then I realized all the things I could still do.

(My home Internet connection finally came back this morning. I’m bit upset that they didn’t figure it out earlier. It turned out that the first technician grossly misdiagnosed the problem. He put in an order for a new drop to be put in. Turned out it was just a broken modem. Why didn’t they try that earlier? Worse, why didn’t I think of it earlier. To be honest, I did think of it, but didn’t push it. Now I just need to get my money back from Comcast.)

Without further ado, here’s my suggestions for what to do when the Internet goes out:

On the computer:

  1. Organize photos in Picasa – I have nearly 6,000 photos on my computer. Many of them need to be deleted, organized, tagged, labeled, e-mailed, etc. (Yes, e-mailed–I can queue them in Outlook until the connection comes back).
  2. Organize My Documents – I’ve let My Documents folder get very messy. Lots of files that don’t need to be there anymore. Others need to be filed, or re-filed.
  3. Organize e-mail – I’ve got hundreds of folders in Outlook. I’ve tried to keep my Inbox empty and put things into @Action, @Someday, or @WaitingFor folders before they find a permanent home, but sometimes it still gets out of hand.
  4. Organize and fill in information in Windows Media Player. I still have music tagged with the wrong genre…
  5. Program. I’ve got two major programming projects I’m working on. They don’t depend on the Internet. The Internet is NICE if you need to learn something, but there’s always plenty of stuff to do that doesn’t require it. Write unit tests, run code coverage, design graphics, do all the other stuff if you must.
  6. Write e-mails to family. Long ones. Your mom will thank you.
  7. Catch up on podcasts. I got through ten episodes of Ask a Ninja, and nearly all backlogged podcasts. Now I’ll have a flood when I sync tonight.
  8. Write blog entries. I use Windows Live Writer. I should have done more of this.
  9. Play a game.
  10. Better, write a game.
  11. Setup appointments and events in Outlook for the next year.
  12. Read some classic programming texts.
  13. General computer maintenance. Defrag your disk, delete temp files, delete old installation files you haven’t used in 5 years (yes, I have some of those…). Use DiskSlicer to find where your space is going.
  14. Do long-avoided projects. I have approximately 20 hours of audio I need to edit and split into tracks. I’ve been putting it off for a very long time.

Off the Computer:

  1. Practice the piano.
  2. Read books. I’ve just started Cryptonomicon by Neal Stephenson. Very good, so far. Go buy it. If you’re a geek, you’ll like it. How can you not love a 2 page diversion into the mathematics of when a bike chain will interfere with a broken spoke and fall off? Other than the geekiness, it’s a good story.
  3. Learn to cook a new dish.
  4. Do crosswords.
  5. Exercise.
  6. Relax.

Or just go to the library and use the Internet. I only did this a few times, despite it being within walking distance from where I live.

Technorati Tags: ,,,,,,

BugTracker.Net

I’ve been meaning to write about this software for a while. When I started my current job, all software development was done by an outside contractor. I quickly took over, and that necessitated implementing a lot of tools and procedures to handle our large C++ and C# code base.

Choosing Subversion for source control was easy–free, open source, better than VSS and CVS.

Bug tracking software was a little harder. There are a lot of packages out there. I eventually decided on a great little package called BugTracker.Net. It’s written by a gentleman named Corey Trager who does it in his spare time. It’s a very simple system, and doesn’t provide a lot of the heavy-weight features of more complete packages, but if you’re a small team (like I’m in), then it could be perfect. I really appreciate Corey’s web-site, because he acknowledges that it’s not written with every scenario in mind. In fact, he even publicizes comparisons of his system with other popular tracking systems out there.

That said, there is a good degree of customizability in it, and it really was easy to setup, upgrade, configure, and customize.

Some of the features:

Suitable for tracking helpdesk customer support tickets as well as software bugs.

Sending and receiving emails is integrated with the tracker, so that the email thread about a bug is tracked WITH the bug.

Allows incoming emails to be recorded as bugs. So, for example, an email from your customer could automatically be turned into an bug/ticket in the tracker.

Allows you to attach files and screenshots to bugs. There is even a custom screen capture utility [screenshot] that lets you take a screenshot, annotate it, and post it as a bug with just a few clicks. (inspired by Fogbugz)

Add your own custom fields.

Custom bug lists, filtered and sorted the way you want, with the columns that you want.

You can display bugs of a certain priority and/or status in a different color, so that the most important items grab your attention.

Configure different user roles to see different lists of bugs. For example, a developer might see a list of open bugs. A QA analyst might want to see a list of bugs ready for testing.

(and more…)

Like I said, if you’re a small team that just needs to coordinate on issues, this platform could be perfect.

(BTW, this is not a sponsored post–I just want to point out some software that I like).

Don’t delay your merging

Another one of those lessons learned posts. I know I’m supposed to merge changes across branches often to minimize the pain, but I didn’t do it.

Here’s the scenario: We’ve got 3 development branches: 6.3, 6.4, and 7.0 (the trunk). 6.3 and 6.4 are technically maintenance branches because we didn’t anticipate needing to them, but we are. Here’s where it gets funny. 6.4 is actually a branch off of 7.0 with some new features removed. 6.4 is the code base converted to handle unicode. 6.3 is the current development version, and it’s features need to be merged into 6.4 These two branches are rather divergent in places. It’s been months since the branches were synchronized. In addition to 20 conflicted files, the 13 localized resource DLLs can’t automatically be merged because their location changed. Yeesh…

So now I’m spending all day using DiffMerge to do these files. Not a fun day…

Lesson learned. Do frequent merges.

At least it’s Friday. Tomorrow, my wife and I are heading down to North Carolina to visit my grandmother before she heads to California for Christmas.

By the way, still no Internet at home. Comcast says it could be 28 days before the local construction company gets around to installing the new drop to our home. I’ve been getting a lot of piano practice and reading in.

San Francisco Restaurants – Dining Guide

We have another sponsor! MyChoyce.com is a free dining guide for  the San Francisco area. And wow. It’s nice. I am really wishing something like this existed for the Washington, DC metro area. The site is attractive, easy to use. And they have menus! Awesome.

You can search and filter by food, services, location, price. I’ve used a few restaurant locaters, with varying results, but so far I like this one the best. If you live in the bay area, check them out. If you’re a restaurant owner–I would get onto this site fast.

Thanks to them for their sponsorship, and if you know somebody who would like a little bit of extremely affordable publicity, send them to BuyMeALego.com!

Technorati Tags: ,,