Tuesday, 27 February 2007

Metric Time

As a computer scientist, working with standard units of time can be a frustrating experience. I'm sure the existing time and calendar systems made sense when everyone followed the gods, the moon, the sun, and the seasons but I think it's safe to say most of the first world population rely on a digital watch and computer-based calendar (and for those who don't, then there's even more reason to move away from their old world equivalents). Since no sane person uses imperial measurement anymore unless they're American or my mom (are either really sane?), I, Pope Michaelus I, hereby deem it 'time' to make the move to metric time. I think we all can handle it.

Everything in glorious units of ten (except weeks—a ten day week might kill me... oh yeah, and months will be a bit weird). So I propose not quite metric time and it all hangs on the seven-day week:

1 year = 10 months

It's pretty simple and time will seem like it goes even faster but you won't get old as quickly.

1 month = 4 weeks

We definitely need to keep months so we can continue having cake days at work once a month. I guess they're communal birthday celebration days really but it's not like I know half the birthday boys and girls anyway. Anyway, cake day might get lost in a year without months. 4 weeks (or 28 days) is a nice compromise and even though 28 is a weird number, at least it will be static. And no leap years—time can move independent of the sun so let it. A month could, following debate, be drawn out to 5 weeks for quasi-metric support but you know what those 31-day months are like—imagine every month being 35 days long. 28 days = more cake.

1 week = 7 days

I'm working a lot of overtime at work these days—mainly weekends—and from current hands-on experience I can tell you do I don't want a 10 day work week. Without a doubt, the business analysts and project managers would jump at the idea so this one's gotta be a special case and it's got to be set in stone up front. 7 is also a lucky number.

1 day = 10 hours

This is where things start getting a bit difficult. A ten hour 'day' is miles off our current 24-hour day so there'll definitely be some adjusting to do. If you put this in context with a week and weeks in months and months in years, those units also start going a bit wonky. But fingers crossed, it'll all work out something like Mexico with lots of sunshine and siesta time. And burritos.

1 hour = 100 minutes

I'm tempted to stick with 10s on this one but seeing as how we've already shrunk down days and stuff... 100 minutes per hour makes sense anyway. Sort of like those 90-minute classes they made me get through in high school—bearable, just. I think all the clock watchers at work would blow a fuse if an hour went by in ten minutes. At any rate, 100s are still metric, so stop your complaining.

1 minute = 100 seconds

No one cares about seconds anyway so just K.I.S.S.

1 second = 1 second

No more of this milli and micro b.s. Like I said, K.I.S.S. and I can never remember which is which so just forget it. Just talk about half a second or tenths of a second or .0484822999299000123 and you'll be fine. That's the beauty of the metric system. Could even just get rid of seconds altogether and just think about bits of a minute—easy!

And of course, most importantly, there will be no daylight savings. I actually read a post out from some guy who manually hacked the Windows registry to program Western Australia Daylight Savings into his PC before Microsoft released their dodgy patch that doesn't work with Vista. I'm a west-aussie so I had to dig around, you see. Anyway, geeks being geeks, I think this guy could have put his time and talents to better use. The debate rages over here but simplicity for us programmers pretty much blows all other arguments out of the water.

By the way, metric time started about half an hour ago so someone better find that registry hacker and see if he fix up our Windows clocks to work all metric like. No doubt Outlook will be off for a while but meetings are a waste of time anyway.

Monday, 26 February 2007

Basic CSS

1. Styles (classes and selectors) can be declared so they're relative to their physically enclosing block

#container .relativeClass
{
color: red;
}

<div id="container">
<span class="relativeClass">My red paragraph</span>
</div>

If relativeClass is assigned to an element that doesn't have the 'container' id, the style will have no effect.

The .reativeClass name can be safely reused/redefined within different scopes.

Elements can be specified to have a specific style within the scope of an enclosing block as well:

#divContainer p
{
color: red;
}

.classContainer p
{
color: red;
}

2. Styles (classes and selectors) can also be declared so they're relative to another class or selector

.containerClass .nestedClass
{
color: red;
}

#containerId #nestedId
{
color: green;
}

