4.1. Creating the Windows Application and Building the Main Window


The first step toward building the library application is to use Visual Studio 2005 to create a new Windows application project and then build the main window. You'll use a variety of new controls that ship with Visual Basic 2005 to get the job done.

  1. Launch Visual Studio 2005 and create a new Windows application by selecting File New Project. Choose the Visual Basic/Windows project type in the Project types dialog panel and select the Windows Application template in the Templates panel, as shown in Figure 4-2. Name the project Text property in the Properties window. When the main application window displays, this name will appear in its titlebar.

    Figure 4-2. Creating a new Windows application project


  2. Now you're ready to construct the application main window. You'll begin by adding an Office style menu to Form1. Click on the Toolbox tab to the left of the Form1 designer page and drag-and-drop a MenuStrip control from the Menus & Toolbars tab onto Form1. The empty menu bar is automatically placed at the top of the page, and an icon for the control appears in a strip at the bottom of the designer page. You can display the Properties window for the control by clicking either the empty bar or the control icon.

    Click on the Insert Standard Items link in the MenuStrip Tasks menu to insert the commonly used File, Edit, Tools, and Help menus, as shown in Figure 4-3.

  3. Next, add a toolbar to the window by dragging-and-dropping the ToolStrip control from the Menus & Toolbars tab in the Toolbox onto Form1. Click on the Insert Standard Items link to add the list of commonly used toolbar icons as shown in Figure 4-4.

    Figure 4-3. Adding a MenuStrip control to the form


    Figure 4-4. Adding a ToolStrip control to the form


    The new MenuStrip and ToolStrip controls in VB 2005 make it much easier for developers to create professional looking Windows applications.


  4. The design for the main window shown in Figure 4-1 calls for a status bar that we'll use to show progress in gathering information from Amazon.com when a user initiates a search. You'll build the bar by dragging-and-dropping a StatusStrip control onto Form1, and then add a StatusLabel control by selecting the StatusLabel item from the StatusStrip drop-down listbox, as shown in Figure 4-5. The StatusLabel control works like any Label control.

    Figure 4-5. Inserting StatusLabel and ProgressBar controls into the StatusStrip control


  5. To create the separate search and book details panels shown in Figure 4-1, drag-and-drop a SplitContainer control from the Containers tab of the Toolbox onto Form1. The SplitContainer control represents a control consisting of a movable bar that divides a container's display area into two resizable panels. Set the BorderStyle property of the SplitContainer control to "Fixed3D" so that it shows a three-dimensional border.

    The SplitContainer control is new in VB 2005 and is a much improved version of its predecessor.


    At this point, your application window should look like the one shown in Figure 4-6.

    Figure 4-6. Adding a SplitContainer control to the form


  6. Populate the left panel of the SplitContainer control with the controls as shown in Figure 4-7 by dragging-and-dropping each control from the Toolbox onto the form. Name the controls as shown by clicking on each control and setting its Name property in the Properties window.

4.1.1. Creating a Database to Store Books Information

The information about each book that a user acquires from Amazon.com needs to be saved to a local database on the PC or workstation. To provide this functionality, you need to add a database to your project. For this project, you'll use a SQL database file to store your book data. Once you've created the database file, you'll add a table to store the individual records for each book in your collection.

Figure 4-7. Populating the left panel of the SplitContainer control


  1. To add a database file to your project, first right-click on the project name, LibraryApp, in Solution Explorer and then select Add New Item…. Now, in the Add New Item dialog box, select SQL Database and set the Name of the database file to Figure 4-8. Adding a SQL database to the project


    The Library.mdf database file icon will now appear in the Solution Explorer window, and the Data Source Configuration Wizard will appear. As you won't be using this wizard, click Cancel.

  2. Now you're ready to create the table to hold the records for the books in your library. Double-click the Library.mdf file icon to view it in more detail in the Database Explorer as shown in Figure 4-9.

    Expand the Library.mdf file, right-click on the Tables subfolder icon, and select Add New Table. Visual Studio 2005 creates the table and displays a blank page (dbo: Table 1) that you'll use to define its records.

    Figure 4-9. Adding a new table to the database


    With a blank table in hand, you'll now define its columns and fields. Enter the name of each field as shown in Figure 4-10. After entering a name, tab to the right to enter a data type. You can type in the data type shown in Figure 4-10, or select it from the drop-down menu provided by Visual Studio 2005. You'll need to enter the Data Type for Title and Publisher manually to specify a 100 character length. Tab to the last column to specify whether null values are allowed. By default, they are. The ISBN field contains the primary key for each record. Select and right-click on the field and select Set Primary Key from the drop-down menu. Uncheck the Allow Nulls box for the field since it would be unacceptable to have a record in the database without a primary key. Figure 4-10 shows the completed page.

    Save the table by selecting "Save Table 1" from the File menu. When prompted, name the table Titles.

    Close the table window by right-clicking on its title tab and selecting Close.

