comments edit

Image of a RIM Blackberry
emulatorI’m currently working on an interesting project to develop a series of HTTP services used by games running on the RIM Blackberry. These services will enable players to compete against one another (though not in real time) in various games and see high scores, challenge friends, etc…. It brings a social aspect to gaming on your blackberry device.

The games are written in Java and I’m using a Blackberry emulator for testing the interaction between the game and the services. I’m running the service at localhost on my local machine to allow me to step through the debugger when necessary.

With all these web requests and response shuttling back and forth between the game and the service, it’d be nice to be able to debug that HTTP traffic using a network analyzer like Fiddler.

What Is Fiddler?

If you’re not familiar with Fiddler, it acts as a local HTTP Proxy on port 8888 allowing you to inspect HTTP traffic between your an application and a web application (even one running at localhost). WinINET-based applications (such as Internet Explorer) automatically use Fiddler when its running. For other applications, you need to configure the application to use Fiddler as a proxy.

It’s immensely useful when debugging web services and weird problems with web applications.

It Wasn’t Working For Me

Unfortunately, I ran into an annoying problem. The emulator is not a WinINET-based application nor does it allow configuring a proxy, thus Fiddler was not reporting any traffic.

Configuring Fiddler as a Reverse Proxy

Fortunately, I found instructions on the Fiddler site that shows you how to configure Fiddler as a Reverse Proxy.

A reverse proxy sits in front of your webserver and forwards requests on to your webserver. Thus the application doesn’t need to be configured to use it. All I had to do was ask the developers to change the application to make requests for port 8888 (I’ll explain later why I couldn’t just set up a HOSTS file entry).

I then added a rule to forward requests for localhost port 8888 to localhost port 80 like so:

if ( == “localhost:8888”) \ = “localhost:80”;

Unfortunately, this didn’t work, creating some weird infinite loop when I would make a request to localhost:8888. To rectify this, I added an entry to the HOSTS file to map the hostname MOBILE to the ip address Fiddler apparently doesn’t work as a simple port forwarder (I’ve got a solution for that, keep reading).

Image depicting a hosts file. The last entry shows the ip address mapped to the host name

I then updated the custom rule in Fiddler to route requests for mobile:8888 to port 80 of the localhost and again asked the developers to change the url encoded in the app (I don’t have the source for the client app).

if ( == “mobile:8888”) \ = “localhost:80”;

Now I can monitor requests from the emulator to localhost using Fiddler. One benefit of using Fiddler is that I can replay requests tweaking form values and such.

Image of a Fiddler

Dealing With Hard-Coded URLs

In the most recent build of the game, the game developers accidentally changed the hard-coded URL to point back to the QA environment. For the sake of this example, suppose it is

Rather than asking them once again to change it, I decided to try and work around this. I added the QA server hostname to the HOSTS file just like I did with MOBILE before, pointing it to localhost. I then had to change IIS on my machine to run on a different port, since I planned to configure TcpTrace to listen in on port 80. I chose the perennial favorite alternate port for IIS, port 8080. and used TcpTrace to listen on port 80 and forward requests to port 8080.

Image of TcpTrace window forwarding requests for port 80 to

This allowed me to view the HTTP traffic back and forth between the emulator and the web service again using TcpTrace. Unfortunately, I could not get Fiddler to work in this setup, so I lost some of the ability to tweak and replay requests. This ended up being fine since the latest build is meant for final testing.

The following are some useful resources for HTTP debugging.

code comments edit

A big
wrenche Jeremy Miller believes that among the various beneficial and important qualities a codebase can have, the single most important quality of code is maintainability. I totally agree, having spent many hours maintaining legacy code written years ago as well as code I wrote a week ago.

As soon as a line of code is typed on the screen, it becomes legacy.You are now maintaining that code.

Enterprise software systems change.  Business rules change, technology platforms change, third party dependencies are upgraded.  …

Enterprise systems typically aren’t replaced because they stop working.  The end of life cycle for an application or system is often brought about because the system has become too difficult, risky, or expensive to modify to keep up with evolving needs.

