Monthly Archives: July 2011

Code and Cuckoos

0
Filed under Cuckoo Clocks, Rants

WP_000163Aside from the obvious connotations of the title, I’m actually talking about real cuckoos here, or rather, cuckoo clocks.

Ages ago, just after we first bought the house we’re in now, I was clearing out the attic space and happened upon an old cuckoo clock. This one was labeled a Schatz 8-day, and I’ve since learned it’s a pretty common German cuckoo, probably from the 50s or 60s. Not really a collector’s piece, but interesting none-the-less.

Of course, there’s no telling how long it had been in the attic before I found it, and, not having time or inclination to do anything with it, I stuck it on a high shelf in the garage and promptly forgot about it. You can see it in all it’s glory as I found it in that first picture.

Flash forward to a few weeks ago. I finished out a second contract with a law firm, doing MSSQL Server tuning and optimization, and had some time, so I decided to clear out the garage.

Lo and behold, that cuckoo was still up on that top shelf. Dusty, but otherwise just as I’d found it almost 7 years ago.

The Old Code

Obviously, it was missing some numerals. The hands were so brittle they snapped when I tried to adjust the time. One of the birds on the front piece was gone, no idea to where. The chains were utterly tarnished. The mechanism was completely dusty and grungy. And the bellows (the parts that actually make the cuckoo sounds) literally disintegrated when I took them out and tried to test them.

WP_000161   WP_000162   WP_000164

However, the mechanism appeared to be all there. Both bellows were there. Both weights were there. I still had the chains and the backplate with the chime, so there were lots of positives.

Refactoring

The first step was getting the mechanism out. Pretty simple, really. The bellows needed to be removed, but they were held in with a single screw and a set nail. The mechanism itself was held in with 4 small screws.

I blew it out with an airgun, but it became clear it needed a full on cleaning. After a little internet research, I found that clock cleaning solution is essentially water, ammonia, and Murphy’s Oil Soap, of which I had all three. Mix it up, soak the mech for a few minutes, wash it out thoroughly and the mech was looking almost new.

WP_000168   WP_000169 

Next, I got online and found a clock store that sold virtually identical parts. 10$ later and I had on order paper for bellows, replacement numerals and a new pair of hands.

Repapering the bellows looks hard, but was quite straightforward. You just have get the folds in the right places. And some glue and clamps later, the numerals and hands were back on and looking MY-T-FINE…

WP_000187   WP_000188

The Build or Buy Decision

At this point, the only thing left was that bird (or lack thereof). I found an auction on eBay selling a virtually identical bird, but at the last minute, I got caught up in, well, life, and completely missed the auction completion. Doh!

Tons of searches and even emails to clock shops turned up nothing. It was becoming clear that this particular decision was being made for me.

Proper Object Inheritance

Obviously, I needed a new bird almost exactly like the original, but in reverse. So, trace and reverse to get this.

WP_000211   WP_000213

I didn’t have any linden wood (the typical Cuckoo clock wood), so some clear pine would have to do. And my carving toolchest is a tad limited.

WP_000215

 

Unit Testing

After a few hours of grinding, whittling and chiseling, I ended up with this.

WP_000216   WP_000218

This was a good enough result that I decided to continue on with the project and finish it out. I had to pick up some modeler’s paints, but I had an airbrush, so I was good on that front.

“Good enough” Engineering

The final result came out pretty reasonable. Not a perfect match, but close enough.

WP_000224  WP_000221 

WP_000220

Post Mortem

So, what does rebuilding a cuckoo clock have to do with developing commercial software?

More than you might think. When you look at cuckoo clocks, or really, mechanical clocks in general, you really come away with the strong conclusion that clockmakers back when were the engineers and programmers of their day. Looking at the complex system of gears, the escapement, and the cams that drive the bellow lifts and gong ringer, it’s not too hard to see a system of subsystems, inputs, outputs, and programmed behaviors.

As programmers, we spend a lot of time staring and computers and wrestling with the bleeding edge of technology.

Sometimes, it can help put things into perspective by wrestling  with a bit of 1700’s bleed edge technology.

Mysterious NET USE Drive Mapping Problem

