How to determine Design Time mode in ASP.NET
During creating of Custom Controls sometimes programmers are dealing with implementation of code which should run only in Design Time mode. And the main question is, how to determine in ASP.NET whether your code is running in Design Time mode or not?
I can offer several approaches for checking that.
DesignMode property
First and obvious decision is to use DesignMode property of Control class. It is a Boolean value which returns true in case when your code in running in Visual Studio.
But this approach has two disadvantages:
1. What if you need to determine design time mode not in control implementation but in some class which is part of your WebSite project. In that case access to DesignMode won’t be such easy ;)
2. DesignMode property is new one in .Net Framework 2.0 and not exists in 1.1
There are several ways how to avoid this problem.
HttpContext
We can check HttpContext object against null value. During design time mode HttpContext object is empty which means we can write something like this:
public bool IsDesignMode
{
get { return System.Web.HttpContext.Current == null; }
}
HostingEnvironment
Second approach is to use IsHosted static property of HostingEnvironment object which provides functionality to manage application within application domain. During design time application is not hosted.
public bool IsDesignMode
{
get{ return !System.Web.Hosting.HostingEnvironment.IsHosted; }
}
Site
Next approach is to use System.Web.UI.Control.Site . It gets information about a container which hosts the current control when rendered on a design surface . And in our case the code can look like this:
public bool IsDesignMode
{
get { return Site!=null; }
}