According to Robert L. Glass in Facts and Fallacies of Software Engineering, research shows that maintenance typically consumes from 40 to 80 percent of software costs, typically making it the dominant life cycle phase of a software project.

Fortunately, Jeremy has your back. He’s written a multi-part treatise/manifesto on writing maintainable code. Some of the posts are a bit longer than your typical skim it while reading blogs during a compile entry, but are well worth reading.

Print them out, sit back with a fine glass of scotch, and savor the excellent knowledge he imparts.

I look forward to the next post in the series.

comments edit

While I really enjoyed the holidays, one part was really difficult for me. There was some great discussions happening about Subtext in the mailing list and in various blog posts, but I was too busy to really get involved.

I’m reading everything, but times are really busy for me right now as I’ve fallen a bit behind on the book and have to play catch up. Not only that, work is really picking up.

Unfortunately this means less time to work on Subtext and blog about it. Fortunately, others have picked up the slack over the holiday weekend. I wanted to highlight a few of those posts.

Adding Custom ASPX pages to Subtext

Now that Barry Dorans finally migrated his blog to Subtext, he’s writing about it. One post he wrote deals with how to workaround the fact that Subtext intercepts all requests for *.aspx pages by default. Thus if you try and add an aspx page for your own needs, it won’t get rendered. Barry walks you through how to add your own .aspx pages to a Subtext installation.

Barry also provides a quick tip on how to recalculate view stats in Subtext.

Subtext and IIS 7

Sascha Sertel wrote a couple of interesting posts that cover how to get Subtext up and running in IIS 7 on Vista.

His first post covers Installing Subtext in an IIS 7 virtual directory with SQL Server 2005. His guide provides some great troubleshooting advice for getting Subtext up and running in this scenario. Hopefully the next version of Subtext will support this scenario much better via improved documentation and error messaging.

He has a short follow up post that covers installing Subtext as its own Website in IIS 7. In truth, this probably applies to any web application in IIS 7.

His latest post in this series covers debugging Subtext on Vista using IIS 7 and Visual Studio 2005. While I personally use the built in Webserver.WebDev for debugging, I do need to test the code using IIS before deployment. This is useful information to have.

Merging Blogs

Keith Elder writes about his experience merging two separate blogs into a single blog on Subtext. Once he had the data imported into a local database, he deployed the Subtext code and ran exported the local data to BlogML and imported that same BlogML from the server. Another success story for BlogML.

So I may not be as heavily involved in current Subtext development at the moment as I would like, but development is still moving forward with or without me. That’s a good feeling.

personal comments edit

Not too long ago I announced that my wife and I are expecting a baby this year as part of our world domination plans. Adding fuel to our plans is the discovery that this year is a special year according to the Chinese Zodiac.

It is not only the year of the Pig, it is the Year of the Golden Pig. According to Chinese Folklore, this is an event that occurs once in every 600 years and will ensure that a baby born on this year will experience a prosperous and wealthy life.

This legend is so popular, that Korea is expected to have a 10% increase in birth rate this year, which is apparently much needed as its birth rate is extremely low.

I’m not going to start taking loans against my child’s future wealth just yet as many Chinese foklorists and historians doubt this belief.

However, a folklore professor, Joo Young-ha, at the Academy of Korean Studies rebuts the theory. He explained that if the year 2007 is the golden pig year which comes every 600 years, there should be records about the special year written in the ‘Taejong Sillok,’ archives of King Taejong. King Taejong ruled the Joseon Dynasty 600 years ago. But there are no such records, which makes him believe the myth was made not long ago.

Well I have a thought for you Joo Young-ha. Quit raining on our parade! Perhaps the Year of the Golden Pig happens every 600 years from now.

comments edit

K. Scott Allen, Jayson Knight, and Keyvan Nayyeri all tagged me, so despite my general antipathy towards these viral questionnaire memes (they remind me of that silly slambook fad in grade school), this one is interesting enough for me to respond.

