'.NET' Articles

Visual Studio debugger is too sensitive about exceptions

I was working on XBList the other day when I hit a peculiarity of Visual Studio. I wanted to call a method asynchronously, so I was using BeginInvoke with a callback, as described in this article on MSDN. So I used BeginInvoke to fire off a method, and the method I invoked happened to throw an exception. I didn’t expect this to be a big deal - when the callback was called, I would call EndInvoke which would re-throw the exception and I could deal with it. However, while running in Visual Studio’s debugger, I got a break and an error dialog that claimed I had an unhandled exception. My code never made it to EndInvoke. It said something like “Exception unhandled by user code”.

It turns out that this is just some weirdness in Visual Studio. If you go to the Debug menu, choose “Exceptions…”, and uncheck “User-unhandled” for Common Language Runtime Exceptions, the exception will get properly thrown when EndInvoke is called, and everything’s fine.

exceptions-setting

It’s annoying that I have to give up the relatively useful unhandled-exception trapping that the Visual Studio debugger gives me, but I guess there’s no other way around it.

Posts I haven't written

, , , , , , ,

I haven’t been updating this blog too much recently. I never meant for this blog to run on a schedule, but I did intend to post more frequently than this. My original idea was that the blog would serve two major purposes. First, it is a place for me to announce new projects or updates to software and websites I’ve already released. It’s done that quite well, though I haven’t had much to announce recently. My job has been taking the majority of my development time, and most of the projects I’ve been working on at home are either private or haven’t been released in the form I’d like to because my employer hasn’t approved them for release yet.

The second major purpose for my blog is as a place for me to record the solution to problems I run across while developing software, so that others won’t have to spend hours Googling or using trial and error to come to the same conclusion. I didn’t intend to rehash things that were easily found or that had already been discussed - only to post when I felt it was something that added value to the internet that hadn’t been there before. So a lot of the blog posts are not really a narrative or running commentary - they’re not meant to be subscribed to, but found individually. It’s for this reason that my most popular posts tend to include the exact text of error messages. This type of post has suffered both because I haven’t been doing as much development, because I can’t discuss a lot of what I’ve learned due to the nature of the projects I’m working on, and because I’ve been learning new stuff (like Ruby on Rails) and haven’t done enough to have solved problems others haven’t already posted solutions for.

The third reason I have this blog is to occasionally talk about my thoughts on different technical topics, from web development to video games. Again, I don’t like to make a post unless I think I’m adding something new, and most of the topics I’ve wanted to talk about have already been covered. I had a lot of draft posts sitting around about web development, web standards, and the evolution of browsers, but then I discovered Alex Russell’s blog and it turns out he’s already said most of what I wanted to say, and better than I could. Other stuff, like my impressions of Windows Vista, critique of stackoverflow.com and suggestions for the Xbox Live Arcade lineup, have been covered to my satisfaction in plenty of places. Maybe some of them will end up posted, but probably not.

Another part of the reason I haven’t posted much is the sheer weight of unfinished posts I have. Right now I have 64 drafts and only 52 real posts! So I’m going to attempt to clear things out by writing a little about what I haven’t posted. A lot of this stuff wasn’t posted because it fell under that third point above, but some of it I was just too lazy to flesh out into real posts. Some of it’s just random stuff. So here’s what’s been happening in the last year:

I got on the bandwagon and picked up iPhone 3Gs for myself and my wife. Everything good you’ve heard about the iPhone is true. Also, almost everything bad you’ve heard about them is true. I really like the device, the UI, and the web browsing, and now that the NDA over the SDK is gone, I might even try to write an app if I get an idea.

I built a new computer in March of ‘07 to replace the machine I had built for college. The new machine is set up as a developer machine primarily, with the additional goal of being as quiet as possible. I can’t say I’m entirely happy with it, since I’ve had some trouble with the hardware and overheating issues mean I have to run the fans above “totally silent” mode. It does its job well enough but I might just buy a Dell next time. The huge CPU heatsink I used is awesome, though.

I’ve been running Windows Vista x64 since my new machine came online. While I think it’s a disappointing release given the 5-year gap between it and Windows XP, I generally like it. It’s certainly better than Windows XP and I wouldn’t go back. I’ve hit some trouble related to using x64, but overall it’s pleasant.

