Andrew J. Bennieston January 2012
The following slides discuss some common programming topics within the context of Visual Basic for ASP.NET websites Emphasis will be placed on the basic concepts such as variables, types, functions and loops At each stage, the concept will be explained and illustrated with Visual Basic code But first, we need to introduce the fundamental structure needed to use ASP.NET
At the very least, a project must contain a.aspx file and a.aspx.vb file The.aspx file contains the HTML for the web page, including any form components The corresponding.vb file contains the code used to react to events such as button presses, page loads, etc. as well as any other helper code (e.g. functions to calculate something)
Define the.net language used (VB) and the.vb file which provides the functionality for this page Begin the HTML document (<html>) and start the header (<head>). The header includes the document title, and may also link to stylesheets (CSS) for control of the layout, colours etc. <%@ Page Language="VB" AutoEventWireup="false" CodeFile="Default.aspx.vb" Inherits="_Default" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/tr/xhtml1/dtd/xhtml1- transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title>untitled Page</title> </head> <body> <form id="form1" runat="server"> <div> </div> </form> </body> </html> Define the XML document type (XHTML; a fully XML compatible dialect of HTML) The body (<body>) defines the content of the webpage. Here, we have an HTML form (the <form> tag) which contains an empty <div>. A <div> is used to group related content together so that it may be kept together and optionally styled using CSS!
Define a class called _Default Partial Class _Default Inherits System.Web.UI.Page Inherit all of the properties & behaviour of a class called System.Web.UI.Page End the class; which is currently empty (except for the behaviour it has inherited from its parent, System.Web.UI.Page End Class
To understand inheritance, we must first understand the concept of a type In a programming language, variables may be of a specific type; the type completely defines their properties and behaviour For example, integers (VB type Integer) represent integer values (whole numbers), and can be manipulated using the normal mathematical operators Decimals (VB type Decimal) are another built in type, which represent real values, and again support the usual complement of mathematical operators In addition, VB defines assorted string types (sequences of characters, such as text typed into an HTML form field) On top of this, ASP.NET provides an entire framework of classes A class is just a user-defined type ; it has exactly the same meaning, an object of a given class will still have a well defined set of properties and behaviours
Examples of a class might be Animal, Shape or Vehicle Each has a set of properties (number of legs, age, number of sides, area, top speed, braking distance) as well as a number of operations (move, breathe, rotate, accelerate, park ) The relationship between these properties and actions or operations can be expressed in VB by creating a class which has those properties (called member variables, or properties), and implements functions (called member functions, or methods) for each action
Once you have one or more classes, you might want to reuse some of the behaviour or properties; for example if we ve already defined how animals breathe, we don t want to write this all over again when we make a Dog class We can use inheritance to share this behaviour and modify it accordingly If class Dog inherits from class Animal, the Dog is automatically capable of doing all the things an Animal can do; and it automatically has all the properties (number of legs, age, etc.) that an Animal had We can then go on to define new actions (bark, growl, walk, etc.) and new properties (name, owner, favourite bone) which will exist in addition to those already provided by the Animal class Furthermore, we can redefine some of the existing actions, so we can change how a Dog breathes, so that it will pant if it is hot!
This is exactly what happens in the automatically generated Visual Basic code we just saw The ASP.NET framework provides a class called System.Web.UI.Page 1 (which presumably defines lots of properties and operations for web pages) We create a class called _Default, which inherits from that class, and thus automatically gains all of those properties and methods! The Partial keyword just tells VB that we might add to the class later, in a different file (in practice, actually doing so is just confusing, and should be avoided!) 1 The class System.Web.UI.Page is documented at http://msdn.microsoft.com/enus/library/system.web.ui.page.aspx
The classic first example for programmers is the Hello, World application We re going to reproduce this in ASP.NET using a small amount of Visual Basic, and a single form element! The idea is straightforward: we create a form with a single label called hellolabel, then we override the OnLoad method of the Page class to fill the label with some generated text!
<%@ Page Language="VB" AutoEventWireup="false" CodeFile="Default.aspx.vb" Inherits="_Default" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/tr/xhtml1/dtd/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title>untitled Page</title> </head> <body> <form id="form1" runat="server"> <div> </div> </form> </body> </html> <asp:label ID="helloLabel" runat="server"></asp:label> We ve just added one line; an ASP form label whose ID is hellolabel (the name we wanted to give it). It is currently empty there is no Text= attribute specified!
We override the protected method (Sub) called OnLoad. The System.Web.UI.Page documentation tells us that it expects a single argument, an EventArgs object Partial Class _Default Inherits System.Web.UI.Page Protected Overrides Sub OnLoad(ByVal e As EventArgs) hellolabel.text = "Hello, World! Today is " & DateTime.Today End Sub End Class The End Sub is inserted automatically by Visual Studio; it just tells us where the code for that function ends! Inside the function, we set the.text property of the hellolabel object to a string which we generate, containing the text Hello, World! Today is followed by the current date, which we obtain from the Today property of the DateTime class in the ASP.NET framework!
If we load the.aspx page now, we get the following:
In the previous example, the most complicated part was probably obtaining the date; if you didn t know that the DateTime class existed, you d struggle with this (the MSDN documentation is very helpful if you re looking for a class to do something!) We also saw an example of overriding a function that was already provided by the System.Web.UI.Page class (OnLoad) Now, we re going to remove that code and build a form with a button we ll perform some action when people click the button!
Let s write a program to calculate someone s (approximate) age in seconds! Here s the HTML form: And finally a label into which we ll write the output; again it has no content initially! <%@ Page Language="VB" AutoEventWireup="false" CodeFile="Default.aspx.vb" Inherits="_Default" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/tr/xhtml1/dtd/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title>untitled Page</title> </head> <body> <h1>age Calculator</h1> <p>enter your date of birth below:</p> We ve added a heading (<h1>) and a paragraph of text (<p> </p>) above the form <form id="form1" runat="server"> <div> <p> DD/MM/YYYY: <asp:textbox ID="dateOfBirth" runat=server></asp:textbox><br /> <asp:button ID="button1" runat="server" Text="Calculate Age" /> </p> <p> <asp:label ID="outputAge" runat="server"></asp:label> </p> </div> </form> </body> </html> and an ASP text box, with a unique ID and with runat= server, so it knows to make the box active in the VB code! We have a button called button1, which will show up with the label Calculate Age
Partial Class _Default Inherits System.Web.UI.Page First, we define the function to handle the button click. If we double click the button itself in the Visual Web Developer form designer, it will generate the empty skeleton of this function for us! Protected Sub button1_click(byval sender As Object, ByVal e As System.EventArgs) Handles button1.click Dim birthdate, currentdate As DateTime Dim num_ticks_elapsed, num_seconds_elapsed As Decimal birthdate = Convert.ToDateTime(dateOfBirth.Text) currentdate = DateTime.Today num_ticks_elapsed = currentdate.ticks - birthdate.ticks num_seconds_elapsed = num_ticks_elapsed / 10000000 outputage.text = "Your age is " & num_seconds_elapsed & " seconds" End Sub End Class Declare some variables. We want to store two DateTime objects, and two Decimal objects The rest of the code does the following: 1. Convert the text entered by the user into a DateTime object 2. Get the current date 3. Subtract one from the other (we use ticks here, which is the number of 100 nanosecond intervals since 12:00:00 midnight on Jan 1 st, 0001 (excluding leap seconds!) 2 4. Convert this value back to seconds by dividing by 10 7 5. Set the result into the label, with appropriate text 2 See http://msdn.microsoft.com/en-us/library/system.datetime.ticks.aspx for details
Not my real date of birth: And confirmation that the calculation is correct:
Write a program to calculate the age difference between two people and display the result in seconds Obviously you ll need to read in two dates Once you ve done that, modify it so it displays the output in years Hint: You might want to use the TimeSpan (http://msdn.microsoft.com/enus/library/system.timespan.aspx) class once you ve got a number of ticks; this lets you convert a number of ticks to an equivalent in seconds, minutes, hours or days (you can then divide by 365 to get the number of years)