App_Code and Namespaces

When working in Asp.net, I discovered something interesting about namespace.  Before I explain what that is, a little background…

If a page accesses it’s masterpage through the typical this.Master way, then any custom methods you’ve written aren’t accessible as it as typed as a MasterPage, not your class that inherits it (presumably something like _MyMasterPage). 

You can get around this easily with something like the following:
_MyMasterPage _myMaster = this.Master;
//now I methods specific to the _MyMasterPage class

I don’t like repeating that code all over the place, so I usually have a BasePage class that inherits from System.Web.UI.Page and then my pages inherit from it.  That way, I can write code like the following:
Public class BasePage
_MyMasterPage _master;

Private void Page_Load(…
{
_master = this.Master;
}

Public _MyMaster MasterExtensions
{
//get…
}

Now, each page (that inherits off of BasePage) can call MasterExtensions.Whatever() without any setup.  And base page can hold similar methods that it’s handy for all pages to be able to call. 

Since this is a project with no clutter (all data and logic are in other libraries, I thought I’d just put the BasePage class(es) in App_Code. 

That’s when I hit a problem that rarely comes up.  App_Code it’s in the project root namespace.  I had set a default root in the project properties of [ClientCompany].[ProjectName].WebUI.  And pages could refer to the BasePage class in App_Code, so you would think that App_Code followed that rule, but it doesn’t.  It builds another namespace, but makes that namespace an automatic import to the rest of the project. 

So where’s my problem?  I refered to _MyMaster a class that is tied to my specific MasterPage.  It’s in the default namespace.  And App_Code doesn’t get an automatic reference back to project namespace.

Solution: Go into the Base class page and give it a:
using [ClientCompany].[ProjectName].WebUI;
Most of the time, this doesn’t come up because classes in App_Code are fairly generic and not tied back to the UI classes.

Another way to solve this (that I’m probably going to do), is to put an interface to the MasterPage in App_Code.  It’s cleaner anyway, in case you end up with multiple masters.


Posted

in

, , ,

by

Tags: