 |
Exercise Answers for Beginning ASP.NET 1.0 with Visual Basic.NET

| Chapter |
Question Number |
Question |
Answer |
 |
| 4 |
1 |
What is a variable and how is it related to data types in VB.NET? |
A variable is a label that points to a piece of information stored in memory. A data type is a set of a particular kind of value, such as a set of numbers or letters. In VB.NET, each variable has a data type attached to it, so they will only accept values of a perticular type. Because of this, we refer to VB.NET as a strongly typed language. |
 |
| 4 |
2 |
Use string, integer and date variables to create an ASPX file to display your name, age and date of birth. |
<script language="vb" runat="server">
Sub Page_Load()
Dim name As String
Dim age As Integer
Dim dateOfBirth As Date
name = "Jake"
age = 40
dateOfBirth = #8/8/1962#
Display1.Text = name
Display2.Text = age
Display3.Text = dateOfBirth
End Sub
</script>
<html>
<body>
Hi, My name is
<asp:label id="Display1" runat="server" />
<br>I am
<asp:label id="Display2" runat="server" />
years old
<br>I was born on
<asp:label id="Display3" runat="server" />
</body>
</html>
|
 |
| 4 |
3 |
Arrange the following into groups of Numeric, Textual and Miscellaneous data types, and give an example of a value and a use for each.
- Integer
- Char
- Byte
- Short
- Boolean
- String
- Long
- Single
- Double
- Date
- Decimal
|
| Numeric Data Types |
Example Value |
Use |
| Integer |
467,892 |
to store an integer within the range -2,147,483,648 to 2,147,483,647 |
| Byte |
174 |
to store an integer within the range 0 to 255 |
| Short |
76 |
to store an integer within the range -32,768 to 32,767 |
| Long |
8,976,347,864 |
to store an integer within the range -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807 |
| Single |
-1.6088E-10 |
to store single precision floating-point numbers, within the range -3.402823E38 to -1.401298E-45 (for negative values), and 1.401298E-45 to 3.402823E38 (for positive values) |
| Double |
3.965468572385E-271 |
to store double precision floating point numbers within the range -1.79769313486232E308 to -4.94065645841247E-324 (for negative values), and 4.94065645841247E-324 to 1.79769313486232E308 (for positive values) |
| Decimal |
12.76 |
to store numbers with up to twenty-eight decimal places |
| Textual Data Types |
Example Value |
Use |
| String |
"I'm going to the shops" |
to store text |
| Char |
"A"C |
to store letters as numbers, perhaps when making your own customized character sets |
| Miscellaneous Data Types |
Example Value |
Use |
| Date |
#09/09/1926# / #16:25:05# |
to store a date or time value |
| Boolean |
True |
to describe whether a particular condition is true or false |
|
 |
| 4 |
4 |
Write an ASPX file that will multiply the values of two integer variables together. Then modify the example to add, divide and subtract the two numbers. After this, experiment with exponential, negation and modulus controls. |
<script language="vb" runat="server">
Sub Page_Load()
Dim integer1 As Integer
Dim integer2 As Integer
Dim Total As Integer
integer1 = 10
integer2 = 5
Total = integer1 + - * \ integer2
Display1.Text = Total
End Sub
</script>
<html>
<body>
The result of your calculation is:
<asp:label id="Display1" runat="server" />
</body>
</html>
|
 |
| 4 |
5 |
Create an array containing your 5 favorite singers. Then concatenate the elements of your array into one string, and after the opening sentence "My 5 favorite singers are:", display them in a clear way using the <asp:label> control. |
<script runat="Server" language="VB">
Sub Page_Load()
Dim strArraySinger(4) As String
strArraySinger(0) = "Aretha Franklin,"
strArraySinger(1) = "Muddy Waters,"
strArraySinger(2) = "Madonna,"
strArraySinger(3) = "Frank Sinatra"
strArraySinger(4) = "Elvis Presley."
singers.Text = strArraySinger(0) & " " & strArraySinger(1) & " " & _
strArraySinger(2) & " " & strArraySinger(3) & " and " & _
strArraySinger(4)
End Sub
</script>
<html>
<body>
My 5 favorite singers are:
<br/>
<asp:label id="singers" runat="server"/>
</body>
</html>
|
 |
| Chapter |
Question Number |
Question |
Answer |
 |
| 5 |
1 |
Explain why XML is so useful for storing data. |
XML is useful for storing data for the following reasons:
- It gives us a way to explicitly structure our data.
- It lets us describe the meaning of our data as part of the structuring process.
- It produces intuitive and easy-to-interpret documents.
|
 |
| 5 |
2 |
Create an XML file to hold the following employee information:
Company: Wrox Press
employee: Hubert Welsch
employee number: 9862
contact numbers: ext - 346
home - 8764 35733
length of service: 2 years
department: .NET Team
employee: Paul Crick
employee number: 7461
contact numbers: ext - 399
home - 2138 90346
length of service: 8 months
department: .NET Team
employee: Alison Freyer
employee number: 7849
contact numbers: ext - 982
home - 7893 42769
length of service: 4 years
department: Java Team
employee: Sandra Jackson
employee number: 9862
contact numbers: ext - 222
home - 8974 389743
length of service: 1 year
department: Finance |
<?xml version="1.0"?>
<company name="Wrox Press">
<employee name="Hubert Welsch" number="9862">
<contact_numbers>
<office>ext.346</office>
<home>8764 35733</home>
</contact_numbers>
<length_of_service>2 years</length_of_service>
<department>.NET Team</department>
</employee>
<employee name="Paul Crick" number="7461">
<contact_numbers>
<office>ext.399</office>
<home>2138 90346</home>
</contact_numbers>
<length_of_service>8 months</length_of_service>
<department>.NET Team</department>
</employee>
<employee name="Alison Freyer" number="7849">
<contact_numbers>
<office>ext.982</office>
<home>7893 42769</home>
</contact_numbers>
<length_of_service>4 years</length_of_service>
<department>Java Team</department>
</employee>
<employee name="Sandra Jackson" number="9862">
<contact_numbers>
<office>ext.222</office>
<home>8974 389743</home>
</contact_numbers>
<length_of_service>1 year</length_of_service>
<department>Finance</department>
</employee>
</company>
|
 |