Besides, since my main machine is still fried until Dell manages to ship me my new video card, I’ve got nothing better to do.

1. In Florida, I helped build a casino.\ Yellow Hotwheel
CarWhen I was around eight or nine years old, I was part of a toy car club. We had meetings to discuss the relative merits of Matchbox vs Hotwheels and what qualities to look for in purchasing a collectible car. We also put on various car shows for the neighborhood kids.

The club leader was a much older kid who decided to raise funds by building a casino. He put us all to work building a shed in his yard and we stocked it with those working toy slot machines, a blackjack table, a roulette wheel etc…

With that in place, we rounded up all the neighborhood kids and had them play the games with real money. I think the club president was using all of us to make himself some extra cash (not to mention doing his chores by building a tool shed/casino) because I recall hefty membership fees to join the club and he pretty much wouldn’t let me cash out my winnings at the casino, egging me on to continue playing until I lost everything.

2. I was part of a breakdancing crew in Spain.\ Man performing a one handed handstand while grabbing his foot with
the other
hand. Who wasn’t part of a breakdancing crew back in the mid-80s? Me and my friends used to battle against the local Spanish kids.

For those who are unfamiliar with the breakdancing vernacular, battling was the act of dancing in a manner so as to impress your buddies and onlookers, while insulting your opponent with such clever actions as pretending to eat an opponent’s head and throwing the excreted result back at him.

My specialty was the head spin.

3. When I was a baby, I nearly drowned in a river in Korea.\ River All I remember was climbing onto an inflatable raft. I must’ve been around three or four. The next thing I know, the sucker flipped and I was drifting towards the bottom. As I was sinking, I remember looking up and seeing my uncle swimming towards me and pulling me up. Apparently I was deathly afraid of water for years afterwards. I’m fine now thank you.

4. I embarrassed myself on television in Guam.\ A ship on the open seas near an island. It is the HMS
Beagle. During Middle School, I was part of the Academic Challenge Bowl team for my school. We would go on local public access television to play a Jeopardy like game against the other middle schools.

In my first game, I got a little buzzer happy and buzzed right in the middle of the question. What I heard was something like this:

Charles Darwin formulated his theory of evolution during a trip to…

I buzzed in and blurted out “Galapagos Islands!” Sorry, no. The moderator continued,

…the Galapagos Islands. What was the name of his ship?


5. In High School, I struggled with math and considered going to art school.\ A self portrait of Van
Gogh I have a bit of a reputation among my friends for being a bit of a math geek. However, due to the fine quality of the educational institutions in Guam, I was actually a year behind my college-bound peers in math when I moved to Alaska.

English was my better subject during highschool. While I struggled with math, I aced both the AP English and AP Literature exams (earning me bookoo college credit).

In fact, during this time, I was seriously considering going to an art institute. What convinced me otherwise was the thought that I would miss the fun of the traditional college experience (Old School anyone?) if I went to a more vocational school. Yeah, that was some seriously deep reasoning.

Tag, You’re It

Ok, so in keeping with this meme, I must now tag five people (a few of whom are the least likely to reply to this) who are then honor bound to reply with their own five things nobody knows or they will lose an eye, or something like that.

comments edit

Here’s wishing you a Merry Christmas and a Happy Holidays. For Christmas, I received a defective video card as a warranty replacement for my defective video card. Thanks Dell! The replacement card was more defective than the one I returned.

Unfortunately this means I can’t work on my book until I get it replaced. On the plus side, I have more time to spend with my visiting family.

Tonight, we have our annual Alaska King Crab Christmas dinner. I’ll post pics later.

personal comments edit

No, this was definitely not a good sight for me. With my team pressing the attack, an unfortunate turnover left our defense out of position to help as the opposing team quickly capitalized.Ezra and
Me (Click on any pic for a larger view).

Squinting toward the sun, I saw 6’ 3” Ezra Hendrickson of the Columbus Crew barreling towards me, the last man back on defense. Fortunately his midfielder’s cross was a bit too long, allowing me to pluck it out of Ezra’s path.

