Test with Coverage.

Your unit tests aren’t as effective if you don’t use code coverage to measure how much of the code your tests are exercising. For development at home and work, I’ve been using NCover, which has worked wonders for my unit tests. When I started using NCover over a year ago, I wanted something that would integrate with VS so I wouldn’t have to do all this configuration work for every project. I started a project that held my interest for about three weeks. That fizzled (I blame TV).

What I resorted to was a batch file that ran NCover followed by NCoverBrowser. Add that as a solution item, and you can launch it from the IDE anytime. (I learned that last bit last week.)

Well, I no longer have to rely on batch files! Jamie Cansdale has taken TestDriven.net to a new level: testing with coverage. One of my favourite features Microsoft didn’t put in every version of Visual Studio 2005 is now present for Visual Studio 2003/2005, including Express Editions. Yes!

It does the exact same thing as my batch file, except I don’t have to write a batch file.

It requires NCover 1.5.1 Beta 2, a brand new version of NCover targetting .NET 2.0. It has some exciting features in its own right, including Attribute-based type exclusion.

Check it out.

The MSBuild Blog

Avalon is flashy. Indigo is robust and extensible. Generics, iterators and anonymous methods make writing extensible code faster than ever. One of the workhorses that doesn’t get a lot of credit is MSBuild. There are so many things you have to do to get software out the door in your customers’ hands, so many things that I won’t bother enumerating them.

Doing them all automatically, the same way every time is a daunting task. In .NET 1.1, automating everything requires third-party tools, such as NAnt. The biggest disadvantage of any tool: VS integration. Visual Studio stores all the solution information in .sln and .*proj files; a third party tool either has to parse that file, which may be well-formed XML, but it certainly takes a lot more than an XML parser to interpret. Or, the tool requires you to add all that project info yourself.

With the new framework, that all changes: MSBuild is a completely new, XML-based tool that allows you to run arbitrary tasks related to your project. The biggest advantage? Visual Studio uses it. And uses it well.

However, you don’t see a lot about MSBuild in the blogs or articles, with the exception of the MSBuild blog. They have some really great articles, including a whole series on how Visual Studio uses MSBuild. One of their latest posts is about extending MSBuild with your own custom tasks.

Recommended.

Writing Your Own UriParser

I posted before about my displeasure using System.Uri for advanced scenarios. It won’t parse mailto-style URIs and extending it is just evil. Yet, I’d still recommend you use System.Uri for your URI needs, even if it won’t parse your URI.

 

Why? Well, with each version of the framework, Microsoft will work to make it better (at least that’s what they promise us). Your classes should version well across framework versions if you use their guidelines. Therefore, if you’re using FxCop to check your code against the guidelines, I’d recommend fixing violations of the “Use System.Uri instead of string” rule.

 

It just so happens that they kinda worked around my two earlier complaints: they deprecated those heinous protected methods; currently you only get a compiler warning, but it’s a start. They also provided a mechanism to parse URI schemes that the framework doesn’t know about: extend UriParser.

 

Before I start with the nitty-gritty details of building your own UriParser, I’d like to point out something amusing (well, amusing to total nerds who’d rather write about parsing URIs than play video games or watch Arrested Development). Go to the documentation on MSDN2 for UriParser, you’ll read this:

 

The UriParser class enables you to create parsers for new URI schemes. You can write these parsers in their entirety, or the parsers can be derived from well-known schemes (HTTP, FTP, and other schemes based on network protocols). If you want to create a completely new parser, inherit from GenericUriParser. If you want to create a parser that extends a well-known URI scheme, inherit from FtpStyleUriParser, HttpStyleUriParser, FileStyleUriParser, GopherStyleUriParser, or LdapStyleUriParser.

Notice something missing? That’s right, there is no fucking MailtoStyleUriParser!

 

Although I’m glad gopher is finally getting its due.

 

When the product feedback center came out, I figured I’d give it a shot so I entered a new feature request to get Uri to parse sip, sips and tel URIs. Read the comment at the bottom by Mr. Daniel Roth; you’ll see that writing your own mailto-style URI parser is easy because mailto is a “so rudimentary” scheme. That kinda begs the question: if it’s so rudimentary, then WHY ISN’T THERE ONE IN THE FRAMEWORK?

 

To add further to the fire, here’s the second paragraph from the UriParser class description:

 

Microsoft strongly recommends that you use a parser shipped with the .NET Framework. Building your own parser increases the complexity of your application, and will not perform as well as the shipped parsers.

Hmph.

I’m not going to go into detail about inheriting from GenericUriParser in this post. Instead, let’s suppose I’ve already done that. I think I should show you how to let the framework know about your parser so that it will load it and use it. I feel obligated to tell you about it because the documentation for these methods is really fucking terrible. Suppose I have two types called PresUriParser and SipUriParser both of which inherit from GenericUriParser. To tell the framework about these parsers, I call the UriParser.Register(uriParser, schemeName, defaultPort) method:

 

      UriParser.Register(new PresUriParser(), “pres”, 1);

       UriParser.Register(new SipUriParser(), “sip”, 5060);

 

That browser of yours isn’t playing tricks: the first call has a port of -1; that means no default port. The terrible, terrible documentation doesn’t show that. Nor does it show that every argument passed is validated and an exception is thrown if validation fails. The exception table should be the following for argument validation:

 

Type of Exception

Reason

ArgumentNullException

if uriParser, schemeName is null