| 5 |
3 |
Create a cascading style sheet to display the XML file you have just created. Use font style and alignment, and color to display the employee information in an attractive way.
|
employee {
display:block;
background: #eeeecc;
color: #7777bb;
border-left:solid;
border-top:solid;
border-width:10;
padding:10,10,10,10
}
name {
display:block;
font-family: Arial, Helvetica;
font-weight: bold;
font-size: 12pt;
background: #ffffee;
color: #aa0066;
border-bottom:solid;
border-top:solid;
border-width:4;
}
number {
display:inline;
font-size: 8pt;
font-weight: normal;
color: #000000;
}
contact_numbers {
display:block;
font-family: Verdana;
font-size: 8pt;
color: #336633;
text-align: right;
}
office {
display:block;
border-bottom:solid;
border-width:1;
}
home {
display:block;
border-bottom:solid;
border-width:1;
}
length_of_service {
font-family: Arial, Helvetica;
font-size: 12pt;
color: black;
}
department {
font-family: Arial, Helvetica;
font-size: 12pt;
font-weight: bold;
color: black;
}
|
 |
| 5 |
4 |
Are the following XML documents well-formed? If not, make the necessary corrections, and explain why your corrections are important in the creation of a well-formed document.
(a)
<?xml version="1.0"?>
<shoppingList>
<title>Shopping List</title>
<items>
<fruit items>
<item>Rasberries</item>
<item>Apples</item>
<item>Oranges</item>
</fruit_items>
<vegetable_items>
<item>Carrots</item>
<item>Onions</item>
</vegetable_items>
<other_items>
<item>Floor cleaner</item>
<item>Bread</item>
<item>Toothpaste</item>
<item>Pasta</item)
</other_items>
</items>
</shoppingList>
<notes> Don't get cooking apples like last time and post letter to Harold</notes>
(b)
<?xml version="1.0">
<order>
<salesperson>Sam Clarke</salesperson>
<customer>Droutledge Waters</customer>
<item>
<description>snorkle</description>
<quantity>37</quantity>
</item>
<date>
<month>7</month>
<day>6</day>
<year>2001</year>
</date>
</order>
|
Both of the XML documents are badly-formed.
a. The opening tag <fruit items> should be <fruit_items> so that it matches the element's closing tag </fruit_items>. An underscore is required to separate the two words, since spaces are not permissible as characters in XML element names.
The items element should be terminated with a closing tag </items>.
<?xml version="1.0"?>
<shoppingList>
<title>Shopping List</title>
<items>
<fruit_items>
<item>Rasberries</item>
<item>Apples</item>
<item>Oranges</item>
</fruit_items>
<vegetable_items>
<item>Carrots</item>
<item>Onions</item>
</vegetable_items>
<other_items>
<item>Floor cleaner</item>
<item>Bread</item>
<item>Toothpaste</item>
<item>Pasta</item>
</other_items>
</items>
<notes> Don't get cooking apples like last time and post letter to Harold</notes>
</shoppingList>
b. The XML version directive requires a question mark before the closing > symbol
<?xml version="1.0"?>
<order>
<salesperson>Sam Clarke</salesperson>
<customer>Droutledge Waters</customer>
<item>
<description>snorkle</description>
<quantity>37</quantity>
</item>
<date>
<month>7</month>
<day>6</day>
<year>2001</year>
</date>
</order>
|
 |
| 5 |
5 |
Once you have finished looking at part b, try rearranging this information so you can view orders that have been placed via Sam Clarke the sales person. Add another order, placed the following week, for 12 goggles, as ordered by Aqua Lake Enterprises. |
This information can be rearranged as follows so that it's possible to view orders placed via Sam Clarke the sales person. Here we have added another order, as described in the exercise:
<?xml version="1.0"?>
<salesperson name="Sam Clarke">
<order>
<customer>Droutledge Waters</customer>
<item>
<description>snorkle</description>
<quantity>37</quantity>
</item>
<date>
<month>7</month>
<day>6</day>
<year>2001</year>
</date>
</order>
<order>
<customer>Aqua Lake Enterprises</customer>
<item>
<description>goggles</description>
<quantity>12</quantity>
</item>
<date>
<month>7</month>
<day>13</day>
<year>2001</year>
</date>
</order>
</salesperson>
|
 |
| Chapter |
Question Number |
Question |
Answer |
 |
| 6 |
1 |
For each of the following Boolean expressions, say for what values of A each of them will evaluate to True and when they will evaluate to False.
a. NOT A > 0 OR A > 5
b. A > 1 AND A < 5 OR A > 7 AND A < 10
c. A < 10 OR A > 12 AND NOT A > 20 |
a.False if A is 0, 1, 2, 3, 4 or 5. True otherwise.
b.True if A is 2, 3, 4, 8 or 9. False otherwise.
c.True if A is 13, 14, 15, 16, 17, 18 or 19, or A is 9 or less. False otherwise. |
 |
| 6 |
2 |
Suggest a loop structure which would be appropriate for each of the following scenarios, and justify your choice:
a. Displaying a set of items from a shopping list, stored in an array
b. Displaying a calendar for the current month
c. Looking through an array to find the location of a specific entry
d. Drawing a chessboard using an HTML table
Bonus: write an ASP.NET page to perform one of these tasks. |
a. For Each would be suitable, because it provides a simple way to handle every item in an array.
b. For ... Next would be suitable, because we know how many days there are in the current month, so we can specify the number of times the loop needs to be performed before it starts.
c. Do ... Until would probably work best, since it allows us to perform the loop until the entry has been found.
d. Tricky: you'd probably want to use two For ... Next loops, one inside the other. We need eight rows, each consisting of eight cells, so two loops, each of which take place eight times, would work fine. |
 |