Before that, I was getting pretty sick of the aging Windows XP, so I bought a Mac Mini and ran it, using OS X 10.4, on a second screen next to my XP machine, joined via Synergy. I liked it a lot, but never moved much of my work over there. After getting set up with Windows Vista, the difference between OS X and Windows wasn’t so great, and I unplugged the Mac so I could have both screens for Windows. I moved the Mini up to my TV and used it with Front Row as a media center. Then the Xbox 360 got the ability to play DivX videos, so I stopped using it for that and brought it back downstairs. I was using it for browser testing, but then Apple released a Windows version of Safari. Now it mostly stays off, except when I want to use Handbrake (which won’t work on Vista x64). I still like it, and I really miss having an OS with a real command line, especially now that I’m doing Rails stuff and spelunking through a lot of badly-documented libraries. I’m not sure I’ll ever make the switch though. That said, my trusty old Thinkpad finally died last week, and if I can’t revive it I might look towards the rumored lower-priced MacBooks that should come out soon.

I got two awesome cats named Ozette and Skagit. A lot of my time at home just involves relaxing and petting the cats these days.

After years of using Thunderbird, I switched to GMail as my main mail client so I could use it from the web and use IMAP on my iPhone. I set it up to read all my old POP mailboxes, and I use Google Chrome’s application mode (I used to use Mozilla Prism) to make it look like a standalone app on my desktop. It’s an OK mail reader, especially since I get a lot less email to my personal accounts these days. The main annoyance is spam - I used to use POPFile to filter spam, and it was perfect, with almost no false positives. In contrast, I get maybe 50 pieces of spam leaking through on GMail a week.

Spam has not been limited to my inbox: my support forums are basically nothing but spam and people complaining about stuff I’ve given them for free. It takes a lot of maintenance, and I’m thinking of either trying to transition them to something less attractive to spammers, or just shutting them down entirely.

Back when IE7 was in beta I wrote a handful of bug repro’s for problems I found with it. Recently I’ve been running across all kinds of crazy things in both Firefox and IE, so I’ve been cataloguing them with little examples. Most of them have been fixed with the latest release of each browser, but I figure they’re still useful if anybody’s seeing those problems happen.

I went to Southeast Asia for two and a half weeks. We toured Vietnam, Cambodia and Thailand. It was incredible.

I finally got so sick of CSS that I decided to write a processor that would take an “evolved” CSS syntax that supported named constants, nested selectors, arithmetic, mixins, and such and spit out real CSS. I had it all sketched out and was ready to start implementing when I found SASS, from the same guy who awesome-ified HTML with HAML. SASS is feature-by-feature the exact same thing I wanted to do (except for the whitespace-significant thing, but I can deal). I love it.

I’ve been pretty disillusioned with ASP.NET as a web platform - the web forms are too inflexible and unfriendly to clean markup and unobtrusive JavaScript, and C# feels too rigid and verbose for what I’m doing. LINQ and the other 3.5 features help a lot, but my host is stuck on 2.0. I still haven’t found any templating system that trumps Web Forms, which is why I’m still stuck on Windows hosting for the most part - a lot of my sites are built on ASP.NET for nothing more than the templating. While I’m keeping my eye on ASP.NET MVC, I’m more interested in cross-platform web technologies that give me a bit more choice in hosting.

To that effect, I’ve started a personal project on Ruby on Rails, mostly to learn the platform. So far I’ve really been liking it - having a functional, dynamic language is great, and the structure Rails gives you really helps to quickly get things running. Hopefully I’ll be able to show what I’m making at some point, assuming it works to my satisfaction.

I actually went through a big comparison of different web platforms and different languages, trying to gauge what would be the best for me to develop for. I’m not sure I’ll ever publish my full results, but Ruby on Rails was obviously up there, and Django / Python looked good too.

Speaking of languages, before I discovered jQuery I didn’t really do much JavaScript if I could avoid it. Now I’m writing tons of JavaScript to produce some really nice interactive web apps. I have never been as impressed with a library or platform as I have been with jQuery.