Figure 4-10. Defining a table


4.1.2. Binding Library Data to the Form

You will now use the data-binding features of VB 2005 to bind the database that you have just created to the form. To do so, you need to add a data source to the Data Sources window.

  1. Go to Data Show Data Sources to display the Data Sources window.


  2. The Data Source Configuration Wizard will appear. Select Database as the Data Source type and click Next.

  3. When the "Choose your data connection" dialog appears, you will notice that the Library.mdf file has already been selected, as shown in Figure 4-12). Click Next.

  4. Now you have the option to save the connection string that the page will use to connect to the Library.mdf database in the application configuration file. This option allows you to change the database details easily without recompiling the application even after it has been deployed. This is the default, so leave the checkbox checked and click Next to go to the next step.

  5. In the next window, the "Choose your database objects dialog," you can select the table(s) you want to work with. For this project, check the Titles table, which contains the records for your stored books. This step is as shown in Figure 4-13.

    Figure 4-12. Selecting the data connection


    Figure 4-13. Selecting the table to work with


    That's it! You've configured the Library.mdf database file as a data source without writing a line of code. Now click Finish.

    You should now see the Titles table displayed as a tree in the Data Sources window, as shown in Figure 4-14.

    Remember to close the table window as described in step 2 of the section "Creating a Database to Store Books Information." Otherwise, the Data Sources window will not display the icons next to the table and fields.


    Figure 4-14. The Titles table in the Data Sources window


  6. You will now change the binding of some of the fields in the table in the Data Sources window. Change the binding of the ISBN field from TextBox to Label so that the ISBN of a book is displayed in a non-editable Label control (see Figure 4-15). Also, change the binding of the Cover field from None to PictureBox. Doing so will display the data contained in the Cover field in a PictureBox control.

    Figure 4-15. Changing the default binding of the Titles table


  7. Drag-and-drop the ISBN, Title, Authors, Publisher, Price, and Cover fields (individually) from the Titles table in the Data Sources window onto the right panel of the SplitContainer control. Also, add in a Button control named Add Title. The form should now look like the one shown in Figure 4-16. Name the controls as shown in the figure callouts (the names appear in parentheses).

    Figure 4-16. Populating the form with the various controls


  8. You will notice that a couple of controls appeared at the bottom of the Form1.vb design page (see Figure 4-17). These controls perform all the magic of binding the data in your database to the controls on your form. Going into the details of what they do specifically is beyond the scope of this book.

    Figure 4-17. The controls added at the bottom of Form1.vb


  9. You will also notice that a control known as the BindingNavigator control is added to the form when you drag-and-drop the fields from the Data Sources window onto the form (see Figure 4-18). This control allows users to navigate through the records in the database. As we are not going to let the user view the list of books in this window, the control is not relevant in this case. So, set its Visible property to False so that it will not display on the form. Alternatively, you can just delete it.

    Figure 4-18. The BindingNavigator control added to the form


  10. Once you've completed the Library Application form, you need to set a few of the properties of the newly added controls. First, you'll want to set the Anchor property of each control to ensure that each is correctly resized and positioned when a user resizes the form. The Anchor property of a control determines where it should be positioned when the form is resized. For example, if a control's Anchor property is set to Top, Left, the control's position will be fixed. However, if its Anchor property is set to Bottom, Right, its position will be anchored to the bottom-right corner of the form (see Figure 4-19).

Figure 4-19. Setting the Anchor property of a control to "Bottom, Right"


If the Anchor property is set to Top, Left, Right, the control will be resized horizontally when the form is resized (see Figure 4-20).

Figure 4-20. Setting the Anchor property of a control to "Top, Left, Right"


If the Anchor property is set to Top, Bottom, Left, Right, the control will be resized both vertically and horizontally when the form is resized (see Figure 4-21).

Set the Anchor property of each control on the main application window to the value shown in Table 4-1.

Figure 4-21. Setting the Anchor property of a control to "Top, Bottom, Left, Right"


Table 4-1. Setting the Anchor property of the various controls

Control name

Value

txtKeywords

Top, Left, Right

btnGetInfo

Top, Right

lstBooks

Top, Bottom, Left, Right

chkAutoAdd