| 6 |
3 |
Write a function that generates a random integer between two integers passed as parameters. Build an ASP.NET page which allows you to enter the lower and upper limits, and generates a set of random numbers in that range.
|
This function generates a random integer between two integers passed in as parameters:
Function RandomNumber(a As Integer, b As Integer) As Integer
Return int((1 + b - a) * rnd) + a
End Function
This ASP.NET page allows you to enter lower and upper limits, and uses the function RandomNumber to generate random numbers in that range:
<%@ Page Language="VB" runat=server %>
<script runat=server>
Sub Page_Load()
if num1.text="" then num1.text="0"
if num2.text="" then num2.text="1"
answer.text = CStr( RandomNumber( CInt(num1.text) , CInt(num2.text) ) )
End Sub
Function RandomNumber(a As Integer, b As Integer) As Integer
Return int((1 + b - a) * rnd) + a
End Function
</script>
<html>
<body>
<form runat="server">
Min: <asp:textbox id=num1 runat=server />
Max: <asp:textbox id=num2 runat=server />
<br />
<input type="Submit" value="Pick random value between limits above">
<br />
<font size=16pt>Value: <asp:label id=answer runat=server /></font>
</form>
</body>
</html>
|
 |
| 6 |
4 |
Write an ASP.NET page that displays the number of days until Christmas. You'll need to use the following function:
DateDiff(Interval As String, Date1 As Date, Date2 As Date)
You need to pass in "d" as the interval specifier to get a difference in days.
Modify your page so that it provides the number of days until one of five different public holidays, according to a user's selection.
|
This ASP.NET page displays the number of days until Christmas:
<%@ Page Language="VB" runat=server debug=true %>
<script runat=server>
Sub Page_Load()
Dim TodaysDate As Date = Now()
Dim XmasDate As Date = "12/25"
lblDate.text = TodaysDate.Date
lblDays.text = DateDiff("d", TodaysDate, XmasDate)
End Sub
</script>
<html>
<head>
<title>Days To Christmas</title>
</head>
<body>
<h2>Today's date is <asp:label id="lblDate" runat="server" />.</h2>
There are <asp:label id="lblDays" runat="server"/> days until Christmas.
</body>
</html>
Modify your page so that it provides the number of days until one of five different public holidays, according to a user's selection:
<%@ Page Language="VB" runat=server debug=true %>
<script runat=server>
Sub Page_Load()
Dim TodaysDate As Date = Now()
Dim HolDate As Date = ddlHoliday.SelectedItem.Value
Dim ExtraDays As Integer
If (HolDate.Date < TodaysDate.Date) Then ExtraDays =365 Else ExtraDays =0
lblDate.text = TodaysDate.Date
lblDays.text = DateDiff("d", TodaysDate, HolDate) + ExtraDays
End Sub
</script>
<html>
<head>
<title>Days To Holiday</title>
</head>
<body>
<h2>Today's date is <asp:label id="lblDate" runat="server" />.</h2>
<form runat="server">
There are <asp:label id="lblDays" runat="server" /> days until
<asp:dropdownlist autopostback="true" id="ddlHoliday" runat="server">
<asp:listitem value="01/01" text="New Years Day" />
<asp:listitem value="06/14" text="Flag Day" />
<asp:listitem value="07/04" text="Independence Day" />
<asp:listitem value="11/11" text="Armistice" />
<asp:listitem value="12/25" text="Christmas" />
</asp:dropdownlist>
</form>
</body>
</html>
|
 |
| 6 |
5 |
Suggest a situation when you might want to pass variables into a function or subroutine by reference. Write an ASP.NET page to illustrate your example. |
This is an open-ended question, so no solution is provided.
|
 |
| Chapter |
Question Number |
Question |
Answer |
 |
| 7 |
1 |
Explain why event-driven programming is such a good way of programming for the Web. |
In an event-driven web page, code is not constrained to being executed in a predetermined order whenever the page is served. Rather, it can be broken up into dedicated blocks of functionality that will be executed in response to specific user-generated events. We can therefore piece together complex functionality from several independent components in a web form, and there is no need for the client software to know anything about how the components are programmed.
|
 |
| 7 |
2 |
Run the following HTML code in your browser (remember to save the page with a .htm extension). Now translate the HTML into a set of ASP.NET server controls so that the information entered into the form is maintained when the submit button is clicked. Add a subroutine to the button to confirm that the details entered were received.
<html>
<head>
<title>HTML</title>
</head>
<body>
<form>
<h4>Please enter your name:</h4>
<input type="text"><br /><br />
<h4>What would you like for breakfast?</h4>
<h4>Cereal<input type="checkbox"></h4>
<h4>Eggs<input type="checkbox"></h4>
<h4>Pancakes<input type="checkbox"></h4>
<h4>Feed me:</h4>
<h4>Now<input type="radio"></h4>
<h4>Later<input type="radio"></h4>
<input type="submit" value="Thank you!">
</form>
</body>
</html>
|
<%@ Page Language="VB" runat="server" %>
<script runat="server">
Sub ClickHandler(Sender As Object, E As EventArgs)
message.text = "Details received."
questions.visible = False
End Sub
</script>
<html>
<head>
<title>ASP.NET</title>
</head>
<body>
<asp:label id=message runat=server />
<form id=questions runat="server">
<h4>Please enter your name:</h4>
<asp:textbox id=name runat="server" /><br /><br />
<h4>What would you like for breakfast?</h4>
<asp:checkboxlist id=food runat="server">
<asp:listitem value="Cereal"/>
<asp:listitem value="Eggs"/>
<asp:listitem value="Pancakes"/>
</asp:checkboxlist>
<h4>Feed me:<h4>
<asp:radiobuttonlist id=when runat="server">
<asp:listitem value="Now"/>
<asp:listitem value="Later"/>
</asp:radiobuttonlist>
<asp:button type="submit" id="btnSubmit" onclick="ClickHandler" text="Thank you!" runat="server" />
</form>
</body>
</html>
|
 |
| 7 |
3 |
Add a Page_Load event handler to the ASPX code you have just created which confirms the selections made in the following format:
Thank you very much _____.
You have chosen _____ for breakfast. I will prepare it for you _____.
|
<%@ Page Language="VB" runat="server" debug = true %>
<script runat="server">
Sub ClickHandler(Sender As Object, E As EventArgs)
dim item as listitem
message.text = "Thank you very much " + name.text
message.text += ". You have chosen "
if food.items(0).Selected then message.text += food.items(0).text + " "
if food.items(1).Selected then message.text += food.items(1).text + " "
if food.items(2).Selected then message.text += food.items(2).text + " "
message.text += "for breakfast. I will prepare it for you " + Request.Form("when") + "."
questions.visible = False
End Sub
</script>
<html>
<head>
<title>ASP.NET</title>
</head>
<body>
<asp:label id=message runat=server />
<form id=questions runat="server">
<h4>Please enter your name:</h4>
<asp:textbox id=name runat="server" /><br /><br />
<h4>What would you like for breakfast?</h4>
<asp:checkboxlist id=food runat="server">
<asp:listitem value="Cereal"/>
<asp:listitem value="Eggs"/>
<asp:listitem value="Pancakes"/>
</asp:checkboxlist>
<h4>Feed me:<h4>
<asp:radiobuttonlist id=when runat="server">
<asp:listitem value="Now"/>
<asp:listitem value="Later"/>
</asp:radiobuttonlist>
<asp:button type="submit" id="btnSubmit" onclick="ClickHandler" text="Thank you!"
runat="server" />
</form>
</body>
</html>
|
 |
| 7 |
4 |
Create a very basic virtual telephone using an ASPX file that displays a textbox and a button named "Call". Configure your ASPX file so that when you type a telephone number into your textbox and press "Call", you are:
- presented with a message confirming the number you are calling
- presented with another button called "Disconnect" that, when pressed, returns you to your opening page, leaving you ready to type another number
|
<%@ Page Language="VB" runat="server" debug = true %>
<script runat="server">
Sub ClickHandler(Sender As Object, E As EventArgs)
if btnSubmit.text = "Call" Then
message.text = "Calling: " + number.text
btnSubmit.text = "Disconnect"
number.enabled = False
else
message.text = ""
btnSubmit.text = "Call"
number.enabled = True
end if
End Sub
</script>
<html>
<head>
<title>Phone</title>
</head>
<body>
<form id=questions runat="server">
Please enter a telephone number:<asp:textbox id=number runat="server" /><br />
<asp:button type="submit" id="btnSubmit" onclick="ClickHandler" text="Call" runat="server" />
<asp:label id=message runat=server />
</form>
</body>
</html>
|
 |
| 7 |
5 |
Using the Select Case construct, associate three particular telephone numbers with three names, so that when you press the "Call" button, your confirmation message contains the name of the person you are 'calling' rather than just the telephone number.
|
<%@ Page Language="VB" runat="server" debug = true %>
<script runat="server">
Sub ClickHandler(Sender As Object, E As EventArgs)
if btnSubmit.text = "Call" Then
dim name as string
select case(number.text)
case "6874923"
name = "Jake"
case "6874831"
name = "Ewan"
case "6874624"
name = "Alessandro"
case else
name = "<unknown>"
end select
message.text = "Calling " + name + " on " + number.text
btnSubmit.text = "Disconnect"
number.enabled = False
else
message.text = ""
btnSubmit.text = "Call"
number.enabled = True
end if
End Sub
</script>
<html>
<head>
<title>Phone</title>
</head>
<body>
<form id=questions runat="server">
Please enter a telephone number:<asp:textbox id=number runat="server" /><br />
<asp:button type="submit" id="btnSubmit" onclick="ClickHandler" text="Call" runat="server" />
<asp:label id=message runat=server />
</form>
</body>
</html>
|
 |
| Chapter |
Question Number |
Question |
Answer |
 |
| 8 |
1 |
Explain the following terms in your own words, and give an example of how each one might be applied in the context of a simple object-oriented holiday booking application:
- Object
- Class
- Property
- Method
|
|
 |
| 8 |
2 |
Explain what classes we might want to define in order to model each of the following real-world scenarios, along with the members we'd expect them to have. If there is more than one possible solution, explain what additional information we require to establish which one will be most suitable.
- Purchasing items at a supermarket checkout
- Enrolling on a college course
- Maintaining an inventory of office equipment
|
|
 |
| 8 |
3 |
Extend our Car example to demonstrate on the browser that the value of the object's Gear property is restricted to a range of values between -1 and +5. Explain in your own words why it's a good idea to define functionality in method overloads that relies on calling an existing version of the same method.
|
<%@ page language="vb" runat="server" debug=true %>
<script runat="server">
Public Class Car
Private _Color As String
Private _Gear As Integer
Public Property Color As String
Get
Return _Color
End Get
Set(value As String)
_Color = value
End Set
End Property
Public ReadOnly Property Gear As Integer
Get
Return _Gear
End Get
End Property
Overloads Public Sub ChangeGear(direction As Integer)
If direction < 0 Then _Gear -= 1
If direction > 0 Then _Gear += 1
If _Gear > 5 Then _gear = 5
If _Gear < -1 Then _gear = -1
End Sub
Overloads Public Sub ChangeGear(direction As String)
If direction = "down" Then ChangeGear(-1)
If direction = "up" Then ChangeGear(+1)
End Sub
Sub New()
_color = "cold grey steel"
End Sub
End Class
Sub Page_Load()
Dim MyCar As New Car()
Dim MyGear As Integer = 0
Response.Write("<b>New object 'MyCar' created.</b>")
Do While (MyGear = MyCar.Gear)
MyCar.ChangeGear("up")
Response.Write("<br />Successfully changed up to gear " & MyCar.Gear)
MyGear += 1
Loop
Response.Write("<br />Failed to change up to gear " & MyGear)
MyGear -= 1
Do While (MyGear = MyCar.Gear)
MyCar.ChangeGear("down")
Response.Write("<br />Successfully changed down to gear " & MyCar.Gear)
MyGear -= 1
Loop
Response.Write("<br />Failed to change down to gear " & MyGear)
End Sub
</script>
It's a good idea to define a method overloads so that it makes a call on the original method rather than reimplementing functionality from scratch. This guarantees a single, well-defined set of rules to govern how that method can modify the object on which it's called. If the original method definition is modified in some way, all relevant overloads will use the modified functionality without any further work required.
|
 |
| 8 |
4 |
We may want to display the Price property of a Book object in some currency other than US dollars. Define a new property ConvPrice, whose accessor method Get takes two parameters denoting a currency symbol and a conversion rate, and returns the book price in the appropriate currency.
|
<%@ page language="vb" runat="server" strict="true" %>
<script runat="server">
Public Class Book
Private _Title As String
Private _Isbn As Integer
Private _Price As Decimal
Private _SubTitle As String
Public Sub New(newTitle As String, newIsbn As Integer)
_Title = newTitle
_Isbn = newIsbn
End Sub
Public Sub New(newTitle As String, newIsbn As Integer, newSubtitle As String)
_Title = newTitle
_Isbn = newIsbn
_Subtitle = newSubtitle
End Sub
Public ReadOnly Property TitleInfo As String
Get
Return _Title & " <i>(ISBN: " & _Isbn & ")</i>"
End Get
End Property
Public ReadOnly Property Title As String
Get
Return _Title
End Get
End Property
Public ReadOnly Property Isbn As Integer
Get
Return _Isbn
End Get
End Property
Public Property Price As Decimal
Get
Return _Price
End Get
Set(value As Decimal)
_Price = value
End Set
End Property
Public ReadOnly Property ConvPrice(MyCurrency as string, MyConversion as double) As String
Get
Return MyCurrency & CStr(Math.Round(_Price * MyConversion, 2))
End Get
End Property
End Class
Sub Page_Load()
Dim MyBook As New Book("Beginning ASP.NET", 1861005040)
Response.Write("<b>New book 'MyBook' created.</b>")
MyBook.Price = CDec(39.99)
Response.Write("<br/>Title info: " & MyBook.TitleInfo)
Response.Write("<br/>Price: $" & MyBook.Price)
Response.Write("<br/>UK Price: " & MyBook.ConvPrice("pound;",0.67) & " + Tax<br/>")
Dim AnotherBook As New Book("Professional ASP.NET", 1861004885)
Response.Write("<b>New book 'AnotherBook' created.</b>")
AnotherBook.Price = CDec(59.99)
Response.Write("<br/>Title info: " & AnotherBook.TitleInfo)
Response.Write("<br/>Price: $" & AnotherBook.Price)
Response.Write("<br/>UK Price: " & AnotherBook.ConvPrice("pound;",0.67) & " + Tax<br/>")
Dim ABigBook As New Book("Professional Linux Programming", 1861003013, "Databases, PostgreSQL, MySQL, LDAP, security, device drivers, GTK+, GNOME, Glade, GUI, KDE, Qt, Python, PHP, RPC, diskless systems, multimedia, internationalization, CORBA, PAM, RPM, CVS, Flex, Bison, Beowulf, Clustering, ORBit, MPI, PVM, and XML")
Dim AnotherBigBook As New Book("Professional C#", 1861004990, "")
End Sub
</script>
|
 |
| 8 |
5 |
Of course, this isn't quite how book prices are calculated for an international market, with additional factors such as local taxation playing a part in the total cost. Normally, separate prices are listed for the main countries in which a book will be sold. Update the book class again, so that we can specify three different prices for each object - you might want to use the values on the back of this book.
Define additional data members for these extra prices, and a property called LocalPrice that lets us specify a country code parameter ("US", "UK", "Can", for example) to denote which country's pricing we want to Get or Set. Prices should still be stored interally as Decimal variables. Overload the Get accessor method so that we can optionally specify a currency symbol for display with that price.
|
<%@ page language="vb" runat="server" strict="true" %>
<script runat="server">
Public Class Book
Private _Title As String
Private _Isbn As Integer
Private _Price As Decimal
Private _UKPrice As Decimal
Private _CANPrice As Decimal
Private _SubTitle As String
Public Sub New(newTitle As String, newIsbn As Integer)
_Title = newTitle
_Isbn = newIsbn
End Sub
Public Sub New(newTitle As String, newIsbn As Integer, newSubtitle As String)
_Title = newTitle
_Isbn = newIsbn
_Subtitle = newSubtitle
End Sub
Public ReadOnly Property TitleInfo As String
Get
Return _Title & " <i>(ISBN: " & _Isbn & ")</i>"
End Get
End Property
Public ReadOnly Property Title As String
Get
Return _Title
End Get
End Property
Public ReadOnly Property Isbn As Integer
Get
Return _Isbn
End Get
End Property
Public Property Price As Decimal
Get
Return _Price
End Get
Set(value As Decimal)
_Price = value
End Set
End Property
Overloads Public Property LocalPrice(locale as string) As Decimal
Get
Select Case locale
Case "UK"
Return _UKPrice
Case "CANADA"
Return _CANPrice
Case Else
Return _Price
End Select
End Get
Set(value As Decimal)
Select Case locale
Case "UK"
_UKPrice = value
Case "CANADA"
_CANPrice = value
Case Else
_Price = value
End Select
End Set
End Property
Overloads Public ReadOnly Property LocalPrice(locale as string, symbol as string) As String
Get
Select Case locale
Case "US"
symbol = "US$"
Case "UK"
symbol = "UKpound;"
Case "CANADA"
symbol = "CAN$"
End Select
Return symbol & LocalPrice(locale)
End Get
End Property
Public ReadOnly Property ConvPrice(MyCurrency as string, MyConversion as double) As String
Get
Return MyCurrency & CStr(Math.Round(_Price * MyConversion, 2))
End Get
End Property
End Class
Sub Page_Load()
Dim MyBook As New Book("Beginning ASP.NET", 1861005040)
Response.Write("<b>New book 'MyBook' created.</b>")
MyBook.Price = CDec(39.99)
MyBook.LocalPrice("UK") = CDec(31.99)
MyBook.LocalPrice("CANADA") = CDec(59.95)
Response.Write("<br/>Title info: " & MyBook.TitleInfo)
Response.Write("<br/>US Price: $" & MyBook.Price)
Response.Write("<br/>UK Price: pound;" & MyBook.LocalPrice("UK"))
Response.Write("<br/>Canada Price: $" & MyBook.LocalPrice("CANADA") & "<br/>")
Dim AnotherBook As New Book("Professional ASP.NET", 1861004885)
Response.Write("<b>New book 'AnotherBook' created.</b>")
AnotherBook.Price = CDec(59.99)
AnotherBook.LocalPrice("UK") = CDec(43.99)
AnotherBook.LocalPrice("CANADA") = CDec(89.95)
Response.Write("<br/>Title info: " & AnotherBook.TitleInfo)
Response.Write("<br/>US Price: " & AnotherBook.LocalPrice("US","yes"))
Response.Write("<br/>UK Price: " & AnotherBook.LocalPrice("UK","yes"))
Response.Write("<br/>Canada Price: " & AnotherBook.LocalPrice("CANADA","yes") & "<br/>")
Dim ABigBook As New Book("Professional Linux Programming", 1861003013, "Databases, PostgreSQL, MySQL, LDAP, security, device drivers, GTK+, GNOME, Glade, GUI, KDE, Qt, Python, PHP, RPC, diskless systems, multimedia, internationalization, CORBA, PAM, RPM, CVS, Flex, Bison, Beowulf, Clustering, ORBit, MPI, PVM, and XML")
Dim AnotherBigBook As New Book("Professional C#", 1861004990, "")
End Sub
</script>
|
 |
| Chapter |
Question Number |
Question |
Answer |
 |
| 9 |
1 |
Name three different types of class relationship, and give examples of when it would be appropriate to use each one.
|
Association
Containment
Inheritance
|
 |
| 9 |
2 |
Create an ASP.NET page that displays the current date and time using the shared property Now of the DateTime class.
|
<%@ page language="vb" runat="server" %>
<script runat="server">
Sub Page_Load()
time.text = DateTime.now
End Sub
</script>
<html>
<body>
<hr />
The date and time is: <asp:label id="time" runat="server" /><br />
</body>
</html>
|
 |
| 9 |
3 |
Define an Account class for library users that has a Borrow() method, and an Item class that represents a library book with properties Title and ISBN. Code the Borrow() method so that it gets the title and the ISBN of the borrowed book from the Item object.
|
|
 |
| 9 |
4 |
Define an Engine class, whose properties include SerialNo, Rpm, and Name (to be set by the class constructor), and whose methods include SwitchOn and SwitchOff. Now integrate it with the Car class so that you can access these properties and methods from instances of the Car class.
|
|
 |
| 9 |
5 |
Using inheritance, define a FlyingCar class that has an Ascend() method, a Descend() method and a read-only property that returns the altitude of the flying car.
|
|
 |
| Chapter |
Question Number |
Question |
Answer |
 |
| 10 |
1 |
Explain the role of the Page class in ASP.NET and describe what sort of things we can do with it.
|
When a browser makes an ASPX file request, the ASP.NET module (aspnet_isapi.dll) deals with it. The aspnet_isapi.dll then places the ASPX file that was requested into a new class definition defined in a namespace called ASP. This ASP class inherits from the Page class so the ASP.NET page has access to the useful functionality that the Page class provides.
The Page class is part of the System.Web.UI namespace. The Page class brings us a wealth of useful properties and methods that we can use on our ASP.NET pages. It also gives us access to a range of other objects created from classes in the System.Web namespace.
|
 |
| 10 |
2 |
Write an ASP.NET page that returns the Windows name of your computer and the URL of the page that you are visiting.
|
<%@ Page Language="VB" %>
<script runat="server">
Sub Page_Load()
name.text= server.machineName
url.text = request.url.ToString()
end sub
</script>
<html>
My computer is named: <b><asp:label id="name" runat="server" /></b><br />
My URL is: <b><asp:label id="url" runat="server" /></b>
</html>
|
 |
| 10 |
3 |
(a) Write one ASP.NET page that prompts a user to enter a value for the radius of a circle then calculates its area (Area = Pi * (radius)²) and another ASP.NET page that prompts the user to enter the length of the radius and then calculates the circumference (circumference = 2*Pi*radius). Both pages should access the value of Pi (3.142) stored in application state.
(b) Repeat the above example storing the value of Pi in global.asax.
|
area.aspx
<%@ Page Language="VB" %>
<script language="vb" runat="server">
Sub Update(Sender As Object, E As EventArgs)
Dim IntInput as integer = CInt(input.text)
Dim pi as double = application("pi")
area.text = pi*Intinput*intinput
end Sub
</script>
<html>
<body>
<form runat="server">
Input = <asp:textbox id="input" runat="server" />
<asp:button text="submit" runat="server" onclick="Update" /><br />
the area is: <asp:label id="area" runat="server" />
</form>
</body>
</html>
circumference.aspx
<%@ Page Language="VB" %>
<script language="vb" runat="server">
Sub Update(Sender As Object, E As EventArgs)
Dim IntInput as integer = CInt(input.text)
Dim pi as double = application("pi")
area.text = pi*Intinput*2
end Sub
</script>
<html>
<body>
<form runat="server">
Input = <asp:textbox id="input" runat="server" />
<asp:button text="submit" runat="server" onclick="Update" /><br />
the circumference is: <asp:label id="area" runat="server" />
</form>
</body>
</html>
Setting variable in application state
<%@ Page Language="VB" %>
<html>
<body>
<%
Application("pi") = "3.142"
%>
</body>
</html>
Setting variable in global.asax
<script language="VB" runat="server">
Sub Application_OnStart()
Application("pi") = "3.142"
End Sub
</script>
|
 |
