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.

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.

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.

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.

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:

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:

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

QuestionNumber

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.

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

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.

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

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.

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.

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

QuestionNumber

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.

(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.

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.

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>

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.

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

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:

(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.

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:

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.

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:

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

QuestionNumber

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

QuestionNumber

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