- •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
BUILDING A WEB APPLICATION 1021
meant for people who are new to ASP programming, and it should help you understand how clients interact with servers. The interaction model is totally different from the one used in Windows applications, and it’s essential to understand it before you start using the visual tools of Visual Studio to build ASP.NET applications.
Building a Web Application
In this section, you’ll build a Web application similar to the RegisterForm application of the preceding section. The first difference you will note between the two applications is that the new one displays the results on the same page. Typical Web applications don’t let you display new information on the same page that submitted the data to the server (the reason being that it’s much easier to create a new page, rather than reconstruct the page that submitted the request). ASP.NET makes it very easy to display the results of the processing on the same page that invoked the script. The control on which the results are displayed is a Label control, which is initially empty.
Start a new ASP.NET Web Application and name it Register. The project will be created in the Register folder under the Web server’s root folder, which is c:\Inetpub\wwwroot by default. A Web project isn’t compiled to an EXE file that can be executed by double-clicking its icon. You must start Internet Explorer, connect to the Web server where the Web application resides, and open its startup page, which is a file with extension ASPX.
Several items will be added to the Solution Explorer automatically, one of them being the WebForm1 item. This is the equivalent of a Windows form, and it’s the page users will see on their browser. The main pane of the IDE shows the WebForm1.aspx form in design view. You can open the Toolbox and select controls to place on the form. The Toolbox contains two tabs with controls you can use on a Web page: the Web Controls tab and the HTML Controls tab. The Web controls are a superset of the HTML controls, and you’ll hardly ever use the plain HTML controls. You can actually turn any HTML control into a Web control by right-clicking the instance of the control on the form and selecting the Run At Server option.
Designing a WebForm is no different than designing a Windows form: just place controls on the form, size and align them, and set their properties, and you have built the Web application’s user interface. The Web controls don’t have as many properties as their Windows counterparts, but they have many more properties than the HTML controls. One property that’s common to all Web controls is the EnableViewState property, which is True by default. This property determines whether the control’s state is automatically saved during round trips to the server. Leave this property to True so that each time the page is returned to the client, the controls will retain their values. For example, if the user forgets to supply a value to a required field, don’t make them retype everything. The controls will maintain their values, and the user can edit the one that’s in error.
When you work with Web forms, the Toolbox displays the controls of the Web Controls tab. These are the controls you can use on a Web form. In addition to the Web controls, you can also place HTML controls on the form, but there’s no good reason to do so. Web controls provide more properties and are easier to program. Add the appropriate controls to create the page of Figure 23.6. At the bottom of the page is a Label control, where we’ll display the data entered by the user on the form. The Label control is invisible the first time the page is opened, because it has the same background color as the page. You can also set its Visible property to False and turn it back on when you want to display something on the control.
Copyright ©2002 SYBEX, Inc., Alameda, CA |
www.sybex.com |
1022 Chapter 23 INTRODUCTION TO WEB PROGRAMMING
Figure 23.6
This page is similar to the one shown in Figure 23.4, only it was designed with Visual Studio.
When you design a page visually in the IDE, you see a grid and you can align the controls to the grid. The page has a property called pageLayout, which has two settings: GridLayout and FlowLayout. The default setting allows you to position controls anywhere on the form and use the alignment tools of the Format menu. The FlowLayout setting takes you back to plain HTML, where controls are placed next to one another. If you switch to the FlowLayout mode, you won’t be able to precisely position your controls on the form.
Now we must add some code behind the Register button. When this button is clicked, the values entered by the user on the form are submitted to the server. All you have to do is read these values and display them on the Label control at the bottom of the form (the Values label). Our application won’t process the values, but once you know how to read them, you can store them in a database, prepare a new page with the specified settings, and so on. Double-click the button on the form and you will see the declaration of the Click event:
Private Sub Button1_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles Button1.Click
End Sub
This is clearly VB code. With ASP.NET, the code running on the server is no longer VBScript; you can write VB code, which will be compiled and executed as needed. The Click event of the Button1 control isn’t fired when the user clicks the button on his browser. It will be fired when a request from this page arrives to the server. ASP.NET simply lets you program the Click event of the Button Web
Copyright ©2002 SYBEX, Inc., Alameda, CA |
www.sybex.com |
BUILDING A WEB APPLICATION 1023
control as if it were a Windows Button control. Insert the statements of Listing 23.4 in the Click event handler, which will display the parameter values on a Label control. The Label control is another Web control that can render HTML code.
Listing 23.4: Displaying the Parameters Passed to the WebForm
Private Sub Button1_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles Button1.Click Values.Text = “LAST NAME “ & txtLName.Text
Values.Text = Values.Text & “<BR>” & “FIRST NAME “ & txtFName.Text Values.Text = Values.Text & “<BR>” & “EMAIL “ & txtEMail.Text Values.Text = Values.Text & “<BR>” & “COMPUTER “ & _
radioHardware.SelectedItem.ToString Values.Text = Values.Text & “<BR>” & “BROWSER “ & _
radioBrowser.SelectedItem.ToString Dim i As Integer
Values.Text = Values.Text & “<BR><B>Preferences</B>” For i = 0 To chkView.Items.Count - 1
If chkView.Items(i).Selected Then
Values.Text = Values.Text & “<BR>” & chkView.Items(i).Value.ToString End If
Next End Sub
As you can see, this is straight Visual Basic (and it could have been any other language running in the Visual Studio environment, from C# to COBOL and FORTRAN). You’re programming Web pages as if they were Windows forms. Of course, this is an illusion. Let’s see what’s sent down to the client. Press F5 to run the application, and Internet Explorer will pop up showing the page you designed. Before filling out the form, open the View menu and select Source. The page’s source code will be displayed on Notepad. I will not repeat the code here, but it’s plain HTML code that describes the contents of the page. The first TextBox control is inserted on the page with the following tag:
<INPUT NAME=”txtLast” TYPE=”text” ID=”txtLast” TABINDEX=”1” STYLE=”z-index: 102; left: 120px; position: absolute; top: 12px” />
The TABINDEX attribute determines the position of the control in the Tab order (some browsers may not interpret this attribute) and the STYLE attribute determines the dimensions and position of the control.
Enter values on the controls and click the Register button. The form will be submitted to the server, where the VB code will prepare the new page. The new page isn’t created from scratch. The code will send out the same page, but this time the Label control at the bottom of the form will contain the values submitted to the server.
If you view the new page’s source code, the tag of the first TextBox has become:
<INPUT NAME=”txtLast” TYPE=”text” VALUE=”Doe” ID=”txtLast” TABINDEX=”1” STYLE=”z-index: 102; left: 120px; position: absolute; top: 12px” />
Copyright ©2002 SYBEX, Inc., Alameda, CA |
www.sybex.com |
1024 Chapter 23 INTRODUCTION TO WEB PROGRAMMING
The only difference is that the VALUE attribute was added. This is what the EnableViewState property does: it causes the various controls to retain their values when a page is updated. If you refresh the page by pressing F5, the controls will be reset to their initial values.
Interacting with a Web Application
Here’s what goes on when a Web application is executed. The first time a user connects to the server and requests the application’s startup Web page, the VB code is compiled—that’s why it takes several seconds for the page to be displayed. The compilation won’t take place in subsequent requests. VB generates a new class that handles the interaction with the browser. This class reads the parameter values sent by the browser along with the request, processes them, and emits HTML code, which is sent to the client. You can create a new page and send it to the client, or you can change the values of the controls on the same page. This model of client/server interaction is closer to a Windows application. With ASP, it was easier to generate a new page with the results, rather than add a few more elements on the same page. The reason was that programmers had to generate all the elements of the current page from within their script and then add the new elements—and of course, it was simpler to create a new page with the new elements only. If this were a Windows application, you wouldn’t display the results on a different form. Why do it with Web applications? It’s a subtle departure from the traditional Web model, and it doesn’t cost you anything. It’s all done by the class that handles the request, and this class is generated and compiled on-the-fly; it doesn’t even appear in the Solution Explorer.
Building a Web application is, in many ways, similar to building a Windows application. Of course, you should be aware of the limitations of the Web and not expect that a Web application will have the same capabilities and responsiveness as a Windows application. You should also keep in mind that the Web application’s code runs on the server and “sees” the values of the controls only when the client submits them (that is, when the user clicks a button that submits the form to the server). While the form is open on the client’s browser, the application doesn’t even execute on the server. This is probably the most important difference between Web and Windows applications: the Web application isn’t running at all times on the server. It starts every time the client submits a request to the server. It runs for a second (or many seconds), generates a new page, and then terminates. It doesn’t remain inactive; it simply dies when it’s done. And this raises the following question: what if we want to maintain the values of some variables between consecutive invocations of the server application?
This is a good point at which to overview the structure of Web applications. A Web application consists of a Web form (or multiple Web forms, as you will soon see). Each Web form consists of HTML tags and VB statements. The HTML part of the page is transmitted as is to the client, where it’s rendered by the browser. In the context of this book, the HTML part is the form on which users enter data—I’m assuming another member of the team is responsible for generating a pretty page.
Another way to look at a Web application is to think of it as a Windows application written in VB, which is executing in the browser. The application’s code is executed on the server, of course, but the application’s interface is displayed on the browser. This is the very essence of a Web application: a visually rich application that appears to be executing in the browser.
Why execute an application in the environment of the browser? First, it’s the simplest type of application to install—you don’t install it. To use it, you just enter a URL in the browser’s Address
Copyright ©2002 SYBEX, Inc., Alameda, CA |
www.sybex.com |