| 10 |
4 |
Using session variables implement a shopping cart that lets you add up to five items from a dropdown listbox and displays:
(a) The total number of items selected
(b) A list of all the items in the cart
There should also be a means of emptying all the items contained in the cart.
|
<%@ Page language="VB"%>
<script language="vb" runat="server">
Sub AddClick(sender As System.Object, e As System.EventArgs)
session("BasketCount") += 1
If Session("basketCount") < 6
Session("BasketItem") = request.Form("list1")
call display
Else
shopping.Text = "I'm full up huney"
End If
End Sub
Sub EmptyClick(sender As System.Object, e As System.EventArgs)
Session("BasketCount") = 0
Session("BasketItem") = ""
shopping.Text = ""
end sub
Sub display
Dim item as string
Dim Items(4) as string
Dim n as integer
n = Session("basketCount") - 1
Items(n) = request.Form("list")
For Each item In items
shopping.Text = shopping.Text & item & "<BR>"
Next
End sub
</script>
<html>
<body>
<form id="BasketForm" method="post" runat="server">
<asp:dropdownlist id="list" runat="server">
<asp:listitem>bread</asp:listitem >
<asp:listitem >fish</asp:listitem >
<asp:listitem >chillies</asp:listitem >
<asp:listitem >olives</asp:listitem >
<asp:listitem >Turnip juice</asp:listitem >
</asp:dropdownlist >
<asp:Button id="Add" OnClick="AddClick" runat="server" Text="Add"/>
<asp:Button id="Empty" OnClick="EmptyClick" runat="server"
Text="Empty"/>
<br />
basketItems: <br/> <asp:label id="shopping" runat="server" />
<br />Number of items : <%=Session("BasketCount")%>
<br />
</form>
</body>
</html>
|
 |
| 10 |
5 |
Create an ASP.NET page that contains textboxes in which a user can enter his name, address and telephone number. Using cookies, display this information on a separate ASP.NET page.
|
Code for setting cookie:
<%@ Page Language="VB" %>
<script language="vb" runat="server">
Public Sub Click(ByVal sender As Object, ByVal e As System.EventArgs)
Dim NameCookie As New HttpCookie("Name")
Dim AddressCookie As New HttpCookie("Address")
Dim PhoneCookie As New HttpCookie("Phone")
NameCookie.Value = name.Text
AddressCookie.Value = address.Text
PhoneCookie.Value = phone.Text
Response.Cookies.Add(NameCookie)
Response.Cookies.Add(AddressCookie)
Response.Cookies.Add(PhoneCookie)
End Sub
</script>
<html>
<body>
<form id="CookieForm" method="post" runat="server">
name: <asp:textbox id=name runat="server"/><br />
address: <asp:textbox id=address runat="server"/><br />
Telephone: <asp:textbox id=phone runat="server"/><br />
<asp:button id=MyButton runat="server" text = "Submit" OnClick="Click"/>
</form>
</body>
</html>
Code for retrieving cookie:
<%@ Page Language="VB" %>
<script language="vb" runat="server">
Sub Page_Load(Source As Object, E as EventArgs)
Response.Cache.SetExpires(DateTime.Now)
Namelbl.text= Request.Cookies("Name").Value
Addresslbl.text= Request.Cookies("Address").Value
Phonelbl.text= Request.Cookies("Phone").Value
End Sub
</script>
<html>
<body>
Your name is: <asp:label id="namelbl" runat="server" /><br />
Your address is: <asp:label id="addresslbl" runat="server" /><br />
Your Telephone number is: <asp:label id="Phonelbl" runat="server" />
</body>
</html>
|
 |
| Chapter |
Question Number |
Question |
Answer |
 |
| 11 |
1 |
Describe a situation in which you would use each of the following and state why that choice is the best:
- arrays
- arraylists
- hashes
- sorted lists
|
Arrays are used when you want a quick and easy to build list that you will not need to resize or add items into the middle of the list.
ArrayLists are used when you need an automatically resizable list that also allows items to be inserted into or removed from the middle, and performance is not an issue.
Hashes are used when you need to do fast lookups from one piece of data to another. The data is not sorted.
Sorted lists are most useful when we have to sort a list of key/value pairs for which the ordering of the key is what matters, rather than the order of the values. For example, we might use a sorted list to hold entries in a dictionary.
|
 |
| 11 |
2 |
Create an array with the following items:
Dog, Cat, Elephant, Lion, Frog.
Display it in a dropdown list alongside another dropdown list that gives options on how the array is sorted.
|
<%@ Page language="vb" %>
<script runat="server" language="vb">
Dim AnimalArray(4) As String
Sub Page_Load()
AnimalArray(0) = "Dog"
AnimalArray(1) = "Cat"
AnimalArray(2) = "Elephant"
AnimalArray(3) = "Lion"
AnimalArray(4) = "Frog"
MyDropDownList.DataSource = AnimalArray
MyDropDownList.DataBind()
End sub
Sub Alphabet(sender As System.Object, e As System.EventArgs)
if Request.Form("sort") = "alphabetical" then
Array.Sort(AnimalArray)
else Array.Reverse(AnimalArray)
end if
MyDropDownList.DataBind()
End Sub
</script>
<html>
<form runat="server" >
<asp:dropdownlist runat="server" id="sort">
<asp:listitem>alphabetical</asp:listitem>
<asp:listitem>reverse</asp:listitem>
</asp:dropdownlist>
<asp:button text="submit" runat="server" OnClick="Alphabet" />
<asp:dropdownlist id="MyDropDownList" runat="server" /><br /><br />
<hr />
</form>
</html>
|
 |
