Wrox Home  
Search

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 = "UK&#pound;"
        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)

12 3

Write an ASP.NET page that uses the connection object to connect to the Northwind database and displays the following information using a datagrid.

(a) The address, city, contact name and telephone number of all suppliers

(b) The names and addresses of all the German customers

(a)

<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Data.OleDb" %>

<script language="vb" runat="server">
  Sub Page_Load()
    dim strConnection as string = "Provider=Microsoft.Jet.OLEDB.4.0;"
      strConnection += "Data source=C:\BegASPNET\ch12\northwind.mdb;"
    dim strSQL as string = "Select Address, City, Phone from suppliers;"

    dim objConnection as new OLEDBConnection(strConnection)
    dim objCommand as new OLEDBCommand(strSQL,objConnection)

    objConnection.Open()
    dgEmps.DataSource = objCommand.ExecuteReader(CommandBehavior.CloseConnection)
    dgEmps.DataBind()
  end sub
</script>

<html>
  <body>
    <h2>Using ExecuteReader to create a table</h2>
    <asp:datagrid id="dgEmps" runat="server"  />
  </body>
</html>

(b)

<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Data.OleDb" %>

<script language="vb" runat="server">
  Sub Page_Load()
    dim strConnection as string = "Provider=Microsoft.Jet.OLEDB.4.0;"
      strConnection += "Data source=C:\BegASPNET\ch12\northwind.mdb;"
    dim strSQL as string = "Select ContactName, address from customers where country = 'germany';"

    dim objConnection as new OLEDBConnection(strConnection)
    dim objCommand as new OLEDBCommand(strSQL,objConnection)

    objConnection.Open()
    dgEmps.DataSource = ObjCommand.ExecuteReader(CommandBehavior.CloseConnection)
    dgEmps.DataBind()
  end sub
</script>

<html>
  <body>
    <h2>Using ExecuteReader to create a table</h2>
    <asp:datagrid id="dgEmps" runat="server" />
  </body>
</html>

12 4

(a) Connect to Northwind and fill a DataSet with the Company Name and Contact Name fields of the suppliers table, create a DataView of the suppliers table and bind it to an <asp:datagrid> server control to display the results.

(b) Repeat the above exercise, but this time bind the DataGrid to the DataSet instead.

(c) Now fill the same DataSet with the first names and last names of the Employees table as well and create another <asp:datagrid> to display the results so that both tables appear on one page.

(a)

<%@ import Namespace="System.Data" %>
<%@ import Namespace="System.Data.Oledb" %>

<script language="vb" runat="server">
  Sub Page_Load()
    Dim strConnection as String = "Provider=Microsoft.Jet.OLEDB.4.0;"
      strConnection += "Data Source=C:\begASPNET\ch12\Northwind.mdb"
      
    Dim strSQL as string = "SELECT companyname, contactname FROM suppliers;"
    Dim objDataSet as new DataSet()

    Dim objConnection as new OledbConnection(strConnection)
    Dim objAdapter as new OledbDataAdapter(strSQL, objConnection)

    objAdapter.Fill(objDataSet, "suppliers")

    Dim objDataView as New DataView(objDataSet.tables("suppliers"))

    dgsuppliers.DataSource=objDataView
    dgsuppliers.DataBind()
  end Sub
</script>

<html>
  <body>
    <asp:datagrid id="dgsuppliers" runat="server" /><br />
  </body>
</html>

(b)

<%@ import Namespace="System.Data" %>
<%@ import Namespace="System.Data.Oledb" %>

<script language="vb" runat="server">
  Sub Page_Load()
    Dim strConnection as String = "Provider=Microsoft.Jet.OLEDB.4.0;"
      strConnection += "Data Source=C:\begASPNET\ch12\Northwind.mdb"
      
    Dim strSQL as string = "SELECT companyname, contactname FROM suppliers;"
    Dim objDataSet as new DataSet()

    Dim objConnection as new OledbConnection(strConnection)
    Dim objAdapter as new OledbDataAdapter(strSQL, objConnection)

    objAdapter.Fill(objDataSet, "suppliers")

    dgsuppliers.DataSource=objDataSet
    dgsuppliers.DataBind()
      
  end Sub
