The Beauty of a Base Page Class

I never, and I mean never use the System.Web.UI.Page class as the class I inherit my Web Forms. I have a base class that I inherit from the Page class that has a set of methods and properties that I reuse many times over. Often I create more classes that inherits that class with special methods for the site.

If you open up the source code for the Page class either in Reflector or in the new source code that is available with Visual Studio 2008 you will see that it essentially does the same thing.

For example something I have done since the old classic ASP days is a method to write a line using the Response.Write method. I always disliked that it did not include an option for a line break, so I wrote the WriteLine method to handle this for me.

Public Sub WriteLine(ByVal sInfo As String)
    Response.Write(sInfo & "<BR>")
End Sub

There are many more examples of how I leverage this technique. Here is a more complicated example where I get HTML content from another page. In fact I think I talked about this a few months ago in a post on reading content from another source.

Private Function readHtmlPage(ByVal url As String) As String

    Dim result As String
    Dim objResponse As WebResponse
    Dim objRequest As WebRequest = System.Net.HttpWebRequest.Create(url)
    objResponse = objRequest.GetResponse

    Dim sr As StreamReader = New StreamReader(objResponse.GetResponseStream)


        result = sr.ReadToEnd


        CType(sr, IDisposable).Dispose()

    End Try

    Return result

End Function

I also use the base page classes to provide a factory type model to access objects. Here is an example where I get access to a photo album data access layer.

Public ReadOnly Property AC() As AlbumController

        If IsNothing(_ac) Then
            _ac = New AlbumController
        End If

        Return _ac

    End Get
End Property

My final example is properties to access Request variables.

Public ReadOnly Property PictureId() As Integer
        If Not Request("PictureId") Is Nothing Then
            If IsNumeric(Request("PictureId")) Then
                Return Convert.ToInt32(Request("PictureId"))
                Return 0
            End If
            Return 0
        End If
    End Get
End Property

I hope this helps you see how sub classing the page class helps make developing applications easier and more consistent.

Share This Article With Your Friends!