I’ve actually been using Eclipse a lot lately, both for Aptana and for straight Java development, and while it’s slower and buggier than Visual Studio, a free copy of Eclipse plus all the free plugins make it much more compelling than the Visual Studio Express products I use for C# work. Stuff like the outline view, refactoring support, quick fix mode, and real unit testing and source control plugins make all the difference.

I think that’s about all I wanted to get off my chest for now. Hopefully I’ll have a chance to flesh some of that out into full posts sometime, but at least I won’t have so many unwritten drafts staring at me every time I log in to Wordpress.

WebLinkLabel Windows Forms Control

While I was updating my PopupNotify control today, I realized that I had created another useful little control for XBList that I hadn’t released, the WebLinkLabel Control. This simple control wraps the standard LinkLabel control to make it easier to embed multiple hyperlinks in a label, each of which will load up a URL in the user’s default browser when clicked. It’s not the most complex thing in the world, but it has proven useful for inserting help links into XBList’s error dialogs, so I suspect it might be of some utility to others. Using it is about as simple as using a standard Label. Just drag the WebLinkLabel onto your form, customize it however you like, then assign a specially-formatted string to the Text property. You use “url” tags to specify where you want links, like this: “Hello, this is text <url=https://benhollis.net>with a link in it</url>.” You can of course have as many links, pointing to as many different URLs, as you would like. If you want to get that formatted string back out, use the LinkText property, or if you want to get a flattened view out (“Hello, this is text with a link in it.”), use the Text property.

This code is licensed under the LGPL, like the other XBList bits I’ve released. As usual, I would appreciate it if whoever uses this code would email me to let me know how they’re using it, just for my own amusement. You can download the control right here.

New Version of the PopupNotify Windows Forms Control

A couple years back I posted the source of XBList‘s tray notification control on my site as the PopupNotify control. I licensed it under the LGPL so people could use it for their own applications. While I requested that whoever used it should let me know, I’ve never received any email about it until this week, when somebody wrote to tell me that they had been using it but it didn’t work on Vista, and they wanted some help getting it to work. Despite the fact that I would rather they had told me about this beforehand, I’ve taken this as an opportunity to update the component. I just pulled out the current version of the control that I’m using for XBList, which has a much prettier Vista-style look, less P/Invoke calls, and other .NET 2.0 improvements. I’ve left the 1.1 version of the control around for anyone who wants to use it but hasn’t updated to .NET 2.0 yet.

The new, Vista-style popup

Hopefully this component will continue to be useful to other developers, and they’ll let me know if they’re using it in their projects, since it’s just so much more fun to release stuff for free when you get to see it in action.

Setting the correct default font in .NET Windows Forms apps

I was working on XBList the other night when I realized something - the font used in its dialogs and the friends list wasn’t Segoe UI. Segoe UI is the very pretty, ClearType-optimized new default dialog font in Windows Vista. In Windows XP and 2000, it’s Tahoma, and in earlier editions it was Microsoft Sans Serif. You can see the subtle differences between them:

Microsoft System Fonts

In .NET and Windows Forms, the default font for controls is actually Microsoft Sans Serif, not the operating system’s default dialog font! Kevin Dente explains this on his blog. This is not the only time Microsoft’s dropped the ball on this - if you go through some dialogs in Vista you’ll see that many of them use Tahoma or even Microsoft Sans Serif instead of Segoe UI. This is pretty funny, especially when Rule #1 of the Top Rules for the Windows Vista User Experience is “Use the Aero Theme and System Font (Segoe UI)”. Mitch Kaplan offers up a pretty good explanation for why getting it all right is very hard, but having a mix of old and new fonts still looks shoddy.

I don’t want my apps to look shoddy. Embarrassingly enough, I’ve been hardcoding Tahoma in all my apps to get the more “modern” XP look. Now that Vista’s on the scene, it’s clear that I want to select the correct default font for whichever OS my app is running on. As Kevin points out, Control.DefaultFont is no help here - it’s what’s driving Windows Forms’ default choice of Microsoft Sans Serif in the first place. After some digging I found this Visual Studio feedback ticket (sign in required), where the Visual Studio guys explain that, while they couldn’t fix the default, they did create a SystemFonts class to help out. They recommend putting this code in your Form’s constructor:

