On this page.... RSS 2.0 | Atom 1.0 | CDF
# Thursday, 27 April 2006

I decided to try something new in ASP.NET 2.0 based on our needs on a current project.  To do this, I followed the tip that K. Scott Allen shares in his blog.  The difference in my case is that I thought I'd do this and make the user control in the App_Code be the base control for a handful of others.  The point here is to achieve visual polymorphism.  Put another way, I want to load up the control differently based on the sub classes rather than, say, having a big switch statement.  This is just good OOD.

The problem is that if you just set a user control in the App_Code directory as a base for other user controls, you will most likely see the following exception.  I was able to consistently reproduce it.  When ASP.NET constructs your derived user control, .NET, as usual, calls the base constructors as well.  When the base constructor is called like this (for reasons beyond my ken), I see this error:

 System.Web.HttpException: An error occurred while try to load the string resources (FindResource failed with error -2147023083).

Looking at what is actually happening (in the call stack), the error appears to be in a call that the parsed constructor makes to System.Web.StringResourceManager.ReadSafeStringResource(Type t).  If you Google like I did, you probably won't find any help (except this blog now, of course).  So on a hunch, I called the LoadControl overload like Scott Allen suggests in his piece, and it loaded fine.  On a further hunch, I then tried to use the derived control again, and voila, it worked fine.

So, since I don't have time to open a case with Microsoft, I just created that as a work around.  I have the application call LoadControl once on the base control so that ASP.NET will properly set it up for use, and then I can use it as a base.  You could do this (presumably) in Global.asax, but I just put this in the page that uses the control(s) in question.

static bool _baseUCLoaded = false;

protected override void OnInit(EventArgs e)
{
  base.OnInit(e);
  if (!_baseUCLoaded)
  {
    ASP.MyUserControlBase thing = (ASP.MyUserControlBase)this.LoadControl(
      typeof(ASP.MyUserControlBase), null);
    _baseUCLoaded = true;
  }
}

And it appears to work.  Maybe someone will enlighten me on this, but I have a hunch that it is just an unexpected scenario (a hack) that wasn't covered by testing.  In any case, it's pretty neat that it works.

Thursday, 27 April 2006 10:41:34 (Eastern Daylight Time, UTC-04:00)  #    Disclaimer  |  Comments [0]  | 
Comments are closed.

Disclaimer
The opinions expressed herein are solely my own personal opinions, founded or unfounded, rational or not, and you can quote me on that.

Thanks to the good folks at dasBlog!

Copyright © 2017 J. Ambrose Little