Outputing a PNG directly to an ASP.NET Response.OutputStream

So you need to generate an image dynamically. Perhaps you want to watermark it. Or change its size based on some information that isn’t available until runtime.

But the call to Image.Save(Response.OutputStream, …) fails with the following error:

A generic error occurred in GDI+.

Turns out PNGs require a stream that’s bidirectional. Response.OutputStream is unidirectional. The solution is to save the PNG to a MemoryStream then write the MemoryStream to the Response OutputStream.

Thanks to this article for clearing it up!

default xml doc comments for c# method parameters

Ever need to quickly generate xml doc comments for C# method parameters? In VS 2010 this can be done with a regular expression find-and-replace.

The “find what” expression: \<param name="{:i}"\>:b*\</param\>

The “Replace with” expression: <param name="\1">The \1.</param>


Not exactly particularly meaningful but it’ll cut down on stylecop warnings…

Installing Windows 7 in UEFI mode from a USB drive

Thanks mainly to this post, I finally installed Window 7 in UEFI mode from a USB drive.

Windows Setup will only install in UEFI mode if it boots in UEFI mode. As PCs transition from BIOS to UEFI many of them automatically fallback to BIOS mode if there’s no EFI-bootable partition.

The Microsoft USB/DVD tool, which modifies a USB key so that Windows 7 can be installed from it, unfortunately formats the USB key NTFS. EFI requires an FAT32 boot partition. So as soon as this particular system, a Fujitsu Lifebook UH572, tried to boot from the USB drive it switched into BIOS mode.

To install Windows 7 from a USB key in UEFI mode:

  1. Format the USB key specifying FAT32 as the filesystem type.
  2. Mount your Windows 7 ISO or DVD.
  3. Copy the contents of the ISO or DVD onto the USB.
    1. That’s right, you can use plain old Windows Explorer to copy the files.
    2. The directory structure on the USB key should be identical to the directory structure on the ISO/DVD when this step is done.
  4. Copy the \efi\microsoft\boot directory up 1 level – to \efi\boot.
    1. This directory was put in the wrong location on the ISO/DVD. A UEFI firmware expects to find a bootloader in \efi\boot.
  5. Download the bootmgfw.efi from this post and copy it to \efi\boot then rename it bootx64.efi.
  6. Boot your target machine from the USB drive.
  7. At the “Welcome to…” window, press SHIFT+F10 to open a command prompt.
  8. Clean the primary disk then convert it to GPT (convert gpt).
  9. Exit then reboot (again from the USB drive).

That’s it. Since the primary disk is GPT formatted and the USB key has \efi\boot\bootx64.efi Windows 7 setup should be running in UEFI mode.

Clean install of Windows 7 on Ultrabook fails

So I get a new ultrabook, the Fujitsu UH572, and promptly plug in my usb stick to do a clean install of Windows. Windows sees 2 drives: a 32GB ssd as Drive 0 and a larger spin drive as Drive 1.

Creating a new partition on Drive 1 doesn't create the expected "System Reserved" 100mb partition on the same drive. It creates it on Drive 0! The installation proceeds but upon reboot the ultrabook will not boot! This cycle repeats with various attempts to patch it on my part (including manually partitioning via diskpart).

The solution? Load the "SATA AHCI Controller Drivers" before partitioning the drives. Once the drivers have been loaded the much bigger spin drive shows up as Drive 0 and Windows installs properly. The drivers are in the files\irst\Drivers\x64 folder of the driver download self-extracting executable. The necessary drivers can be downloaded from Fujitsu's mobile support website.

*whew* For a few hours this ultrabook was looking like it'd be a glorified paperweight...

Windows Search and Undoing RAID-0

So you'd like to undo RAID-0, perhaps because you're replacing the array with a single SSD, perhaps for other reasons.

As far as I can tell there's no "undo RAID-0 but keep my data" option. Most of the articles on the web boil down to "copy your data off the RAID-0 array then delete it."

I've periodically kept a few backups to an external 1TB USB drive. So much of the data on the RAID-0 array has already been backed up.

But how to determine which files have been modified since my last backup?