3. Classes and selectors can be constrained to apply only to a specific element

p.elementLimitClass
{
color: red;
}

p#elementLimitId
{
color: green;
}

<p class="elementLimitClass">My elemented limited class paragraph</p>

<p id="elementLimitId">My elemented limited id paragraph</p>

Friday, 16 February 2007

Generic Dictionary Wrapper Class Cannot be Restored from ViewState

The .NET 2.0 generic Dictionary class can be serialised to and deserialised from the ViewState of a web application but extending the Dictionary class to derive a named collection grounded in the business domain requires some extra attention. Essentially, the derived class needs to call a specific constructor in the base class when deserialisation occurs and this doesn't happen implicitly (List-based classes seem to work fine without modification). Note: the derived class will serialise happily--deserialisation is the problem).

The System.Collections.Generic.Dictionary class defines a constructor used to restore the Dictionary's internal data during the deserialisation process:

"Initializes a new instance of the Dictionary class with serialized data."

protected Dictionary (
SerializationInfo info,
StreamingContext context
)


Constructors are not inherited in C# so a wrapper class must explicitly define this constructor and pass the data back up the inheritance hierarchy to the base Dictionary class:

[Serializable]
public class CustomCollection : Dictionary
{
protected CustomCollection (
System.Runtime.Serialization.SerializationInfo info,
System.Runtime.Serialization.StreamingContext context

) : base (info, context)
{
// no implementation
}
}

Depending on how you construct your wrapper class, you'll most likely want to define additional constructors as well or the default (empty) constructor at a minimum as it will no longer be injected by the compiler with the deserialisation constructor present.

Without this constructor, I was receiving a corrupted ViewState exception

The state information is invalid for this page and might be corrupted.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

.NET Properties – Infinite Loop

What's wrong with this code?

public bool IsModify
{
get
{
return IsModify;
}
set
{
IsModify = value;
}
}

The title of the post might give away the problem. This code will compile happily and any surrounding code will most likely execute without a problem—until the property is accessed. You have to look closely and compare the property name with the variable name but once you do, you'll realise they're identical; the result is get calling get on IsModify and so until a StackOverflowException is thrown—an infinite loop (the same thing occurs with the set).

What I failed to reveal in the code above is the variable name the property should be wrapping (note the casing):

private bool isModify;

Unfortunately, Visual Studio 2005 doesn't issue a warning about this potentially disastrous little bit of code.

What the problem boils down to is a difference in casing between the variable name and the property. My team's coding standards dictate this naming convention but I otherwise might have used _isModify for the local variable to identify it as such and differentiate it from its property name. On a style note, I find the underscores make the code a bit busy and my eye tends to jump to the variable names—which is probably inappropriate. Alternatively, I could give the variable a completely different name from the property name but that severs the implicit connection between the two.

This can result in all sorts of semi-intelligible error messages. Today, after waiting for the server to run its course, I got my old favourite:

Server Application Unavailable

The web application you are attempting to access on this web server is currently unavailable. Please hit the "Refresh" button in your web browser to retry your request.

Administrator Note: An error message detailing the cause of this specific request failure can be found in the application event log of the web server. Please review this log entry to discover what caused this error to occur.

The event log reveals two entries of interest:

Event Type: Error
Event Source: .NET Runtime 2.0 Error Reporting
Event Category: None
Event ID: 5000
Date: 16/02/2007
Time: 8:02:51 AM
User: N/A
Computer: PHO02078ITDEV
Description:
clr20r3, P1 aspnet_wp.exe, P2 2.0.50727.210, P3 45063b16, P4 app_web_nr0px690, P5 0.0.0.0, P6 45d4e6d7, P7 8, P8 0, P9 system.stackoverflowexception, P10 NIL.

and

Event Type: Error
Event Source: ASP.NET 2.0.50727.0
Event Category: None
Event ID: 1008
Date: 16/02/2007
Time: 8:02:59 AM
User: N/A
Computer: PHO02078ITDEV
Description:
aspnet_wp.exe (PID: 2168) was recycled because it failed to respond to ping message.

Thursday, 15 February 2007

