- •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
1000 Chapter 23 INTRODUCTION TO WEB PROGRAMMING
Tip I need to begin with some basic concepts, such as the components of the Web and the evolution from static Web pages to Web applications. If you’re already familiar with HTML or the Web, bear with us and pick up the discussion when we get to material that’s new to you. If you have a good command of HTML and ASP, you can skip ahead to the section “Building a Web Application.”
An HTML Primer
Hypertext Markup Language (HTML) is the language used to prepare most documents for online publication. HTML documents are also called Web pages; a page is what you see in your browser at any time. Each Web site, whether on the Internet or on an intranet, is composed of multiple related pages on a particular server, and you can switch among pages by following hyperlinks. The collection of public HTML pages out there makes up the World Wide Web.
A Web page is basically a text file that contains the text to be displayed and references to other elements such as images, sounds, and of course, other documents. You can create HTML pages with a text editor such as Notepad or with a “what you see is what you get” (WYSIWYG) application such as Microsoft FrontPage. In either case, the result is a plain text file that computers can easily exchange. The browser displays this text file on the client computer by interpreting part of the text as instructions and presenting the rest as content.
Web pages are stored on computers that act as servers: they provide a page to any computer that requests it. Each server computer has an address, or Uniform Resource Locator (URL), that is something like the following:
http://www.example.com
The first portion, http, is the protocol used in accessing the server, and www.example.com is the name of the server on the Internet. All computers on the Internet have a unique, four-octet numeric address, such as 193.22.103.18. This numeric address is known as the Internet Protocol (IP) address, which is more difficult for us humans to remember than names. The server looks up the mnemonic names in tables and translates them into IP addresses.
To post an HTML document on a computer so that users can access and display it with their browsers, the computer that hosts the document must run a special application called the Web server. The Web server acknowledges requests made by other computers—the client computers—and supplies the requested document. The browser, which is the application running on the client computer, gets the document and displays it on the screen.
HTML Code Elements
The simplest component of the Web is HTML, which is a basic language for formatting documents that are displayed in a Web browser. The primary task of the browser is to render documents according to the HTML instructions they contain and display them on the monitor.
HTML is made up of text-formatting tags that are placed in a pair of angle brackets; they usually appear in pairs. The first, or opening, tag turns on a formatting feature, and the matching closing tag turns it off. To format a few words in bold, for example, enclose them with the <B> and </B> tags, as shown here:
Some <B>words</B> in the sentence are formatted in <B>bold</B>.
Copyright ©2002 SYBEX, Inc., Alameda, CA |
www.sybex.com |
AN HTML PRIMER 1001
Of course, not all tags are as simple. The <TABLE> tag, for example, which is used to format tables, requires additional tags, like the <TR> tag, which delimits a new row in the table, and the <TD> tag, which delimits a new cell in a row.
Tags are also assisted by attributes, which are keywords with special meanings within a specific tag. The <A> or “anchor” tag, which is used to insert a hyperlink in the document, recognizes the HREF attribute. The syntax of a hyperlink to Microsoft’s home page on the Web would be something like:
This <A HREF=”http://www.microsoft.com”>link</A> leads to Microsoft’s home page.
The text between the <A> and </A> tags is marked as a hyperlink (displayed in a different color and underlined). The HREF attribute in the <A> tag tells the browser which URL, or address, to jump to when a user clicks this hyperlink. (For more on attributes, see the section “Attributes” later in this chapter.)
HTML Syntax and XHTML
HTML 4, the last version of the language, was released in 1997. In January 2000, the World Wide Web Consortium (W3C) released XHTML 1 (for Extensible HTML). This standard is a reformulation of HTML to comply with XML syntax rules; it uses almost the same set of tags, but with several restrictions:
HTML 4 code was not case-sensitive; for example, you could enter the opening table tag as <table> or <TABLE>. Lowercase items will work with old or new browsers; but uppercase ones won’t work with future versions, because XML (and therefore XHTML) won’t read them. Note: In this book, I use uppercase for HTML tags, only so that they stand out. The projects on the CD use lowercase for tags.
In HTML 4, attribute values only needed to be quoted in certain circumstances. In XHTML, all attribute values must be in quotation marks.
In HTML 4, some tags didn’t need to be closed; you could enter a <P> paragraph tag, type some text, and start the next paragraph with another <P>, without ever using a closing </P> tag. Browsers just figured it out; they’d “know” that when the new paragraph began, that meant the old one had to end:
<P>This is a paragraph. <P>This is a new paragraph.
In XHTML, every element must be closed. This means that any element that includes content must have paired opening and closing tags.
<p>This is a paragraph.</p> <p>This is a new paragraph.</p>
There are other differences, but these are the important ones during this transition phase from HTML to XHTML. You can learn more about XHTML from books such as Mastering XHTML by Tittel et al. (Sybex, 2001) or from the W3C Web site:
http://www.w3.org/MarkUp/
In addition to the formatting commands (HTML is basically a document-formatting language), HTML can handle a few controls, which are known as HTML controls. These controls include text boxes, radio buttons, check boxes, buttons (specifically, a Submit and a Reset button), and a few
Copyright ©2002 SYBEX, Inc., Alameda, CA |
www.sybex.com |
1002 Chapter 23 INTRODUCTION TO WEB PROGRAMMING
more simple controls. The user can enter data or make selections on these controls and submit them to the server by clicking the Submit button. The Submit button may have any caption, but its function is to submit the data on the various controls on the page to the server by appending them to the server’s URL. The server reads these values, processes them, and prepares a new page, which is downloaded to the client. You’ll find out more about the HTML controls and how they’re submitted to the server later in this chapter.
You’re more than familiar with this interaction model, and it’s no different with ASP.NET. No matter what you do on the server side, it’s the client’s capabilities that determine the structure of the application running on the server. ASP.NET uses this model to interact with the browser. It does a fine job of hiding most of the mundane details and gives you the illusion that you’re writing code for a client that can execute VB applications. But in reality, ASP accepts the values submitted by the client and creates a new HTML file to download to the client.
As a VB programmer, you’ll have no problem picking up the syntax of HTML. It’s a very simple language, and you can pick up the basics as you go along. The visual tools of VB.NET allow you to create HTML documents with point-and-click operations, so a thorough knowledge of HTML is not really required for developing Web applications. However, you need to understand how clients interact with Web servers.
Server-Client Interaction
A Web site consisting of HTML pages is interactive only in the sense that it allows the user to jump from page to page through hyperlinks. The client requests documents from the server, and the server supplies them. In this simple interaction model, which dominates the Web today, Web pages reside on the disks of the servers waiting to be requested by a client. Obviously, updating the information entails editing the HTML documents; no wonder most sites can’t provide up-to-date information. The disadvantage of this model is that the client can’t engage in a conversation with the server so
that information can flow in both directions. The development of gateway interfaces such as the Common Gateway Interface (CGI) has enabled Web authors to add dynamic content to the Web. The client can send specific requests to the server (e.g., “show me the invoices issued last month” or “show me the customers in North America”). The server doesn’t return a static page (a page that exists on the disk and can be called by its name). Instead, it executes a script, or application, that extracts “live” data from a database, formats the data as an HTML document, and sends the document to the client. The client sees up-to-date, accurate information.
The disadvantage of gateway programs is that they are difficult to implement and maintain. To simplify CGI programming, Microsoft introduced several technologies, the most recent and
popular being Active Server Pages (ASP). An Active Server Page is a program (or script), usually written in VBScript, which interacts with the client. ASP scripts can also interact with other components on the server. The clients can’t access a database directly, for example, but an ASP script can. By
passing the proper parameters to the ASP script, an HTML page can request data from the database. The latest version of ASP, ASP.NET, is a greatly improved version of ASP and allows you to write scripts that run on the server in VB.NET. The first advantage of using VB.NET on the server is that the application running on the server is compiled and runs much faster that a script written in VBScript. Actually, you can use any language that runs in the environment of Visual Studio to write an ASP application—you can write Web applications in COBOL, if you wish. There are many more advantages, such as exploiting the features of the IDE.
Copyright ©2002 SYBEX, Inc., Alameda, CA |
www.sybex.com |
AN HTML PRIMER 1003
ASP was limited to the HTML controls. ASP.NET uses a new family of controls, the Web controls. The Web controls exist on the server, and you can program against them, just as you program Windows controls. Your code resides on the server and manipulates Web controls. When it’s time to send a response to the client, ASP.NET translates the Web controls into HTML controls and HTML code, and sends to the client a page that can be rendered by the browser. As you will realize after reading this and the following chapter, ASP.NET abstracts much of the mundane tasks of client/server interaction and makes the process look like programming a Windows application.
I should clarify this point for the benefit of readers who are already familiar with ASP. If you’re new to Web programming, please bear with me. Before you reach the end of this chapter, everything will make perfect sense. With ASP, the browser submits the contents of the controls on the current page to the server when a special button is clicked, the Submit button. This button may be named anything: Go, Show Results, Place Order, whatever. The HTML code of the page uses a Submit button to send the data on the current page to the server (or post the page back to the server, as this process is known).
The ASP script on the server knows the names of the controls on the page and must extract their values from the QueryString property of the Request object. If the page being submitted contains two Text controls, named ProdID and Quantity, it must use the following statements to extract the values on these two controls:
ProductID = Request.QueryString(“ProdID”)
Quantity = Request.QueryString(“Quantity”)
Then, it must process them (retrieve the price of the specified product from a database, multiply it by the quantity ordered, and apply some discount) and create a page to send to the client. The page is created by sending HTML code to the client through the Write method of the Response object:
Response.Write “Thank you for ordering”
Response.Write “Your total is “ & price * Quantity
where price is a variable that holds the product’s price (I’m not showing the code that retrieves this value from the database).
With ASP.NET, you can use the TextBox Web control, which is very similar to the
Windows TextBox control. Let’s say that the names of the two TextBoxes are ProdID and Quantity, and that the form also contains a Label control. To program the application, you double-click the Submit button and insert the following statements in its Click event handler:
Label1.Text = “Thank you for ordering” & vbCrLf
Label1.Text = Label1.Text & “Your total is “ & price * Quantity.Text
This is VB.NET code, which will be compiled and executed on the server. You don’t have to use the Request object to retrieve the values of the TextBox controls, and you don’t have to use the Response object to create a new page. The results of the processing are placed on a Label control on the current form, which is then sent to the client. Obviously, ASP.NET parses the data submitted by the client through the QueryString object and makes them available to your code as control properties.
In short, ASP.NET is a vastly improved version of ASP, abstracting many of the tasks in client/server interaction. It makes the whole process look like a Windows application to the developer, but behind the scenes it generates the HTML that will produce the desired page on the client. This page contains straight HTML code.
Copyright ©2002 SYBEX, Inc., Alameda, CA |
www.sybex.com |