Monday, 8 February 2010

Detecting if a piece of code is running in Design Time

Sometimes, you will want to distinguish if a certain piece of your code is being executed at run-time or as a part of the Visual Studio Design-Time calls.

A very easy way of checking this is:

bool isDesignTime = (this.Site != null && this.Site.DesignMode == true);

Why to explain this?

This is something quite obvious, but some people ask in the forums why they are receiving an exception when trying to open the design view of a form, in Visual Studio. Those exceptions can be caused by many things, but the one explained here is one of the frequent reasons.

Use case

Imagine you have developed a custom UserControl class, which needs to do something everything it´s made visible. You will probably override the OnVisibleChanged event to perform that operation. Now, imagine that operation can only be done at runtime. For example, if you need in that operation some data to be loaded, data that won´t be available at Design-Time. Now, imagine that you insert that UserControl into one of your forms.

As you can probably imagine, each time you open that form in the Design View of VisualStudio, the overriden OnVisibleChanged event will be fired, and as that data is not available, you will receive an exception, ruining the initialization of the DesignView, and banning you from editing anything at design time in your form.

In such cases, using the above check will save you from this behavior. Just put that check in the OnVisibleChanged event, and use the mentioned data only if not in Design Time. Et voilá. You have design view operative again.


No comments: