0
votes

I'm trying to get the namespace from ASP.NET template (.aspx) code-behind class. The code-behind file contains something like:

namespace MyTopNamespace.SubNamespace
{
    public partial class PageClass : System.Web.UI.Page
    {
        // ...
    }
}

And I'm passing an instance of this PageClass to the following method.

private static string GetNamespace(Page page)
{
    const string desiredPart = "MyTopNamespace";
    if (page == null)
    {
        throw new ArgumentNullException("page");
    }
    string pageNamespace = page.GetType().FullName;

    // For debugging
    string pageAssembly = page.GetType().Assembly.FullName;
    string pageAsmQualified = page.GetType().AssemblyQualifiedName;

    if (!pageNamespace.Contains(desiredPart) && 
        !pageAssembly.Contains(desiredPart) &&
        !pageAsmQualified.Contains(desiredPart))
    {
        throw new ApplicationException(string.Format(
            "Unexpected namespace or assembly: \n\n'{0}'\n'{1}'\n'{2}'", 
             pageNamespace, pageAssembly, pageAsmQualified)); 
    }
    // Remaining implementation ...
}

Exception output:

Unexpected namespace or assembly:

'ASP.pageclass_aspx'

'App_Web_pageclass.aspx.cdcab7d2.v4dudq3x, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'

'ASP.pageclass_aspx, App_Web_pageclass.aspx.cdcab7d2.v4dudq3x, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'

What happened to MyTopNamespace, and can it be obtained from the type using reflection?

1

1 Answers

1
votes

This is because the page is compiled at runtime, which then gives it a temporary assembly, namespace and sometimes a temporary class name as well (it seems not in this example). There is no way to retrieve the previous namespace from a page instance that has been instantiated through runtime compilation.