February, 2006

  • Eric Gunnerson's Compendium

    Exception handling guidelines...


    This morning, I was reading a post on the GDN C# Language board about exception handling, and a reply got away from me, so I thought I'd put it here instead.

    I was going to link to the post, but I think that might be unfair to the poster, so I'll skip it.

    The discussion is about additional exception handling features in C#.


    The vast majority of exceptions should not be caught, except perhaps by a last-chance handler.

    In rare and very specific situations, you may want to implement recovery logic for a specific situation. The canonical case of this is when you get an exception when trying to open a file, though even in this case, you only catch it if there's something you can do about it. Can't open a user file? Ask the use for the filename again. Can't open a system file? Well, there's probably no way to recover from that, so catching it probably doesn't do any good.

    Without any user-written exception handling, the behavior of your code WRT exceptions is fully specified. Every exception makes it up to the outmost layer, so you know about everything bad that happens.

    When you start adding in exception handling, that's no longer true. A catch block that you write may be perfect for the exception you catch, which is a good thing - that's why exception handling is there. Or, it may appear to work but harbor a latent bug. I've used this example a number of times:

    catch (Exception e)
       if (e.InnerException.GetType() == typeof(MyFileNotFoundException)
          Recover();   // use your imagination for how this works

    This code appears to work fine - the recovery works great. But it swallows any other exception that happens in the try block.

    This specific example is an illustration of why wrapping is something to be approached carefully and thoughtfully, but the general point is that exception handling needs to be targetted extremely tightly.  Even then it's possible to get unexcepted behavior.

    Or, to put it another way, the less exception handling the better. Even experienced programmers will make mistakes - I inserted 250K records into a database a while back because of a flaw in my recovery logic in a catch clause.

    If you've spent time working with return codes in the unmanaged world, my experience suggests that you are likely to use too much exception-handling code in the managed world.

    To go on to a couple of the specific proposals:

    1) One proposal is to add try(count), which would automatically retry the block up to count times.

    There are a few scenarios where this makes sense, but they're pretty rare.

    My group came across a situation in unmanaged code recently. The low-level code needed to open a file, but sometimes it wasn't quite closed, so the developer wrote some retry code - it would sleep for a second, then retry - up to 10 times before failing. That code worked fine, but then one day the process hung. It turned out that the file was just missing, and the code tried for 10 seconds, then errored out.

    But the calling code also implemented a retry mechanism. As did the calling code of that.

    So, the system would wait for about 15 minutes before it finally decided that it couldn't find the file.

    I think try(count) would quickly become a crutch for taming behavior that wasn't understood, with lots of weird behavior.

    A second proposal was to expand the scope of a catch clause, either making it apply to a whole method or supplying a handler method to be called when an exception arises.

    The essence of exception handling is to be able to respond to a specific exception in a specific situation.  The chance that such a handler can do the right thing in all situations seems remote to me, and the chance that it would do the wrong thing seems high.

  • Eric Gunnerson's Compendium

    Windows DVD Maker - Slide Show Page


    To keep things simple, DVD Maker puts all still images in a single slideshow. This page is used to set the options for that slideshow.

    The top part of this page is used to set the background music for the slide show. You can add, re-order, or remove items with the buttons on the right, and you can also drag/drop into the listview.

    There are two modes for the slideshow.

    If you set the picture length through the "picture length" combo box, the length of the slideshow is based on the number of pictures that you have. If you have more background music than required, we'll fade it out at the end of the slideshow. If you don't have enough music, we'll loop through the songs until we have enough.

    If you check the "Change slide show length to match music length", we'll modify the length of each picture so that the slideshow duration is equal to the music duration. If we can - there's a lower limit to how short each slide can be, which I think is 1 second.

    The transition combo is used to - you guessed it - set the transition used between pictures. I've tried to describe the transitions below, but it's a bit challenging on some, so bear with me:

    1. Cut. Switches directly from one image to the other.
    2. Cross fade. The cross fade gently fades from one image to the other.
    3. Dissolve. Individual pixels randomly change to the new image..
    4. Flip. This one's a bit hard to describe. Take two post-it notes, and draw a picture on each one. Stick them back-to-back, but put a pencil vertically between the two in the middle. Hold the pencil so one picture is towards you, and the gently rotate the pencil so the other one comes into view. That's what flip looks like, though we use a "virtual pencil" that you can't see.
    5. Inset. Stack the new picture under the current one. Starting at one of the four corners, progressively reveal a rectangular-shaped portion of the new picture.
    6. Page curl. Stack the new picture under the current one. Grab the lower-left or lower-right corner, and peel the old picture off the new one.
    7. Pixelate. Like a cross fade, but the picture is pixelated into big pixels at the middle of the transition.
    8. Random. A random choice of all the transitions except for cut.
    9. Wipe. Stack the new picture under the current one. Starting at the top or left, progressively reveal the picture underneath, but blur the edge between the two. It's the effect used in the early Star Wars movies...

    Finally, the "Pan and zoom pictures" checkbox lets you control whether there is a slight pan and/or zoom of a slide between the transitions (this is sometimes known as the "Ken Burns" effect or the "Photo Story" effect). There isn't a ton of intelligence in how it does this, but the effect is mostly pleasing.

    That's about it for the slideshow page.

    In my next installment, I'll return to the Hub page and talk about the styles that we support.

  • Eric Gunnerson's Compendium

    Regex 101 Exercise I8 - replace space count with spaces


    Exercise I8 - replace space count with spaces

    Given a string with embedded space counts:

    <15sp>Indented by 15 spaces

    Replace the <<count>sp> with <count> spaces.

    So, if you have


    you should end up with




  • Eric Gunnerson's Compendium

    Regex 101 Exercise I7 - Make sure all characters inside <> are uppercase


    Regex 101 Exercise I7 - Make sure all characters inside <> are uppercase


  • Eric Gunnerson's Compendium

    Regex 101 Discussion I6 - Remove font directives from HTML


    Regex 101 Exercise I6 - Remove font directives from HTML

    Remove all <font…> or </font> directives from an HTML string.


    I've decided to start linking my answers back to the original posts, since the answers given there are often as good or better than the one that I give.

    The most obvious way to write this is:


    That's pretty straightforward - match either a <font...>, or a </font>. But it's also wrong, since the ">" in the first part will match the last ">" in the string. We need the non-greedy qualifier:


    That does what we want it to do (assuming we use singleline and ignorecase options...)

    Other ways of doing this showed up in the comments. Maurits suggested using 3 regexes, or a simple one:


    I don't know whether I prefer that one over mine. It is shorter, though it's a bit harder for me to read the /? part.

    Kbiel suggest a version without the non-greedy option:


    which also works well, though I prefer the non-greedy version due to readability.

  • Eric Gunnerson's Compendium

    DVD Maker - Customize Disc Menu Style page


    Welcome to the Customize Disc Menu Style page.

    This page is used to customize the style of the DVD menu. Like the menu text page, this page has two previews on the right side. The top one is the main DVD menu preview that you've seen before. The bottom one, however, is a preview of the scenes menu on the DVD.

    The scenes menu page(s) allow the viewer to navigate to different sections of the content, and there are either one or two menu pages. How they are set up depends on the content, with the following basic rules:

    • If there is a single video (or a slideshow), two pages of buttons link into 12 separate spots in the video. I think that they are equidistant, but they might be on scene break points.
    • If there are multiple videos, there is one scene button per video.

    We played around with a bunch of different options here, but it turned out that the simple approach worked best. On to the customizations:

    The font ones are the same as those on the menu text page.

    Foreground and background video allow you to override these values in the style that your using. The usages of foreground and background video vary from style to style, and some styles don't use the background video. If you don't specify anything here, the default is to use your content for both the foreground and background. And if you want to use a picture here instead of a video, you can do that as well.

    The menu audio allows you to change the background audio during the menu introduction (the time between when the menu starts to play and it's done playing). If not, we'll use the audio from the foreground video

    Menu motion determines whether the buttons on the scenes menu show moving video, or whether they are still images.

    Finally, the scenes button combo allows you to choose a different style button for the scenes menu. This will default to the appropriate shape for the style you have chosen.

    If you've customized the menu in a way that you'd like to use again, you can choose "Save as new style", enter a name, and you can then use your style.

    And preview lets you see an interactive preview of the DVD.


  • Eric Gunnerson's Compendium

    Regex 101 Exercise I9 - Count the number of matches


    Regex 101 Exercise I9 - Count the number of matches

    Given a string like:

    # # 4 6 # # 7 # 45 # 43 # 65 56 2 # 4345 # # 23


    Count how many numbers there are in this string


  • Eric Gunnerson's Compendium

    Super bowl officials...


    I'd like an unbiased opinion on this one. And I'm only going to make one post on this, so bear with me.

    I think the Steelers played a pretty good game - and managed to do some nice things - converting both long runs and a nice trick play for touchdowns. The Seahawks did some good things, but did a poor job managing the clock at the end of both halves.

    But the officiating was, well, just weird.

    Darrell Jackson catches the ball in the endzone, the ref doesn't signal anything, the Steeler DB protests, and the ref throws a flag. Clearly no interference. Seahawks settle for a field goal.

    Roethlisberger's touchdown was pretty darn close, and I couldn't really tell if he scored, but it looked like he didn't. I think this is largely irrelevant as my guess is that they would have gone for it on 4th and scored, but the Seahawks have stopped a few of those this year, so it wouldn't have been as clear.

    The killer, however, was the holding call on the Hasselbeck throw to Jeremy Stevens. It was pretty clearly not holding, and this was the big momentum change of the game.

    Then, on the ensuing interception, Hasselbeck gets called for a low block, which is just wrong.

    So, what do you think?

  • Eric Gunnerson's Compendium

    Regex 101 Discussion I7 - Make sure all characters inside <> are uppercase


    Regex 101 Exercise I7 - Make sure all characters inside <> are uppercase

    First, as Sheva pointed out, making them all *lowercase* would make a lot more sense, but you have probably noticed that the correlation between these exercises and making sense is tenuous at best.

    This is another case where that MatchEvaluator functionality is so useful. To match inside the <>, we simply use:


    (Extra Credit: Discuss why the "?" is required, what other options are available, and the relation between the different match options and Adam Smith's market theories.)

    Then, our MatchEvaluator is as follows:

    static public string Evaluator(Match match)

          return match.Groups[0].Value.ToUpper();

  • Eric Gunnerson's Compendium

    Random Acts of Giftitude


    I was reading Bob's Top 5 post on Valentine's Day, where he gives the typical male perspective on Valentine's day.

    Before I go on, I'll let the 2% of you who don't know the male perspective on Valentine's day spend some time reading his response.

    I share his attitude towards Valentine's day, but rather than complain about the expectations of popular culture, I've taken a different tact.

    I practice random acts of giftitude.

    Rather than following some calendar-based approach, I give my wife gifts at random intervals, and of random sizes.

    Now, I don't suggest that you go cold turkey and totally abandon such biggies as birthdays, or any major family holidays. I don't think that's a healthy thing to do. But you can reduce their size.

    There are some big benefits to this approach:

    • Random gifts == no expectations of gifts. Your love isn't guided by the whim of an advertising executive. Your love is original
    • You get much more credit. Any slob can pick up some flowers on valentines day. But how many can pick up a single rose on April 8th?
    • There's no expectation of the size of gift on a random day.
    • There's no chance of forgetting to get a present.

    Two caveats:

    1. It may not be a good idea to disclose this approach to the giftee
    2. At least initially, you will probably need to increase the gift amount, and it's a good idea to "accidentally" come home with something a few days before one of the traditional dates.
  • Eric Gunnerson's Compendium

    DVD Maker Tour - The disc menu text page


    The disc menu text page is one of the customization pages that you access using the toolbar buttons on the "Ready to burn disc" page (what we call the "hub page" internally).

    The right side of this page has two previews. The top preview is the main DVD menu that will show up when you start playing the DVD. It shows the state of the menu after any intro animation has played. On it you will see the disc title, play button, scenes button, and notes button, and the text of each of these is set using the editboxes on the left side of the screen. The font, text color, and boldness and italicality of all the text is set using the font controls at the top of the screen.

    The bottom of the page shows the notes pages preview. This is an optional page that you can use to add some notes about the DVD. If there is text in the Notes editbox, we'll create the notes page, and if there is no text, the page does not exist (and there is no "notes" pick on the main menu).

    Changing any of the settings on the left side will start an update to the appropriate preview windows on the right side. This may take a few seconds, since we're using the same rendering process on these previews as we use to create the menus that we put on the DVD.

    Red vs blue can be found here.

  • Eric Gunnerson's Compendium

    Would you like sauce with your ribs?


    On February 20th, 2005, I hit a big rock in the middle of a ski slope at Stevens Pass, popped both skis, slammed my chest into the ground, and cracked a rib.

    This February 20th, I skied off a groomer ledge in a white-out, caught an edge, popped my right ski, slammed my chest into the ground, and cracked the same rib.

    I will no longer ski on February 20th


  • Eric Gunnerson's Compendium

    TrainRight Fitness Testing

    TrainRight Fitness Testing
    After doing a bit of research, I decided to sign up  for coaching at TrainRight.com in January. And since then, I've been following their training advice faithfully, in the sense that I have a lot of faith that I will see big improvements.
    This faith is very important, you see, since I haven't done much in the way of riding the past 6 weeks. The big problem (aka "excuse") has been that the weather for January ranged from wet to "weather reporter standing around in blowing rain". I have my rain bike, but there's no much light on weekday nights, and I don't ride in 30 MPH winds. But the skiing has been good on Sundays...
    About three weeks ago, I finally broke down and ordered a Kinetic fluid trainer, which is the company lunchroom analog of real riding: it's like real riding, but misses a few of the finer points. I've only ridden it once, but my guess is that I'll put a fair number of hours on it.
    Last week, finally, the weather improved. I got in a 24 mile Wednesday ride with my Cascade group in 38 degree weather, and the forecast was good for the weekend.
    That meant that I wouldn't be able to put off my fitness test any more.
    One of the reasons I signed on with TrainRight was Carmichael's assertion that most athletes are unfocused and work out too hard, and I was looking forward to having some guidelines for how hard to work out. But to generate those guidelines, their system needs some data, and you generate the data for fitness test.
    The test format is simple: find yourself a 3 mile flat-ish course, warm up before, and then do two three-mile maximum effort time trails, with 10 minutes of recovery in between. I choose East Lake Sammamish South from the Marymoor entrance, loaded my bike and stuff up, and drove to the park.
    Driving to Marymoor is a bit of a wimp manuever - it's only about 3 miles from my house - but with it being my first test and the temperature hovering at 34 degrees, I thought I might need alternate transportation back home. I got to the parking lot, put all my clothes on (undershirt, jersey, arm warmers, leg warmers, shorts, socks, shoes, booties, over jersey) and my gear (hat, helmet, sunglasses, gloves, camelback), and started warming up. Or trying to warm up. The only thing that saved me was the bright sunshine.
    After the warmup, I headed over to the course, zeroed out my computer/HRM, and started out. The goal is to get to your top speed in about 45 seconds, but it took me a bit longer. I got close, but I didn't want to go anaerobic, and it took about 90 seconds before my heart rate stabilized in the mid 150s and I could ramp it up a bit more.
    This is where the pain started. In the "Double E half-hour of pain...", I peaked at around 161 BPM, which was painful, but bearable. That was for half an hour, and I needed to push a little more on this one, which I thought would take around 10 minutes. So, I kept my heart rate at about 163-165.
    You may be asking, "How can 163 be that much different than 161 - it's only two beats per minute!". I was asking that as well, in an attempt to distract myself from the rather significant difference. I don't know the physiology of it, only that it hurts. The course I picked out was a good one, however - it has a few rolling hills to it, and you need to shift up or down to maintain your cadence. If I didn't have that to focus on, it would have  been much harder.
    So, three miles come, I spin out for about 6 minutes, turn around, come back, and then do it the other way. This time I knew what was coming, but I did it anyway.
    So, the results were:
    Attempt #1: 9:55, 18.2 MPH
    Attempt #2: 9:10, 19.6 MPH
    I think the first one is slower because of my cautious start, and perhaps not being fully warmed up. I had hoped for a bit faster, but my fitness isn't great right now.
    This gives me an endurance ride limit of about 140, which means I'm supposed to spend 95% of my time below that ceiling. That seems pretty comfortable.
    After the ride, in what I hope will be a rare display of very bad judgment, I went on a group ride with some friends. Some more talented friends. After about 20 miles of fast and hilly riding, I begged off and spun home.
    I'm going to try to be better about following the program, and I'm looking forward to seeing what gains I'll make in the next 6 weeks or so.
    Oh, and my Polar 720i is great for this sort of thing - I could reset it at the start of a run, then just go and ride and pull any numbers off later.
  • Eric Gunnerson's Compendium

    Regex 101 Discussion I8 - replace space count with spaces


    Exercise I8 - replace space count with spaces

    Given a string with embedded space counts:

    <15sp>Indented by 15 spaces

    Replace the <<count>sp> with <count> spaces.

    So, if you have


    you should end up with



    This is fairly straightforward. First, we need to match the space count "thingy". We'll use:


    And then we'll use a MatchEvaluator to do the replacement.

    static public string Evaluator(Match match)

       int count = Int32.Parse(match.Groups["Count"].Value); 
       return new String(' ', count);

  • Eric Gunnerson's Compendium

    Life and Times of Anders Hejlsberg


    Newly released on Channel 9:

    Life and Times of Anders Hejlsberg

    This isn't a technical talk - it's more a talk about what Anders has done, but it includes some good stuff about design philosophy and the history of C#.

    Not only has Anders done some great stuff, he remains one of the nicest people I know.


  • Eric Gunnerson's Compendium



    Raymond writes an interesting post about how some programs run faster if you hold down the mouse.

    This is a classic situation to get yourself into - I've probably seen it 5 times, and hit it again recently.

    When we're burning a DVD, the burn engine calls back into the UI layer so that we can update the progress bar. To give the user a single monotonically-increasing progress bar, we (well, Dean, actually) have to play some games with our progress tracking, which means that sometimes we get progress callbacks once a second, and sometimes we get them 100 times a second.

    The progress dialog looks fine, but if you look a profile of the burn, you'll find that a fair amount of time is being spent in the UI code updating. In this case, it's not a big deal, but I've seen cases where programs are spending 90% of their time updating the UI. That takes a 10 second operation and makes it take 100 seconds, which is pretty bad.

    The fix? Well, there are two good ones.

    The simplest one is to simply update every <N> calls. I traditionally start with N=10, which is guaranteed to same 90% of the overhead, and usually works fine.

    If your callbacks are sporadic - as they are in the DVD Maker case - it works better to timebox the updates. Whenever you update the UI, record the time, and then don't update it again until a specific time has gone by. I usually find 1/4 second to work well.


  • Eric Gunnerson's Compendium

    Exercise your wit


    If you fancy yourself as funny, please help me out..

    at Explanations...

  • Eric Gunnerson's Compendium

    Resistance to pairing


    Paul wrote an informative response to my post on collaboration.

    I've just been writing some stuff about where I think our group should go in the future, and I've decided to downplay pair programming. Not because I think it's a bad idea, but more because I think that opinions around it tend to be a bit religious.

    Instead, I've decided to advocate an open environment where pairing can happen in a natural way

  • Eric Gunnerson's Compendium

    How many of these did you use?


    There's a big auction on ebay of vintage PC equipment.

    Look through the pictures, I think I used about 12 of them.

    How many have you used?


  • Eric Gunnerson's Compendium

    Big White-Out


    Last week, we spent a few days up north skiing at Big White, eh?

    So, I thought I'd write a few random comments:

    • Kelowna is a long way from Seattle. Count on at least 6 hours to get to Kelowna, plus another hour or so to get to Big White. About the same as it takes to get to Sun Peaks. You can fly in if you wish.
    • Brr. The first day was about 5 degrees but sunny. The second day was 5 degrees and windy. The third was 10 degrees and snowy. If you ski the Cascades, you aren't used to those conditions. Bring extra clothes and buy some hand warmers.
    • Cold == powder. We had about 5-8" of powder on our third day of skiing. Some nice skiing for a few hours.
    • Big White has interns setting up the top of their lifts. All of the high speed lifts I've ever ridden have a nice flat spot at the top, so you can stand up as the lift slows down. Big White has 4 high-speed quads, none of them are set up like this. Some of them go dead slow before you can stand up, some are a bit different. They're really hard to get off of.
    • Big White has a big area known as Gem Lake, with 2300' of vertical on a single lift. It has some nice terrain, except: 1) Some runs are marked as blue but have never been groomed, so you go down and then up on them and 2) you get there via a cat track named "oh go slow" (and various less-nice appelations) that is approximately 500 miles long and 3) the route on the map to get back to the village involves climbing a hill and then finding out that the route is closed.
    • Grooming is uneven. In a white-out at the top of Gem Lake on Monday, we were following a cat track down and I skied off of an 8" groomer lip and fell.
    • The village is small but nice. Interestingly, they have put their main school and lodge in the middle of the village.
    • We stayed at Moguls, which is true ski in/ski out. A great convenience.
    • We got a discount for our Stevens Pass Season Passes, so if you have a northwest pass, it's worthwhile to ask.
    • The mountain skis a lot like Bachelor does. It's not particularly challenging (we didn't ski the steep stuff because of weather).
    • My daughter recommends the Mega Snow Coaster. I do not recommend the "Outback spin" on the exit road from the resort. I used up about 50 years of car kharma there.


  • Eric Gunnerson's Compendium

    Coolest thing, parent edition..


    Last Friday, we went to the movies to see the remake of the Pink Panther. It was okay, but it's pretty hard to keep up with the original.

    The cool part was that my 11-year-old daughter paid for dinner and the movie for the three of us.

  • Eric Gunnerson's Compendium

    Top Gear Window Olympics 2006


    What a great video.

    Top Gear Window Olympics 2006

Page 1 of 1 (22 items)