Browsing Posts published in June, 2006

CopySourceAsHtml is a godsend for those developers who need to display source code in HTML format. (Blogs, online documentation, and developer forums all come to mind as reasons you need to display code as well-formated HTML.) A version compatible with VS 2005 was just released. To understand why you need this VS add-in, take a look at Hello World as copied and pasted using Edit… Copy… Paste…

using System;

namespace JamesKovacs.Examples {
    /// <summary>
    /// Summary description for HelloWorld
    /// </summary>
    static class HelloWorld {
        public static void Main() {
            Console.WriteLine(“Hello, World!”);

With CSAH, you get:

using System;


namespace JamesKovacs.Examples {

    /// <summary>

    /// Summary description for HelloWorld

    /// </summary>

    static class HelloWorld {

        public static void Main() {

            Console.WriteLine(“Hello, World!”);




CSAH is highly configurable with options to display line numbers, change fonts, override tab size, etc. If you have Consolas installed on your system, the above code snippet will be displayed in it. Otherwise, I configured a fallback to Courier then sans-serif by overriding the font list. (If you don’t override it, it uses whatever your current editor font is set to.) Awesome VS add-in!!!

After a long hiatus, Richard Lander is back. Richard is a PM on the CLR team at Microsoft responsible for the loader and versioning. He’s also a Cannuck working in Redmond. I’ve had the distinct pleasure of chatting with him on a number of occassions. Due to moving, a second child, and site-hosting changes, his blog – CLR Hoser – went off-line about 6 months ago. He’s back and ready to blog. You can also catch him on DNIC discussing all things CLR with John Bristowe.

I’ll be heading up to Edmonton at the end of this month to present a double-header on Enterprise Architecture and .NET Tools to the Edmonton .NET User Group. The site says it’s a Level 300 talk. So I better go make my examples more complicated. :^)

Date/time: Thursday, June 29, 2006 starting at 5:30pm
Location: Stanley A. Milner library (7 Sir Winston Churchill Square)

You can sign up on the EDMUG website.

I’ll also be playing Santa Claus (minus the roly poly belly) as I’ll be bringing the Calgary Code Camp prizes that the Edmontonians mopped up on. (Thanks to everyone from Edmonton who came down and attended the Calgary Code Camp!)

So TechEd 2006 has wrapped up. I haven’t blogged as much as I had originally planned, but that’s because I’ve been busy attending sessions and talking to cool people. It’s been a pleasure and an honour to talk to some of the biggest names in the industry. (No, I didn’t get a chance to talk to Mr. Gates or Mr. Ozzie. Maybe next time.) :^) Being in Boston again has been a blast, but I’m looking forward to heading home to Calgary. Coming with me is a bag o’ swag, much of which you can see pictured below. (After snapping the pics, I noticed another pile that I’d forgotten to include.)

Of particular note is the Office System “chalk duster” – behind the action figures. It’s actually a T-shirt. I’m told the wrinkles iron out easily. You can also see the Source Fource action figures, a SQL Server magic 8-ball, loads of flashlights, magazines, and book samples. I got the backpack for trying out Windows Vista and won Halo 2 at the booth. (Now I just need an XBox to play it on.) Of special note, Compuware – the makers of some truly awesome developer tools – allowed attendees to spin a wheel for the chance to win a USB key! I won the chapstick with the freaky-looking purple hair – you can see it to the left of the Source Fource. Definitely the lamest prize I saw at the show. I also managed to replace my entire wardrobe with the number of free T-shirts I received.

I did snap a few amusing pictures while at the show. I think the “InfoCard” team really liked the name change to “Cardspace”.

And is Business Objects trying to make a statement about the ease of use of their Crystal Reports product?

Overall I had a blast at TechEd 2006 in Boston. TechEd 2007 will be in New Orleans again. Hopefully I’ll be there!!!

People have been hypothesizing about this moment for years. The rumours became even more heightened with the hiring/purchase of Ray Ozzie. Bill Gates’ non-appearance at the keynote for TechEd, which I highlighted here, was another hint. Well, the day has come. Bill Gates has announced that he is transitioning away from his daily duties at Microsoft to focus on his charitable work with the Bill & Melinda Gates Foundation, though he will remain CEO in name. Everyone saw it coming, but I personally didn’t think the announcement would come this soon. The transition will take place over a two year period. Ray Ozzie, currently CTO, will take on Gates’ title of Chief Software Architect. Craig Mundie, another CTO, will take on the title of Chief Research and Strategy Officer.

It’s been an exciting past two days. Unfortunately FireFox ate my Day 2 report. So I’ll have to resummarize it. (I’ve downloaded BlogJet, which is a well-respected offline blogging package, to craft up this blog post and prevent a repeat performance of yesterday.) I saw some great talks and the highlights from Day 2 included:

  • Live from Tech-Ed: .NET Rocks! Show by Carl Franklin and Richard Campbell, hosts of .NET Rocks, where they talked to two members of the team building Visual Studio Team System for Database Professionals. This new SKU of VSTS brings refactoring, unit testing (written in T-SQL), test data generation, schema diffing, and source control to database gurus. We don’t get any nice design surfaces for modelling or the ability to design logical model and then build physical model. Those are features they’re thinking about for vNext along with supporting databases other than SQL Server. The team’s dev cycle is only 9 months and they plan to ship by the end of the year. Not bad for a major product release. This looks to be a promising SKU for the data-inclined.
  • Windows Communication Foundation: More Than Just SOAP by Steve Maine where he showed off some nifty tricks on making WCF produce RSS and ATOM feeds. Very neat stuff. He talked about the extensibility of the WCF pipeline. Steve is a smart guy and it was neat to see some of the crazy stuff you can do to extend WCF.
  • Windows Vista: Kernel Changes by Mark Russinovich and David Solomon where they talked about all the changes that are coming in the Windows Kernel, both for Vista and “Longhorn” Server. Deep stuff. These guys just make your head hurt, but in a good way. One neat change is that applications can reserve I/O bandwidth and boost themselves up to a “real-time” mode. This means that Windows Media Player 11 won’t stutter or drop clip when your virus scanner kicks in. The music/video will just keep on playing as if nothing happened. They also talked about User Account Protection (UAC), new synchronization primivitives in the OS, user-mode device drivers, and other nerdy stuff. I loved it! 
  • CLR: IronPython and .NET Scripting Languages by Mahesh Prakriya and John Lam (creator of RubyCLR) where they tried to convert us to dynamic language zealots. Dynamic languages are scripting languages on steroids. All the good things of scripting (easy development, flexibility, terse yet readable syntax) without the bad (read VBScript). RubyCLR is a bridge (like COM Interop) that allows Ruby to call into .NET and vice-versa. Ruby code still runs in the Ruby interpreter (irb.exe) and .NET code still runs inside the CLR. People are working on compiling Ruby to IL so that it can run directly in the CLR. Microsoft is even working at making the CLR friendlier for dynamic languages. I’m not going to be dropping C# anytime soon, but I might take John up on his offer of one hour to show me the zen of Ruby. If you’ve never tried Ruby, I would recommend taking TryRuby for a spin. Mahesh talked about IronPython, which is a super-fast Python implementation for .NET. IronPython actually compiles Python code to MSIL. Both guys gave a great talk, but John definitely stole the show (in a good way).

So here I sit in my hotel having just attended the keynote. Before I get to talking about the keynote, I noticed these signs all over the place on the way over:

You know that you’re at a big conference when the city puts up big signs all over the downtown welcoming you. Uh, thanks, Boston. Glad to be here.

So let’s talk about the keynote… Bob Muglia started things off. This year’s theme was “People-Ready Software”. Bob reiterated Steve Ballmer’s sentiments that the products (Vista, Longhorn Server, Exchange 2007, Office 2007, etc.) will ship when they are ready. They are on-target for the planned dates, but that could change based on feedback on the betas from a wider audience. (Steve Ballmer got everyone’s knickers in a knot when he made this comment a few weeks ago. Some analysts and journalists took this to mean that Vista is going to slip again rather than the real sentiment that they won’t knowingly ship a shoddy product.) With that, Bob introduced Ray Ozzie. (Rumour has it that Ray is being groomed to take over from Bill.) Overall I enjoyed hearing Ray Ozzie speak – definitely the best speaker of the keynote. People describe him as a visionary, which I think is accurate, though I was hoping for him to be more visionary. Much of what he said was common sense. Even if you don’t agree with everything he says, you can see that he has an idea of the future and how to get there. His track record speaks volumes as he was involved in Visi-calc, Lotus 1-2-3, Lotus Notes, and Groove. (Microsoft bought Ray Ozzie and got a nice product called Groove thrown in for free.) To further fuel the rumour that Ray is taking over for Bill is that Bill was neither seen nor mentioned.

So what did Ray talk about? He forsees a new era of disruption, much like the disruption caused by the PC, the LAN, the internet, and P2P networks. He dismissed other companies’ (read Google) notions that the next big event will be completely web-based AJAX-enabled applications. Yes, you can do amazing things on the web and Microsoft will help developers build those next generation web applications, but more important is applications with architectural flexibility, for which he used Groove as an example. (Big surpirse.) The next generation of software will be enabled to connect peer-to-peer or client-server, depending on whether you’re inside or outside your corporate firewall. Applications will be centrally managed whether they’re connecting P2P or client-server. So if you have a number of employees away from head-office, they can create an ad-hoc network for sharing ideas and information and then sync up once they are back. He also talked about the work that Microsoft is doing with respect to federating corporate Active Directory with Windows Live Identity. This will allow your corporate identity to be used in trust relationships with partners. The basic idea of federation is one corporate identity that can be used with trading partners. So if someone from ABC Inc. buys widgets from XYZ Corporation and she needs to log into the XYZ order fulfilment site, federation would allow XYZ Corporation to assign access permissions based on her ABC login rather than having to issue her a XYZ user account. Very cool stuff. He talked about managing personal devices via group policy. People bring personal cell phones, laptops, and memory sticks to work because they find them useful. Rather than forbidding all personal devices, the plan is to establish acceptable use policies using group policy. Lastly he talked about “The Services Disruption” – Enterprise Services and Internet Services melding together. Blended internet/intranet search. The idea of “Client, Server, and Service”. Dynamic and charismatic speaker. I can see why everyone thinks he’ll take over from Bill. So that was The Good.

Bob comes back and introduces the idea of the “4 Promises” that Microsoft is making to its customers and partners. He introduces Mary Lynn Rajskub, who plays Chloe on the show “24″ opposite Kiefer Sutherland. (I’ve never actually watched “24″. So no comments on the show.) This is a lead-up to the first of a 4-part series called “4″, which parodies “24″, and stars much of the Microsoft brass (minus Bill again) as the server room interns. We see the 4 parts in installments throughout the 2-1/2 hour keynote. Some are vaguely amusing, but overall rather silly. The outtakes at the end are the best part showing the Microsoft brass goofing around. Chloe also visits us repeatedly throughout the keynote delivering lame lines read verbatim from a ticker. Her performance was painful. I could almost hear her thinking “what has my agent gotten me into”. That was The Bad. So rather than dwell on that any more, let’s look at the 4 promises:

  1. Manage Complexity, Achieve Agility
  2. Protect Information, Control Access
  3. Advance the Business with IT Solutions
  4. Amplify the Impact of Your People

I won’t recount each of the promises, but here are some outtakes from each one.

Promise #1: Manage Complexity, Achieve Agility

  • 3 different types of virtualization, each with its own benefits and drawbacks
    • Hardware virtualization – Where we are today
    • OS Services virtualization – furthest out – past Longhorn – very important in hosting situations
    • Application virtualization – Microsoft acquired Softricity to enable this scenario – incompatible applications running side-by-side in the same OS – for instance different versions of Office
  • Demo of Windows Server Virtualization, which will ship with Longhorn Server
    • Can allocate more than 3.6 GB of memory to a guest OS with >32 GB possible
    • Guest OSs can be assigned up to up to 8 CPUs – currently Virtual Server supports 1 or 2
    • You can dynamically change the amount of memory allocated to a guest OS without re-starting the guest! Very cool!
    • Hot adding of disk space, CPUs, and NICs is also possible.
    • 64-bit guest OS support!

Promise #2 – Protect Information, Control Access

  • Microsoft Forefront Client Security announced
  • Antigen (for Exchange, SharePoint, etc.) can use up to 9 AV engines for enhanced protection

Promise #3 – Advance the Business with IT Solutions

  • Demo of Visual Studio Team System for DB Pros
    • Refactoring support in the database
    • Unit testing in the database written in T-SQL
  • Demo of Expression Interactive Designer for use by graphic artists
    • File format is XAML
    • Programmer can use the same file in Visual Studio and implement code-behind much like ASP.NET, but for a graphically rich application

Promise #4 -Amplify the Impact of Your People

  • Product launches announced
    • Office Enterprise 2007 – October 2006
    • SPS 2007 – October 2006 – intranet, internet, extranet, enterprise search
    • Exchange 2007 – Beta 2 in July – email, calendar, & unified messaging server
    • Live Communications Server “12″ – Available in 2007 – real-time communication – IM and video calls
  • Office SharePoint Server will allow you to create wikis and blogs

It was an interesting keynote, but no huge revelations. Much of what was announced had been discussed previously. We did get to see some cool demos. You may be wondering what the ugly was from my list. In my notes I have written, “Chloe is back to wrap up show – please kill me”. Still it promises to be a fun TechEd.

So Bil, fellow dwarf plumber, and I are off to TechEd 2006 in Boston, the city of Duck Boats, marathons, and poor drainage. 47 institutions of higher learning in one city – everything from Harvard to MIT to Boston College. Enough concentrated brain power to do some serious synaptic damage. The Big Dig is still underway – it was years over schedule when I lived in Boston in the mid- to late 90′s… and you thought developers had problems estimating accurately! I lived in Boston for 5 years and it will be good to see the city again as well as a few friends. We’re sitting in Minneapolis airport wasting 4 hours between flights. Bil is busy exercising his thumbs (read playing PSP). I’m busily working on some code for a top-secret project (and thinking that I’d rather be playing PSP). We’re both taking a break to blog about our roadtrip, but decide to post later since we’re both to cheap to shell out the $7.95 USD for wireless access. Bil’s got some cool pics on his blog, including lotto ticket vending machines. As my contribution, I give you the $5 cell phone charging machine and an automatic defibrillator for when you get bored waiting for your flight.

A week of geeking out is ahead of us. We’re both tricked out with more toys than Inspector Gadget and hoping for more swag once we get there. This should be a blast!

If you’ve developed on a web application of any degree of complexity, you’ve encountered times when you would like to politely take the site offline or make it unavailable to some users. ASP.NET 2.0 introduced a nifty new feature the App_Offline.htm file. If ASP.NET detects this file in your vroot, it drains the request queue, displays the contents of App_Offline.htm for any new request, and politely shuts down the app domain. You can then update the application, remove (or rename) the App_Offline.htm file and a new app domain will be spun up to start servicing requests again. Wonderful stuff, but what happens when your requirements are more complex? For instance, what if you need to take the application offline for a nightly database
backup? What if certain users can only access a data entry application
during certain hours of the day? What if you want to deploy updates to
an application and only allow a group of testers and/or admins in to
verify the updates? Enter the SiteAvailabilityModule. The SiteAvailabilityModule allows you to control whether or not your site is available to users based on group membership and time of day. For instance, normal users are only allowed access during normal business hours, but administrators can access the site at any time for maintenance and troubleshooting.

Now before we get too deeply engrossed in the code, let’s take a step back and think about how one might naively implement this feature. If you don’t know your ASP.NET pipeline, Grasshopper, you would likely code this logic into every Page_Load method on every ASPX page. If you were smart (but still didn’t know your ASP.NET pipeline), you would write a helper class so that the logic isn’t repeated in every Page_Load. (Neither solution is ideal because it’s too easy to forget to add the logic when implementing a new page.) If you were really smart, you would know a thing or two about the ASP.NET pipeline and realize that you could implement a HttpModule to accomplish this in one place.

Let’s start by taking a look at the ASP.NET pipeline:

The stages in the above diagram marked with an asterisk (*) have a corresponding “Post” event. For example, AuthenticateRequest and PostAuthenticateRequest. (This is a prettier version than the one I included in the third ImpostorHttpModule post.)

Now at which stage do we want to patch into the ASP.NET pipeline? As a general rule, you want to patch in as early as possible. For instance, if we were only concerned with the time of day, we would patch into the BeginRequest. The reason for patching in as early as possible is that the later you patch in, the more work ASP.NET has done. If you’re going to display a static page (or at least one with low processing overhead), try to do as little work as possible in making that determination.

Now let’s see why you might want to patch in at other places…

If you need to know who is accessing the site… PostAuthenticateRequest.

If you need to know whether that user is authorized to access a particular resource… PostAuthorizeRequest.

If you only want to execute if there is no cached content for that resource… PostResolveRequestCache.

If you need to know which handler will be executed… PostMapRequestHandler.

If you need something that you squirreled away in session state… PostAcquireRequestState.

You get the idea. Depending on what information you require, you will want to patch in at a particular stage. For our purposes, we need to know if the user is in the Administrators group. The user’s group memberships are determined in AuthorizeRequest. So we need to hook into PostAuthorizeRequest.

public void Init(HttpApplication context) {
    context.PostAuthorizeRequest += new EventHandler(context_PostAuthorizeRequest);

Easy enough, but let’s look at the event handler as that is where the real action is happening…

void context_PostAuthorizeRequest(object sender, EventArgs e) {
    string ext = Path.GetExtension(HttpContext.Current.Request.Path).ToLowerInvariant();
    if(ext == “.aspx”) {
        TimeSpan now = DateTime.Now.TimeOfDay;
        if(now < Availability.Instance.StartTime.TimeOfDay
                || now > Availability.Instance.EndTime.TimeOfDay) {
            // If we’re outside normal hours, check to see if the user is in any
            // of the exempt roles. By default, only members of the SiteAvailabilityExempt
            // role are exempt from site availability constraints.
            if(!HttpContext.Current.User.IsInRole(Availability.Instance.ExemptRole)) {

We first check to see if we’re dealing with a request for an ASPX page. Remember, we’re patched into the ASP.NET pipeline, which in ASP.NET 2.0 means that we’re being called when serving up both dynamic and static content. So if we’re dealing with a request for an image, cascading stylesheet (CSS), JavaScript file, or other non-ASPX content, we better not serve up the site unavailable page! We need to allow requests for resources to pass through unaltered. Hence the check for whether we’re dealing with an ASPX page or not.

Next part is simple. Are we outside of the normal hours of operation? The Availability class is derived from System.Configuration.ApplicationSettingsBase and leverages off the new System.Configuration features. We set our configuration properties in Web.config beneath the <configuration/> root element:

    <sectionGroup name=”applicationSettings” type=”System.Configuration.ApplicationSettingsGroup, System, Version=, Culture=neutral, PublicKeyToken=b77a5c561934e089″>
        <section name=”JamesKovacs.Web.HttpModules.Availability” type=”System.Configuration.ClientSettingsSection, System, Version=, Culture=neutral, PublicKeyToken=b77a5c561934e089″/>

        <setting name=”StartTime” serializeAs=”String”>
            <value>8:00 AM</value>
        <setting name=”EndTime” serializeAs=”String”>
            <value>4:00 PM</value>

The class defines some sensible default values so that we can run without any configuration in Web.config.

If we’re outside of regular hours, we need to find out if the user is in the exempt role, which by default is a local group called SiteAvailabilityExempt. If we’re not a member of the exempt role, we re-write the URL to point to SiteUnavailablePage, which by default is ~/SiteUnavailable.aspx.

Let’s look at what is actually happening because it’s not a redirect or transfer. We are in PostAuthorizeRequest. We don’t decide which ASPX page we will be executing until the step marked “IHttpHandler Created”. So we haven’t created the HttpHandler, or System.Web.UI.Page-derived class, in this case. HttpContext.Current.RewritePath() actually changes the URL of the request while the request is “in-flight”. So no matter which page the user browses to, she will see the contents of SiteUnavailable.aspx. She won’t know it’s SiteUnavailable.aspx, but it is. The URL will show or whatever page was originally requested. Think about how powerful this technique is. If we redirected to SiteUnavailable.aspx, the user could refresh her browser all day and she would always see SiteUnavailable.aspx even if the clock rolled over into business hours. To the server, you’re requesting SiteUnavailable.aspx and that’s what I’m going to serve up. With URL rewriting, we keep the original URL, but serve up alternate content. If the user refreshes and we’ve rolled into business hours, the SiteAvailabilityModule lets the request through unaltered and the user sees the correct page. Cool or what?

You can download the code here. I’ve included all the HttpModules from the Calgary Code Camp in addition to an updated version of the SiteAvailabilityModule. As always, feedback is appreciated. Enjoy!

[EDIT -- Corrected text to match the code. Thanks, Lance, for catching the error.]

A few days ago, I blogged about the Calgary Code Camp being a huge success based on verbal testimony from quite a number of people, as well as the evals from the event. Unsolicited, written testimony is always better than just taking my word for it, especially given that I was one of the organizers. Justice Gray documents his roadtrip to the Calgary Code Camp along with poetic summaries of the talks he attended. Glad you enjoyed my talk, Justice. I would agree that “ASP.NET Kung-Fu: Intermediate Techniques and Idioms” just doesn’t sound as sexy. So I think I’ll stick to my title. Besides intermediate for you is advanced to most. :^) I’m flattered to hear that I’m your favourite presenter ever. Gave me a warm fuzzy feeling all weekend. Now I just have to organize a bunch of Calgarians to come up to your Code Camp in September and win all of your door prizes. :^P (The folks from Edmonton will know what I’m talking about.)