I love Windows Search. In Win7 (and earlier versions) the following query does the trick:

datemodified:>9/1/2012 NOT kind:music NOT kind:folder

All of my music is backed up to Amazon's Cloud Drive so I'm not worried about backing that up.

Logitech Squeezebox and Podcasts

Just got a Logitech Squeezebox and I have to say that I’m very impressed. I was looking for a near-one-click solution for listening to music from the internet through the home stereo speakers.

Things that I like so far:

  1. Ease of setup. Although the jog wheel isn’t the most efficient way to enter an email address or password Logitech has made it as painless as possible. It’s a tradeoff between simplicity (jog wheel) vs speed (keyboard) but since the jog wheel is only painful in one-time setup tasks I think they’ve made the right call. I especially like the fact that the default selection is enter so when you’re done you just click the jog wheel and your entry is submitted.
  2. Breadth of app support. Facebook integration, Spotify and Pandora were a snap to add. I’m listening to one of my Spotify stations right now in fact Smile. Since I moved all of my music to amazon’s cloud player, let’s see if it has support for that.
  3. Podcast support! It would have been easy to overlook this in a mass market but there’s a Squeezebox app for it.
  4. WiFi and Ethernet support. I’m using Ethernet since I had one port left on a switch right next to the player. Switching from WiFi to Ethernet was easy enough to do with the well designed combination of the large jog wheel, bright display and simple menu structure.
  5. This thing is sturdy. It might look cheap but feels quite solid.
  6. The “take it outside” feature might come in handy one day.
  7. It’s at least $100 cheaper than Sonos. And has a built-in speakers.

Speaking of podcasts, I manage all of my podcast feeds through Google Listen. Google Listen uses Google Reader to manage the feeds. Wondering how to find out the URL of one of your feeds? Click the triangle to the right of the feed name in the left nav and a menu will appear. Click the “Details and Statistics” menu entry. The URL and a bunch of other information will be displayed.

Time zones and SQL databases

While working on a project I’ve encountered a need to store time and date information.

Over the past 15 years or so I’ve seen many different frameworks and libraries fail colossally when it comes to dates and times.To mitigate against these issues I went with what was considered best practice around the time I last looked into dates and times: store timestamps in UTC, render them in local time.

This makes date arithmetic easier since UTC doesn’t change during Daylight Savings Time (DST) whereas any given locale’s offset from UTC does change depending on the whether or not DST is in effect. And DST itself gets periodically redefined.

Out of curiosity I wondered when Microsoft’s SQL Server added time zone awareness? Was it much later than Oracle?

Oracle 9i, released in 2001, has the first reference I can find to time zone awareness in Oracle’s date and time formats.

SQL Server’s 2008 release has the first reference I can find to time zone awareness in its date and time formats.

That’s at least 7 years later. Seriously?

Parameter Games: Guessing For Profit

Suppose you’ve got a really nifty way to measure a certain physical property.  It could be height, weight, temperature, pressure, etc…  This measurement wows everyone that takes a few moments to get the gist of it.

Due to TANSTAAFL a measurement so nifty will of course have drawbacks.  In this case the drawback is that this measurement takes a pretty long time relative to other measurements of interest.
So what do you do when you want the benefit of the nifty measurement without the cost of waiting for it to be done everywhere you’d like to do it?

Enter interpolation.  In mathematics, interpolation “fills in” a function given N or more known values.  There are lots of ways to interpolate a function some of which perform better (that is, they more closely approximate the underlying function over the interval of interest) in some circumstances than others.  There are, among others, linear interpolation, quadratic interpolation (or more generally, polynomial interpolation), piecewise interpolation and splines.  Interpolation itself is a specific case of the more general concept of approximation.

In a sense neural networks perform approximation in that they are trained on existing data sets (these are the “known values”) and are later used to produce values on inputs where the outputs are not known.

A common theme with all of these approaches to “filling in” functions is the parameter game.  They’ve all got parameters, some more than others, and tuning those parameters for a specific application (the tuning game) is usually more art than science.

Asynchronous programming using the upcoming await C# 4.5 keyword

One of the features in the Base Class Library of the upcoming 4.5 .Net Framework is a new way to do asynchronous programming. While reading the “Walkthrough: Accessing the Web by Using Async and Await” I started to wonder: How are these method calls updating the UI (by appending to the textbox) from a non-UI thread?

The short answer? They’re not! Asynchronous methods (the ones you await) don’t run on their own thread. For a developer coming from a Windows Forms background (land of the Holy BackgroundWorker) I assumed that the whole await business was a new way of doing multithreading.

Apparently it’s not. It’s a new way of doing asynchronous programming. Until now I considered the two synonymous. await makes it clear that they’re not.

SA1202 All private fields must be placed after all public fields

Resharper’s default type members layout for C# doesn’t enforce the accessibility ordering on fields. So if you turn it on by checking the “Reorder type members” option and you’ve got private constants before public constants then you’ll run into SA1202.

The fix? Add the Access elements to the entry that matches fields and constants. The entire match should look like the following:

<!--fields and constants-->
Kind Is="constant"/>
Kind Is="field"/>
Access Order="public internal protected-internal protected private" />
Kind Order="constant field"/>

And that’s it!

Upgrading the Galaxy Nexus to Android 4.0.4

I decided to flash my Samsung Galaxy Nexus (Verizon) to Android 4.0.4. I went with this ROM (IMM76K) from XDA forums.
Before installing a ROM you need to install the Galaxy Nexus Drivers on your PC, root your phone and install ClockworkRecovery. You can do that manually or use the GNext Toolkit. I highly recommend using the toolkit and watching the 1st or 2nd video because it explains when and how to boot your phone into fastboot mode (adb reboot-bootloader).
Once you’ve installed the drivers and rooted your phone installing a new ROM is a cinch.
There were 2 add-ons that I wanted: tethering and Facebook contacts sync. These are packaged like ROM updates but are downloaded separately (they’re linked in the XDA post for the ROM).

USB Tethering results

And the configuration screen itself. No more carrier check for tethering Smile

Visual Studio Power Tools

If you’re a fan of tools like I am then you’ll appreciate the wonder of the Visual Studio 2010 Productivity Power Tools! They’ve been out for a while but I just got around to installing them. So far I’m loving:

  1. HTML Copy. Now when I copy code from Visual Studio into other applications (like OneNote) the syntax coloring is preserved! Yippee!!
  2. Column Guides. I have mine set at 120 since that’s the recommended line length on my current team. Great to have a visual indicator of this! Just move the cursor to column 120, right click –> Guidelines –> Add Guideline and it’s there.
  3. CTRL+Click to go to definition.

How Ultrabooks Will Restore Traditional PC Dominance

The “Post PC” revolution is on the tip of every pundit’s tongue these days. So I’ve been thinking about how PCs can reclaim some of their former glory. Here’s a quick list of what I’ve come up with so far:

  1. Put every low-cost sensor into every ultraportable pc. Ambient light sensors, accelerometers, GPS, thermometers, barometers, front and rear-facing webcams, etc… The PC needs to be able to accept any input that a smartphone can accept and then some.
    1. With options for more sensitive/higher resolution versions of each of these sensors.
  2. Touch, touch, touch. Windows 8 will help in a big way. It should be easier to find a mobile PC with a floppy drive than it is to find a mobile PC WITHOUT touchscreen support.
  3. Cellular connectivity in addition to WiFi and Bluetooth. Ultrabooks should be able to use voice (GSM and CDMA) and data (3G, 4G) connections from the top US-based carriers without anything dongles sticking out of the chassis. I should be able to go to AT&T, Verizon or T-mobile, pick up a SIM card, pop it into my laptop and be instantly connected. Or pay $25 and have it installed.
    1. With options for supporting top international carrier standards.

The PC’s strong point has always been its general purpose nature. Smartphones and tablets are currently able to do things that cannot be done easily on a PC (e.g., an always one cellular data connection, GPS, etc…). Making these items standard would go a long way towards bridging that gap.

What do you think traditional PCs can do to reassert their dominance over the home computing landscape?