With Ezra backtracking towards me attempting to regain the attack, I looked up for a midfielder to distribute the ball to, finding Preki, former U.S. National team player, ready to receive the pass and orchestrate the counterattack.

Jerseys Might sound like a soccer lover’s wet dream, but this is just a small snippet of what I’ve been up to this past week. I attended the Los Angeles Galaxy’s Adult Fantasy Soccer Camp.

Yeah, the name is a bit snicker-worthy (Adult Fantasy Camp, heh-heh heh-heh?), but such camps are common for other sports such as baseball and basketball. It’s an opportunity for soccer lovers to get a taste of the pro treatment.

For me, it was four straight days of heaven. Two practices a day with former and current Galaxy coaches. Expert guidance from fitness trainers from the company who Jürgen Klinsmann selected to work with the German National team. Guest appearances from several soccer celebrities (though three of them happen to be in my soccer league).

Lounge The camp was held at the Home Depot Center, the home of the Los Angeles Galaxy. We used the same facilities they use, including their lockers, their training fields, and their lounge (seen here at right).

When I first arrived, my locker had two kits neatly displayed in my locker. An away jersey and a practice jersey. You can see my jersey in the picture below right.

#8 Each day started with a morning session which commenced with a warmup lead by an instructor from Athelete’s Performance. I particularly appreciated their philosophy against static stretching before exercise as it can decrease performance. Instead, athletes get a stretch by working through the natural range of motions in various warm-up exercises. Static stretching is great for after workouts.

Afterwards, we ran through various drills and small sided games led by the expert coaches. The afternoon sessions focused more on actual playing and tactics, with the occasional shooting and defensive drill thrown in.

For the most part, the other participants were a diverse group, but the soccer community is a small world in Los Angeles. Four other participants were current or former teammates of mine.

Max, Me, and
Joaquin, and

The Grand Finale of the camp is a full field game with professional MLS referees between two teams chosen by the coaches. On the penultimate day, I noticed the two coaches hunched over their notes furiously picking teams and making trades between the two of them. For the coaches, this was a matter of pride to see who could pick and coach the better team.

The morning of match day, they revealed the lineup, but did not reveal the allocations (marquee players to be announced) until lunchtime. The other team received a current pro and a former college player. We received a former college player, our second allocation not able to make it.

Fortunately, our coach is quite shrewd and happened to run into Preki who was there to interview for the Chivas coaching job. After his interview, he was happy to come out and play one half with us.

The coach gave me a decisision to make, would I stay in the attacking midfield, or reliquish the spot to Preki. That, my friends, is a no-brainer. With a player of that caliber around, I moved back to central defense, ready to get my Beckenbauer (actual compliment from a teammate after the game).

Although I felt we were the superior team, we ended up tying the match 3 to 3. A disappointing result considering how much we possesed the ball. Our last shot of the game nicked the post, almost giving us a game winner at the last second.

My friend Donny filmed much of the camp and will be putting together a video for the MLS. Being his carpool partner, it’ll have a lot of me in it. ;) If you’re a soccer lover in or near Los Angeles, I totally recommend this camp next year.

comments edit

VillagersClean drinking water piped to my house is something I take for granted (yes, even in Los Angeles). When I stop to think about it a bit, I can’t imagine how tough it must be to not have clean drinking water.

For people in four remote areas of Malawi, this is a day to day reality. Fortunately, there are people trying to do something about it. Wells for Zoë is a charity dedicated to bringing clean water to these areas.

Jamie Cansdale, famous for TestDriven.NET (a tool near and dear to my heart), is doing his part to contribute to this good cause by starting a .NET software charity auction. Several generous vendors have donated licenses to great software you can bid on. If you have the means, consider making a bid. If not, perhaps you can make a small direct donation.

comments edit

Today my team had a friendly preseason game against Hollywood United. They fielded a mixture of a few players from their 40 and over team, but most of the players were from their main team.