</script>

<html>
  <body>
    <asp:datagrid id="dgsuppliers" runat="server" /><br />  
  </body>
</html>

(c)

<%@ import Namespace="System.Data" %>
<%@ import Namespace="System.Data.Oledb" %>

<script language="vb" runat="server">
  Sub Page_Load()
    Dim strConnection as String = "Provider=Microsoft.Jet.OLEDB.4.0;"
      strConnection += "Data Source=C:\begASPNET\ch12\Northwind.mdb"
    
    '--------first table  
    Dim strSQL as string = "SELECT companyname, contactname FROM suppliers;"
    Dim objDataSet as new DataSet()

    Dim objConnection as new OledbConnection(strConnection)
    Dim objAdapter as new OledbDataAdapter(strSQL, objConnection)

    objAdapter.Fill(objDataSet, "suppliers")

    '------second table
    strSQL = "SELECT FirstName, LastName from Employees;"
    objAdapter = New OleDbDataAdapter(StrSQL, objConnection)
    objAdapter.Fill(objDataSet, "employees")
    
    '---------binding both tables to DataGrids    
    dgemployees.DataSource=objDataSet.Tables("employees")
    dgemployees.DataBind()
    
    dgsuppliers.DataSource=objDataSet.Tables("suppliers")
    dgsuppliers.DataBind()
  
  end Sub
</script>

<html>
  <body>
    <asp:datagrid id="dgsuppliers" runat="server" /><br />
    <asp:datagrid id="dgemployees" runat="server" /><br />
  </body>
</html>

12 5

Connect to a SQL Server database using the SqlConnection object including a Try ... Catch block that traps login failures and incorrect connection strings.

<%@Page Language="VB"%>

<%@Import Namespace="System.Data" %>
<%@Import Namespace="System.Data.SqlClient" %>

<html>
<head><title> WROX Beginning ASP.NET - Data - Data Table <br/>
Using Microsoft SQL Objects</title></head>

<body>
<h2>Display of Data in a Table (Grid) Using SQL Objects</h2>
Northwind Employees:
<asp:datagrid   id="dgrEmployees" runat="server" />

<script language="vb" runat="server">
Sub Page_Load()

Dim strSQL as string = "SELECT FirstName,LastName FROM Employees;"
Dim strConnection as String ="server=wrox-3y0k9ywf5s\netsdk;database=Northwind;uid=sa;password=;"

Dim objDataSet As New DataSet()
Dim objConnection As New SqlConnection(strConnection)

Try
  Dim objDataAdapter As New SqlDataAdapter(strSQL, objConnection)
  
  objDataAdapter.Fill(objDataSet, "Employees")
  
  Dim objDataView As New DataView(objDataSet.Tables("Employees"))

  dgrEmployees.DataSource = objDataView
  dgrEmployees.DataBind()  

Catch objError as SQLexception
  If Left(objError.Message,21)="Login failed for user" Then
    divErrorReport.InnerHTML = "Problem with Log-in"
  ElseIf Left(objError.Message,19)="Could not find file" Then
    divErrorReport.InnerHTML = "We could not find the MDB file that you asked for"
  Else
    divErrorReport.InnerHTML =  "<br />message - " & objError.Message
    divErrorReport.InnerHTML += "<br />source - " & objError.Source
  End If
End Try

End Sub
</script>

<h4>Writing data from the connection
    <asp:label id="data_src" runat="server"/>
    to the DataGrid control with error checking.</h4>
  <div id="divErrorReport" runat="server"> </div>
  <asp:datagrid id="dgNameList" runat="server" /><br />