0
Filed under Troubleshooting, Windows 7

At some point recently, my workstation became unable to map drive M: to a particular server share.

If I tried “net use m: \\server\share”, I’d end up with an error stating that “That device name is already in use” or better “System Error 85 has occurred”.

But, if I then did a “net use” to list the active mappings, drive M didn’t show up in the list.

I tried rebooting, both client and server, as well as a few minor registry tweaks (under the advice from one site that mentioned Windows will cache drive mappings in some cases), but nothing worked.

Finally, I just happened to open up the Disk Management screen from “Computer Management” (Right click on “Computer” and select “Manage”).

image

Notice the Drive M line and the “Removable” disk type. Ugh.

At some point, I must have inserted a new USB thumbdrive when I didn’t happen to have a connection (and hence a mapped M drive) to my server, and Windows just decided to map the thumbdrive to the empty M: slot.

But, when I got my server back up, even though the thumbdrive was long gone, that mapping was persisted and thus the slot was taken.

To fix it, I just right clicked on the highlighted line above, and selected “Change Drive Letter”. Remove the old M: mapping, and add a new W: mapping.

image

and the problem is solved.

Expression Blend Finally Does VB!

0
Filed under Expression Blend, Windows Phone 7

imageI started playing with the VB.net functionality associated with Windows Phone 7 months ago. As it was, it worked pretty well and I’ve definitely been able to move forward with a few side projects.

But, one thing that always bothered me was Expression Blend’s lack of support for VB projects. If I wanted to open a XAML file in Blend, I had to construct this complex project arrangement where I shared the XAML file between a VB and C# project and then opened it through the C# project. It worked, but it wasn’t particularly pretty.

My how things have changed!

First, be sure and grab the Visual Studio 2010 Service Pack 1.

Then, download and install the Windows Phone SDK 7.1 Beta 2.

Note that the Beta 2 install takes forever to install. I swear, I think they copy your entire harddrive to the cloud, reformat your drive and then copy it all back down.

But, once it’s done, open up a VB.net phone project, right click on a XAML file in the solution explorer and select “Open with Blend”.

Life is good!

Now if we could just get the ListPicker fixed.

Google Mail and Attachments

0
Filed under Rants, Tweaks

imageJust discovered something incredibly nifty about GoogleMail (GMail).

I’d written a message, and had included the sentence “I’ve attached this document in Word format for your review”.

Unfortunately, I forgot to attach the document.

When I clicked Send, Gmail popped up a messagebox asking me if I’d intended to include an attachment, because I’d written in the email “I’ve attached….”.

Clever stuff. Simple, but clever.

I can’t count how many times having that little feature in Outlook would have saved me from having to respond later with the attachment I meant to send.

It’s little things like that that can make a big difference in app usability. Things like automatically formatting a phone number, or automatically picking a Zip code once the city and state have been entered, or entering the city and state from the Zip code. Or how about a calendar system where, for the date of the appointment, you could enter “2 weeks from monday” and have the system determine the correct date?

Sizing a Variable Entry Size ListBox under Windows Phone 7

0
Filed under Windows Phone 7

imageI’ve been working a little with the latest Windows Phone 7 development options in Visual Studio 2010. Fun stuff!

One widget I was recently working on was a modified ListBox.

Essentially, the idea was to have a normal ListBox, where each Item (the ListBoxItem ControlTemplate) was actually a TextBlock (to show the actual item name), and a custom control (for editing addresses in this case). For the user, clicking an item “opened” the listbox to reveal the address associated with that item. Clicking again closed the item and the ListBox once again looked like a plain ol’ ListBox.

This is also sometimes called an Accordion Box.

The problem (actually, there were several problems, this was just one <g>) was that when the custom control was “revealed”, the ListBox would no longer scroll quite right. If the user was at the very end of the list, invariably, the last bit of the ListBox contents was cut off.

Here’s a picture of the bare ListBox with two items.

image

The red box is my own highlight (not part of the phone’s UI). When the user clicks on “New York” for instance, they should see this.

image

Note the highlighted area at the bottom. Even though I could press and drag the list box contents “up”, it would spring right back to this look when I let go. As a result, that last textbox would never be fully visible on-screen.