Centre Block CSS2

To centre a block item, set the margin-left and margin-right CSS properties to 'auto'; this sets the computed values of both margins equal. IE won't listen so set the text-align property of the containing element to center as well.

<div style="width: 500px; text-align: center;">
<div style="margin-left: auto; margin-right: auto; width: 100px;">My stuff</div>
</div>

Page & User Control Event Execution Order

  1. ASPX: Page_Load
  2. ASCX: Page_Load
  3. ASPX: Page_PreRender
  4. ASCX: Page_PreRender

Scientific Creativity

Does the term 'scientific creativity' satisfactorily define the analyst programmers?

Wednesday, 14 February 2007

List.Clone ( )

The List class does not expose any form of Clone method—either directly through the List class itself or indirectly through its parent classes and interfaces.

To work around this, the List class does expose the AddRange ( ) method. To “clone” a list, simply create a new List and invoke AddRange ( ), passing in the list to be copied.

The result is a shallow clone of the existing list.

Monday, 29 January 2007

Media Center Revisited with Vista Ultimate RTM

With the Windows Vista RTM finally available on MSDN and a spare day over the Christmas holidays it was time for a home Media Centre rebuild. What follows documents my Vista/MCE installation experience and my perspective one week in.

First, some background…

My Windows MCE experience has been generally positive since I first took on the construction of a media centre box in September 2005. At the time, standard definition digital set top boxes were reasonably new-fangled and cost a fair packet (the high-def equivalent was definitely out of my league). More importantly, hard disk recorders were not integrated and were selling around the $600 mark—and that price didn’t include a DVD player. As I also wanted a digital jukebox, Windows Media Center Edition offered a complete solution but pre-built MCE machines were selling for $4000 or more.

By late 2005 the consumer magazines were on to their second round of TV tuner card reviews and HD cards were beginning to creep into the mix. Despite reported problems receiving a consistent digital signal in some areas, hardware incompatibility, and slow channel changes I thought I’d chance building my own box. I had an unused P4 1.7 IBM desktop machine with a quiet fan, 512MB of RAM, and a DVD-ROM so I added a Hauppauge Nova-T PCI tuner card and a second-hand nVidia GeForce 4 video card with video out. I also splurged and added a secondary 250GB hard drive to the mix and purchased Microsoft’s MCE remote. Stereo audio comes from the integrated sound card but the Logitech speakers I’m using also include a sub, giving me 2.1 channel audio. My total cost was around $550 (AUD) including the speakers.

The box went together without any issues and I installed Windows Media Center Edition 2005. This version of Windows did not include a DVD decoder, which is required to watch DVDs and television, so I had to acquire a decoder before anything video-related would work. With the decoder installed, I then noticed DVD playback would flicker from dark to not-so-dark every few seconds. Since I’ve got an older television with only a coax input, I’m forced to run the composite RCA output from the media centre into my VCR, which then connects to the television (call me old fashioned—and yes, I’m aware the benefits of HD will go unnoticed on a monitor like this); to make a long story short, I determined Macrovision was most likely interfering with the signal but a Macrovision tool got around this problem. I also installed Daemon Tools to mount DVD ISOs.
I couldn’t believe it when all the free TV stations (and digital radio stations) scanned and I was finally watching live television through the computer; controlling it all from my sofa (the old television doesn’t have a remote) was a luxury! Pausing live TV when the phone rings and skipping all the loud, budget commercials made me feel like I was finally in control of my television experience. I bet my dad probably felt the same way when he bought our first VCR back in 1843.

Despite my initial enthusiasm, the Hauppauge card never seemed to like its new home too well and seven times out of ten the live television signal would stutter and skip when the box was started cold. My gigantic new hard drive wasn’t always detected either which meant no access to my media library and only limited television recording space. A reboot was the only effective work around, apart from leaving the thing on 24/7, which I refuse to do as a greenie. This box is connected to my home Windows domain and while the box (the MCE app in particular) fires up quickly when the domain controller is available, it would take a good minute or two otherwise. As reported, channel changes are slow in MCE 2005 and can take more than just a few seconds but I understand this is consistent across most tuner cards from that era. Less importantly, pressing the PC on/off switch on my MCE remote control would put the machine to sleep but waking it up always resulted in a blank screen.

