Really Detecting Design Mode

- - posted in C# coding | Comments

I recently had to deal with the problem of ADO.NET data access occurring on user controls, and forms in the Visual Studio design view. Now the data access depended upon a connection string in the App.config file and consequently, when run from Visual Studio it could not connect to the database since the connection string wasn’t available.

So, I proceeded to do some searching on the problem. I very quickly discovered the DesignMode flag for components, and thought I’d found my solution.

I promptly added the following to the UserControl that was blowing up when I opened it in the Designer.

public UserControlCtor()
          // Do the data access here.

I quickly discovered however, that the DesignMode flag wasn’t set until AFTER the constructor had run, and the parent object set the DesignMode flag on this control. Okay, simple enough we just move it to the OnLoad event for the UserControl right? Well, yes that would probably work in most cases however in our application this practice of doing data access in the constructors was rampant and therefore the dozen or so UserControls that were placed on this UserControl had the same problem. I’d need to make the this change to… well… pretty much every UserControl in the application. While that’s something that should happen, right now we cannot afford the technical debt to fix it.

Fortunately, all of our ADO.NET access in this application is abstracted into a library class which does all the data access, and handles things like opening and closing/disposing the database connection and just generally insulating users from the complexities of using ADO.NET. That’s the obvious candidate for the best place to filter design or runtime mode and either run the data access or not.

But wait, a helper class in the app won’t have a DesignMode flag and besides, how would it get set, you say? Well, in my travels looking for ways to detect that the code is running in design mode, I stumbled across several solutions. The most intriguing of which is the UsageMode flag. This can be checked in any class at any time and gives you an accurate gauge of what mode your code is running in.

So, in the few methods that do the data access in our ADO.NET abstracting class, I simply do the following.

if(System.ComponentModel.LicenseManager.UsageMode ==

This checks to see if we’re in design mode or not, and if we are simply bails out of the method effectively skipping the data access and solving our problem. Pretty cool eh?

I found several suggestions on how to detect design mode, they pretty much consisted of the following.

  1. Check the DesignMode Flag
  2. Check if the current process is Visual Studio
  3. Check the UsageMode Flag