ArgumentOutOfRangeException

if schemeName has length 1 or violates the rules for scheme names through myriad different ways.

ArgumentOutOfRangeException

if defaultPort >= 65535 or (defaultPort < 0 and defaultPort != -1)

 

But wait, there’s more! Suppose you get passed the argument validation, you’re not yet through the exception danger zone. Suppose you had code like this:

 

      PresUriParser p = new PresUriParser();

       UriParser.Register(p, “pres”, 1);

       UriParser.Register(p, “presence”, 5060);

 

This will throw an InvalidOperationException; apparently, you can only have one instance parse one scheme, even if your parser can parse multiple schemes. This makes sense, especially in multi-threaded scenarios, but does the documentation say this? Hell, no!

 

So you get the argument validation and now a potentially invalid operation. All undocumented. But I have more for you: a free set of knives!

 

Suppose you wanted to parse http on your own, with code like this:

 

  public class HttpUriParser : HttpStyleUriParser

  {

    public HttpUriParser() { }

  }

 

And then I register my parser, like so:

 

  UriParser.Register(new HttpUriParser(), “http”, 80);

 

Guess what? InvalidOperationException! That scheme is already registered.

Makes me wonder why there are all those parsers for known schemes if you can’t use them on the schemes that they parse.

 

There was a way to do it through the config file, but that content has been retired according to MSDN2. There appear to be some issues with Uri and security, outlined here in the breaking changes list. Perhaps Microsoft didn’t want others screwing up the perfectly good parsing for the known schemes, like they can by overriding the methods I mentioned last time.

 

Whatever the case, hopefully this quick article helps with the documentation for System.UriParser. Next time, we’ll get our hands dirty overriding methods and abusing Console.WriteLine().

Item Templates in Visual Studio 2005

When Beta 1 of the VS Express Editions came out, I wrote an article about Item Templates for Visual Studio 2005; a topic I was excited about ’cause I hate typing more than I have to (if I had a quarter for everytime I wrote [TestFixture]…). I always meant to update it for Beta 2.

Um, yeah: I didn’t do that, and when RTM came around, I promised myself, I’ll update it again. But I’m too lazy to do so for three reasons: 1) Most of you will create it with the Export Template… menu item under the File menu (which didn’t work in any beta I tried), so knowing about the XML Schema for vstemplate files won’t matter much; 2) If you really need to know about it, look at a few of the built-in templates: you’ll see a pattern, I reckon; finally 3) David Hayden already did a fantastic job of how to modify the existing templates and creating custom templates with the Export Template Wizard.

Why System.Uri sucks, Part 1

I recently reviewed Framework Design Guidelines, the new book by Abrams and Cwalina about designing frameworks for .NET. In the review, I mentioned that I disagreed with their advice of using System.Uri (v.1.1) to represent some URIs. Here’s why.

 

The name System.Uri implies, to me, a URI, any URI. If your URI scheme follows the “rules” of the URI RFC (when .NET 1.1 came out, that would be RFC 2396), the System.Uri should be able to parse it, and you should be able to use the properties exposed by the type for information inside the URI: the host, the scheme, the user info, etc.

 

For the “big” URI schemes – http, ftp, file, mailto, news, and, of course, gopher – this is not a problem. They are parsed according to the rules and everything works as expected. Even if you decided to use your own, custom hierarchical URI scheme (http is an example of a hierarchical URI scheme), then System.Uri will parse it, as the code below demonstrates.

 

However, try giving System.Uri a mailto-style URI (i.e. something:user@example.com), and it’ll shit the bed. Then it’ll deny anything is wrong. You may be struggling to come up with an example, but, trust me, there are many; and they will quickly gain importance in our daily programmer lives: SIP, XMPP (kinda), and common presence and IM all represent users with mailto-style URIs. The only property that doesn’t return null with those URIs is Uri.Scheme. When I first found this out, I was shocked; I thought I was doing something wrong. One of the things that Brad and Krzysztof advise is not to surprise the user of your API, or go against their expectations.

 

Do you think System.Uri succeeds here?

 

using System;

 

class Program

{

   static void Main(string[] args)

   {

      Uri[] u = new Uri[7];

      u[0] = new Uri(“http://www.jasonkemp.ca/Rss.aspx”);

      u[1] = new Uri(“feed://www.jasonkemp.ca/Rss.aspx”);

      u[2] = new Uri(“purplemonkeydishwasher://www.jasonkemp.ca/Rss.aspx”);

 

      u[3] = new Uri(“mailto:jasonkemp@example.com”);

      u[4] = new Uri(“msn:jasonkemp@example.com”);

      u[5] = new Uri(“sip:jasonkemp@example.com”);

      u[6] = new Uri(“pres:jasonkemp@example.com”);

 

      for (int i = 0; i < u.Length; i++)

      {

         PrintHost(u[i]);

      }

 

      for (int i = 3; i < u.Length; i++)

      {

         PrintUserInfo(u[i]);

      }

   }

 

   private static void PrintUserInfo(Uri uri)

   {

      Console.WriteLine(“uri.UserInfo for {0} = {1}”,

uri, uri.UserInfo);

   }

 

   private static void PrintHost(Uri uri)

   {

      Console.WriteLine(“uri.Host for {0} = {1}”, uri, uri.Host);

   }

}

 

In part 2, I’ll discuss why extending Uri to make up for the above deficiencies will cause you to shit the bed.