While Alexi and Frank were not there today, Hollywood did field the Mean Machine, Vinnie Jones. He is a former professional player from England who was part of the Crazy Gang team that won the FA cup in 1988. He’s notorious for dirty play, but now more well known for his acting, such as the role of the Juggernaut in X-Men 3.

Grabbing the wrong soccer


Despite being known for his rough tactics, it still takes talent to play at the level he played at, and it showed today. He put in a sweet freekick to the upper corner. And yes, he looks even meaner in person than he does on film. He’s a tough looking Mofo.

Another well-known player was Steve Jones, former guitarist for the punk band the Sex Pistols, who also hosts Jonesy’s Jukebox. Jimmy Jean-Louis is also on the team. He plays the guy who can erase memories on the new NBC show, Heroes. They’re not kidding when they call themselves Hollywood United.

At the end of regulation, we were tied 4 to 4. Since it was a friendly and we had paid for the field for 10 more minutes, we played a short overtime period in which they scored two more goals, the final being 6 to 4. We should’ve faked injuries and left while we were tied. Wink

comments edit


I know what you’re probably thinking. Did Phil forget to take his meds today? Let me explain.

Yesterday I thought I would try my hand at upgrading to Vista. But first, being the conscientious geek that I am, I tried to mirror my current drive to a brand new drive.

I plopped the new drive carefully (as carefully as one can plop anything) into the machine, and the system wouldn’t boot. So I retreated, pulling the old drive out and putting everything back the way it was.

Or so I thought.

The machine still wouldn’t boot. I ran the entire suite of Dell diagnostics tests on it. I also ran CHKDSK /F on it. Nothing. I ran out and bought a new SATA cable. Nothing. As far as any software test could tell, the drive was fine. It was being recognized by the BIOS, it just wouldn’t boot.

I plopped my new drive (again carefully) into the primary spot and was able to perform a clean install on it. So my machine can boot on my new drive with Vista, but not my old drive with Windows XP. How strange! At least I can access my old drive from Vista in order to copy important files over to the new drive.

As an aside, why do we say we perform installs? It’s not like anyone is watching, nor would they really want to. Who is being entertained?

Today, I was still dealing with the aftermath of this drive failure when I chatted up Micah on Skype. He remarked that everyone in our company seems to be having computer issues today. Jon’s having problems with his sound card, Pat misplaced his laptop, and Micah’s USB flash-drive failed. He says,

Must be something in the air. Maybe there was a huge solar flare or something.

Then it struck me.


I remembered reading that in fact there is a huge solar flare headed towards Earth. Well there you go, say no more. That explains it. A solar flare hosed my drive. Right now I am trying to mirror my new drive over my old drive to see if it’ll boot up with Vista. If it does, then it would seem to me that somehow Windows got corrupted on my old drive. Perhaps a solar particle flipped the AllowBootAndJustWork bit to 0. Just my luck.

In any case, it’s a good thing I have a couple of backup machines to blog from.

comments edit

I don’t suffer from classic OCD (Obsessive Compulsive Disorder), but I do sometimes have OCD tendencies. Just ask my poor wife when we’re having dinner while my mind is still trying to resolve a thorny programming problem. Earth to Phil. Are you on this planet?

Lately, the object of my OCD-like tendencies is getting the Subtext unit test code coverage up to 40%. At the time of this writing (and after much work), it is at 38%. Why 40%? No reason. Just a nice round number that we’ve never yet hit. Remember, OCD isn’t necessarily a rational affliction.

If code coverage is my disease,TestDriven.NETwithNCoverExplorerintegration is my drug, andJamie Cansdaleis my dealer. He graciously gave me a pro license as a donation to the Subtext project.

So here’s the anatomy of a code coverage addiction. First, I simply right click on our unit test project, UnitTests.Subtext, from within VisualStudio.NET 2005 (also works with older versions of VS.NET). I select the Test With menu option and click Coverage as in the screenshot below.

Test With Coverage in VS.NET

After running all of the unit tests, NCoverExplorer opens up with the a coverage report.