I was hopeful the MCE rollup released late in 2005 would fix some of these issues but in the end it botched up the machine and I did a clean rebuild on the off chance doing so might also correct the skipping and disk issue (it didn’t). I put this down to the IBM hardware in the end.
Needless to say, my opinion is that Windows MCE 2005 was a good introduction to the media centre experience but I found myself looking forward to the Vista release almost immediately. MCE is the gateway to entertainment in my home and I have every intention of keeping it that way—despite the fact that it hasn’t intrigued friends and family as much as I hoped. The wife was actually impressed and told me as much, however, so I guess it can’t be that bad! Looking back on the experience, my only regret was not buying a dual-tuner card such as the Hauppauge Nova-T 500.

The Move to Vista

Moving to Vista was predestined since the MCE app doesn’t ship as a stand-alone product and I soon found MCE 2005 to be lacking. The questions in my mind related to how the new OS would perform with my existing hardware and what changes and improvements it would bring to the MCE experience.

I first installed one of the initial Vista builds in a virtual PC around November 2005 and although I moved through a beta or two and the first release candidate I was never sure the thing would fare much better on my antiquated P4. My first “physical” Vista experience was at TechEd ‘06 in Sydney using the Dell machines set up for the event. These were pretty decent desktops with 1GB of RAM and I’m pretty certain they were running the Aero Glass interface since they could do that fancy 3D alt-tab thing.

To play it safe, I decided to leave the existing MCE 2005 box in a semi-functional state and elected to build my Vista media centre on a spare box. I was fortunate to have another IBM desktop sitting unused in my study (or rather, it was only used as a test machine) and I deemed it Windows Media Center capable. This box is an P4 1.8 IBM desktop with 512MB RAM. I first installed the Vista RTM to see how it would fare on the minimum required RAM. I didn’t play around for long with it for long but installation was successful. Boot time was very slow (a good four plus minutes) but it seemed like it might work. A quick review of the Media Center application (which I’d seen only briefly in Sydney) showed a revised UI but not much else was evident without a proper video card and tuner.

In addition to swapping over the video card, tuner card, and the 250GB hard drive, I also filled the last empty memory slot in the new machine with a 256MB stick of RAM from the existing MCE box, giving the Vista box a total of 768MB of RAM. I would have preferred (and still would prefer) to have a full gigabyte or more of memory but the desktop case means I’m fairly limited in that sense (this is also one of the reasons I haven’t added a better sound card or a second tuner card).
Installation of the operating system proceeded with no issues and my new Vista media centre was soon booting. To my surprise, the Hauppauge Nova-T card wasn’t automatically detected during installation but I thought I’d take a chance with the XP drivers that came with the card. Although I checked the Hauppauge site for a Vista driver before starting, the site wasn’t forthcoming about whether the existing drivers were compatible or a new set of drivers would be released. The Hauppauge forums are full of reports of channel scanning issues with the dual-tuner Nova-T 500 card and Vista RC1 and I thought I might end up in the same camp. In the end, the factory drivers installed without a hitch and are working fine.

I chose Windows Vista Ultimate, which includes a DVD decoder, so I ran a problem-free channel scan and installed a Vista-ready version of Daemon Tools before configuring the OS to automatically log on using a domain service account under the local Users group. My second MCE 2005 build had issues with live TV signal stability when using a non-admin account so I was happy to see my account configuration working as intended. I also installed the Western Australia Daylight Savings patch since the system clock was off by one hour. At this point, everything was working beautifully and even the PC on/off button worked to put the computer to sleep!

First Impressions

One week later and I’ve got a lot of good things to say about Vista and Windows Media Centre. This has been my first extended experience with Vista and while it’s been mainly over a remote desktop connection (apart from WMC), the interface feels different but intuitive. It’s taken a second to find some things and learn how to do them differently using the new UI but the concepts are generally the same as they always have been. I’m not a big fan of UAC and have to admit I’m already blindly clicking through the prompts. Boot time is also pretty lengthy—it takes this machine about two minutes to boot the OS and log in using the pre-configured credentials regardless of whether the domain controller is available (the upshot is that boot time is about the same when the DC isn’t available).