</body>
</html>



Chapter Question
Number
Question Answer
13 1

What do we mean by 'disconnected data' and why is it so important?

Once data is extracted from a database, ADO.NET disconnects from the database and works with the data independently. This data is called disconnected data. The reason this is done so that the limited database connections are freed up as soon as possible, increasing performance. This is particularly important on the web where thousands of users could be trying to use a database concurrently.

Another reason for using disconnected data is that it suits the ASP.NET application architecture and allows us to build better, more robust applications in less time.

13 2

Load a DataSet with the Shippers table from Northwind and add the following data into the DataSet using a DataTable:

  • Company Name: FastShippers
  • Phone (503) 555-9384

<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Data.OleDb" %>

<script language="VB" runat="server">
  Sub Page_Load(Sender As Object, E As EventArgs)
    Dim strConnection As String
    Dim strSQL        As String
    Dim objDataSet    As New DataSet()
    Dim objConnection As OleDbConnection
    Dim objAdapter    As OleDbDataAdapter

    strConnection = "Provider=Microsoft.Jet.OLEDB.4.0; " & _
                    "Data Source=C:\BegASPNET\ch13\Northwind.mdb"
    
    strSQL = "SELECT CompanyName, Phone FROM Shippers;"    
    objConnection = New OledbConnection(strConnection)
    objAdapter = New OledbDataAdapter(strSQL, objConnection)

    objAdapter.Fill(objDataSet, "Suppliers")

    Dim objTable  As DataTable
    Dim objNewRow As DataRow
  
    objTable = objDataSet.Tables("Suppliers")
    objNewRow = objTable.NewRow()
    objNewRow.Item("CompanyName") = "fastshippers"
    objNewRow.Item("phone") = "(503) 555-9384"
    objTable.Rows.Add(objNewRow)
    
    ' bind the data grid to the new data
    dgSuppliers.DataSource = objTable.DefaultView
    dgSuppliers.DataBind()
  End Sub
</script>

<html>
  <body>
    <asp:DataGrid id="dgSuppliers" runat="server" /></td>
  </body>
</html>

13 3

Using the CommandBuilder object, update the Northwind Shippers table with the new information held in the DataSet.

<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Data.OleDb" %>

<script language="VB" runat="server">
  Sub Page_Load(Sender As Object, E As EventArgs)
    Dim strConnection As String
    Dim strSQL        As String
    Dim objDataSet    As New DataSet()
    Dim objConnection As OleDbConnection
    Dim objAdapter    As OleDbDataAdapter

    strConnection = "Provider=Microsoft.Jet.OLEDB.4.0; " & _
                    "Data Source=C:\BegASPNET\ch13\Northwind.mdb"
    
    strSQL = "SELECT ShipperID, CompanyName, Phone FROM Shippers;"
    objConnection = New OledbConnection(strConnection)    
    objAdapter = New OledbDataAdapter(strSQL, objConnection)

    objAdapter.Fill(objDataSet, "Suppliers")

    Dim objTable  As DataTable
    Dim objNewRow As DataRow
  
    objTable = objDataSet.Tables("Suppliers")
    objNewRow = objTable.NewRow()
    objNewRow.Item("CompanyName") = "fastshippers"
    objNewRow.Item("phone") = "(503) 555-9384"
    objTable.Rows.Add(objNewRow)
          
    Dim objBuilder    As OleDbCommandBuilder

    objBuilder = New OleDbCommandBuilder(objAdapter)
    objAdapter.InsertCommand = objBuilder.GetInsertCommand()
    objAdapter.Update(objDataSet, "Suppliers")
    
    '---get updated data from database and load datagrid with it
    
    strSQL = "SELECT ShipperID, CompanyName, Phone FROM Shippers;"
    objConnection.Open()
    Dim objCmd As New OleDbCommand(strSQL, objConnection)
    dgUpd.DataSource = objCmd.ExecuteReader(CommandBehavior.CloseConnection)
    dgUpd.DataBind()  
  End Sub
