Question

I have an asp.net webforms application. Every single aspx.cs class needs to inherit from BasePage.cs which inherits from System.Web.UI.Page.

Desired Page Inheritance:

class MyChildPage : BasePage :  System.Web.UI.Page

How do I force that when a new child page is created it inherits from BasePage.cs and not System.Web.UI.Page?

Potential solutions:

  • Is there a way to change default creation of an aspx.cs page?
  • Is there a way to throw a compiler error if it inherits from System.Web.UI.Page?

Note: These child pages to share the same master page so that might help.

Was it helpful?

Solution 2

You could implement this with a custom MSBuild task that validates all pages. For example, here is a Task that will check that only BasePage inherits from Page. If any other class inherits from Page, an error will be logged in the output and the build will fail:

public class CheckBasePage : Task
{
    public override bool Execute()
    {
        var assm = Assembly.LoadFile("/path/to/WebsiteAssembly.dll");
        var types = assm.GetTypes();

        var pages = new List<string>();
        foreach (var t in types)
        {
            if (t.BaseType == typeof(Page) && t.Name != "BasePage")
            {
                pages.Add(t.FullName);
            }
        }

        if (pages.Count > 0)
        {
            Log.LogError("The following pages need to inherit from BasePage: [" + string.Join(",", pages) + "]");
            return false;
        }

        return true;
    }
}

Then you would add this custom task as part of the build process in your project file:

<UsingTask TaskName="CheckBasePage" AssemblyFile="/path/to/MyCustomTasksAssembly.dll" />

<Target Name="PostBuild">
  <CheckBasePage />
</Target>

Now this assumes that MyCustomTasksAssembly is a separate project you create for managing custom MSBuild tasks like this. If you want to embed the CheckBasePage task into the same project as the rest of the code, you will need to apply the same trick from here.

OTHER TIPS

Not sure if it fits your situation but you can specify the base page for the entire application via web.config-

<system.web>
    <pages pageBaseType="BasePage" />
</system.web>

Documentation on msdn: http://msdn.microsoft.com/en-us/library/950xf363(v=vs.85).aspx

As an alternative to Kelly's answer, you can do this, which is more flexible but more of a pain to configure:

class MyChildPage : BasePage

and...

class BasePage : System.Web.UI.Page

So MyChildPage inherits from BasePage, which inherits from System.Web.UI.Page.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top