The Western Australia Daylight Savings patch didn’t work and despite being a seemingly unimportant OS issue it affects scheduled recording times in Media Center. Even after installation, Vista didn’t move the clock forward and a few days later I noticed the patch wasn’t even showing up under the Programs applet. Changing the clock manually isn’t a realistic option since it synchronises with the domain controller’s time server. In the end, I installed a
registry hack from a Microsoft site which corrected the problem—the end result was that it also shifted all of my scheduled TV recordings forward one hour! I’ve also heard rumours about the DVD decoder time bombing in some of the betas/release candidate and the Vista Home edition so I’m not sure how long the decoder will hang on with Ultimate. This is a bit of a bummer really—I think any modern OS should have the capability to play something as ubiquitous as a DVD without additional software. My guess is that it will keep chugging with Ultimate.

On the hardware side, the live TV jumpiness has disappeared on the new machine and the secondary hard drive is being detected without fail. The PC on/off sleep button is back to its old ways once again, however, but I suspect that’s a video card issue.

Finally, the Vista version of Media Centre is a big improvement over previous versions—not a massive improvement but a big improvement. My favourite enhancement is how the media library caches album and picture information. I’ve got a large collection of digital music and MCE 2005 takes ages to present me with a list of music. The new version remembers not only the music it’s already scanned but it also remembers the view I was at last (i.e. sort by album or sort by artist). Channel change time is still slow and is possibly a second or two slower than it was but as I don’t generally watch live TV it’s not a big issue for me.

The menu system has been nicely refined since MCE 2005 with a lot of the individual menu items now combined and streamlined. I understand this is targeting widescreen displays but I find it quite useable on the old 4:3 TV. Despite the improvements in this area, I am finding the menus harder to read from the sofa… in fact, I’m feeling a bit old because of it!!! I know this is due to the ancient Sharp Lyntron I’m using as a display (it’s an okay size but it is fuzzy and dark). I’m navigating some of the primary functionality from memory (like view scheduled) because I can’t read the menu text. My charming wife actually decided she would try to change the font size to correct the problem and ran through the WMC setup wizard; the wizard ended up changing the resolution when the WMC window is active and killed video playback until the machine was rebooted. I got in there and tried to undo whatever resolution the wizard selected because it looked terrible and didn’t change the main OS resolution, meaning an epileptic fit-inducing bzit! whenever WMC starts or closes or I toggle back to the desktop. I ended up synchronising the WMC and OS resolution at 640x480. Despite having the media centre connected to a television display over a composite/coax connection, the only way to change the WMC resolution is to tell the wizard you’re using a DVI connection.

I would really like to see an option to play a CD in the physical drive without having to click into the Music menu. DVDs can be played directly from the TV + Movies menu so the current CD playback interface doesn’t feel natural to me. I was also really hoping to see a better shut down menu. I do prefer having the Shutdown option under the Tasks menu but I hate how the shut down option defaults to Close (as in close WMC and return to the desktop). As mentioned, I shut down my media centre box at the end of the day so it’s an extra hassle to move two buttons to the right with the remote and then shut down. Fortunately, despite being an old PC, the IBM will shut down the computer properly when I press the physical on/off button.

One of my biggest gripes is the time it takes to switch to live TV for the first time. If I’m booting from a cold state, it takes two minutes to get to the desktop, another ten or fifteen seconds to get into Windows Media Center, and another two minutes once I’ve pressed the Live TV button on the remote before a picture comes up. The situation is mildly better if I turn on the machine, walk away, and then come back to it after WMC is loaded and has sat for a few minutes. I’m not certain if additional system memory would improve this.

