tags:

views:

69

answers:

2

My custom controls are not loading in VS.NET's designer because of a null reference exception. It's got everything to do with the way I am retrieving the baseUri of the application when it runs in the browser:

_uriPrefix = Application.Current.Host.Source.AbsoluteUri.Substring(0,
     Application.Current.Host.Source.AbsoluteUri.IndexOf("/ClientBin")).Trim();

According to the exception details and the help file I'm directed to (here) I'm not correctly designing my app for a runtime that's not the browser (i.e. the new WPF editor in VS.NET or Expression Blend).

So, the question is how do retrieve the baseUri (the http://localhost:#### part of my application) if I can't use Application.Host which apparently is null during design time? is there a safe way to do this so I can load my custom controls in a designer?

A: 

Duh! I hate/love when I do this. I'm answering my own question (again). I can use the DesignerProperties.IsInDesignTool boolean to test if I'm in design mode or not:

if (!DesignerProperties.IsInDesignTool)
     _uriPrefix = Application.Current.Host.Source.AbsoluteUri.Substring(0,
          Application.Current.Host.Source.AbsoluteUri.IndexOf("/ClientBin")).Trim();

Now I can view my custom control in the new VS 2010 editor. Yeah!

beaudetious
Oh, yeah... it's under the System.ComponentModel namespace.
beaudetious
+1  A: 

To eleborate on the problem and solution (i wasn´t finished writing it when you posted your own answer)

Your problem is the runtime context you are in.

When your page is run as on a ASPX.Net page, your are hosted by the IIS->ASP.Net pipeline. This application will give your the HTTPContext and your Application.Current is refering to the W3WP.EXE process in which the ASP.Net pipeline is serving your page.

When your page is displayed in the MS Visual Studio designer it does not provide this HTTPContext since there is none. The request to render your control did not come through an HTTP request, but the Visual Studio designer running inside Visual Studio.

To have your control be displayed correctly during design time, you´ll have to add ´design time support classes´. There are a number in the .Net framework you can use directly, but for custom serialization (writing the server ASP.Net tags or rendering a HTML preview with styling) you´ll have to put in some more effort and write your own designer classes.

Hope this helps,

Marvin Smit
Maybe we need to talk to Dino (the author of the article you linked to) and ask him to update his article to include modern technology. ;) That was written in 2003. Thanks for the input.
beaudetious