Environment Variables in FOR loops

Let’s say you want to run a program multiple times. The output of each execution should be stored in a separate file to allow for easy comparison. The output filename has useful information so it would be nice to simply append a counter to indicate which run a given output file is associated with. In other words run 1 produces output-1, run 2 produces output-2, …, run N produces output-N.

If you’ve ever tried this using .bat files on windows you might have come up with something along the lines of the following:

@echo off
set f=%1

for /l %%i in (1,1,5) do (
set nf=%f%-%%i

if not exist %nf% (
echo %nf% does not exist
) else (
echo %nf% does exist

Which surprisingly produces output along the lines of output-5, output-5, output-5, ….

By default the command interpreter CMD only evaluates environment variables (nf in this case) once. To evaluate environment variables more than once it is necessary to enable “delayed environment variable expansion".

This can be enabled when the CMD is started with /v:on. (e.g., cmd /v:on). Alternatively, it can be enabled via setlocal enabledelayedexpansion in an already running CMD prompt.

However, %nf% must replaced with !nf! to get the value of the variable based on the current iteration of the enclosing FOR loop.

So the corrected code is:

@echo off
set f=%1

setlocal enabledelayedexpansion

for /l %%i in (1,1,5) do (
REM set nf=!f!-%%i
set nf=%f%-%%i

if not exist !nf! (
echo !nf! does not exist
) else (
echo !nf! does exist


Usability and Answering a Computer’s Questions

One of my favorite things to do is observe how people use software. This is partly self-interest since user interface development is a part of my job and watching people use software makes my job easier.

One of the biggest difficulties can be summarized thusly: Most people do not expect software to ask them questions.

One case illustrates the point. A friend of the family, a doctor, needed her OS reinstalled. During the installation process she had to leave before providing a logon password. I chose the simplest password I could think of (“password”) and set the windows password hint to “your password is password”.

A few days later I received a call wherein she indicated that she was unable to logon to her computer. She had even clicked on the “click here for your password hint” link which displayed the hint “your password is password”. This doctor was somewhat more computer savvy than most – she conducted business remotely over her PC and had been using software for years.

As soon as she re-read the password hint to me over the phone (by then I’d forgotten about it) she immediately said, “Oh! Silly me…” and proceeded to logon using “password” as her password.

This problem spans nearly every level of computing expertise. I’ve seen it in first time users, teenagers, adults, programmers, attorneys, doctors and, on at least one occasion, computer science professors.

It’s difficult because it is nearly impossible to write software that does much of anything without, at some point, needing to ask the user a question.

Developers have tried to approach this problem in a variety of ways. With a text based user interface there’s the prompt that must be answered to proceed. But often user’s aren’t expecting to be prompted. So they start the program, wait a few seconds, then switch to something else. They’re usually quite annoyed to discover, possibly hours or days later, that the program hasn’t done anything because it is waiting on the user to answer a question.

With graphical user interfaces there are several attempts to address the issue. There’s the famous popup (formerly known as a modal dialog box). Users find popups annoying and they suffer from the same problem as text based prompts.

There’s the “flashing taskbar icon” wherein Windows tries to alert users that a program needs their attention. The major benefit of this approach is that it doesn’t interrupt the user thereby reducing user frustration. The downside to this approach is that users will often fail to see the flashing icon.

There are other more exotic approaches: use of audio, video, biometric interfaces, etc… As sensors become cheaper and more ubiquitous these approaches will probably gain traction as they provide a way for software to get answers to its questions without asking users.

In a sense this problem arises from the general purpose nature of the personal computer. Most tools that people use are capable of only a limited number of uses. It’s rare for a tool to have to ask you a question before it can be used (imagine a hammer asking you “how hard do you want to hit this nail?”). Tools that require answers to more than one question are rarer still. Software turns this on its head as it’s rare to find a software program that needs you to answer at most 1 questions for it to be usable.

Until computers can read minds, something us humans have yet to perfect, I think this problem will only be solved by incorporating basic computer literacy into the education that everyone receives. Basic computer literacy must include creating the expectation that computers will ask users questions.