Despite being able to happily watch live TV and play my music I was nearly ready to report two major blockers to a future with the current Vista RTM build: manual and series recording was only succeeding intermittently and the machine was crashing hard when I wasn’t looking. As mentioned, I don’t watch much live TV and have the majority of the programs I watch on a regular basis configured as recordable series in WMC. For some reason, these programs were only recording sporadically. Kicking off a manual recording would start recording but the box would usually crash at some point and the recorded program wouldn’t appear in the recorded tv list. The event log revealed nothing interesting. I was thinking the Hauppauge XP drivers or mixed brand memory might be to blame—or perhaps WMC was simply having problems closing off the file when recording completes. I tried swapping the third stick or RAM with the left over module from the old MCE box and also shuffled the sticks around but the problem didn’t go away. I was willing to try a Vista-specific driver for the Nova-T but, as mentioned, the Hauppauge sites are pretty useless for this sort of thing.
www.hauppauge.com.au leads to an online retailer site, www.hauppauge.com doesn’t list the Nova-T PCI as such (I’m not sure if it comes under a different name in the US), and www.hauppauge.co.uk isn’t any better. The Hauppauge forums reference a 43MB driver on their FTP site that might work with the Nova-T so my next step was to get that sucked down and see what happened.

In the end, a late night brainwave suggested the power settings might be shutting down the hard drive while WMC was in the process of recording. Since I do occasionally leave the box running throughout the day or over night, I tweaked the power options after the initial install to shut down the hard drive when idle and turn off the monitor, throttle the CPU power, etc… Silly me, I assumed WMC would prevent Vista from shutting down the hard drive if it was busy recording. To keep the HD from shutting down, I created a new power profile and set everything to never shutdown, never sleep, and run full blast all the time. The mysterious crash problem is gone and scheduled programs are recording perfectly. I’ll plan to incrementally scale back my power settings after I figure out how to build a Windows Image file.

All’s now pretty happy in the land of WMC. Not everything is perfect—kicking off live tv occasionally puts up a black screen but skipping back on the playback timeline starts it running happily again. Changing channels also periodically results in WMC “forgetting” its list of scanned channels and only a time-consuming re-scan will correct the problem. But we soldier on…

Looking Forward

Considering Windows 2003 runs on early Pentium hardware, I initially expected Vista would still run on a minimalist hardware platform… a minimum requirement of 512MB of memory is not (or should I say was not?) a minimalist hardware platform. I haven’t previously been critical of the so-called bloatware Microsoft produces—both XP and Vista do a lot of things quite well and take some big steps forward toward the future of computing. With the Glass interface turned off and a reasonable amount of system muscle behind it, I was surprised to find that Vista doesn’t boot any quicker than XP and takes so agonisingly long to do something like fire up live TV and switch channels. I do believe Vista was ready for release (I’m comparing the RTM with the early release I saw back in 2005) but I wonder if the supporting structures around the OS are up to scratch—I’m thinking mainly of the daylight savings patch issue.

With WMC in its fourth version now, I also expected some big changes to WMC. I’m happy with what was fixed and what was refined but I’ll be really happy when the size of the UI text is user configurable and Windows Media Player can play .m4a files out of the box. While I’m happy to soldier on with funky channel rescans, I’m my own IT support department; whether the average family is happy to do the same is questionable.

Vista has found a home in my living room for the enhancements WMC offers and so I can keep on top of Vista until the OS makes it to my desktop. It will be very interesting to see what SP1 brings and it will be revealing to watch uptake of the pending consumer release—I wonder if cheap second-hand laptops will flood eBay when people realise they’re underpowered to run the new OS? In conjunction with Longhorn Server, my guess is there will be a business case for the pair within the enterprise. As long we don’t have to wait another five years for the next Windows release, I think we’ll be travelling okay.

Wednesday, 24 January 2007

Zero-Defect Code

I was surprised and flattered today when my tech lead casually mentioned that I'm "the only developer he knows that writes bug-free code."

I find the concept of zero-defect code quite interesting and suggested that if it is true that I write defect-free code, perhaps I plan to do so from the get go. I stuttered on about hanging up "DO GOOD WORK" signs around the office and how I think it is possible to write defect-free code if you try.

I don't consider myself a slow coder and I believe strongly that quality doesn't cost money; I am, however, calculated and organised. I also take the time to step through my code and review it a few days or weeks after writing it.