
Beginning Visual Basic 2005 (2006)
.pdf
Appendix D
‘Dispose of the object objCar.Dispose() objCar = Nothing
‘Wait for input from the user Console.ReadLine()
Exercise 2
This exercise required you to encapsulate the declaration and usage of the SportsCar class in a Using . . .
End Using statement. Keeping in mind that the Using . . . End Using statement automatically handles disposal of objects that implement the IDisposable interface; the code can be implemented as highlighted here.
Sub Main()
Using objCar As New SportsCar
‘Set the horsepower and weight(kg) objCar.HorsePower = 240 objCar.Weight = 1085
‘Display the details of the car DisplayCarDetails(objCar) DisplaySportsCarDetails(objCar)
End Using
‘Wait for input from the user Console.ReadLine()
End Sub
Chapter 11 Solution
You should have added code similar to this at the end of the Form1_Load event. First you use the Count property of the Items property to ensure that one or more items exist in the list view control before proceeding. Then you select the first item in the list view control by setting the Selected property to True for the first item in the Items collection. Finally, you call the Click event of the list view control, passing it a value of Nothing for the Object and System.EventArgs parameters.
‘If one or more items exist...
If lstFavorites.Items.Count > 1 Then ‘Select the first item
lstFavorites.Items(0).Selected = True lstFavorites_Click(Nothing, Nothing)
End If
Chapter 12 Solution
Modifying the Favorites Viewer project requires two steps. First, you right-click the InternetFavorites project in the Solution Explorer and choose Remove from the context menu. Then you right-click the Favorites Viewer project in the Solution Explorer and choose Add Reference from the context menu. You
756

Solutions
scroll down the list of components in the .NET tab, select InternetFavorites, and then click OK. Then you run your project as normal with no code changes required.
Chapter 13 Solution
You start by adding a Private Boolean variable to hold the value that determines whether a message box is shown. Since this is a Boolean variable, you also provide a default value of True so that when the control is dragged onto a form, the SuppressMsgBox property will have a default value set.
Public Class MyNamespace ‘Private members
Private strApplicationName As String = String.Empty Private blnSuppressMsgBox As Boolean = True
Next, you add a Public property to get and set the private variable blnSuppressMsgBox. This property will be exposed by the MyNamespace control in the Properties Window.
Public Property SuppressMsgBox() As Boolean
Get
Return blnSuppressMsgBox
End Get
Set(ByVal value As Boolean) blnSuppressMsgBox = value
End Set End Property
Now you add code to each of the button to show the message box if the property is not set to True.
Private Sub btnApplicationCopyright_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles btnApplicationCopyright.Click
RaiseEvent ApplicationCopyrightChanged( _
My.Application.Info.Copyright)
If Not blnSuppressMsgBox Then MessageBox.Show(My.Application.Info.Copyright, _
strApplicationName)
End If End Sub
Private Sub btnScreenBounds_Click(ByVal sender As Object, _
ByVal e As System.EventArgs) Handles btnScreenBounds.Click
RaiseEvent ScreenBoundsChanged(My.Computer.Screen.Bounds)
If Not blnSuppressMsgBox Then MessageBox.Show(My.Computer.Screen.Bounds.ToString, _
strApplicationName)
End If End Sub
Private Sub btnScreenWorkingArea_Click(ByVal sender As Object, _
757

Appendix D
ByVal e As System.EventArgs) Handles btnScreenWorkingArea.Click
RaiseEvent ScreenWorkingAreaChanged(My.Computer.Screen.WorkingArea)
If Not blnSuppressMsgBox Then MessageBox.Show(My.Computer.Screen.WorkingArea.ToString, _
strApplicationName)
End If End Sub
Next, you need to rebuild the control so that it can pick up the code changes in order to display the SuppressMsgBox property in the Properties Window. After that, you switch to the Controls project and can select a True/False value for the SuppressMsgBox property in the Properties Window.
Chapter 15 Solutions
Exercise 1
The SQL statements for your EmployeeQuery should look like this:
SELECT Employees.FirstName, Employees.LastName, Employees.Title
FROM Employees
ORDER BY Employees.LastName;
You should have followed most of the steps in the “Binding Data to a DataGridView Control” Try It Out exercise and used the EmployeeQuery above in the Choose Your Database Objects screen of the Data Source Configuration Wizard. Your results should look similar to those shown in Figure D-1.
Figure D-1
Exercise 2
To create this application, you should have followed most of the steps in the “Binding Data to TextBox Controls” Try It Out exercise. Your completed form should look similar to the one shown in Figure D-2, and you should be able to navigate through the records in the database.
758