NCoverExplorer coverage results in Left

I can drill down to take a look at code coverage all the way down to the method level. In this case, let’s take a look at the Subtext.Akismet assembly. Expanding that node, I can drill down to the Subtext.Akismet namespace, then to the HttpClient class. Hey! The PostClient method only has 91% code coverage! I’ve gotta do something about that!

NCover Drill

When I click on the method, NCoverExplorer shows me the code in the right pane along with which lines of code were covered. The lines in red were not executed by my unit test. Click on the below image for a detailed look.

NCoverExplorer Code Coverage

As you can see, there are a couple of exception cases I need to test. It turns out that one of these exception cases never happens, which is why I cannot get that line covered. This may be better served using a Debug.Assert statement than throwing an exception.

If you haven’t played around with TestDriven.NET and NCoverExplorer, give it a twirl. But be careful, this is powerful stuff and you may spend the next several hours writing all sorts of code to get that last line of code tested.

Here are a few posts I’ve written that you may find useful to eke out every last line of code coverage.

Now get out there and test!

code, tdd comments edit

Here we are already looking ahead to learn about the language features of C# 3.0 and I am still finding new ways to make my code better with good “old fashioned” C# 2.0.

Like many people, I tend to fall into certain habits of writing code. For example, today I was writing a unit test to test the source of a particular event. I wanted to make sure that the event is raised and that the event arguments were set properly. Here’s the test I started off with (some details changed for brevity) which reflects how I would do this in the old days.

private bool eventRaised = false;

public void SettingValueRaisesEvent()
    Parameter param = new Parameter("num", "int", "1");
    param.ValueChanged += OnValueChanged;
    parameter.Value = "42"; //should fire event.

    Assert.IsTrue(eventRaised, "Event was not raised");

void OnValueChanged(object sender, ValueChangedEventArgs e)
    Assert.AreEqual("42", e.NewValue);
    Assert.AreEqual("1", e.OldValue);
    Assert.AreEqual("num", e.ParameterName);
    eventRaised = true;

A couple of things rub me the wrong way with this code.

First, I do not like relying on the member variable eventRaised because another test could inadverdently set that value, unless I make sure to reset it in the SetUp method. So now I need a SetUp method.

Second, I don’t like the fact that this test requires this separate event handler method, OnValueChanged. Ideally, I would prefer that the unit test be self contained as much as possible.

Then it hits me. Of course! I should use an anonymous delegate to handle that event. Here is the revised version.

public void SettingValueRaisesEvent()
    bool eventRaised = false;
    Parameter param = new Parameter("num", "int", "1");
    param.ValueChanged += 
        delegate(object sender, ValueChangedEventArgs e)
            Assert.AreEqual("42", e.NewValue);
            Assert.AreEqual("1", e.OldValue);
            Assert.AreEqual("num", e.ParameterName);
            eventRaised = true;
    param.Value = "42"; //should fire event.

    Assert.IsTrue(eventRaised, "Event was not raised");

Now my unit test is completely self-contained in a single method. Lovely!

In general, I try not to use anonymous delegates all over the place, especially delegates with a lot of code. I think they can become confusing and hard to read. But this is a situation in which I think using an anonymous delegate is particularly elegant.

Contrast this approach to the approach using Rhino Mocks I wrote about a while ago. In that scenario, I was testing that a subscriber to an event handles it properly. In this case, I am testing the event source.

Technorati Tags: Tips, TDD, C#, Rhino Mocks

comments edit

Steve Harman just announced the release of Subtext 1.9.3. This is primarily a bug fix release, though there are a couple of small improvements.

You can download the latest bits here.

Many thanks to Steve and the rest of the Subtext crew for all the hard work in getting this release together. Ever since I wrote that Subtext Job Posting blog post, we’ve had a lot more active contributors lending a hand, which has been a big help. Your participation is very much appreciated!

With 1.9.3 out of the dock, all focus is now on getting Subtext 2.0 ready for deployment.