this.Font = SystemFonts.DialogFont;
InitializeComponent();

Unfortunately, this doesn’t work in a number of ways. The first is that on Vista, SystemFonts.DialogFont is… Tahoma! Closer, but not quite right yet. If you pop open SystemFonts in Reflector, you’ll see that the DialogFont property just does some simple platform-detection, and then just hardcodes Tahoma. This worked when it was just 2000/XP vs. 9x, but Vista throws it for a total loop. Fortunately the fix is easy - use SystemFonts.MessageBoxFont instead. This one seems to always return the correct default dialog font.

However, I ran into one more problem. If I set the default font on the Form, like the code above does, I get weird, bloated controls:

Setting the default font on the form screws up controls

Fortunately I’ve got a solution for that one too. Instead of setting the font on the Form and letting it inherit, just loop through the Controls property, and individually set the right font on each control:

// Set the default dialog font on each child control
foreach (Control c in Controls)
{
    c.Font = SystemFonts.MessageBoxFont;
}

// Use a larger, bold version of the default dialog font for one control
this.label1.Font = new Font(SystemFonts.MessageBoxFont.Name, 12f, FontStyle.Bold, GraphicsUnit.Point);

Now I get a more familiar-looking dialog:

Setting the default font on each control looks fine

I could always make a subclass of Form to do this for me, but I’m OK with copying it into each new form. With this code, all my controls come up with the pretty new Segoe UI font in Windows Vista, and Tahoma in XP.

Using MyODBC with ASP.NET in IIS7 on Vista x64

,

That’s a heck of a title, but it’s a problem I hit recently. I have a bunch of ASP.NET sites that use MySQL as their datastore, but I hadn’t tried the on IIS7 yet. It took a while to get them to work at all (I had to set permissions on web.config and the other website files so that they could be read by both the Users group and the IIS_IUSRS group), but then I was left with an error about my MySQL connection. “ERROR [IM002] [Microsoft][ODBC Driver Manager] Data source name not found and no default driver specified” - another very general error that basically means “Something is wrong with your ODBC driver, somewhere.”