Solutions
Figure D-2
Chapter 16 Solutions
Exercise 1
To complete this exercise, you were to use a DataGridView object to display the data from the pubs database. First, you should have created a Windows Application and added two references, one to the System.Data namespace and one to the System.XML namespace. Next, you needed to add a datagridview control to your form. That was all you needed to do before adding the code listed here.
Imports System.Data
Imports System.Data.SqlClient Public Class Form1
Dim strConnectionString As String = “server=bnewsome;” & _ “database=pubs;uid=sa;pwd=!p@ssw0rd!”
Dim cnnAuthors As New SqlConnection(strConnectionString) Dim daAuthors As New SqlDataAdapter
Dim dsAuthors As New DataSet
Private Sub Form1_Load(ByVal sender As Object, _ ByVal e As System.EventArgs) Handles Me.Load
daAuthors.SelectCommand = New SqlCommand daAuthors.SelectCommand.Connection = cnnAuthors daAuthors.SelectCommand.CommandText = “Select * From Authors” daAuthors.SelectCommand.CommandType = CommandType.Text
cnnAuthors.Open()
daAuthors.Fill(dsAuthors, “authors”)
cnnAuthors.Close()
dgvAuthors.AutoGenerateColumns = True dgvAuthors.DataSource = dsAuthors dgvAuthors.DataMember = “authors”
daAuthors = Nothing cnnAuthors = Nothing
End Sub End Class
759

Appendix D
Exercise 2
To complete this exercise, you were to use a DataGridView object to display the data from the pubs database. First, you should have created a Windows Application and added two references, one to the System.Data namespace and one to the System.XML namespace. Next, you needed to add a datagridview control to your form. That was all you needed to do before adding the code listed here. You will notice the difference from the first solution is just the SQL.
Imports System.Data
Imports System.Data.SqlClient Public Class Form1
Dim strConnectionString As String = “server=bnewsome;” & _ “database=pubs;uid=sa;pwd=!p@ssw0rd!”
Dim cnnAuthors As New SqlConnection(strConnectionString) Dim daAuthors As New SqlDataAdapter
Dim dsAuthors As New DataSet
Private Sub Form1_Load(ByVal sender As Object, _ ByVal e As System.EventArgs) Handles Me.Load
Dim strSQL As String
strSQL = “Select au_id as ID, au_lname as [Last Name], “ & _ “au_fname as [First Name], Phone, Address, City, State, “ & _ “Zip, Contract From Authors”
daAuthors.SelectCommand = New SqlCommand daAuthors.SelectCommand.Connection = cnnAuthors daAuthors.SelectCommand.CommandText = strSQL daAuthors.SelectCommand.CommandType = CommandType.Text
cnnAuthors.Open()
daAuthors.Fill(dsAuthors, “authors”)
cnnAuthors.Close()
dgvAuthors.AutoGenerateColumns = True dgvAuthors.DataSource = dsAuthors dgvAuthors.DataMember = “authors”
daAuthors = Nothing cnnAuthors = Nothing
End Sub End Class
Chapter 17 Solution
The entire code listings follow the answer.
You should have made the following additions.
To web.config:
760