</script>

<html>
  <body>
    <asp:DataGrid id="dgUpd" runat="server"/>
  </body>
</html>

13 4

Using direct SQL commands, change the phone number of FastShippers to (503) 555-0000 and display the updated table in a DataGrid.

<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Data.OleDb" %>

<script language="VB" runat="server">
  Sub Page_Load(Sender As Object, E As EventArgs)
    Dim objConnection As OleDbConnection
    Dim objCmd        As OleDbCommand
    Dim strConnection As String
    Dim strSQL        As String
    
    strConnection = "Provider=Microsoft.Jet.OLEDB.4.0;" & _
                    "Data Source=C:\BegASPNET\ch13\Northwind.mdb"
  
    ' Create and open the connection object
    objConnection = New OleDbConnection(strConnection)
    objConnection.Open()
    
    ' set the SQL string
    strSQL = "Update `Shippers` SET `phone` = '(503) 555-0000' Where (`CompanyName`='fastshippers')"

    ' Create the Command and set its properties
    objCmd = New OleDbCommand(strSQL, objConnection)
    
    ' execute the command
    objCmd.ExecuteNonQuery()
  
    ' display updated data
    strSQL = "SELECT ShipperID, CompanyName, Phone FROM Shippers;"
    
    objCmd = New OleDbCommand(strSQL, objConnection)
    dgUpd.DataSource = objCmd.ExecuteReader(CommandBehavior.CloseConnection)
    dgUpd.DataBind()
  End Sub
</script>

<html>
  <body>
    <h2>Using SQL directly</h2>
    <asp:DataGrid id="dgUpd" runat="server"/>
  </body>
</html>

13 5

a. Generate a dataset from this XML file, bind it to a DataGrid to display it:

<?xml version="1.0" standalone="yes" ?>
<NewDataSet>
  <books>
    <BookName>Beginning ASP.NET programming</BookName>
    <ISBN>1861005040</ISBN>
  </books>
  <books>
    <BookName>Professional ASP.NET programming</BookName>
    <ISBN>1861004885</ISBN>
  </books>
  <books>
    <BookName>Beginning VB.NET programming</BookName>
    <ISBN>1861004966</ISBN>
  </books>
</NewDataSet>

b. Add a new book to this DataSet, Beginning C# programming, ISBN 1861004982.

c. Delete the entry for Beginning ASP.NET programming and display the DataSet in a DataGrid.

a.

<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Data.OleDb" %>

<script language="VB" runat="server">
  Sub Page_Load(Sender As Object, E As EventArgs)
    Dim objDataSet    As New DataSet()

    objDataSet.ReadXml(Server.MapPath("books.xml"))
    
    dgBooks.DataSource = objDataSet.Tables(0).DefaultView
    dgBooks.DataBind()
  End Sub
</script>

<html>
  <body>
  <asp:DataGrid id="dgbooks" runat="server" />
  </body>
</html>

b.

<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Data.OleDb" %>

<script language="VB" runat="server">
  Sub Page_Load(Sender As Object, E As EventArgs)
    Dim objDataSet    As New DataSet()

    objDataSet.ReadXml(Server.MapPath("books.xml"))
    
    dgBooks.DataSource = objDataSet.Tables(0).DefaultView
    dgBooks.DataBind()
    
    Dim objTable  As DataTable
    Dim objNewRow As DataRow
  
    objTable = objDataSet.Tables("books")
    objNewRow = objTable.NewRow()
    objNewRow.Item("bookName") = "Beginning C# programming"
    objNewRow.Item("ISBN") = "1-861004-98-2"
    objTable.Rows.Add(objNewRow)
    
    objDataSet.WriteXml(Server.MapPath("books.xml"))

    dgBooks2.DataSource = objDataSet.Tables(0).DefaultView
    dgBooks2.DataBind()
  End Sub