Not good.

The Solution

Turns out, the solution is simple, but I never was able to find it online (though I did find this exact question asked on StackOverflow, no solution there either).

The ListBox will automatically size itself to fit its contents under normal circumstances.  If the list is small, that’s fine, but if the list is bigger than a screen, and the listbox isn’t positioned at the VERY TOP of the screen, that can cause problems, the kind of which I was seeing.

To fix it, you can simply set the HEIGHT property of the ListBox to something other than Auto. While this DOES WORK, it’s not terribly elegant. What if the page needs to handle being switched to landscape mode?

In this case, the ListBox itself was a child (the only child) of a StackPanel, that itself was the only child of the PivotItem you see above, which was a child (among several) of a Pivot control.

The StackPanel was being sized properly (I could tell by setting it’s border to red and running the app), so the problem was with the ListBox only.

Then it hit me.

Databind the ListBox HEIGHT property to the StackPanel ActualHeight property (you can’t use the StackPanel’s HEIGHT property because, most likely, it’s set to Auto as well).

Here’s the XAML…

<controls:PivotItem Header="Destinations" Margin="0,0,12,0" Name="pvtItemDestinations">
    <StackPanel Name="stkDestinations">
        <ListBox Name="lstDestinations" HorizontalContentAlignment="Stretch" Height="{Binding ElementName=stkDestinations, Path=ActualHeight, Mode=OneWay}">
            <ListBox.ItemTemplate>
                <DataTemplate>
                
                ...
                Data template here
                ...
                
                </DataTemplate>
            </ListBox.ItemTemplate>
        </ListBox>
    </StackPanel>
</controls:PivotItem>

You can see the PivotItem, with the contained StackPanel, and within it, the ListBox.

The key is the Height="{Binding ElementName=stkDestinations, Path=ActualHeight, Mode=OneWay}".

This binds the height of the ListBox to the ActualHeight of its container. Once the Height of the Listbox is set to something other than “Auto”, its internal scrolling logic automatically kicks in and handles scrolling of variable item height items properly.

Simple, sweet, and all XAML!

WordPress 3.2.1 and Comment Notification

0
Filed under WordPress

One of the nice features of WordPress is it’s extensive notification options. It’s nice to get an email notifying me when someone has commented on a particular post.

However, something doesn’t seem quite right with the feature.

In the admin screen, under Settings-Discussions, you’ll see these options.

image

Notice the highlighted option. The idea here is that for a comment to be considered “Legitimate”, it’s author should have at least 1 previously approved comment. Otherwise, you could potentially have a ton of spam get posted "and visible until I notice it and remove it.

Unfortunately, this option doesn’t appear to work quite right in conjunction with notifications.

If the option is unchecked, things seem to be ok, the comment is posted and readable right from the first, AND I get a notification email.

However, if the option is checked, and the comment author doesn’t already have an approved comment, the comment is posted for moderation but not visible (which is correct), but I never receive a notification email of the comment. This is bad because I’ll never know to approve the comment, so no comments that the author posts will be visible until I explicitly go to my site admin pages and check for comments.

So far, I’ve been unable to find any info about this, but I can repeatable reproduce the behavior.

URL Rewriting with WordPress

0
Filed under Troubleshooting, WordPress

imageI moved this blog from dasBlog to WordPress back around the middle of 2010. At the time, I had gotten pretty permalinks operational just fine. If you don’t know what pretty permalinks are, they’re essentially alternate URLs for the pages of a blog, that are nice and human readable, like www.vbfengshui.com/contact-me instead of www.vbfengshui.com?page=564.

However, just in the last few days, I noticed they weren’t working anymore.

What happened?

Unfortunately, this is one of those situations, where, as a developer and not a web admin, I don’t do this sort of thing often enough to really remember what I do to get things operational. Ask me about multithreading in MSSQL, or how to make the best use of an anonymous delegate in .net, no problem. But configuring WordPress!?! <g>

The problem was, any time I’d try navigating to a pretty URL (say www.vbfengshui.com/contact-me), I’d end up at a page saying

“the system cannot find the file specified”

Not much help.