| 11 |
3 |
Bind a dropdown list to an array containing five colors, then create a submit button that displays a line of etxt in the selected color when clicked.
|
<%@Page language="vb" %>
<script runat="server" language="vb">
Sub Page_Load(Source As Object, E as EventArgs)
if not Page.IsPostback
Dim StrColor as string
Dim colorArray(4) as string
colorArray(0) = "mediumorchid"
colorArray(1) = "firebrick"
colorArray(2) = "cornflowerblue"
colorArray(3) = "sienna"
colorArray(4) = "deepskyblue"
MyDropDownList.DataSource = ColorArray
MyDropDownList.DataBind()
End if
End Sub
Sub ChangeColor(Sender As Object, E As EventArgs)
Dim color as string
color = MyDropDownList.SelectedItem.Value
label.text = "<font color=" & color & ">This is your color</font>"
End Sub
</script>
<html>
<form runat="server" >
<asp:dropdownlist id="MyDropDownList" runat="server" />
<asp:Button id="change" text="pick a color" runat="server" OnClick="ChangeColor" />
</form>
<asp:label id="label" runat="server" />
</html>
|
 |
| 11 |
4 |
Using a hashtable, display a list of user names in a dropdown list with a submit button that displays the corresponding user ID when pressed. On the same page add two textboxes in which a user can enter new user names and IDs into the hashtable.
The newly created user name should appear in the dropdown box, and the corresponding user ID should be displayed when the submit button is clicked.
|
<%@Page language="vb" debug="true" %>
<script runat="server" language="vb">
Dim Users as new Hashtable
Dim Item As DictionaryEntry
Sub Page_Load(Source As Object, E as EventArgs)
Users("RedmanJ") = "Redman Jones"
Users("PaintM") = "Painter Mo"
Users("MirrorD") = "Mirror Dede"
users("BabaF") = "Baba Farooq"
If Not Page.IsPostback Then
For Each Item In Users
Dim newListItem As new ListItem()
newListItem.Text = Item.Value
newListItem.Value = Item.Key
myDropDownList.Items.Add(newListItem)
Next
End If
End Sub
Sub Add(Sender As Object, E as EventArgs)
users(userID.text) = Name.text
Dim newListItem As new ListItem()
newListItem.Text = name.text
newListItem.Value = userID.text
myDropDownList.Items.Add(newListItem)
End Sub
Sub Click(Source As Object, E as EventArgs)
myLabel.Text = myDropDownList.SelectedItem.Value
End Sub
</script>
<html>
<form runat="server">
<asp:dropdownlist id="myDropDownList" runat="server" />
<asp:button id="myButton" runat="server" text="Get user ID" Onclick="Click" />
<br /><br /><br /><br /><br /><br />
Add user: <asp:textbox id="name" runat="server" />
ID: <asp:textbox id="userID" runat="server" />
<asp:button id="addusr" runat="server" text="Add User" Onclick="Add" /><br /><br />
<hr />
<asp:Label id="myLabel" runat="server" text="" />
</form>
</html>
|
 |
| 11 |
5 |
Create an ASPX page that takes value entered via a textbox and searches for it in this sorted list:
mySortedList("armadillo")="any of a family ... small bony plates"
mySortedList("amaryllis")="an autumn-flowering ... Hippeastrum or Sprekelia)"
mySortedList("zebra")="any of several fleet ... white or buff"
mySortedList("artichoke")="a tall composite herb ... cooked as a vegetable"
mySortedList("aardvark")="a large burrowing ... termites and ants"
The results of the search should be displayed on the page.
|
<%@Page language="vb" debug="true" %>
<script runat="server" language="vb">
Dim mySortedList as new SortedList
Dim Item As DictionaryEntry
Sub Page_Load(Source As Object, E as EventArgs)
mySortedList("armadillo")="any of a family ... small bony plates"
mySortedList("amaryllis")="an autumn-flowering ... Hippeastrum or Sprekelia)"
mySortedList("zebra")="any of several fleet ... white or buff"
mySortedList("artichoke")="a tall composite herb ... cooked as a vegetable"
mySortedList("aardvark")="a large burrowing ... termites and ants"
End Sub
Sub search(Source As Object, E as EventArgs)
For Each item in mySortedList
if input.text = Item.key
result.text = "<b>" & item.key & "</b>: " & item.value
end if
next
end sub
</script>
<html>
<asp:label id="MyLabel" runat="server" />
<form runat="server">
<b>search for: </b><asp:textbox id="input" runat="server" />
<asp:Button id="enter" onClick="search" runat="server" text="search!"/>
</form>
<asp:label id="result" runat="server" />
</html>
|
 |
| Chapter |
Question Number |
Question |
Answer |
 |
| 12 |
1 |
Explain how the process of normalization helps us optimize databases.
|
Normalization is the process by which data is broken out of a larger table and placed into smaller tables for the purpose of eliminating redundancy, saving space, increasing performance and increasing data integrity.
|
 |
| 12 |
2 |
Rewrite this section of code using the relevant connection object and Namespace so that it can be used to connect to an SQL Server database, and modify the connection string accordingly:
Dim strConnection as String = "Provider=Microsoft.Jet.OLEDB.4.0;"
strConnection += "Data Source=C:\begASPNET\ch12\Northwind.mdb"
Dim objConnection as New OledbConnection(strConnection)
|
<%@ Import namespace="System.Data.SqlClient" %>
Dim strConnection as String = "server=your_server_name;database=Northwind;uid=sa;password=;"
Dim objConnection as New OledbConnection(strConnection)
|
 |
|