Bottom, Left, Right

chkShowCover

Bottom, Left, Right

btnViewCatalog

Bottom, Left, Right

lblISBN

Top, Left

txtTitle

Top, Left, Right

txtAuthors

Top, Left, Right

txtPublisher

Top, Left, Right

txtPrice

Top, Left, Right

picCover

Top, Right

btnAddTitle

Bottom, Left


While you're at it, also set the properties of three other controls on the window to the values shown in Table 4-2.

Table 4-2. Setting the properties of the various controls

Control name

Property

Value

Description

lblISBN

BorderStyle

FixedSingle

This draws a rectangle around the control.

chkShowCover

Checked

TRue

The control is checked by default.

picCover

SizeMode

AutoSize

The image will be displayed in its original size.


The resizing and reallocating of controls is much improved in VB 2005 compared to VB 6. By setting the Anchor property of each control, you can ensure that the controls are automatically resized or repositioned when the user resizes the form, as shown in Figure 4-22.

Figure 4-22. Resizing the controls


4.1.3. Adding a Web Reference to Amazon.com

The Library Application uses Amazon.com's E-Commerce web service (ECS for short) to obtain detailed information about a book, such as its description, selling price, customers' reviews, and cover image. To use the Amazon. com web service, you need to register as a user and use the subscription ID assigned to you by Amazon to access the service programmatically. You can register for the service at: www.amazon.com/gp/aws/landing.html. There is no charge for using the service. To continue with this example, you should register now.

Once you have registered with Amazon.com, you need to add a web reference to your project to use the service. Once you have added the web reference, Visual Studio 2005 can automatically generate a proxy class for you so that you can invoke the web service as if you were making calls to a normal object, as you will see in the next section, "Accessing the Amazon.com Web Services."

  1. To add a web reference to your project, right-click on the project name in Solution Explorer and then select Add Web Reference.

  2. In the Add Web Reference window, enter the following URL and click Go: http://webservices.amazon.com/AWSECommerceService/AWSECom-merceService.wsdl.

    This URL contains the location of the WSDL document needed by Visual Studio 2005 to generate the web proxy class.


  3. If the WSDL document is retrieved successfully, you can add it to your project by clicking the Add Reference button (see Figure 4-23). Name the web reference AmazonWS.

Figure 4-23. Adding a web reference


4.1.4. Accessing the Amazon.com Web Services

When a Library Application user enters search keywords for a book, the application needs to connect to Amazon.com's web service to request a search and download the list of titles returned. While the user waits for the result, it's always a good idea to report the status of the search in the StatusStrip control with some text as well as an hourglass cursor, as shown in Figure 4-24.

In this section, you'll first program the controls that show status. You'll use the StatusLabel control on Form1 to display some status text while the search proceeds and change the cursor to an hourglass to provide a visual representation of work in progress. Once the status controls are coded, you'll write the code that calls the Amazon.com web service and loads information retrieved by the keyword search into the ListBox control (lstBooks) that displays the result.

Web Services

A web service is a business object residing on a server that you can programmatically access through the network. For example, companies like Amazon.com and Google have both found values in making parts of their data available to their customers through web services. Using web services, customers can now integrate data from Amazon.com or Google into their own application. To ensure interoperability between web services and their users (known as web service consumers), most web services use open standards such as SOAP, XML, HTTP, and WSDL:


XML

Used as the language for exchanging messages between a web service and its consumer.


SOAP (Simple Object Access Protocol)

Used as the XML messaging format.


HTTP

Used as the transport protocol to carry web services messages.


WSDL (Web Services Description Language)

Used to write the contract that defines the functions that the web service has to offer.


Figure 4-24. Displaying the status in the StatusStrip control


  1. You will first define two global variables within the form to use the Amazon.com web service:

     Public Class Form1  '---objects to store the response of the Web service  Dim amazonResponse As AmazonWS.ItemSearchResponse = Nothing     Dim amazonItems As AmazonWS.Item() = Nothing 

    Note the parentheses () after Item, which are required.


  2. To code the status control and change the default cursor to the hourglass, double-click on the Get Info button (btnGetInfo) to switch to the code behind for its Click event handler. Enter the code shown in Example 4-1.

    Example 4-1. btnGetInfo Click event handler
     Private Sub btnGetInfo_Click( _    ByVal sender As System.Object, _    ByVal e As System.EventArgs) _    Handles btnGetInfo.Click     '---changes the cursor to an hourglass  Me.Cursor = Cursors.WaitCursor  ToolStripStatusLabel1.Text = "Retrieving book information…"     GetBookInformation(Trim(txtKeywords.Text)) End Sub 

    The code in Example 4-1 displays status text (by setting the Text property of ToolStripStatusLabel1) and changes the default cursor to use an hourglass (using the Me.Cursor property). Next, the event handler calls GetBookInformation, which calls the Amazon.com event handler and passes it the search keywords that the user has entered into the txtKeyword text box control.

  3. Now you need to code the GetBookInformation subroutine. The GetBookInformation subroutine takes a single parameter (keyword) and calls the Amazon.com web service. When the result is returned, display it in the Search Results window of the Library Application. Figure 4-25 shows the results you'll get when you enter my name as the search string.

