Visual Studio Design Mode – another approach.

Some time ago I published here a piece of code that detects the design mode in Visual Studio Designer. The code worked great (as long as you use only MS Visual Studio). However, after some time, with our project getting more and more complex, the solution turned out to be problematic, as its usage is limited only to classes that extend the BaseDesignModeUserControl. If, for instance, you need to extend System.ComponentModel.Component, then you have to duplicate the code (and the rhetorical question is who likes to duplicate the code?)
So, it turns out that we should forget about “the-base-class” approach and use an extension method instead:

    public static class ExtensionMethods
    {
        private static bool? isDesignMode = null;

        [DebuggerStepThrough]
        public static bool IsDesignMode(this object obj)
        {
            if (!isDesignMode.HasValue)
                isDesignMode = (System.Diagnostics.Process.GetCurrentProcess().ProcessName.IndexOf("devenv") != -1);
            return isDesignMode.Value;
        }
    }

It seems that this piece of code may be called anywhere and I hope that this is the final solution of the problem.

VS .NET 2008 design mode issue

Today I came across a strange issue related to VS .NET 2008 design mode. I was coding a c# stand-alone application whose purpose was to connect to database using NHibernate library. I created a couple of controls which all inherit from DevExpress.XtraEditors.XtraUserControl (btw. I am using DexExpress in this project). The controls were using NHibernate DAOs in order to load data from database. However, when I was trying to edit them in Visual Studio designer I kept getting the following error:

vs_design_mode

Of course, as you may probably have guessed, I have not paid too much attention to catch NHibernate exceptions properly and that is why the exception in the picture above crashes VS designer. Nevertheless, something should be done to handle such issues properly. After a few minutes of google’ing I have found the solution. I put it here, simply because the useful information on the Internet is apt to dissapear quickly:

public class BaseDesignModeUserControl : UserControl
{
private static readonly bool isDesignMode;

static BaseDesignModeUserControl()
{
isDesignMode =
(System.Diagnostics.Process.GetCurrentProcess().
ProcessName.IndexOf("devenv")
!= -1);
}

protected bool IsDesignMode
{
[DebuggerStepThrough]
get
{
return isDesignMode;
}
}

}