So far, progress on Subtext 2.0 has been going better than I expected. We have an early implementation of our plugin framework working, though we still have a lot of improvements and polishing to do on it. The Membership Provider is also working, though we have a few refactorings we’re considering to the data model.

code, tdd comments edit

A Scanning Test - From

Last night a unit test saved my life (with apologies). Ok, maybe not my life, but the act of writing some unit tests did save me the embarrasment of an obscure bug which was sure to hit when I least expected it.  It is cases like this that made me into such a big fan of writing automated unit tests.

Not too long ago I wrote a C# Akismet API for Subtext. In writing the code, I followed design principles focused on making the API as testable as possible. For example, I applied Inversion of Control (IOC) by having the AkismetClient constructor take in an HttpClient instance as an argument. The HttpClient instance is responsible for making the actual HTTP request.

This allowed me to use Rhino Mocks to replace the HttpClient with a mock enabling me to build unit tests that ensured that the Akismet API was doing the right thing without having to make any actual web requests.

Of course this approach only delays the inevitable. I still want to have an automated test for the HttpClient class.

So last night, I took a step back and revisited this excellent post by Scott Hanselman in which he shows how to use Cassini in your unit tests. I decided to update his pioneering approach to use the latest incarnation of Cassini, WebServer.WebDev. I also decided to refactor what he did into a reusable TestWebServer class in order to make the barrier to entry in using it as low as possible.


WebServer.WebDev is the built in Web Server (formerly known as Cassini) used by Visual Studio.NET 2005. The main functionality of the server is located in WebDev.WebHost.dll. You can find this assembly in the GAC. On my machine, it is located in the following directory:


Note that the .NET framework installs an explorer extension for the GAC so you won’t see this directory using Windows Explorer. I navigated to the directory using the command prompt.

Setting up the test web server is a two step process once you’ve located the WebDev.WebHost assembly.

  1. Copy WebDev.WebHost into your unit test project and add a reference to it.
  2. Add the TestWebServer.cs file into your unit test project.

Note: To make this really reusable, you could drop this class into a separate Unit Test Helper assembly that you reference in your unit test projects. If you do go that route, be sure to heed the “//NOTE” I left for you in the ExtractResources method.

TestWebServer Usage

The following shows a couple of ways you can use this test web server in your own unit tests. If you have a single test in a fixture that needs to use the server, you can do something like this:

using (TestWebServer webServer = new TestWebServer())
      , "SomePage.aspx");
    string response = webServer.RequestPage("SomePage.aspx");
    Assert.AreEqual("Done", response);

If you have a set of tests that need to use the web server, I suggest using the [TestFixtureSetUp] and [TestFixtureTearDown] attributes to start the web server just once for all the tests.

private TestWebServer webServer = new TestWebServer();
private Uri webServerUrl;

public void TestFixtureSetUp()
    this.webServerUrl = this.webServer.Start();

public void TestFixtureTearDown()
    if(this.webServer != null)

I added several helper methods to the TestWebServer class based on what Scott did.

ExtractResource takes in the full path to an embedded resource and extracts it into the test webroot. In the first code example above, I extracted an embedded resource into a file named SomePage.aspx. Be sure to call this method after the webserver is started.

RequestPage has two overloads. One which makes a simple GET request to the test web server, and the other which makes a POST request.


In the past, I have gone to great lengths to not using a web server to unit test my code, as that takes us more into the realm of Integration testing. A while ago I wrote a post on how to simulate the HttpContext for unit tests without using a web server. This approach has been improved upon in the Subtext unit test codebase and has served me well.

But even that approach can only go so far. As I pointed out in my post on a Testing Mail Server, it’s a good thing to abstract out these extensibility points using an interface or a provider. But at some point, you have to test the concrete implementation. I can’t keep delegating functionality endlessly to another abstraction. Somebody has to make a real HTTP request.

So consider this approach the method of last resort.


The test webserver class can be downloaded here from my company’s tools site.

comments edit

