- •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
Session 26—Handling ADO.NET Errors |
265 |
End Sub
Function GetRecords() As DataSet Try
Dim connection as New OleDBConnection(txtConnStr.Text)
Dim command as New OleDBDataAdapter(txtSQLStr.Text, connection) Dim dataset As New DataSet()
command.Fill(dataset, “dataset”) Return dataset
Catch myException as OLEDBException OLEDBErrorHandler(myException)
End Try End Function
The GetRecords() function pulls the connection string from a textbox txtConnStr and the SQL statement from a textbox txtSQLstr. Next it attempts to fill the dataset and then return it. Whenever an error occurs in the ADO.NET Adapter, for instance if the password or server is invalid, or an incorrect statement is encountered in the SQL statement, then an exception is thrown. Using the Try . . . Catch statement, you can catch the OLEDBException and then begin the process of handling and evaluating the errors collection that it contains. This is a much more convenient solution than we had in ASP for capturing and passing a collection of errors. The ability for the OLEDBException class to act as a wrapper for the OLEDBErrors collection, makes passing the collection to a generic error handler much more simple.
In the next section, we will expand on the above code example and build an OLEDBErrorHandler() function in order to examine the ways that we can evaluate the errors collection.
OLEDBError Object Description
You can sort through the OLEDBException object to work with each of the OLEDBError objects it wraps. The OLEDBError class is created by the OleDBDataAdapter whenever an error occurs in connecting to or executing against a datasource. For each error encountered by the OleDBDataAdapter, a new OLEDBError object is instantiated and added to the OLEDBErrors collection, which is then wrapped by the OLEDBException class and instantiated as an object.
Listing 26-2, extends Listing 26-1 to illustrate how the OLEDBException object is passed to a generic error handler function OLEDBErrorHandler. The function can then process the errors collection. First, we dynamically add a label to the bottom of the page so that we can display the list of error messages. We will use the label to hold the text of our
OLEDBException and OLEDBError properties.
Listing 26-2 Passing an OLEDBException to an error handler
Function OLEDBErrorHandler(ByVal myException as OLEDBException)
Dim sMess as String
Dim oLabel as new Label()
Dim eItem as OLEDBError
‘Add a label to the page dynamically to show errors
Continued
266 |
Sunday Morning |
Listing 26-2 |
Continued |
oLabel.Text = “” oLabel.Id=”OleDBLabel”
Page.Controls.Add(new LiteralControl(“<hr>”)) Page.Controls.Add(oLabel)
‘Loop throught the Errors in OLEDBException
sMess=sMess & “<p><b>Database Error” & myException.ErrorCode.ToString() &” Occurred: “ & myException.Message &”</b></p>”
sMess=sMess & “<p>StackTrace: “ & myException.StackTrace.ToString()
&”</p>”
sMess=sMess & “<p>TargetSite: “ & myException.TargetSite.ToString()
&”</p>”
For each eItem in myException.Errors sMess=sMess & “<ul>”
sMess = sMess &”<li>Error Message: “ & eItem.Message & “</li>” sMess = sMess &”<li>Source of Error: “ & eItem.Source & “</li>” sMess = sMess &”<li>Native Error Id: “ &
eItem.NativeError.ToString() & “</li>”
sMess = sMess &”<li>SQL State: “ & eItem.SQLState & “</li>” sMess=sMess & “</ul>”
oLabel.Text = oLabel.Text & sMess
Next WriteEvent(myException)
End Function
This function works by defining a variable, eItem as an OLEDBError object. You can then use a For . . . Each . . . Next loop to iterate through the collection, and process each error respectively. The results of this process can be seen in Figure 26-1.
Figure 26-1 Example of handling the OLEDBErrors collection
Session 26—Handling ADO.NET Errors |
267 |
Now the OLEDBError object properties can be accessed and displayed. We will cover these properties in the next section.
OLEDBError Object Properties
In Listing 26-1, we displayed each of the OLEDBError properties on the label by adding them consecutively to the sMess string variable. We then displayed the results on the runtime generated label control. Let’s take a quick review of each of these properties and see what type of information that they provide:
The Message property provides a short description of the error that was generated. In Figure 26-1 you can see that we attempted to include an invalid column create_error in the SQL Statement. The Message property generates a clear description of the error, Invalid column name ‘create_error’.
The NativeError property enables you to obtain the database-specific error information typically in the form of a code that you can utilize to reference the database technical manuals. Only as a last resort do you want to be utilizing these codes for troubleshooting!
The Source property retrieves the name of the object that generated the error. In Figure 26-1 you can determine that we were using the OLEDB provider and connecting to a SQL Server Database.
The SQLState property gets the five-character error code following the ANSI SQL standard for the database. The character string value returned for an SQLSTATE consists of a two-character class value followed by a three-character subclass value. A class value of 01 indicates a warning and is accompanied by a return code of SQL_SUCCESS_WITH_INFO. Class values other than 01, except for the class IM, indicate an error and are accompanied by a return value of SQL_ERROR. The class IM is specific to warnings and errors that derive from the implementation of ODBC itself. The subclass value 000 in any class indicates that there is no subclass for that SQLSTATE. The assignment of class and subclass values is defined by SQL-92. The specific references and descriptions for these values can be identified by referencing the provider documentation. In Figure 26-1, we were provided a SQLState code of 42S22, which maps to an error description of Column not found.
OLEDBError Object Methods
The methods of the OLEDBError object are the same as the other ASP.NET equivalents.
The Equals() method (inherited from object) determines whether the specified object is the same instance as the current object.
The GetHashCode() method (inherited from object) serves as a hash function for a particular type, suitable for use in hashing algorithms and data structures like a hash table.
The GetType() method (inherited from object) gets the type of the object.
268 |
Sunday Morning |
The ToString() method provides a conversion to string method.
The Finalize() method (inherited from object) enables the object to attempt to free resources and perform other cleanup operations before the object is reclaimed by the Garbage Collector (GC). This method may be ignored by the Common Language Runtime; therefore, necessary cleanup operations should be done elsewhere.
MemberwiseClone (inherited from object) creates a shallow copy of the current object.
OLEDBException Properties
The OLEDBException class wraps the OLEDBErrors collection, and as such draws much of the values for its properties from the underlying collection of OLEDBError objects. For instance, the values stored in the Source and Message properties are exactly the same as that of the first OLEDBError object stored in the OLEDBErrors collection. Let’s look at each property to evaluate how it can be used to garner additional information about the error.
The ErrorCode property (inherited from ExternalException) provides the error identification number (HResult) of the error generated by the first OLEDBError object, the property is read-only, and can be useful for researching the cause of the error.
The Errors property contains the OLEDBErrors collection and captures all errors generated by the OleDB data adapter. This is the most frequently used property, and the one that allows you to cycle through all the errors generated by the OleDB data adapter.
The HelpLink property (inherited from Exception) indicates a link to the help file associated with this exception, and is read-only. Typically in the case of the OLEDBErrors collection, this property will be emptied; it is more commonly
used with the generic Exception object when errors are raised specifically by the application.
The InnerException property (inherited from Exception) retrieves a reference to an inner (that may be nested) exception.
The Message property is simply a copy of the message contained in the first OLEDBError of the Errors collection.
The Source property is simply a copy of the source property contained in the first OLEDBError of the Errors collection.
The StackTrace property (inherited from Exception) indicates the stack trace as a text string, which is valuable for determining where the error occurred. This property allows you to follow from the lowest child in the hierarchy to the originating function, which initiated the call that established the error. Figure 26-1 shows that by reviewing the StackTrace property you can identify that the original call that created the error was in ASP.default_aspx.GetRecords(), indicating the default.aspx page and the GetRecords() function.
The TargetSite property (inherited from Exception) indicates the method that threw this exception. This property is read-only.