</script>

<html>
  <body>
  <asp:DataGrid id="dgbooks" runat="server" />
  <asp:DataGrid id="dgbooks2" runat="server" />
  </body>
</html>

c.

<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Data.OleDb" %>

<script language="VB" runat="server">
  Sub Page_Load(Sender As Object, E As EventArgs)
    Dim objDataSet    As New DataSet()

    objDataSet.ReadXml(Server.MapPath("books.xml"))
    
    dgBooks.DataSource = objDataSet.Tables(0).DefaultView
    dgBooks.DataBind()
    '--add new row
    Dim objTable  As DataTable
    Dim objNewRow As DataRow
  
    objTable = objDataSet.Tables("books")
    objNewRow = objTable.NewRow()
    objNewRow.Item("bookName") = "beginning C# programming"
    objNewRow.Item("ISBN") = "1-861004-98-2"
    objTable.Rows.Add(objNewRow)
    
    objDataSet.WriteXml(Server.MapPath("books.xml"))

    dgBooks2.DataSource = objDataSet.Tables(0).DefaultView
    dgBooks2.DataBind()
    '--delete first row
    objTable.Rows(0).Delete()
    dgBooks3.DataSource = objDataSet.Tables(0).DefaultView
    dgBooks3.DataBind()
  End Sub
</script>

<html>
  <body>
  <asp:DataGrid id="dgbooks" runat="server" /><br />
  <asp:DataGrid id="dgbooks2" runat="server" /><br />
  <asp:DataGrid id="dgbooks3" runat="server" /><br />
  </body>
</html>



Chapter Question
Number
Question Answer
15 1

Explain what a User Control is, and under what circumstances you'd use User Controls in your pages.

A User Control is a section of ASP.NET code that can be reused as many times as necessary in a web site. It contains standard ASP.NET code which could have resided in each of the pages that required that particular set of functionality, but to promote good coding practice and the reuse of code, while making it easier to debug and maintain your code, you can separate this code out into a User Control.

15 2

Think of a scenario where using a User Control is beneficial, and explain what kind of controls you might have in that situation. Explain which parts of your code could be separated out into a Code Behind file, and why you would do this.

A User Control can be used in any situation where repetition of identical code blocks is to be avoided by lumping the repeated code into a User Control. Examples of where this is useful are things like headers and footers on a web site, or menus that are at the side of every page, but we can also use these controls for things like login controls.

15 3

Create a User Control that produces a user login control. You'll need to ask the users for a User ID, which will be an email address, and they'll need to enter their password.

Here's some code that can be used to create our User Control:

<%@ Control inherits="UserLoginClass" src="Exercise.vb" ClassName="UserLogin" %>

Account Login  <br /><br />
Email: <br />
<asp:TextBox id="email" runat="server" /> <br />
Password: <br />
<asp:TextBox id="password" textmode="password" runat="server" /> <br />
<asp:button text="Log In" OnClick="LoginBtn_Click" runat="server" /> <br /><br />
<asp:label id="Message" runat="server" /> <br />

Our code behind file for this page is where we could do some work with the information entered:

Imports System
Imports System
Imports System.Web.UI
Imports System.Web.UI.WebControls

Public Class UserLoginClass : Inherits UserControl

  Public email as textbox
  Public password as textbox
  Public message as label

  Public Sub LoginBtn_Click(Sender As Object, E As EventArgs)

    Message.Text = "Hello, your email is " & email.text & _
      "<br />Your password is " & password.text

  End Sub
End Class

Of course, this is all very basic, and you would be very unlikely to actually display this sort of information. You would be more likely to do a quick look through a database using the email address to search for a specific user's records, then display a welcome message with their name, rather than their email address. The database could also store previous purchases, and other information, so this process is just the beginning of creating a personalized user experience.

15 4