Solutions
<configuration>
<appSettings>
<add key=”ConnectionString” value=”Server=bnewsome; User ID=sa;
Password=!p@ssw0rd!; Database=pubs;” /> </appSettings>
</configuration>
To Default.aspx, add script for the <Head> element:
<script runat=”server” language=vbscript>
Sub sdsAuthors_Init(ByVal sender As Object, ByVal e As System.EventArgs) sdsAuthors.ConnectionString = _
ConfigurationManager.AppSettings(“ConnectionString”) End Sub
</script>
You should have made the following changes to Default.aspx.
Removed the attribute ConnectionString from sdsAuthors on Default.aspx
The complete code starting with the <HTML> element for Default.aspx should look like this.
<html xmlns=”http://www.w3.org/1999/xhtml” > <head id=”Head1” runat=”server”>
<title>Grid View</title>
<script runat=”server” language=vbscript>
Sub sdsAuthors_Init(ByVal sender As Object, ByVal e As System.EventArgs) sdsAuthors.ConnectionString = _
ConfigurationManager.AppSettings(“ConnectionString”) End Sub
</script>
</head>
<body>
<form id=”form1” runat=”server”> <div>
<asp:SqlDataSource ID=”sdsAuthors” Runat=”server” ProviderName = “System.Data.SqlClient”
SelectCommand = “SELECT au_id, au_lname, au_fname, phone, address, city, state, zip FROM authors”
UpdateCommand = “UPDATE authors SET au_lname = @au_lname, au_fname = @au_fname, phone = @phone, address = @address, city = @city, state = @state, zip = @zip
WHERE au_id = @original_au_id” OnInit=”sdsAuthors_Init”> <UpdateParameters>
<asp:Parameter Type=”String” Name=”au_lname”></asp:Parameter> <asp:Parameter Type=”String” Name=”au_fname”></asp:Parameter> <asp:Parameter Type=”String” Name=”phone”></asp:Parameter> <asp:Parameter Type=”String” Name=”address”></asp:Parameter> <asp:Parameter Type=”String” Name=”city”></asp:Parameter> <asp:Parameter Type=”String” Name=”state”></asp:Parameter> <asp:Parameter Type=”String” Name=”zip”></asp:Parameter> <asp:Parameter Type=”String” Name=”au_id”></asp:Parameter>
</UpdateParameters>
761

Appendix D
</asp:SqlDataSource>
<asp:GridView ID=”gdvAuthors” Runat=”server” DataSourceID=”sdsAuthors” AllowPaging=”True” AllowSorting=”True” AutoGenerateColumns=False DataKeyNames=”au_id” >
<PagerStyle BackColor=”Gray” ForeColor=”White” HorizontalAlign=”Center” /> <HeaderStyle BackColor=”Black” ForeColor=”White” />
<AlternatingRowStyle BackColor=”LightGray” /> <Columns>
<asp:CommandField ButtonType=”Button” ShowEditButton=”true” /> <asp:BoundField Visible=”false” HeaderText=”au_id” DataField=”au_id”
SortExpression=”au_id”></asp:BoundField> <asp:BoundField HeaderText=”Last Name” DataField=”au_lname”
SortExpression=”au_lname”></asp:BoundField> <asp:BoundField HeaderText=”First Name” DataField=”au_fname” SortExpression=”au_fname”></asp:BoundField>
<asp:BoundField HeaderText=”Phone” DataField=”phone” SortExpression=”phone”></asp:BoundField>
<asp:BoundField HeaderText=”Address” DataField=”address” SortExpression=”address”></asp:BoundField>
<asp:BoundField HeaderText=”City” DataField=”city” SortExpression=”city”></asp:BoundField>
<asp:BoundField HeaderText=”State” DataField=”state” SortExpression=”state”></asp:BoundField>
<asp:BoundField HeaderText=”Zip Code” DataField=”zip” SortExpression=”zip”></asp:BoundField>
</Columns>
</asp:GridView>
</div>
</form>
</body>
</html>
The complete code for web.config should look like this.
<?xml version=”1.0” ?>
<!-- Note: As an alternative to hand editing this file you can use the web admin tool to configure settings for your application. Use the Website->Asp.Net Configuration option in Visual Studio. A full list of settings and comments can be found in machine.config.comments usually located in \Windows\Microsft.Net\Frameworks\v2.x\Config -->
<configuration xmlns=”http://schemas.microsoft.com/.NetConfiguration/v2.0”> <appSettings>
<add key=”ConnectionString” value=”Server=bnewsome; User ID=sa; Password=!p@ssw0rd!;Database=pubs;” />
</appSettings>
<connectionStrings />
<system.web>
762