Googling that error turned up a number of posts, most of which indicates that either .htaccess didn’t have the proper permissions, or that, under IIS, the URL Rewrite module wasn’t installed.

Unfortunately, I’m running hosted IIS, and my host doesn’t provide access to installing things like URL Rewrite.

So what had happened?

After more Googling, I came across this post on the ikailo.com site. The hint (or the reminder as the case may be) I needed was this comment in their 404-handler.php script:

The name of this file.
// Set this value for the URL in Custom Error Properties of your website in IIS.
// Goto: IIS Manager > Websites > [Site Name] > Properties > Custom Errors >
Aha! My host DOES allow me to edit custom 404 handlers, and checking that, I’d already configured it to /wp-404-handler.php. Hmm. Why wasn’t that working? I loaded up FileZilla and started looking around. Lo and behold, that file was no longer there!
Fortunately, the ikailo.com site provides a great little 404 handler script that works just fine with WP 3.2.1. I’m including it here:
<?php
// This is the default file for the site. Usually index.php
$default = 'index.php';
 
// The name of this file.
// Set this value for the URL in Custom Error Properties of your website in IIS.
// Goto: IIS Manager > Websites > [Site Name] > Properties > Custom Errors >
// 404 & 404;2 & 404;3 > URL (Requires a '/' prefix in IIS).
$thisfile = '404-handler.php';
 
$_SERVER['ORIG_PATH_TRANSLATED'] = str_replace($thisfile, $default, $_SERVER['ORIG_PATH_TRANSLATED']);
$_SERVER['SCRIPT_FILENAME'] = str_replace($thisfile, $default, $_SERVER['SCRIPT_FILENAME']);
$_SERVER['ORIG_PATH_INFO'] = str_replace($thisfile, $default, $_SERVER['ORIG_PATH_INFO']);
$_SERVER['SCRIPT_NAME'] = str_replace($thisfile, $default, $_SERVER['SCRIPT_NAME']);
$_SERVER['PHP_SELF'] = str_replace($thisfile, $default, $_SERVER['PHP_SELF']);
$_SERVER['PATH_INFO'] = false;
 
$qs =& $_SERVER['QUERY_STRING'];
$ru =& $_SERVER['REQUEST_URI'];
$pos = strrpos($qs, '://');
$pos = strpos($qs, '/', $pos + 4);
$_SERVER['URL'] = $ru = substr($qs, $pos);
$qs = trim(stristr($ru, '?'), '?');
 
// Required for WordPress 2.8+
$_SERVER['HTTP_X_ORIGINAL_URL'] = $ru;
 
// Fix GET vars
foreach ( $_GET as $var => $val ) {
  if ( substr($var, 0, 3) == '404') {
    if ( strstr($var, '?') ) {
      $newvar = substr($var, strpos($var, '?') + 1);
      $_GET[$newvar] = $val;
    }
    unset($_GET[$var]);
  }
  break;
}
include($default);
?>

Just follow the directions at the top of the file and you should be good to go with nice URLs, even under IIS without the Rewrite module.

I’m guessing that an upgrade of WP at some point removed the old WP-404-Handler.php file. This one, I’ve saved as just 404-handler.php. No idea whether that’ll help to preserve it through the next upgrade but we’ll see.

A Reasonable Approach to Exceptions

0
Filed under Error Handling, VB Feng Shui

A comment thread on LinkedIn today ended up pointing me to an article by Eric Lippert about Vexing Exceptions.

The article is a little old (around 2008), but I found it to be one of the best-reasoned articles on exception handling I’ve seen.

In it, he basically categorizes exceptions into 4 types:

  • Fatal – You can’t predict and can’t do anything about it
  • Boneheaded – Results from a bug in your code
  • Vexing – Results from a bad design (like Integer.Parse)
  • Exogenous – Results from outside factors, but can be handled by your code.

Fatal and boneheaded exceptions you can’t do anything about (at least not initially). The best defense against them is a good logging framework that allows for multiple logging levels, like off, normal, and debug  for instance.

