Sunday, 2 March 2008

Simplify your ASP.net code by putting common bits in an external file

As you may know, in the code page or section of your asp.net page, you can use functions to re-use code over and over to save space. For example:


Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

dim Result As Integer = AddUp(2, 3) 'AddUp is the name of the function below,
'we pass it the numbers here for it to use

Response.Write(Result)
'Writes the result out at the top of
the page


End Sub

Function AddUp(ByVal firstNumber As Integer, ByVal secondNumber As Integer)

Dim Result As Integer
Result = firstNumber + secondNumber
Return Result

End Function

This is handy for individual pages, but what if you want to have a function you can call from anywhere in your site?

It's easy!...

1) In your website, make a folder called 'App_Code'

2) In here, make a new 'class' file. For example, if you add it in Visual Web Developer, it will be a .vb file, eg. FrequentCode.vb (Don't worry if you don't know what a class is...i'm not completely sure!!)

At minimum, this page needs the following in:


Public Class FrequentCode

End Class


3) Now, between the above, you write the 'function' that you'll be able to use on any page...note the slightly different way you write it in here...

Public Shared Function AddUp(ByVal firstNumber As Integer, ByVal secondNumber As Integer)

Dim Result As Integer
Result = firstNumber + secondNumber
Return Result

End Function


4) Now, to use this code on any page..simply use the following...

Dim Result As Integer = FrequentCode.Addup(2, 3)


That's it!

Please comment or email with questions!

Larry