Solutions
<!-- Set compilation debug=”true” to insert debugging symbols into the compiled page. Because this affects performance, set this value to true only during development. -->
<compilation debug=”false” />
<!-- The <authentication> section enables configuration of the security authentication mode used by ASP.NET to identify an incoming user. -->
<authentication mode=”Windows” />
<!-- The <customErrors> section enables configuration of what to do if/when an unhandled error occurs during the execution of a request. Specifically, it enables developers to configure html error pages to be displayed in place of a error stack trace.
<customErrors mode=”RemoteOnly” defaultRedirect=”GenericErrorPage.htm”> <error statusCode=”403” redirect=”NoAccess.htm”/>
<error statusCode=”404” redirect=”FileNotFound.htm”/> </customErrors>
-->
</system.web>
</configuration>
Chapter 18 Solutions
Exercise 1
Your web.config file in the Members folder should look like this:
<?xml version=”1.0” encoding=”utf-8”?> <configuration>
<system.web>
<pages theme=”MainTheme” /> <authorization>
<deny users=”?” /> </authorization>
</system.web>
</configuration>
The Main.skin file should look like this (only one line of code in file):
<asp:Label runat=”server” ForeColor=”Red” />
Exercise 2
Your web.config file in the Root folder should look like this (although you will find some additional items and comments):
763

Appendix D
<?xml version=”1.0” encoding=”utf-8”?> <configuration>
<system.web>
<pages theme=”MainTheme” />
<roleManager enabled=”true” /> <authentication mode=”Forms” />
</system.web>
</configuration>
The Main.skin file should look like this:
<asp:Label runat=”server” ForeColor=”Red” />
<asp:Login runat=”server” ForeColor=”Red” />
Chapter 19 Solutions
Exercise 1
For this exercise, you were required you to create an XML document that described a table lamp. There are a number of ways to correctly describe a lamp. You could have used child elements and no attributes. Also, you could have used different language to describe a lamp. Either way, you should have used the same case and closed your elements.
You can validate your XML at a site like www.w3schools.com/dom/dom_validate.asp that offers a free validator. The code for the document should look similar to this:
<?xml version=”1.0” encoding=”utf-8”?>
<lamps xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance” xmlns:xsd=”http://www.w3.org/2001/XMLSchema”>
<lamp type=”table” desing=”modern” price=”269”>
<base shape=”square” color=”black” height_inches=”24”></base> <bulbs max_watts=”60” number_of_bulbs=”3” type=”soft white”></bulbs> <shade color=”white” shape=”oval” size_inches=”18 X 8”></shade>
</lamp>
</lamps>
Exercise 2
For this exercise, you were to find the syntax for a valid XML comment. The comment is like a HTML comment and starts with <!-- and ends with -->. Your comment should look similar to this:
<!-- This is a valid XML comment -->
764

Solutions
Chapter 20 Solutions
Exercise 1
For this exercise, you were required to create a Web Service with three methods. The three methods should have individually returned the server date, time, and name. First, you had to create a new Web site project and then add the Web Service methods. The code for the methods should look similar to these:
Imports System.Web
Imports System.Web.Services
Imports System.Web.Services.Protocols
<WebService(Namespace := “http://tempuri.org/”)> _ <WebServiceBinding(ConformsTo:=WsiProfiles.BasicProfile1_1)> _ Public Class WebService
Inherits System.Web.Services.WebService
Public Sub WebService
End Sub
<WebMethod()> _
Public Function ServerName() As String Return My.Computer.Name
End Function
<WebMethod()> _
Public Function ServerDate() As Date Return Now().Date
End Function
<WebMethod()> _
Public Function ServerTime() As String Return Now().ToShortTimeString
End Function
End Class
When you ran the Web Service, you may have been asked to add a web.config file for debugging. You could have chosen either to add the file or to continue without debugging. When you tested each method, you should have seen the date, time, and name of your server.
Exercise 2
In Exercise 2, you needed to create a Remoting server that would return the date and time on the server. You had to create a class that inherits from MarshalByRefObject. Next, you needed to create an application (we used a console application) that registered the object on a known channel and port. Finally, you were to create a client that could consume the object and test the methods that returned the date and time. Here is an example of the Remoting server code:
765