Figure 4-25. Displaying the results from Amazon.com


Add the GetBookInformation subroutine to the Form1 class on its codebehind page by entering the code shown in Example 4-2. Remember to assign the value of the subscription ID assigned you by Amazon.com to SubscriptionId.

Example 4-2. GetBookInformation subroutine
 Public Sub GetBookInformation(ByVal keyword As String) Dim itemSearchRequest As New AmazonWS.ItemSearchRequest Dim itemSearch As New AmazonWS.ItemSearch '---initialize objects With itemSearchRequest         '---set the search keyword(s) .Keywords = keyword '---set the size of the response .ResponseGroup = New String() {"Medium"} '---set the SearchIndex or search mode .SearchIndex = "Books"    End With    With itemSearch '---set the Amazon.com SubscriptionId .SubscriptionId = "your_subscription_Id_here" .Request = New AmazonWS.ItemSearchRequest() _            {itemSearchRequest}    End With    Try '---invoke the Amazon.com web service amazonResponse = _    My.WebServices.AWSECommerceService.ItemSearch(itemSearch)         If amazonResponse IsNot Nothing Then amazonItems = amazonResponse.Items(0).Item         End If    Catch ex as Exception       MsgBox(ex.ToString)    Finally   '---change the cursor to default   Me.Cursor = Cursors.Default   ToolStripStatusLabel1.Text = ""    End Try    If amazonItems Is Nothing then Exit Sub    lstBooks.Items.Clear()    '---add the books to the listbox    For i As Integer = 0 To amazonItems.Length - 1        With amazonItems(i)            lstBooks.Items.Add(.ItemAttributes.Title)        End With    Next End Sub 

For simplicity, the Library Application will retrieve only the first 10 results from Amazon.com.


4.1.5. Displaying Book Information and Covers

With the results of a search now available in the Search Results window, you want to enable users to view the details of any title in the list by selecting its name.

When a title is selected, a number of actions need to occur. First, the application needs to display the book details in the righthand pane of the Library Application window. Book covers require special handling. Since most users will want to see the cover of a book they've chosen, the Show Cover checkbox in Figure 4-24 is set to true (checked) by default. Unless the user unchecks the box, the cover of a title is always retrieved along with its other information. However, the Amazon.com web service supplies a URL that points to the location of the image, not the image itself. So, you'll need to write code to download the image onto the local computer before you can display it.

Finally, if the user has checked the Auto-add Title checkbox, the application needs to automatically add the selected title to the database.

Abiding by the Amazon Web Services Licenses Agreement

The Amazon Web Services Licenses Agreement describes the set of rules and time limits that you must respect to remain compliant with the license. In particular, applications that store data in a database must store a timestamp along with the data, show this timestamp adjacent to the data, and offer a Refresh function.