After some searching, I learned two things. The first is that if you’re running 64-bit you can’t use the standard ODBC Data Source Administrator in Administrative Tools with MySQL. You’ve got to go to C:\Windows\SysWOW64\odbcad32.exe and set up your DSN, if that’s your thing. The other thing is that the MyODBC driver is 32-bit only. So to use it at all, you need to make sure you’re calling it from 32-bit apps only. That means you’ve got to tweak the Application Pool you’re using to run all its ASP.NET applications as 32-bit. To do this, go to Administrative Tools > Internet Information Services (IIS) Manager (or just hit the Windows key and type “IIS”). Then go to “Application Pools” and select whichever application pool your ASP.NET app uses (or create a new one just for your MySQL apps. Click “Advanced Settings…” and set “Enable 32-Bit Applications”. Now the AppPool will use the 32-bit .NET CLR to run your app, and it’ll be able to see your MyODBC driver (whether you use a DSN or not).

IIS7 32-bit Application Pool

Creating nested custom configuration sections in ASP.NET 2.0

,

This weekend I decided to go through the hodgepodge of common code that’s shared between a lot of my ASP.NET websites and refactor it a bit. I’d only just learned about the magic of HttpModules and HttpHandlers, and I immediately saw a lot of canidates in my copy-paste code and global.asax handlers where a HttpModule would be a better solution. One of these was the code I was using to redirect old pages to new pages whenever I moved them. For example, at some point I had moved http://www.numbera.com/rome/tools.aspx to http://www.numbera.com/rome/tools/, and I wanted anyone who visited the old URL to get redirected to the new one. Previously, I just had some code in global.asax that hooked Application_OnError, checked to see if it was an HttpException (a 404 file not found, specifically), and then redirected if it knew where the file really was. Pretty simple, but not very general. So I broke it out into an HttpModule that basically did the same thing, but no longer required me to cut and paste code into my global.asax. However, one improvement I wanted to make was to allow for configuration through my web.config file, instead of having to hardcode an if/else tree for each redirect. I basically wanted to have a section in my web.config like this:

<configSections>
    <sectionGroup name="brh.web">
     <section 
       name="redirectOldUrls" 
       type="Brh.Web.RedirectConfigurationHandler, Brh.Web.Utility"
     />
 </sectionGroup>
</configSections>

<brh.web>
  <redirectOldUrls>
      <redirect filePattern="tools.aspx" url="~/tools/" />
    <redirect filePattern="strategy.aspx" url="~/strategy/" />
    <redirect filePattern="military_people.aspx" url="~/people/" />
    <redirect filePattern="history.aspx" url="~/history/" />
    <redirect filePattern="teacher.aspx" url="~/teacher/" />
  </redirectOldUrls>
</brh.web>

To do this, I needed to create a custom configuration handler. There’s plenty of documentation out there on how to create a single-tag configuration handler using the new ConfigurationSectionHandler class, and all of the sites I could find talked about how much easier it was to do things the new .NET 2.0 way instead of using IConfigurationSectionHandler. However, nothing I could find would tell me how to make a config section with sub-elements. It’s certainly easy to decorate a property with the ConfigurationProperty attribute, but setting up the collection of subelements is significantly harder. Finally, after chancing upon a forum post, I was able to hack together something that worked:

using System;
using System.Collections.Generic;
using System.Text;
using System.Configuration;

namespace Brh.Web
{
    class RedirectConfigurationHandler : ConfigurationSection
    {
        [ConfigurationProperty("", IsDefaultCollection=true, IsKey=false, IsRequired=true)]
        public RedirectCollection Redirects
        {
            get
            {
                return base[""] as RedirectCollection;
            }

            set
            {
                base[""] = value;
            }
        }
    }

    class RedirectCollection : ConfigurationElementCollection
    {

        protected override ConfigurationElement CreateNewElement()
        {
            return new RedirectElement();
        }

        protected override object GetElementKey(ConfigurationElement element)
        {
            return ((RedirectElement)element).FilePattern;
        }

        protected override string ElementName
        {
            get
            {
                return "redirect";
            }
        }

        protected override bool IsElementName(string elementName)
        {
            return !String.IsNullOrEmpty(elementName) && elementName == "redirect";
        }

        public override ConfigurationElementCollectionType CollectionType
        {
            get
            {
                return ConfigurationElementCollectionType.BasicMap;
            }
        }


        public RedirectElement this[int index] {
            get
            {
                return base.BaseGet(index) as RedirectElement;
            }
        }
    }

    class RedirectElement : ConfigurationElement
    {
        [ConfigurationProperty("filePattern", IsRequired=true, IsKey=true)]
        public string FilePattern
        {
            get { return base["filePattern"] as string; }
            set { base["filePattern"] = value; }
        }

        [ConfigurationProperty("url", IsRequired=true, IsKey=false)]
        public string RedirectUrl
        {
            get { return base["url"] as string; }
            set { base["url"] = value; }
        }
    }
}

The important parts here are that I overrode the CollectionType on RedirectCollection, which allows me to use a simple mapping instead of the more complex add/remove/clear pattern that the new Configuration API selects by default. Also, I overrode the parts about the element name, so that it would recognize a series of “redirect” tags as my collection. The last bit that hung me up for a long time was that my ConfigurationElement, RedirectElement, needs to store its data in the base property collection. I had been storing them as properties, thinking that the configuration framework would populate them via reflection, but all that got me was a “Invalid key value” error, since the collection was exposing RedirectElement.FilePattern as the “key” (whatever that means) and it was null. I still don’t really understand all the craziness about this new configuration system, but at least I got it working. I wish there was better documentation out there (or at least better error messages). In general I think this is way too complex a way to go about handling configuration - I’ll stick with simply serializing/unserializing a custom settings object in my Windows apps.

One last bit: to use this in your app, simply do this:

RedirectConfigurationHandler config = (RedirectConfigurationHandler)System.Configuration.ConfigurationManager.GetSection("brh.web/redirectOldUrls");

Now you have a strongly typed config object that you can use to read your settings.