5

While looking at source of Ayende's Racoon Blog, I saw this in global.asax.cs:

// Work around nasty .NET framework bug
try
{
    new Uri("http://fail/first/time?only=%2bplus");
}
catch (Exception)
{
}

This appears to be a workaround for a bug that happens on the first request. Does anyone know what the bug is or how to reproduce it?

George Stocker
  • 57,289
  • 29
  • 176
  • 237
Goran Obradovic
  • 8,951
  • 9
  • 50
  • 79
  • Have you actually had an issue with this, or are just wondering because you saw this in that code? That works fine for me, and looking through the `Uri` constructor in ILSpy, it doesn't look like that would fail. Conditions that will cause that constructor to throw a `UriFormatException`: http://msdn.microsoft.com/en-us/library/z6c2z492(v=vs.100).aspx – Gromer Sep 20 '12 at 22:29
  • Did you remove it and see if something failed? – paparazzo Sep 20 '12 at 22:37
  • 2
    No, I did not encounter an issue, that is reason more to ask, because I don't think they put it there just for fun. It would be good to know if and when you can avoid something to fail. – Goran Obradovic Sep 21 '12 at 05:52

1 Answers1

2

A bit of googling gets to this Ayende blog post from March 2010 from which I quote an excerpt:

I can reproduce this now, here it how it got there:

public class Strange : MarshalByRefObject
{
    public void WTF()
    {
        Console.WriteLine(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile);
        new Uri("http://localhost:58080/indexes/categoriesByName?query=CategoryName%3ABeverages&start=0&pageSize=25");
    }
}

public class Program
{
    private static void Main()
    {
        var instanceAndUnwrap = (Strange) AppDomain.CreateDomain("test", null, new AppDomainSetup
        {
            ConfigurationFile = ""
        }).CreateInstanceAndUnwrap("ConsoleApplication5", "ConsoleApplication5.Strange");
        instanceAndUnwrap.WTF();
    }
}

That took some time to figure out.

From the comment thread below, which I have skimmed but not read in detail, the root cause appears to be an error in the machine root config file, which is only parsed once per ?AppDomain, hence the lack of an error the second and subsequent times.

Habitually using this construct having been burned by it once is the kind of habit that programmers accumulate through hard experience. The less experienced may snigger "cargo cult" or "programming by coincidence", to which the more experienced will just smile and nod.

AakashM
  • 62,551
  • 17
  • 151
  • 186