The actions can all be carried out by the event handler for the SelectedIndexChanged event of the lstBook listbox control, which fires when a user clicks on any item in its list.

  1. To generate a code stub for the SelectedIndexChanged event of the lstBook control, double-click on the control on Form1. To code the event, enter the code shown in bold in Example 4-3.

    Example 4-3. 1stBooks SelectedIndexChanged event handler
     Private Sub lstBooks_SelectedIndexChanged( _    ByVal sender As System.Object, _    ByVal e As System.EventArgs) _    Handles lstBooks.SelectedIndexChanged If lstBooks.SelectedIndex < 0 Then Exit Sub     Try         '---display detailed book information With amazonItems(lstBooks.SelectedIndex)             lblISBN.Text = .ASIN  txtTitle.Text = .ItemAttributes.Title  txtAuthors.Text = Join(.ItemAttributes.Author, ",")  txtPublisher.Text = .ItemAttributes.Publisher  txtPrice.Text = _    .ItemAttributes.ListPrice.FormattedPrice.ToString  ToolStripStatusLabel1.Text = .ItemAttributes.Title             '---downloads the cover of the book If chkShowCover.Checked Then                  '---download the cover image  Dim webReq As Net.HttpWebRequest = _                    Net.HttpWebRequest.Create( _                        .MediumImage.URL.ToString)                  Dim webResp As Net.HttpWebResponse = _                                       webReq.GetResponse() '---displays the image  picCover.Image = _ Image.FromStream(webResp.GetResponseStream())                  End If                  '---auto-add a title  If chkAutoAdd.Checked Then                      AddTitle()                  End If              End With       Catch ex As Exception           DisplayError(ex.ToString)       End Try End Sub 

  2. The DisplayError method that you call in Example 4-4 simply sounds a beep and displays the error message in the StatusLabel control in the StatusStrip control.

    Example 4-4. DisplayError subroutine
      Private Sub DisplayError(ByVal message As String)     My.Computer.Audio.PlaySystemSound( _                   System.Media.SystemSounds.Exclamation)     ToolStripStatusLabel1.Text = "Error : " & message  End Sub  

    You can play different types of sounds by supplying the PlaySystemSound method with one of the following values from the System.Media. SystemSounds enumeration:

    • Asterisk

    • Beep

    • Exclamation

    • Hand

    • Question

Figure 4-25, earlier in this chapter, shows the result of a search for the author Wei-Meng Lee. When you click on the title of one of the books in the results list (for example, ASP.NET 2.0: A Developer's Notebook), the detailed information available for the selected book is displayed.

4.1.6. Saving Book Information

Now you need to write the routines that add book information to the user's database either because "Auto-add Title box" is checked or because the user has clicked the Add Title button. While the detailed book information about a title is displayed on the form, you'll also want to give the user the option to modify the data before saving it to the local database file.

  1. First, you'll code the Add Title button event handler. Double-click the Add Title button on Form1 and enter the code in Example 4-5.

    Example 4-5. btnAddTitle Click event handler
     Private Sub btnAddTitle_Click( _     ByVal sender As System.Object, _     ByVal e As System.EventArgs) _     Handles btnAddTitle.Click     AddTitle()  End Sub 

    The event handler calls the AddTitle subroutine, where the heavy lifting is done.

  2. The AddTitle subroutine called by Example 4-6 is responsible for recording the details of a title you want stored in the local database file, Library.mdf. The subroutine first converts the image displayed in the PictureBox control into a byte array. The new record is then saved into the database using the TitlesTableAdapter control that you added to the form earlier (see also Figure 4-17, earlier in this chapter).

    Example 4-6. AddTitle subroutine
     Public Sub AddTitle()     Try          '---get the book cover image as a byte array---  Dim ms As New System.IO.MemoryStream()  picCover.Image.Save(ms, picCover.Image.RawFormat)          Dim coverimage() As Byte = ms.GetBuffer ms.Close()  '---add the new title to the database--- TitlesTableAdapter.Insert(lblISBN.Text, _            txtTitle.Text, txtAuthors.Text, _             txtPublisher.Text, txtPrice.Text, coverimage)         ToolStripStatusLabel1.Text += " - Added"      Catch ex As Exception          DisplayError("Error adding title.")      End Try  End Sub  

All the hard work needed to save the new record into the database is performed by the TitlesTableAdapter control. The TitlesTableAdapter control uses ADO.NET (the data access technology used in the .NET Framework) behind the scenes to accomplish this mean feat.


4.1.7. Testing the Application

Now you are ready to take the application for a test drive. Start it up by pressing F5. Enter some keywords for a book, say, the author name, title, or ISBN. Click on the Get Info button to retrieve a list of titles matching your search criteria and list them on the Listbox control. You'll notice that the application hangs for a while when you submit the search request, and the form does not appear to repaint itself when overlapped by another window. We'll deal with this problem in a future section, "Accessing the Web Services Asynchronously." You can display the details of a book in the righthand pane of the application window by selecting an item in the ListBox control of the Search Results window, as shown in Figure 4-26.

Figure 4-26. Testing the application


Click the Add Title button to save the book information into the local database. If you check the "Auto-add Title" checkbox, book information is saved automatically just by selecting a title from the Search Results list.

If you were to include similar functionality in a production application, you would need to store the "freshness date" along with each book, display that date along with the other information, and offer the user the ability to refresh the data to make sure the price and other information is accurate. See the Amazon license agreement for details.




Visual Basic 2005 Jumpstart 2005
Visual Basic 2005 Jumpstart
ISBN: 059610071X
EAN: 2147483647
Year: 2005
Pages: 86
Authors: Wei-Meng Lee

Similar book on Amazon

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net