PDC 2007 Developer
Powered According to Brad Abrams, it looks like we’re going to have us another PDC in 2007. For those of you not in the know, PDC stands for Professional Developer Conference. These are conferences in which Microsoft shows off upcoming technologies that us developers will be using.

It’s not till October 2, so there’s still time to scrounge up the money to go, assuming I don’t lose it all at the blackjack tables at Mix 07 (I should have stayed at the craps table,Steve Mainecan back me up on that).

I probably know a back door or two I can sneak through if it comes to that. I’m looking forward to having all you illustrious developers in my neighborhood (Westside!). It’s too early for a roll call, but be sure that I hear about it when you decide to attend.

I do know where to get the best Korean food.

comments edit

Subtext has a pretty sweet Continuous Integration setup using CruiseControl.NET running inside a virtual server inside a real computer in my home office. The man responsible for this setup is Simone Chiaretta, who just unveiled his new English language blog, CodeClimber.

His former blog was in Italian, which made it diffult reading for me, as Babelfish totally mangled translations.  When Simone is not writing about broken ribs from kite surfing or bagging the latest peak, he just might get around to writing about the CCNET setup he created for Subtext. Wink

comments edit

Green Light from Code Search is truly the search engine for the uber geek, and potentially a great source of sublime code and sublime comments.  K. Scott Allen, aka Mr. OdeToCode, posted a few choice samples of prose he found while searching through code (Scott, exactly what were you searching for?).

One comment he quotes strikes me as a particularly good point to remember about using locks in multithreaded programming.

Locks are analogous to green traffic lights: If you have a green light, that does not prevent the idiot coming the other way from plowing into you sideways; it merely guarantees to you that the idiot does not also have a green light at the same time. (from

The point the comment makes is that a lock does not prevent another thread from going ahead and accessing and changing a member.  Locks only work when every thread is “obeying the rules”.

Unfortunately, unlike an intersection, there is no light to tell you whether or not the coast is clear. When you are about to write code to access a static member, you don’t necessarily know whether or not that member might require having a lock on it. To really know, you’d have to scan every access to that member.

This is why concurrency experts such as Joe Duffy recommend following a locking model.  A locking model can be as simple or as complex as needed by your situation.

In any case, have fun with Google Code Search. You might find yourself reviewing the code of a Star Trek text-based sex adventure.

comments edit

Just thought I would highlight something I mentioned in my last post because I thought it was particularly funny. I wrote about joys using Google Code Search to search through source code for interesting comments. Definitely a geeky pasttime.

However that geekiness is overshadowed by something interesting I found. In this case, it’s not the comments that are interesting, but the actual code itself.

It appears to be a lonely geek’s fantasy written in code. A text-based adventure about sexcapades with Dr. Beverly Crusher on the star trek enterprise. Here’s a tame snippet to give you an idea.

dancewithdesc ( actor ) = { "You and [Dr. Beverly Crusher] dance a quiet, soft, close dance around her quarters. It is really quite chaste, but you find yourself intoxicated by her scent and stimulated by your grasp and hers, both of which stray far lower on each others’ backs than is supposedly called for with this step.";


You have to read it to believe it (warning, trashy novel style adult content).

comments edit

UPDATE: Looks like the DNS issue is starting to get resolved. The fix may not have fully propagated yet.

If your Akismet Spam Filtering is currently broken, it is probably due to a DNS issue going around. I reported it to the akismet mailing list and found that people all over the world are having the same issue. It is not just a Comcast issue.

The temporary fix is to add the following entry into your hosts file:

Hopefully the Akismet team will fix this problem shortly.

comments edit

My favorite unit testing framework just released a new version. Andrew Stopford has the announcement here and you can download the release from the MbUnit site.

I met Andrew at Mix 06 early this year and he’s a class act and great project lead. I’ve been following MbUnit’s progress on and off and am really happy with the team’s responsiveness to my submitted issues.

My one tiny contribution to the project was to purchase the domain for them. Perhaps a little bribe to get my feature requests looked at promptly. ;)

If you are wondering why I prefe MbUnit of NUnit, check out these posts: