- •Preface
- •Who Should Read This Book
- •Organization and Presentation
- •Contacting the Authors
- •Acknowledgments
- •Contents
- •Introduction
- •Why Microsoft .NET?
- •The Microsoft .NET Architecture
- •Internet Standards
- •The Evolution of ASP
- •The Benefits of ASP.NET
- •What Is .NET?
- •.NET Experiences
- •.NET Clients
- •.NET Services
- •.NET Servers
- •Review
- •Quiz Yourself
- •Installation Requirements
- •Installing ASP.NET and ADO.NET
- •Installing the .NET Framework SDK
- •Testing Your Installation
- •Support for .NET
- •Review
- •Quiz Yourself
- •Designing a Database
- •Normalization of Data
- •Security Considerations
- •Review
- •Quiz Yourself
- •Creating a Database
- •Creating SQL Server Tables
- •Creating a View
- •Creating a Stored Procedure
- •Creating a Trigger
- •Review
- •Quiz Yourself
- •INSERT Statements
- •DELETE Statements
- •UPDATE Statements
- •SELECT Statements
- •Review
- •Quiz Yourself
- •The XML Design Specs
- •The Structure of XML Documents
- •XML Syntax
- •XML and the .NET Framework
- •Review
- •Quiz Yourself
- •ASP.NET Events
- •Page Directives
- •Namespaces
- •Choosing a Language
- •Review
- •Quiz Yourself
- •Introducing HTML Controls
- •Using HTML controls
- •How HTML controls work
- •Intrinsic HTML controls
- •HTML Control Events
- •The Page_OnLoad event
- •Custom event handlers
- •Review
- •Quiz Yourself
- •Intrinsic Controls
- •Using intrinsic controls
- •Handling intrinsic Web control events
- •List Controls
- •Rich Controls
- •Review
- •Quiz Yourself
- •Creating a User Control
- •Adding User Control Properties
- •Writing Custom Control Methods
- •Implementing User Control Events
- •Review
- •Quiz Yourself
- •Common Aspects of Validation Controls
- •Display property
- •Type Property
- •Operator Property
- •Using Validation Controls
- •RequiredFieldValidator
- •RegularExpressionValidator
- •CompareValidator
- •RangeValidator
- •CustomValidator
- •ValidationSummaryx
- •Review
- •Quiz Yourself
- •Maintaining State Out of Process for Scalability
- •No More Cookies but Plenty of Milk!
- •Out of Process State Management
- •Review
- •Quiz Yourself
- •Introducing the Key Security Mechanisms
- •Web.config and Security
- •Special identities
- •Using request types to limit access
- •New Tricks for Forms-based Authentication
- •Using the Passport Authentication Provider
- •Review
- •Quiz Yourself
- •ASP.NET Updates to the ASP Response Model
- •Caching with ASP.NET
- •Page Output Caching
- •Absolute cache expiration
- •Sliding cache expiration
- •Fragment Caching
- •Page Data Caching
- •Expiration
- •File and Key Dependency and Scavenging
- •Review
- •Quiz Yourself
- •A Brief History of Microsoft Data Access
- •Differences between ADO and ADO.NET
- •Transmission formats
- •Connected versus disconnected datasets
- •COM marshaling versus text-based data transmission
- •Variant versus strongly typed data
- •Data schema
- •ADO.NET Managed Provider Versus SQL Managed Provider
- •Review
- •Quiz Yourself
- •Review
- •Quiz Yourself
- •Creating a Connection
- •Opening a Connection
- •Using Transactions
- •Review
- •Quiz Yourself
- •Building a Command
- •Connection property
- •CommandText property
- •CommandType property
- •CommandTimeout property
- •Appending parameters
- •Executing a Command
- •ExecuteNonQuery method
- •Prepare method
- •ExecuteReader method
- •Review
- •Quiz Yourself
- •Introducing DataReaders
- •Using DataReader Properties
- •Item property
- •FieldCount property
- •IsClosed property
- •RecordsAffected property
- •Using DataReader Methods
- •Read method
- •GetValue method
- •Get[Data Type] methods
- •GetOrdinal method
- •GetName method
- •Close method
- •Review
- •Quiz Yourself
- •Constructing a DataAdapter Object
- •SelectCommand property
- •UpdateCommand, DeleteCommand, and InsertCommand properties
- •Fill method
- •Update method
- •Dispose method
- •Using DataSet Objects
- •DataSetName property
- •CaseSensitive property
- •Review
- •Quiz Yourself
- •Constructing a DataSet
- •Tables property
- •TablesCollection Object
- •Count property
- •Item property
- •Contains method
- •CanRemove method
- •Remove method
- •Add method
- •DataTable Objects
- •CaseSensitive property
- •ChildRelations property
- •Columns property
- •Constraints property
- •DataSet property
- •DefaultView property
- •ParentRelations property
- •PrimaryKey property
- •Rows property
- •Dispose method
- •NewRow method
- •Review
- •Quiz Yourself
- •What Is Data Binding?
- •Binding to Arrays and Extended Object Types
- •Binding to Database Data
- •Binding to XML
- •TreeView Control
- •Implement the TreeView server control
- •Review
- •Quiz Yourself
- •DataGrid Control Basics
- •Binding a set of data to a DataGrid control
- •Formatting the output of a DataGrid control
- •Master/Detail Relationships with the DataGrid Control
- •Populating the Master control
- •Filtering the detail listing
- •Review
- •QUIZ YOURSELF
- •Updating Your Data
- •Handling the OnEditCommand Event
- •Handling the OnCancelCommand Event
- •Handling the OnUpdateCommand Event
- •Checking that the user input has been validated
- •Executing the update process
- •Deleting Data with the OnDeleteCommand Event
- •Sorting Columns with the DataGrid Control
- •Review
- •Quiz Yourself
- •What Is Data Shaping?
- •Why Shape Your Data?
- •DataSet Object
- •Shaping Data with the Relations Method
- •Review
- •Quiz Yourself
- •OLEDBError Object Description
- •OLEDBError Object Properties
- •OLEDBError Object Methods
- •OLEDBException Properties
- •Writing Errors to the Event Log
- •Review
- •Quiz Yourself
- •Introducing SOAP
- •Accessing Remote Data with SOAP
- •SOAP Discovery (DISCO)
- •Web Service Description Language (WSDL)
- •Using SOAP with ASP.NET
- •Review
- •Quiz Yourself
- •Developing a Web Service
- •Consuming a Web Service
- •Review
- •Quiz Yourself
- •ASP and ASP.NET Compatibility
- •Scripting language limitations
- •Rendering HTML page elements
- •Using script blocks
- •Syntax differences and language modifications
- •Running ASP Pages under Microsoft.NET
- •Using VB6 Components with ASP.NET
- •Review
- •Quiz Yourself
- •Preparing a Migration Path
- •ADO and ADO.NET Compatibility
- •Running ADO under ASP.NET
- •Early Binding ADO COM Objects in ASP.NET
- •Review
- •Quiz Yourself
- •Answers to Part Reviews
- •Friday Evening Review Answers
- •Saturday Morning Review Answers
- •Saturday Afternoon Review Answers
- •Saturday Evening Review Answers
- •Sunday Morning Review Answers
- •Sunday Afternoon Review Answers
- •What’s on the CD-ROM
- •System Requirements
- •Using the CD with Windows
- •What’s on the CD
- •The Software Directory
- •Troubleshooting
- •ADO.NET Class Descriptions
- •Coding Differences in ASP and ASP.NET
- •Retrieving a Table from a Database
- •Displaying a Table from a Database
- •Variable Declarations
- •Statements
- •Comments
- •Indexed Property Access
- •Using Arrays
- •Initializing Variables
- •If Statements
- •Case Statements
- •For Loops
- •While Loops
- •String Concatenation
- •Error Handling
- •Conversion of Variable Types
- •Index
170 |
Saturday Evening |
time-consuming process. Connection pooling is effectively a method of improving performance when a Web server is regularly accessed.
Creating a Connection
With ADO, ADO.NET’s predecessor, you, as the developer, could create Connection objects explicitly or through another object such as a Command object. That is no longer the case. With ADO.NET you must explicitly open your connections using one of its constructors.
Some developers might be taken aback by this feature, however, we recommend that developers create their connection objects explicitly for two reasons: (1) the code is easier to maintain and (2) connection pooling can be utilized.
In order to use the OLEDB Managed Provider objects, such as OleDbConnection, OleDbCommand, and so on, you need to include the OleDb namespace in your ASP.NET page. To do this, you use the Import construct at the top of your ASP.NET page:
<%@ Import Namespace=”System.Data.OleDb” %>
For all you Visual Basic programmers out there, using a namespace is like adding a Reference to your project.
Note
Table 17-1 lists the various namespaces you are likely to use in order to access the ADO.NET objects.
Table 17-1 Namespaces Used to Access ADO.NET Objects
Namespace |
Contains |
System.Data |
ADO.NET base objects |
|
|
System.Data.OleDb |
Managed OLDDB data store objects |
|
|
System.Data.SqlClient |
SQL Server-specific implementation |
|
of the ADO.NET objects |
|
|
System.Data.SqlTypes |
SQL Server data types |
|
|
Now you’re ready to create your connection object. In the following code, we’ve used VB to create a connection object called oConn:
<%@ Import Namespace=”System.Data.OleDb” %> <script language=”VB” runat=”server”>
Dim oConn As New OleDbConnection </script>
The ADO.NET Connection objects, OleDb and Sql, have several constructors. A constructor is essentially the syntax you use to instantiate an object. Any given object can have several constructors, like the Connection objects, or no constructors, like the DataReader objects,
Session 17—Opening a Connection |
171 |
which need to be instantiated or created by another object. In the previous code snippet, we demonstrated the use of the OleDbConnection’s default constructor that does not accept any parameters. The Connection objects have another constructor that accepts a connection string as its only parameter.
If you think back to your telephone analogy, what we have done thus far is pick up the telephone. Now that you have picked up the phone, it’s time to make a call or open a connection.
Opening a Connection
In order to open a connection to a data source, you need to know a little about the database. Kind of like making a phone call, you need to have a phone number. When opening a connection, you need to supply several pieces of information depending on the Relational Database Management System (RDBMS) you are using. Some of these pieces of information could be server name or IP address, database name, user name, and password. With this crucial information, you will construct a connection string that is effectively a collection of name/value pairs, separated by semicolons, which tell the Connection object how to connect to your database. The information that you use to construct your connection string will vary depending on the type of database to which you are trying to connect. Table 17-2 lists some of the most common parameters you will use to build a connection string.
Table 17-2 Parameters Used to Construct a Connection String
Parameter |
Description |
Provider |
The OLEDB provider used to access the database. |
|
|
Data Source |
The IP address or name of the server on which the database resides. |
|
|
Database |
The name of the database to be used once the connection is open. |
|
|
User ID |
The user ID for the account used to access the database. |
|
|
Password |
The password for the account used to access the database. |
|
|
All of the parameters listed in Table 17-2 are optional with the exception of the Provider parameter.
Here is a snippet of code that opens, using the OleDbConnection object’s Open method, a connection to a SQL Server database named “Music” that is located on my local machine:
<%@ Page LANGUAGE=”VB”%>
<%@ Import Namespace=”System.Data” %>
<%@ Import Namespace=”System.Data.OleDB” %> <SCRIPT LANGUAGE=”VB” RUNAT=”server”>
Sub Page_Load(Sender As Object, E As EventArgs) Dim oConn As OleDBConnection
Dim sConnString As String
sConnString = “Provider=SQLOLEDB;Data Source=(local);Initial Catalog=Music;User ID=music;Password=music”
172 |
Saturday Evening |
oConn = New OleDBConnection(sConnString) oConn.Open()
oConn.Close() End Sub </SCRIPT> <HTML>
<BODY>
Opening a Connection! </BODY>
</HTML>
Note
In the previous code listing, the connection string, sConnString, contains a user ID/password combination. You may need to alter the user ID/password combination to get the code to run successfully on your computer.
We constructed a string, sConnString, that we passed to the connection’s Open() method. The Open() method in turn parses this string and attempts to open a connection to the database. The Open() method is equivalent to an operator in our telephone analogy. The operator takes the phone number you dial and attempts to place the call. The connection string contains several very important pieces of information including Provider, Data Source, Initial Catalog, User ID, and Password. The Provider specifies which method you are using to connect to the database, the Data Source indicates on which server your database resides, the Initial Catalog represents the name of the database you are attempting to access, and the User ID and Password are the credentials you need to pass to the RDBMS in order to gain access. The OleDbConnection object actually has a read-only property for each of these pieces of information. So, you can easily gather a connection’s settings using these properties as shown in Listing 17-1.
Listing 17-1 Inspecting a Connection’s Properties
<%@ Page Language=”VB” debug=”true” %> <%@ Import Namespace=”System.Data” %>
<%@ Import Namespace=”System.Data.OleDb” %> <SCRIPT LANGUAGE=”VB” RUNAT=”server”>
Sub Page_Load(Sender As Object, E As EventArgs) Dim oConn As New OleDbConnection
Dim sConnString As String
sConnString = “Provider=SQLOLEDB;Data Source=(local);Initial
Catalog=Music;User ID=music;Password=music”
With oConn
.ConnectionString = sConnString
.Open()
Response.Write(.Provider & “<BR>”)
Response.Write(.DataSource & “<BR>”)
.Close()
End With
End Sub
Session 17—Opening a Connection |
173 |
</SCRIPT>
<HTML>
<BODY>
Opening a Connection! </BODY>
</HTML>
Let’s talk about the Provider property for a second. There are actually several ways to connect to a database in the Microsoft world. You can use OLEDB or you can use ODBC. What’s the difference? The major difference, from a developer’s viewpoint, is performance. OLEDB communicates directly with the data source whereas ODBC, in most instances, must go through the OLEDB provider for ODBC in order to access the data source. So, OLEDB provides a little better performance.
In the previous examples, we used OLEDB. When accessing a database via OLEDB, a data source-specific provider needs to be specified via the Provider property. Because, in our examples, we were accessing a SQL Server database, we used the SQLOLEDB provider. To obtain a provider for the data source you need to access, try contacting the product’s vendor or Microsoft. The most common providers, for example Oracle, SQL Server, and Microsoft Access, are readily available.
Connecting to a database via ODBC and ADO is very simple. You simply create a data source name (DSN) on the server from which you are accessing the data source and then add a “DSN=value” name/value pair to your connection string.
Creating a DSN is fairly straightforward and well documented. For details see www.15seconds.com or www.4guysfromrolla.com.
Note
However, it’s not quite as simple with ADO.NET. You cannot connect to a database via ODBC directly with the OleDbConnection or SqlConnection objects. As a matter of fact, you can’t use the SqlConnection to a database via ODBC at all. The .NET SQL Server data provider uses its own protocol to communicate with SQL Server therefore it does not support the use of an ODBC DSN because it does not add an ODBC layer. You can use the .NET OleDb data provider in conjunction with a Universal DataLink (UDL) file to connect to a database via ODBC; however, this is not the approach we recommend. To this point, we have neglected to mention a third .NET data provider, ODBC. To access the ODBC data provider, use the following namespace:
System.Data.ODBC
You may need to download the .NET update that includes the ODBC data provider from www.microsoft.com.
Note
Suppose you’ve created a DSN to a Music database, named “Bands.” To access the database via ODBC, you would use the following code: