Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to throw Exception when class has wrong inheritance

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.

like image 835
Rafi Avatar asked Mar 31 '14 19:03

Rafi


2 Answers

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

like image 126
Kelly Robins Avatar answered Oct 30 '22 02:10

Kelly Robins


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.

like image 33
mellamokb Avatar answered Oct 30 '22 01:10

mellamokb