Add some very basic validation to the control to check that they've entered a value in the email address box, and to check that the password field has a value in it too, also checking that the email is a valid email, and the password is exactly eight characters, no spaces. Next, create a simple web form that displays this control on the page. Test your code to see if the validation is being performed correctly.

Validation controls are a very effective way to perform complex validation with ease. We can add some validation to our user control fairly simply:

<%@ Control inherits="UserLoginClass" src="Exercise.vb" ClassName="UserLogin" %>

Account Login  <br /><br />

Email: <br />

<asp:TextBox id="email" runat="server" />

  <asp:RequiredFieldValidator id="requiredEmail" runat="Server"
     ControlToValidate="email"
     ErrorMessage="* Please enter your email address"
     Display="Dynamic">
  *
  </asp:RequiredFieldValidator>

  <asp:RegularExpressionValidator id="regexpEmail" runat="server"
       ControlToValidate="email"
       ValidationExpression=".+@.+\..+"
       ErrorMessage="* Email address invalid - please re-enter!"
       Display="Dynamic">
  *
  </asp:RegularExpressionValidator>

<br />Password: <br />
<asp:TextBox id="password" textmode="password" runat="server" />

  <asp:RequiredFieldValidator id="requiredPassword" runat="Server"
       ControlToValidate="password"
       ErrorMessage="* Please enter your password"
       Display="Dynamic">
  *
  </asp:RequiredFieldValidator>

  <asp:RegularExpressionValidator id="regexpPassword" runat="server"
       ControlToValidate="password"
       ValidationExpression="\w{8,8}"
       ErrorMessage="* Password must be 8 characters, no spaces"
       Display="Dynamic">
  *
  </asp:RegularExpressionValidator>

<br /><asp:button text="Log In" OnClick="LoginBtn_Click" runat="server" />
<br /><br />

<asp:label id="Message" runat="server" /> <br />

<asp:ValidationSummary id="valSummary" runat="server"
     HeaderText="<b>The following errors were found:</b>"
     ShowSummary="true"
     DisplayMode="List" />

