- •Using Your Sybex Electronic Book
- •Acknowledgments
- •Contents at a Glance
- •Introduction
- •Who Should Read This Book?
- •How About the Advanced Topics?
- •The Structure of the Book
- •How to Reach the Author
- •The Integrated Development Environment
- •The Start Page
- •Project Types
- •Your First VB Application
- •Making the Application More Robust
- •Making the Application More User-Friendly
- •The IDE Components
- •The IDE Menu
- •The Toolbox Window
- •The Solution Explorer
- •The Properties Window
- •The Output Window
- •The Command Window
- •The Task List Window
- •Environment Options
- •A Few Common Properties
- •A Few Common Events
- •A Few Common Methods
- •Building a Console Application
- •Summary
- •Building a Loan Calculator
- •How the Loan Application Works
- •Designing the User Interface
- •Programming the Loan Application
- •Validating the Data
- •Building a Math Calculator
- •Designing the User Interface
- •Programming the MathCalculator App
- •Adding More Features
- •Exception Handling
- •Taking the LoanCalculator to the Web
- •Working with Multiple Forms
- •Working with Multiple Projects
- •Executable Files
- •Distributing an Application
- •VB.NET at Work: Creating a Windows Installer
- •Finishing the Windows Installer
- •Running the Windows Installer
- •Verifying the Installation
- •Summary
- •Variables
- •Declaring Variables
- •Types of Variables
- •Converting Variable Types
- •User-Defined Data Types
- •Examining Variable Types
- •Why Declare Variables?
- •A Variable’s Scope
- •The Lifetime of a Variable
- •Constants
- •Arrays
- •Declaring Arrays
- •Initializing Arrays
- •Array Limits
- •Multidimensional Arrays
- •Dynamic Arrays
- •Arrays of Arrays
- •Variables as Objects
- •So, What’s an Object?
- •Formatting Numbers
- •Formatting Dates
- •Flow-Control Statements
- •Test Structures
- •Loop Structures
- •Nested Control Structures
- •The Exit Statement
- •Summary
- •Modular Coding
- •Subroutines
- •Functions
- •Arguments
- •Argument-Passing Mechanisms
- •Event-Handler Arguments
- •Passing an Unknown Number of Arguments
- •Named Arguments
- •More Types of Function Return Values
- •Overloading Functions
- •Summary
- •The Appearance of Forms
- •Properties of the Form Control
- •Placing Controls on Forms
- •Setting the TabOrder
- •VB.NET at Work: The Contacts Project
- •Anchoring and Docking
- •Loading and Showing Forms
- •The Startup Form
- •Controlling One Form from within Another
- •Forms vs. Dialog Boxes
- •VB.NET at Work: The MultipleForms Project
- •Designing Menus
- •The Menu Editor
- •Manipulating Menus at Runtime
- •Building Dynamic Forms at Runtime
- •The Form.Controls Collection
- •VB.NET at Work: The DynamicForm Project
- •Creating Event Handlers at Runtime
- •Summary
- •The TextBox Control
- •Basic Properties
- •Text-Manipulation Properties
- •Text-Selection Properties
- •Text-Selection Methods
- •Undoing Edits
- •VB.NET at Work: The TextPad Project
- •Capturing Keystrokes
- •The ListBox, CheckedListBox, and ComboBox Controls
- •Basic Properties
- •The Items Collection
- •VB.NET at Work: The ListDemo Project
- •Searching
- •The ComboBox Control
- •The ScrollBar and TrackBar Controls
- •The ScrollBar Control
- •The TrackBar Control
- •Summary
- •The Common Dialog Controls
- •Using the Common Dialog Controls
- •The Color Dialog Box
- •The Font Dialog Box
- •The Open and Save As Dialog Boxes
- •The Print Dialog Box
- •The RichTextBox Control
- •The RTF Language
- •Methods
- •Advanced Editing Features
- •Cutting and Pasting
- •Searching in a RichTextBox Control
- •Formatting URLs
- •VB.NET at Work: The RTFPad Project
- •Summary
- •What Is a Class?
- •Building the Minimal Class
- •Adding Code to the Minimal Class
- •Property Procedures
- •Customizing Default Members
- •Custom Enumerations
- •Using the SimpleClass in Other Projects
- •Firing Events
- •Shared Properties
- •Parsing a Filename String
- •Reusing the StringTools Class
- •Encapsulation and Abstraction
- •Inheritance
- •Inheriting Existing Classes
- •Polymorphism
- •The Shape Class
- •Object Constructors and Destructors
- •Instance and Shared Methods
- •Who Can Inherit What?
- •Parent Class Keywords
- •Derived Class Keyword
- •Parent Class Member Keywords
- •Derived Class Member Keyword
- •MyBase and MyClass
- •Summary
- •On Designing Windows Controls
- •Enhancing Existing Controls
- •Building the FocusedTextBox Control
- •Building Compound Controls
- •VB.NET at Work: The ColorEdit Control
- •VB.NET at Work: The Label3D Control
- •Raising Events
- •Using the Custom Control in Other Projects
- •VB.NET at Work: The Alarm Control
- •Designing Irregularly Shaped Controls
- •Designing Owner-Drawn Menus
- •Designing Owner-Drawn ListBox Controls
- •Using ActiveX Controls
- •Summary
- •Programming Word
- •Objects That Represent Text
- •The Documents Collection and the Document Object
- •Spell-Checking Documents
- •Programming Excel
- •The Worksheets Collection and the Worksheet Object
- •The Range Object
- •Using Excel as a Math Parser
- •Programming Outlook
- •Retrieving Information
- •Recursive Scanning of the Contacts Folder
- •Summary
- •Advanced Array Topics
- •Sorting Arrays
- •Searching Arrays
- •Other Array Operations
- •Array Limitations
- •The ArrayList Collection
- •Creating an ArrayList
- •Adding and Removing Items
- •The HashTable Collection
- •VB.NET at Work: The WordFrequencies Project
- •The SortedList Class
- •The IEnumerator and IComparer Interfaces
- •Enumerating Collections
- •Custom Sorting
- •Custom Sorting of a SortedList
- •The Serialization Class
- •Serializing Individual Objects
- •Serializing a Collection
- •Deserializing Objects
- •Summary
- •Handling Strings and Characters
- •The Char Class
- •The String Class
- •The StringBuilder Class
- •VB.NET at Work: The StringReversal Project
- •VB.NET at Work: The CountWords Project
- •Handling Dates
- •The DateTime Class
- •The TimeSpan Class
- •VB.NET at Work: Timing Operations
- •Summary
- •Accessing Folders and Files
- •The Directory Class
- •The File Class
- •The DirectoryInfo Class
- •The FileInfo Class
- •The Path Class
- •VB.NET at Work: The CustomExplorer Project
- •Accessing Files
- •The FileStream Object
- •The StreamWriter Object
- •The StreamReader Object
- •Sending Data to a File
- •The BinaryWriter Object
- •The BinaryReader Object
- •VB.NET at Work: The RecordSave Project
- •The FileSystemWatcher Component
- •Properties
- •Events
- •VB.NET at Work: The FileSystemWatcher Project
- •Summary
- •Displaying Images
- •The Image Object
- •Exchanging Images through the Clipboard
- •Drawing with GDI+
- •The Basic Drawing Objects
- •Drawing Shapes
- •Drawing Methods
- •Gradients
- •Coordinate Transformations
- •Specifying Transformations
- •VB.NET at Work: Plotting Functions
- •Bitmaps
- •Specifying Colors
- •Defining Colors
- •Processing Bitmaps
- •Summary
- •The Printing Objects
- •PrintDocument
- •PrintDialog
- •PageSetupDialog
- •PrintPreviewDialog
- •PrintPreviewControl
- •Printer and Page Properties
- •Page Geometry
- •Printing Examples
- •Printing Tabular Data
- •Printing Plain Text
- •Printing Bitmaps
- •Using the PrintPreviewControl
- •Summary
- •Examining the Advanced Controls
- •How Tree Structures Work
- •The ImageList Control
- •The TreeView Control
- •Adding New Items at Design Time
- •Adding New Items at Runtime
- •Assigning Images to Nodes
- •Scanning the TreeView Control
- •The ListView Control
- •The Columns Collection
- •The ListItem Object
- •The Items Collection
- •The SubItems Collection
- •Summary
- •Types of Errors
- •Design-Time Errors
- •Runtime Errors
- •Logic Errors
- •Exceptions and Structured Exception Handling
- •Studying an Exception
- •Getting a Handle on this Exception
- •Finally (!)
- •Customizing Exception Handling
- •Throwing Your Own Exceptions
- •Debugging
- •Breakpoints
- •Stepping Through
- •The Local and Watch Windows
- •Summary
- •Basic Concepts
- •Recursion in Real Life
- •A Simple Example
- •Recursion by Mistake
- •Scanning Folders Recursively
- •Describing a Recursive Procedure
- •Translating the Description to Code
- •The Stack Mechanism
- •Stack Defined
- •Recursive Programming and the Stack
- •Passing Arguments through the Stack
- •Special Issues in Recursive Programming
- •Knowing When to Use Recursive Programming
- •Summary
- •MDI Applications: The Basics
- •Building an MDI Application
- •Built-In Capabilities of MDI Applications
- •Accessing Child Forms
- •Ending an MDI Application
- •A Scrollable PictureBox
- •Summary
- •What Is a Database?
- •Relational Databases
- •Exploring the Northwind Database
- •Exploring the Pubs Database
- •Understanding Relations
- •The Server Explorer
- •Working with Tables
- •Relationships, Indices, and Constraints
- •Structured Query Language
- •Executing SQL Statements
- •Selection Queries
- •Calculated Fields
- •SQL Joins
- •Action Queries
- •The Query Builder
- •The Query Builder Interface
- •SQL at Work: Calculating Sums
- •SQL at Work: Counting Rows
- •Limiting the Selection
- •Parameterized Queries
- •Calculated Columns
- •Specifying Left, Right, and Inner Joins
- •Stored Procedures
- •Summary
- •How About XML?
- •Creating a DataSet
- •The DataGrid Control
- •Data Binding
- •VB.NET at Work: The ViewEditCustomers Project
- •Binding Complex Controls
- •Programming the DataAdapter Object
- •The Command Objects
- •The Command and DataReader Objects
- •VB.NET at Work: The DataReader Project
- •VB.NET at Work: The StoredProcedure Project
- •Summary
- •The Structure of a DataSet
- •Navigating the Tables of a DataSet
- •Updating DataSets
- •The DataForm Wizard
- •Handling Identity Fields
- •Transactions
- •Performing Update Operations
- •Updating Tables Manually
- •Building and Using Custom DataSets
- •Summary
- •An HTML Primer
- •HTML Code Elements
- •Server-Client Interaction
- •The Structure of HTML Documents
- •URLs and Hyperlinks
- •The Basic HTML Tags
- •Inserting Graphics
- •Tables
- •Forms and Controls
- •Processing Requests on the Server
- •Building a Web Application
- •Interacting with a Web Application
- •Maintaining State
- •The Web Controls
- •The ASP.NET Objects
- •The Page Object
- •The Response Object
- •The Request Object
- •The Server Object
- •Using Cookies
- •Handling Multiple Forms in Web Applications
- •Summary
- •The Data-Bound Web Controls
- •Simple Data Binding
- •Binding to DataSets
- •Is It a Grid, or a Table?
- •Getting Orders on the Web
- •The Forms of the ProductSearch Application
- •Paging Large DataSets
- •Customizing the Appearance of the DataGrid Control
- •Programming the Select Button
- •Summary
- •How to Serve the Web
- •Building a Web Service
- •Consuming the Web Service
- •Maintaining State in Web Services
- •A Data-Driven Web Service
- •Consuming the Products Web Service in VB
- •Summary
992 Chapter 22 PROGRAMMING THE ADO.NET OBJECTS
To delete a row, we call the DataRow’s Delete method. The code behind the Delete Product button executes the following statement:
DsProducts1.Products(Me.BindingContext(DsProducts1, _
“Products”).Position).Delete()
The expression
Me.BindingContext(DsProducts1, “Products”).Position
returns the index of the selected row in the DataTable—an integer value. DSProducts1.Products is a DataTable object that represents the Products table in the DataSet. By calling this object with a numeric value as argument, we isolate a DataRow object, which represents the selected row in the Products table. Finally, we call the Delete method on this row to delete it. The row isn’t actually removed from the DataSet. It will be removed only when we call the DataSet’s AcceptChanges method—and this method must be called only after the underlying row has been successfully removed from the underlying table.
Open the DataEntry project on the CD and experiment with its code. See how the ComboBox controls were bound to the DataSet so that they always display the selected product’s category and supplier. You can add more features to the application, starting with a better navigational model.
The rows on the ListBox control are displayed in the same order as they were retrieved from the original table. In a “real” table with thousands of products, you wouldn’t want to read the entire table into the DataSet. You should allow the user to specify the subset of the products they’re interested in and upload only the matching rows to the client.
Building and Using Custom DataSets
In this section, we’ll build a DataSet that’s not connected to a data store. We’ll create a new DataSet by specifying its schema with the XML Schema tools of the Toolbox. Then we’ll make this DataSet the data source of a DataGrid control, and we’ll be able to add data directly on the grid. With a few statements, we’ll be able save the contents of the DataSet to a disk file and load it back from the disk file into the application.
Start a new project (it’s the XMLGrid project on the CD) and add an XMLSchema component to the project. Right-click the project’s name and, from the context menu, select Add New Item. Select the XML Schema template, specify a name for the new component (or accept the default name), and click OK to close the dialog box. An XMLSchema component will be added to the project; its default name is XMLSchema1.xsd. Double-click its icon to open it on the design surface.
Open the Toolbox, which now contains the XML Schema tools, and double-click the Element tool to add a new element to the XMLSchema. An XML element is equivalent to the table of a regular DataSet. The new XML element will be depicted on the design surface by an empty box. The default element’s name is element1; change it to GridData. Each XML element has one or more attributes, so let’s add a few. Open the Toolbox and drag the icon of the Attribute tool on the existing element. By default, new attributes are named attribute1, attribute2, and so on, and their default type is “string.” Figure 22.5 shows an XML element with four attributes and the XML Toolbox.
Copyright ©2002 SYBEX, Inc., Alameda, CA |
www.sybex.com |
BUILDING AND USING CUSTOM DATASETS 993
Figure 22.5
Designing an XML schema
The box with the attribute’s type is a drop-down list of all the data types you can assign to an attribute. The schema shown in Figure 22.5 contains an element with three string attributes and one positive Integer attribute. It’s like a table with four columns—three string columns and one numeric column. As you will see shortly, if you attempt to assign a value of the incorrect type to an attribute, the attribute’s current value won’t change.
So far you’ve created the schema of the DataSet—the information that came from the database in the previous examples. Now we must use the XMLSchema component to create a DataSet object. Right-click somewhere on the XMLSchema design surface and, from the context menu, select Generate Dataset. Switch to the form and add a DataSet object. The Add Dataset dialog box pops up, prompting you for the dataset’s schema information, as shown in Figure 22.6. Click OK and a new typed DataSet will be added to the project.
Figure 22.6
Adding a typed
DataSet to a project
At this point, you’re ready to use the custom DataSet. Place a DataGrid control on the form, set the control’s DataSource property to xmlschema11.GridData (you’ll select this item from a list), and run the project. You can optionally set some of the DataGrid control’s attributes. You have a DataGrid control that you can put any type of information on or use as a data-entry tool.
Copyright ©2002 SYBEX, Inc., Alameda, CA |
www.sybex.com |
994 Chapter 22 PROGRAMMING THE ADO.NET OBJECTS
You can also add multiple elements to the XMLSchema and relate them to one another. Create each element separately and then add the appropriate relationships with the Relation tool.
Figure 22.7 shows the form of a simple application that allows you to populate a DataGrid control and persists the data to a file. It can also read the data from the disk file.
Figure 22.7
The main form of the
XMLGrid project
To persist the data on the grid to a disk file, insert the code of Listing 22.15 in the Persist Data button’s Click event handler. The Read Data button reads the data from the same file and populates the DataGrid control, and the code behind it is shown in Listing 22.16.
Listing 22.15: Persisting DataSets as XML Files
Private Sub Button1_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles Button1.Click
Dim FS As Stream
FS = New FileStream(“C:\GRID.XML”, FileMode.OpenOrCreate)
XmlSchema11.WriteXml(FS)
FS.Close()
End Sub
Listing 22.16: Populating a DataGrid Control with XML Data
Private Sub Button2_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles Button2.Click
Dim FS As Stream
FS = New FileStream(“C:\GRID.XML”, FileMode.Open)
XmlSchema11.Clear()
XmlSchema11.ReadXml(FS)
FS.Close()
End Sub
Copyright ©2002 SYBEX, Inc., Alameda, CA |
www.sybex.com |
SUMMARY 995
You should also import the System.IO namespace, so that you won’t have to fully qualify the FileStream objects. The XMLGrid project demonstrates how to design schemas for your DataSets. You can also create generic DataSets and use them as data-entry tools for many operations.
If you open the GRID.XML file created by this application, you’ll see that it contains XML code. Figure 22.8 shows the XML generated by the data shown in Figure 22.7, opened with Internet Explorer.
Figure 22.8
Viewing an XML file with Internet Explorer
You may wish to explore XML in depth, as it’s one of the hottest topics in the industry today. ADO.NET uses XML to format the data as well as describe the structure of its DataSets, and you can take advantage of this to move DataSets between computers or between applications. You’re actually taking advantage of XML without having to write a single line of XML code.
Summary
You’ve learned a lot about ADO.NET in Chapters 21 and 22, but there’s even more to learn. ADO.NET is one of the most elaborate and complex components of .NET, and it couldn’t be exhausted in two chapters. These chapters were meant to help you familiarize yourself with the visual database tools, understand the structure of a DataSet, learn how to navigate the related tables of the DataSet and the rows of the individual DataTables, and know how to execute commands against the database. You should also be able to improve the code generated by the DataForm wizard and generate more robust and user-friendly applications.
Copyright ©2002 SYBEX, Inc., Alameda, CA |
www.sybex.com |
Part VI
VB.NET on the Web
In this section:
Chapter 23: Introduction to Web Programming
Chapter 24: Accessing Data on the Web
Chapter 25: XML Web Services
Copyright ©2002 SYBEX, Inc., Alameda, CA |
www.sybex.com |
Chapter 23
Introduction to
Web Programming
If there is one technology that caught on overnight and has affected more computer users than any other, it is the World Wide Web—the set of all public Web sites and the documents they can provide to clients. The computers that host Web sites are called servers; their service is to provide the documents to the clients that request them. Clients are the millions of personal computers connected to the Internet. To exploit the Web, all you need is a browser, such as Internet Explorer, that can request documents and render them on your computer.
This chapter is a compendium of information on how to apply the knowledge you acquired in previous chapters to the Web—or, to use a popular term, how to leverage your knowledge of Visual Basic by applying it to the Web. To do so, you need a basic understanding of Hypertext Markup Language (HTML), the language used to build Web documents, and a good understanding of how the clients interact with the servers on the Internet. Building a Web application with Visual Studio is very similar to building a Windows application, but there are many differences you should be aware of.
The Internet is a global, distributed network of computers that use a common protocol to communicate: Transmission Control Protocol/Internet Protocol (TCP/IP). TCP/IP is a simple protocol because it had to be implemented consistently on all computers and operating systems. Indeed, TCP/IP is a truly universal protocol, but you needn’t know much about it. It’s there when you need it and allows your computer to connect to any other computer on the Internet.
If TCP/IP enables any two computers on the Internet to talk to each other, why do we need any other protocol? Hypertext Transfer Protocol (HTTP) is the protocol of the Web. Whereas TCP/IP allows two computers to connect on the hardware level, HTTP is the language servers and clients use to exchange information. HTTP is optimized for requesting and supplying HTML documents. The Internet is more than the Web (although it seems the Web is taking over). To exchange files through the Internet, for example, computers use File Transfer Protocol (FTP). The protocol that is used depends on the type of information to be exchanged. All other protocols, however, run on top of TCP/IP.
Copyright ©2002 SYBEX, Inc., Alameda, CA |
www.sybex.com |