Vexing Exceptions are those that result from a poor API design. The example Eric gives is the Integer.Parse function. It will throw an exception when the parsed text doesn’t result in an integer, but that’s the whole point of parsing the text in the first place! With vexing exceptions, I usually try to find an alternate implementation that simply doesn’t generate the exception. When that’s not possible, you wrap the block in a Try and just eat the exception. It’s the only other choice you have.

Exogenous exceptions are probably the most typical exceptions you’ll handle in normal code. These are exceptions that you can generally deal with when they occur, but you can’t write code such that they won’t occur, because they are caused by factors outside your code. The typical example is a File Not Found error. Your code can usually easily recover from this type of error, but there’s simply no way to code around it such that you can guarantee it won’t happen.

Which actually leads me to an additional conclusion Eric touched on.

Pre-coding Exceptions (or Why you shouldn’t)

Often, I’ll see (and have certainly written more than once) code such as:

if not FileExists(MyFile) then

   Msgbox “The File Doesn’t exist”

else

   OpenFile MyFile

   Read/Write/Whatever

   Close MyFile

End If

This is an example of an exogenous error that I’m trying to “Code around”, using the FileExist function to detect whether the file is there before trying to open it.

Unfortunately, because there’s no way to predict when the file in question might be deleted, you can still get a file not found error at the OpenFile line, because other code may have deleted the file between the execution of the FileExists test and the OpenFile command itself.

Because of this, it’s often just a waste of time and code to put the FileExists test in, since to be truly covered, you also have to trap for the FileNotFound exception.

And since most exogenous exceptions fall into this pattern, I generally don’t try to code around them anymore. Rather, I just put the appropriate Try Catch blocks in place and deal with those exceptions that way.

Try

   OpenFile MyFile

   Read/Write/Whatever

   Close MyFile

Catch Ex as FileNotFoundException

   Msgbox “The File wasn’t found”

Catch Ex2 as Exception

   ‘Handle other exceptions as applicable
End Try

To do otherwise means you’re likely to miss exceptions occasionally, or you’ll be doing more coding than necessary (and repeating yourself, an even worse situation).

Typical Application Types

What Eric’s post didn’t touch on was exception handling strategies for different application types.

Most applications will fall into a few distinct types. Granted, you’ll always have drivers, embedded systems, and others that have even more specific error handling needs, but I generally see these types most often.

Command line applications

Your typical command line app is single purpose, with a host of command line switches to control its behavior. For these apps, I generally set up a single TRY CATCH in the sub Main to log or display to the console any unhandled exceptions, and then use a few scattered try blocks throughout the processing code to handle any vexing or exogenous exceptions. Everything else, just let fall back to the main Try block, since the run has basically been fatally terminated anyway.

Event driven UI applications

For these, I usually setup a thread exception handler and a process wide exception handler, just to prevent the application from failing completely with no logging of any sort.

Then, I always setup try blocks in the sub Main, and in every non-trivial event handler, at a minimum. “Non-trivial” here means any event handler containing code or calls to code that could possibly result in an exception.

And finally, I use a small scattering of Try blocks to deal with code where I expect there “could” be an exception, even though there normally won’t be, but that I can adequately handle in any case.

For this scenario, I’ve found that an AOP (aspect oriented programming) approach, using something like PostSharp or Spring.net, is a quick, easy and very maintainable way to get these try blocks in place.

Function Libraries

Since function libraries typically don’t (and shouldn’t) display any UI components, I generally let any unexpected exceptions bubble out of the library code back to the caller naturally.

On some occasions, it’s necessary to expose new exceptions from the library. In those cases, I usually create an MyLibrary.Exceptions namespace, containing all the custom exceptions that might be thrown from my library, and then throw them when appropriate.

Logging

No discussion on exception handling would be complete without mentioning logging. Any non-trivial app really should have a logging framework in place. Two of my (free) favorites are Log4Net, and NLog.

They’re both very similar, very capable and very easy to use. Log4net is the “old guy on the block” having been around for a number of years now. NLog is the newcomer, but very capable none-the-less.

Both make configurable logging so trivially easy, it’s almost criminal not to use them.

And, realistically speaking, exception handling is a much more powerful concept when coupled with a comprehensive logging strategy.

Finally, logging is a perfect use case for AOP, so definitely investigate some of the AOP frameworks when you start down this path.