Our email address has two validators – the first of which checks to see if there is a value entered into the box, and the second contains a regular expression to check to see if the data entered into the box is a valid format for an email address (in our case, we check to see that it's something@something.something. The password control also has two validators – the first checks that the password has been entered, and the second checks that it is the correct length and does not include spaces.

15 5

As an additional exercise, you may want to write some code that connects to a database, and retrieves the user's details, provided the email address and password that are entered match up with the records in the database. This would be useful for retrieving information on a customer's previous orders, etc.

This exercise is open-ended and therefore no solution is given.



Chapter Question
Number
Question Answer
16 1

Explain the benefits of using Components, and what sorts of things we should encapsulate in a .NET assembly. When should we use compiled .dlls instead of Code Behind files and User Controls?

Encapsulating commonly-used functionality into components is a core concept for scalable programming. Re-using code is not only a time-saver, but it helps to ensure consistency in our applications. Compiling this reusable code into a .dll makes it very easy to re-distribute our functionality in a neat and tidy package.

Code Behind files are more of a logistical separation of code from presentation of HTML to make it easier for two types of developer to work with the code. A web designer who is more interested in the aesthetics of a page can be left to concentrate on the display elements of a site, whereas a developer who is interested in programming logic can make use of the code behind file to amend the code to produce a programmatically different result.

A User Control is more commonly used for repeated elements in a site that are only really going to be used in that site itself, and are less likely to be re-used in multiple sites. If, however, we're talking about elements that would be useful to many different sites, for example, a custom control that would obtain the Amazon ranking for a book and display it wherever you wanted to, you could compile the control into a custom server control, and distribute it to friends, family, or even sell it to other developers who might want to use this code to save them time.

16 2

What is business logic? Give an example of the sort of code that can be described as business logic, and talk about how this code can be reused elsewhere.

Business Logic is the term we apply to code that is used for retrieving, storing, or manipulating data. For example, you could have a database that held information about your favorite albums. You could write a method that connects to that database, another method that retrieves the list of albums by a particular artist, another method that is used to retrieve all albums of a certain genre, and other methods that are used to add, edit, or remove an album from a database. You could then use this functionality for personal use to manage your collection, or you could extend it to incorporate reviews of each album or artist on a review web site.

16 3

Create a new component that converts from imperial units to metric and back again. You'll need four methods: Celsius to Fahrenheit temperatures, Fahrenheit to Celsius, Kilometers to Miles, and Miles to Kilometers. You'll need the following data:

  • Fahrenheit temperature = Celsius temperature * (9/5) + 32
  • Celsius temperature = (Fahrenheit temperature - 32) * (5/9)
  • 1 Mile = 1.6039 Kilometers (to 4 decimal places)
  • 1 Kilometer = 0.6214 Miles (to 4 decimal places)
 
16 4

Create an ASP.NET page that uses this functionality. One example might be a page about holiday destinations. Users in other countries might want to know distances in metric instead of imperial, or temperatures in Celsius, rather than Fahrenheit.

 
16 5

Additionally, you might want to access this functionality from a completely different type of site, for example, one that has some scientific purpose that requires unit conversion, a route planner that will provide results in both miles and kilometers, or a weather site that needs to provide today's temperatures in both Celsius and Fahrenheit. A completely different situation would be a cookery site that displayed instructions for cooking a meal in an oven set to either Celsius or Fahrenheit temperatures.

 


Chapter Question
Number
Question Answer
18 1

a. Explain the role of the Simple Object Access Protocol (SOAP) in web services.

b. What is the purpose of the WSDL?

c. How would you locate a web service that provides the functions you require?

a. Simple Object Access Protocol (SOAP) is the protocol with which functions are called remotely in Web Services.

b. The WSDL is an XML file that specifies the parameters that are used in the Web Services. By means of the WSDL file, consumers know what parameters to send to the Web Service and what values they will receive.

c. To locate a Web Service the UDDI service is used. Businesses register their Web Services on the UDDI database which then be searched for a service that may suit our needs.

18 2

Create a Web Service with a class name of circles that calculates the area of a circle, the circumference of a circle and the volume of a sphere. (Area = (Pi) r²; Circumference = 2(Pi)r; Volume of a sphere = 4/3 (Pi)r³)

<%@ WebService Language="VB" Class="Circles"%>

Imports System.Web.Services

Public Class Circles

  <WebMethod()> _
  Public Function Areaofcircle(radius As Decimal) As Decimal
    Return radius*radius*3.142
  End Function

  <WebMethod()> _
  Public Function CircumferenceofCircle(radius As Decimal) As Decimal
    Return 2 * 3.142 * radius
  End Function

  <WebMethod()> _
  Public Function VolumeofSphere(radius As Decimal) As Decimal
    Return (4 / 3) * 3.142 * radius * radius * radius
  End Function

End Class

18 3

Create a Web Service that connects to the Northwind database and returns Employee's addresses based on their last names.

<%@ WebService Language="vb" Class="Addresses" %>
Imports System.Web.Services
Imports System.Data
Imports System.Data.OleDb
Public Class Addresses
    Inherits System.Web.Services.WebService

<WebMethod()> _
Public Function NorthwindAddresses(ByVal strLastName As String) As String
  Return GetAddress(strLastName)
End Function

Private Function GetAddress(ByVal strLastName As String) As String
  Dim objDataReader As OleDbDataReader
  Dim objConnection As OleDbConnection
  Dim objCommand As OleDbCommand
  Dim strConn As String = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\BegASPNET\ch18\Northwind.mdb;"
  Dim strSQL As String = "SELECT Address FROM Employees WHERE lastName = '" & strlastName & "'"
  Dim strAddress As String

  objConnection = New OleDbConnection(strConn)
  objCommand = New OleDbCommand(strSQL, objConnection)
  objConnection.Open()

  objDataReader = objCommand.ExecuteReader(CommandBehavior.CloseConnection)

  If objDataReader.Read() Then
    strAddress = objDataReader(0)
  Else
    strAddress = "Address not found in the database"
  End If
  objDataReader.Close()

  Return strAddress
End Function

End Class

18 4

Create an ASP.NET page containing a dropdown listbox in which a user can select names of Northwind employees to return their addresses.

<%@ Page Language="vb" Debug="true"%>
<%@ Import namespace="AddressService" %>

<script language="vb" runat="server">
Private Sub RetrieveAddress(ByVal sender As System.Object, ByVal e As System.EventArgs)
  Dim adr As New AddressService.Addresses()
  lblAddress.Text = adr.NorthwindAddresses(Request.Form("list"))
End Sub
</script>

<html>
  <body>
    <form runat="server">
      <asp:dropdownlist id="list" runat="server">
      <asp:listitem>Davolio</asp:listitem>
      <asp:listitem>Fuller</asp:listitem>
      <asp:listitem>Leverling</asp:listitem>
      <asp:listitem>Peacock</asp:listitem>
      <asp:listitem>Buchanan</asp:listitem>
      <asp:listitem>Suyama</asp:listitem>
      <asp:listitem>King</asp:listitem>
      <asp:listitem>Callahan</asp:listitem>
      <asp:listitem>Dodsworth</asp:listitem>
      </asp:dropdownlist>
      <asp:Button id="Button1" runat="server" Text="Submit" OnClick="RetrieveAddress"></asp:Button><br />
      <asp:Label id="lblAddress" runat="server" />
    </form>
  </body>
</html>

18 5

Secure the Northwind employee Addresses Web Service so that no unauthorized users have access to it.

Imports System.Data
Imports System.Data.OleDb

Public Class Addresses
    Inherits System.Web.Services.WebService

<WebMethod()> _
Public Function NorthwindAddresses(ByVal strLastName As String, ByVal strUsername As String, ByVal strPassword As String) As String
  Dim objSecurityDR As OleDbDataReader
  Dim objSecurityConn As OleDbConnection
  Dim objSecurityCmd As OleDbCommand

  Dim strConn As String = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source="
      strConn += Server.MapPath("Security.mdb") & ";"
  Dim strSQL As String = "select Username from Users where username = '"
      strSQL += strUsername & "' and password = '" & strPassword & "'"

  objSecurityConn = New OleDbConnection(strConn)
  objSecurityCmd = New OleDbCommand(strSQL, objSecurityConn)
  objSecurityConn.Open()

  objSecurityDR = objSecurityCmd.ExecuteReader(CommandBehavior.CloseConnection)
  If objSecurityDR.Read() Then
    objSecurityDR.Close()
    Return GetAddress(strLastName)
  Else
    objSecurityDR.Close()
    Return "Login to Northwind Employees Directory failed."
  End If
End Function

Private Function GetAddress(ByVal strLastName As String) As String
  Dim objDataReader As OleDbDataReader
  Dim objConnection As OleDbConnection
  Dim objCommand As OleDbCommand
  Dim strConn As String = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\BegASPNET\ch18\Northwind.mdb;"
  Dim strSQL As String = "SELECT Address FROM Employees WHERE lastName = '" & strlastName & "'"
  Dim strAddress As String

  objConnection = New OleDbConnection(strConn)
  objCommand = New OleDbCommand(strSQL, objConnection)
  objConnection.Open()

  objDataReader = _
   objCommand.ExecuteReader(CommandBehavior.CloseConnection)

  If objDataReader.Read() Then
    strAddress = objDataReader(0)
  Else
    strAddress = "Address not found in the database"
  End If
  objDataReader.Close()

  Return strAddress
End Function

End Class