applied ado.net: building data-driven

30
Applied ADO.NET: Building Data-Driven Solutions MAHESH CHAND AND DAVID TALBOT APress Media, LLC

Upload: others

Post on 10-Jun-2022

3 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Applied ADO.NET: Building Data-Driven

Applied ADO.NET: Building Data-Driven

Solutions

MAHESH CHAND AND

DAVID TALBOT

APress Media, LLC

Page 2: Applied ADO.NET: Building Data-Driven

Applied ADO.NET: Building Data-Driven Solutions

Copyright© 2003 by Mahesh Chand and David Talbot Originally published by Apress in 2003

AII rights reserved. No part of this work may be reproduced or transmitted in any form or by any means, electronic or mechanical, including photocopying, recording, or by any information storage or retrieval system, without the prior written permission of the copyright owner and the publisher.

ISBN 978-1-59059-073-7 ISBN 978-1-4302-0759-7 (eBook) DOI 10.1007/978-1-4302-0759-7

Trademarked names may appear in this book. Rather than use a trademark symbol with every occurrence of a trademarked name, we use the names only in an editorial fashion and to the benefit of the trademark owner, with no intention of infringement of the trademark.

Technical Reviewer: Philip Pursglove

Editorial Directors: Dan Appleman, Gary Cornell, Jason Gilmore, Simon Hayes, Karen Watterson, John Zukowski

Managing Editor: Grace Wong

Project Manager: Tracy Brown Collins

Development Editor: Philip Pursglove

Copy Editor: Kim WliDpsett

Compositor: Diana Van Wmkle, Van Wmkle Design Group

Artist and Cover Designer: Kurt Krames

Indexer: Ron Strauss

Production Manager: Kari Brooks

Manufacturing Manager: Tom Debolski

The information in this book is distributed on an "as isn hasis, without warranty. Although every precaution bas been taken in the preparation of this work, neither the author nor Apress shall have any liability to any person or entity with respect to any loss or damage caused or alleged to be caused directly or indirectly by the information contained in this work.

The source code for this book is available to readers at http: //WNW. apress. corn in the Downloads section.

Page 3: Applied ADO.NET: Building Data-Driven

To uncles Bans hi Lal and Rajbir Singh Malik for their support and guidance. -Mahesh Chand

For Nadia whose patience has carried me through this book. -David Talbot

Page 4: Applied ADO.NET: Building Data-Driven

Contents at a Glance

About the Authors ............................................................................................ xxi About the Technical Reviewer ................................................................... xxiii Acknowledgments ................................................................................................. xxv Introduction ..................................................................................................... xxvii

Chapter 1 AOO.NET Basics .................................................................... 1

Chapter 2 Data Components in Visual Studio • NET ....... 33

Chapter 3 AOO.NET in Disconnected Environments ......... 73

Chapter 4 ADO.NET in Connected Environments ............... 135

Chapter 5 Handling ADO. NET Events ......................................... 209

Chapter 6 Integrating XML with ADO.NET ............................. 233

Chapter 7 Data Binding and Windows Forms Data-Bound Controls .................................................... 287

Chapter 8 Constraints and Data Relations ........................ 345

Chapter 9 AOO.NET Exception Handling .................................. 359

Chapter 10 Working with the ODBC • NET Data Provider ....................................................... 375

Chapter 11 Stored Procedures and Views ............................... 393

Chapter 12 Oracle, SQLXML, and Other • NET Data Providers ................................................... .413

Chapter 13 Developing a Custom Data Provider ............... .437

Chapter 14 Developing Database Web Applications Using ASP. NET ....................................... ; ............................ 465

v

Page 5: Applied ADO.NET: Building Data-Driven

Contents at a Glance

Chapter 1.5 Using AOO.NET in XML Web Services ................ 517

Chapter 1.6 ASP. NET Server Controls and Data Binding ............................................................ 537

Chapter 1.7 Building Real-World Web Applications ........ 609

Chapter 1.8 Object-Relational Mapping in .NET ................ 637

Chapter 1.9 Mapped Objects: Performance Considerations and Data Binding ..................... 675

Chapter 20 COM Interoperability and AOO.NET .................. 709

Chapter 21. Messaging .............................................................................. 725

Chapter 22 SQL Server and ADO.NET: Notes on Performance ................................................. 753

Appendix A Relational Databases: Some Basic Concepts .................................................... 779

Appendix B Commonly Used SQL Statements ............................. 793

Appendix C ADO.NET Frequently Asked Questions ............ 811

Index .................................................................................................................... B47

vi

Page 6: Applied ADO.NET: Building Data-Driven

Contents

About the Authors ............................................................................................. xxi About the Technical Reviewer ................................................................... xxiii Acknowledgments ................................................................................................. xxv Introduction ..................................................................................................... xxvii

Chapter 1 ADO.NET Basics ..................................................................... 1

Overview of Microsoft Data Access Technologies ................................. 2 ODBC ...................................................................................... ~ ............................ 2 DA0 ...................................................................................................................... 4 MFC ODBC and DAO Classes ............................................................................ 5 RD0 ...................................................................................................................... 5 OLEDB ................................................................................................................ 5 AD0 ...................................................................................................................... 6 ADO.NET ............................................................................................................. 6

What Is ADO.NET? ................................................................................................ 7 Why ADO.NET Was Designed ............................................................................... 8 Advantages of ADO.NET ..................................................................................... 9

Single Object-Oriented API ............................................................................... 9 Managed Code .................................................................................................. 1 0 XML Support ..................................................................................................... 1 0 Visual Data Components ................................................................................. 11 Performance and Scalability ........................................................................... 11

Comparing ADO. NET and ADO ........................................................................... 11 Connections and Disconnected Data ............................................................. 11 Recordsets vs. DataSets .................................................................................... 12 XML Support ..................................................................................................... 12

Overview of ADO. NET Name spaces and Classes ..................................... 13 Understanding ADO. NET Components ........................................................... 15

The Connection Object .................................................................................... 16 The Command Object ...................................................................................... 17 The Command Builder .................................................................................... 19 The DataAdapter Object .................................................................................. 19 DataSet Structure ............................................................................................. 20 DataSets in Data Views ..................................................................................... 21

vii

Page 7: Applied ADO.NET: Building Data-Driven

Contents

Writing ADO.NET Applications .................................................................... 22 Choosing a .NET Data Provider ....................................................................... 22

Adding Namespace References ....................................................................... 23 Establishing a Connection ............................................................................... 24 Creating a Command or DataAdapter Object ................................................ 25 Filling Data to a DataSet or DataReader Object ............................................. 25 Displaying Data ................................................................................................ 25 Closing the Connection ................................................................................... 26

Creating a Simple ADO.NET Application ................................................ 26 Using a DataSet to Read Data .................................... · ................................ 28

Summary .................................................................................................................. 31

Chapter 2 Data Components in Visual Studio • NET ....... 33

Creating an ADO. NET Project ........................................................................ 33 Using the Server Explorer ........................................................................... 34

Adding a New Connection ............................................................................... 35 Managing and Viewing Data ........................................................................... 36

Using Visual Data Components .................................................................... 37 Understanding Data Connections .................................................................. 38 Understanding Connection Strings ................................................................ 40 Working with SQL DataAdapters ..................................................................... 40

Using DataSet and DataView Components ................................................ 51 Understanding'!YPed DataSets in VS .NET .................................................... 51 Understanding the Data View .......................................................................... 54

Using the Data Form Wizard ........................................................................ 57

Data Form WIZard: Looking under the Hood ................................................. 66 Understanding MyDS.xsd ................................................................................ 67 Understanding DataForml.vb ........................................................................ 67

Summary .................................................................................................................... 71

Chapter 3 AOO.NET in Disconnected Environments ......... 73

Understanding the ADO. NET Architecture ................................................ 75 Exploring the ADO.NET Class Hierarchy ................................................... 76

Choosing a Data Provider ............................................................................... 80

Understanding ADO.NET Disconnected Classes ........................................ 81

The System.Data Namespace .......................................................................... 81 The System.Data.Common Namespace ......................................................... 82

Working with DataTables ................................................................................. 83

The DataColumn .............................................................................................. 85 The DataRow .................................................................................................... 94

viii

Page 8: Applied ADO.NET: Building Data-Driven

Contents

The DataRelation .............................................................................................. 99 The DataTable ................................................................................................. 100 More DataTable Operations .......................................................................... 106 The Row and Column Collections ................................................................ 115

The DataRow States and Versions ................................................................. 117

Using DataSet, DataView, and DataViewManager ............................... 120

The DataSet: The Heart of ADO.NET ............................................................ 121 Typed and Untyped DataSets ........................................................................ 127

The Data View ................................................................................................. 128

The DataViewManager .................................................................................. 132

Summary .................................................................................................................. 133

Chapter 4 ADO.NET in Connected Environments ................ 135

Understanding the Generic Data Provider Model ............................... 135 Importing a Namespace .................................................................................... 137 Exploring the System. SqlClient Name space .......................................... 137

The Connection: Connecting to a Data Source ................................... 139 Creating a Connection ................................................................................... 139

Understanding the Connection Properties and Methods ........................... 140 Opening and Closing a Connection .............................................................. 142

Understanding Connection Pooling ............................................................. 145 Using the CreateCommand and ChangeDatabase Methods ...................... 149

The Command: Executing SQL Statements .............................................. 150 Creating a Command Object ......................................................................... 151 Creating and Using OleDbCommand ........................................................... 153 Using the CommandType Enumeration ...................................................... 154 Calling a Stored Procedure ............................................................................ 155 UsingTableDirect ........................................................................................... 157 Executing a Command ................................................................................... 158 Using Other Command Methods .................................................................. 160

The DataReader: Walking through the Data ........................................ 160 Initializing a DataReader ............................................................................... 161

Understanding DataReader Properties and Methods ................................. 161 Reading with the DataReader ........................................................................ 162

Interpreting Batches of Queries ................................................................. ... 164 Understanding Command Behaviors ........................................................... 165

The DataAdapter: Adapting to Your Environment ............................. 166

Constructing a DataAdapter Object ............................................................. 166 Understanding DataAdapter Properties ....................................................... 168

Understanding DataAdapter Methods ......................................................... 170 Filling the DataSet ...................................................................................... .... 170

Adding a Data Table to a DataSet ................................................................... 172

ix

Page 9: Applied ADO.NET: Building Data-Driven

Contents

Looking at a DataAdapter Example .............................................................. 172 Filling the DataAdapter from a Recordset .................................................... 175 Updating the Database Using the Update Method ..................................... 176 Table and Column Mapping .......................................................................... 178

CommandBuilder: Easing the Work of Programmers ........................... 181 Creating a CommandBuilder Object ............................................................ 182 Using SqlCommandBuilder Members .......................................................... 182 Using SqlCommandBuilder ........................................................................... 182

Staying within the Parameters ................................................................ 184 The DataSet in Connected Environments .............................................. 188

Filling a DataSet from Multiple Tables .......................................................... 188 Using a SQL Statement to Read Data from 1\vo or More Tables ................ 190 Adding, Updating, and Deleting Data through the DataSet ....................... 190 Accepting and Rejecting Changes through the DataSet ............................. 191 Saving Changed Data Only ............................................................................ 192 Using a DataSet vs. Using a DataReader ....................................................... 193 Fetching Data Based on Wildcard Characters .............................................. 194

The DataView in Connected Environments ............................................ 194 Creating Multiple Views ................................................................................. 195 Using Transactions in ADO.NET ................................................................... 200 Using Concurrency in ADO.NET ................................................................... 201 Understanding Rollback, Commit, and Savepoints .................................... 204 Executing Batches .......................................................................................... 206

Summary .................................................................................................................. 208

Chapter 5 Handling ADO.NET Events ......................................... 209

Working with Connection Events ............................................................... 211 Working with DataAdapter Events ........................................................... 215 Working with DataSet Events .................................................................... 220 Working with DataTable Events ................................................................ 221 Working with XmlDataDocument Events ................................................... 226 Working with DataView and DataViewManager Events ...................... 229 Summary .................................................................................................................. 231

Chapter 6 Integrating XML with ADO.NET ............................. 233

Understanding Microsoft • NET and XML ................................................... 233 Using the System.XInl Namespace ............................................................... 234 Using the System.Xml.Schema Namespace ................................................. 235 Using the System.Xml.Serialization Namespace ......................................... 236 Using the System.XmlJ{Path Namespace .................................................... 236

X

Page 10: Applied ADO.NET: Building Data-Driven

Contents

Using the System.xmi.XSl Namespace ......................................................... 236 Using the Document Object Model Interfaces ............................................ 237 Looking at the XML .NET Architecture ......................................................... 237 Adding a System.Xml Namespace Reference ............................................... 238

Reading XML ......................................................................................................... 238 Getting Node Information ............................................................................. 239 Moving to a Content Node ............................................................................. 242 Using the GetAttributes of a Node ................................................................ 243 Searching for a Node ...................................................................................... 244 Closing the Document ................................................................................... 245

Understanding the XmlWriter Classes ................................................... 246 Setting XmlWriter Properties ......................................................................... 247 WritingXMLitems ......................................................................................... 247 Seeing XmlWriter in Action ........................................................................... 248 Using the Close Method ................................................................................. 250

Using the XmlConvert Class ...................................................................... 251 Understanding the OOM Implementation ................................................. 251

Using the XrnlNode Class .............................................................................. 252 Using the XrnlDocument Class ..................................................................... 252 Saving a Document ....................................................................................... 253 Using the XmlDocumentFragment Class ..................................................... 253 Using the XmlElement Class ......................................................................... 254 Adding Attributes to a Node ......................................................................... 259

Understanding Transformation and XSL T .............................................. 260 Using the Transform Method ........................................................................ 261 Looking at an Example ................................................................................... 261

Using ADO.NET and XML Together .............................................................. 262 Reading XML Using a DataSet ....................................................................... 262 Writing XML Using a DataSet ........................................................................ 264 Using XInlDataDocument and XML ............................................................. 267 Displaying XML Data in a DataSet Format ................................................... 270 Saving Data from a DataSet to XML .............................................................. 271 XrnlDataDocument: Looking under the Hood ............................................ 272

Navigating in XML .......................................................................................... 272 Using the XPathNavigator Class .................................................................... 273 Using XPathNavigator Move Methods ......................................................... 274 Searching Using XPathNavigator .................................................................. 276

Working with Schemas .................................................................................... 277 Generating a New Schema ............................................................................. 277 Adding Schema from a Database Objects .................................................... 283 Generating a Typed DataSet from a Schema ................................................ 285

Summary .................................................................................................................. 286

xi

Page 11: Applied ADO.NET: Building Data-Driven

Contents

Chapter 7 Data Binding and Windows Forms Data-Bound Controls .................................................... 287

Understanding Data Binding ...................................................................... 287 Using the Binding Class ................................................................................. 288 Understanding the BindingManagerBase Functionality ............................ 293 Understanding BindingContext .................................................................... 296 Building a Record Navigation System ........................................................... 296

Working with Complex Data-Bound Controls ........................................ 301 The Role of Control Class in Data Binding ................................................... 301 Using the ListControl Class ........................................................................... 301 ListControl DataBinding-Related Events ..................................................... 302 Data Binding in ComboBox and ListBox Controls ...................................... 304 Data Binding in a DataGrid Control ............................................................. 306 Deleting Data Binding .................................................................................... 307

The Data~rid: Super Data-Bound Control ............................................ 307 Understanding the DataGrid Class Members .............................................. 309 Exploring the DataGrid Helper Objects ........................................................ 312 Understanding the DataGrid and DataGrid Column Styles ....................... 313 Seeing DataGridTableStyle and DataGridColumnStyle in Action .............. 321 Seeing HitTest in Action ................................................................................. 324 Implementing Custom Sorting in a DataGrid .............................................. 334 Building a DataGrid Record Navigation System .......................................... 335 Implementing Search in a DataGrid ............................................................. 338 Inserting, Updating, and Deleting Data through DataGrids ...................... 342

Summary .................................................................................................................. 344

Chapter 8 Constraints and Data Relations ........................ 345

Understanding Constraints ........................................................................... 345 Implementing the Constraint Classes .......................................................... 346 Implementing the ForeignKeyConstraint Class ........................................... 346

Understanding Data Relations .................................................................. 353 Understanding the DataRelation and DataRelationCollection Objects ................................................................ 354 Summary .................................................................................................................. 358

Chapter 9 ADO. NET Exception Handling .................................. 359

Why Use Exception Handling? ...................................................................... 360 Using 'Iiy ... Catch Statements ......................................................................... 361 Using 'Iiy ... Catch ... Finally Statements .......................................................... 362

xii

Page 12: Applied ADO.NET: Building Data-Driven

Contents

NestingTry ... Catch Statements ..................................................................... 363 Using Try with Multiple Catch Statements ................................................... 363 Defining Custom Filters and Error Messages ............................................... 364

Understanding the Exception Classes ................................................... 365 Using the Exception Class: Mother of All Exceptions .................................. 365 Understanding Other Exception Classes ...................................................... 366

Exception Handling in ADO.NET ................................................................ 366 Recognizing SQL Server 2000 Errors ............................................................. 368 Using SQL Server Error Logs .......................................................................... 370 Using the SqlException Class ........................................................................ 371 Using the SqlError and SqlErrorCollection Classes ..................................... 373

Summary .................................................................................................................. 374

Chapter 10 Working with the OOBC • NET Data Provider ....................................................... 375

Using the ODBC • NET Data Provider ......................................................... 375 Installing the ODBC .NET Data Provider ...................................................... 376 Understanding the ODBC .NET Data Provider ............................................ 377

Accessing Access Databases ......................................................................... 378 Accessing MySQL Databases ............ ~ .............................................................. 380 Accessing MySQL Databases ........................................................................... 381 Accessing Text File Databases ................................................................ 382

Exporting an Access Table to a Text File ....................................................... 383 Accessing a Text File ....................................................................................... 385

Accessing Excel Databases ......................................................................... 389 Implementing Two • NET 1.1 Updates ......................................................... 391 Sununary .................................................................................................................. 391

Chapter 11 Stored Procedures and Views ............................... 393

Working with Stored Procedures ................................................................ 393 Creating a Stored Procedure .......................................................................... 393 Executing a Stored Procedure from VS .NET ................................................ 397 Executing a Stored Procedure Programmatically ....................................... 399

Understanding SQL Injection ................................................................... .405 Working with Views ........................................................................................ 406

Creating a View ............................................................................................... 406 Executing a View from VS .NET ..................................................................... 409 Retrieving Data from a View Programmatically .......................................... .409 Filling a DataSet from Multiple Views ......................................................... .411

Summary .................................................................................................................. 411

xiii

Page 13: Applied ADO.NET: Building Data-Driven

Contents

Chapter 12 Oracle, SQLXML, and Other . NET Data Providers ................................................... .413

Using Oracle • NET Data Providers .......................................................... .413

Adding a Reference to the Oracle .NET Data Provider ................................ 415

Using the Oracle .NET Data Provider Classes .............................................. 416

Using the SQLXML and SQL XML • NET Data Providers ...................... 426

Using the FOR XML Keyword ........................................................................ 427 Using the SqlXmlAdapter Object .................................................................. 428

Using the SqlXInlParameter Object .............................................................. 429 Using the SqlXInlCommand Object .............................................................. 430

Using a MySQL Database and the • NET Data Provider .................... 435

Summary .................................................................................................................. 435

Chapter 13 Developing a Custom Data Provider ................ 437

Overview of the Data Provider Interfaces .......................................... 438

Understanding the Connection Object ........................................................ 439 Understanding the Command Object .......................................................... 440 Understanding the Reader Object ................................................................ 441 Understanding the Adapter Object ............................................................... 443

Building a Custom Data Provider ........................................................... 446 Creating the PipedDataConnection Object ................................................. 446 Creating the PipedDataCommand Object ................................................... 449 Creating the PipedDataReader Object .......................................................... 453 Creating the PipedDataAdapter Object ........................................................ 460 Testing the PipedDataProvider Application .............................................. .. .462

Debugging Your Custom Data Provider .................................................. .464 Summary .................................................................................................................. 464

Chapter 14 Developing Database Web Applications Using ASP. NET .................................................................... 465

Introducing ASP. NET ........................................................................................ 465

ASP.NET Platform Requirements .................................................................. 466 ASP.NET Language Support ........................................................................... 466 Installing ASP.NET .......................................................................................... 466 ASP.NET Editors .............................................................................................. 466 ASP.NET: An Evolution of ASP ....................................................................... 467 Web Forms and Web Services ........................................................................ 468

xiv

Page 14: Applied ADO.NET: Building Data-Driven

Contents

Developing Your First ASP. NET Web Application ............................. 468

Creating a Web Application Project ............................................................. .469

Adding Web Controls to a Web Form ........................................................... .472

Setting Control Properties ............................................................................. 474

Using Document Outline ............................................................................... 475

Writing Code on the Button Click Event Handler ....................................... .477

Creating Your First ADO.NET Web Application ................................ .478

Using ASP.NET Server-Side Controls .................................................... .480

HTML Server Controls ................................................................................... 481

Validation Controls ........................................................................................ 482

User Controls .................................................................................................. 483

Server Controls and the .NET Framework Library ..................................... .483

Why Are Web Forms Controls Called Server-Side Controls? ...................... .485

Adding Server-Side Controls to a Web Form ............................................... .485

Understanding Data Binding in ASP.NET ............................................. .487

Data-Bound Controls ..................................................................................... 488

Data Grid and DataList Controls .................................................................. .490

Paging in the DataGrid Control .................................................................... .499

Enabling Paging Programmatically ............................................................... 500

Adding, Editing, and Deleting Data in Web Forms ...................................... 502

Adding Data .................................................................................................... 505

Updating Data ................................................................................................ 506

Deleting Data .................................................................................................. 507

Creating a Guest Book in ASP. NET ......................................................... 507

Default Web Form: MyGuestBook.aspx ........................................................ 508

Adding Forms to the Guest Book .................................................................. 511 Compiling and Running the Guest Book Project ......................................... 514

Summary .................................................................................................................. 516

Chapter 15 Using ADO.NET in XML Web Services ................ 517

Exploring Web Services and the .NET Framework Library .............. 518

Creating a Web Service in VS .NET ......................................................... 518

Testing Your Web Service ............................................................................. 521

Creating the Web Service Consumer ....................................................... 524

Adding Data to a Database Through a Web Service ..................................... 529

Adding More Functionality to the Web Service ............................................ 534

Summary .................................................................................................................. 535

XV

Page 15: Applied ADO.NET: Building Data-Driven

Contents

Chapter 16 ASP.NET Server Controls and Data Binding ............................................................ 537

Data Binding in Web Forms, Revisited ................................................. 537 Read-Only Data Binding ................................................................................ 537 Simple and Complex Data Binding ............................................................... 538 The Roles of the Control and Page Classes in Data Binding ....................... 539

Data Binding in Simple Web Forms Controls ...................................... 540 Using the Button Control ............................................................................... 540 Using the Calendar Control ........................................................................... 542 Understanding Web Server Control Templates ............................................ 546 Using the Repeater Control ........................................................................... 552 Understanding the Role of the ListControl Class ........................................ 555 Using the ListBox Control .............................................................................. 556 Using the DropDownList Control ................................................................. 558 Data Binding in Other Simple Controls ........................................................ 560

Data Binding in Complex Web Forms Controls ................................... 562 Understanding the BaseDataList Class ........................................................ 562 Using the DataKeyCollection Class ............................................................... 563 Using the DataListWeb Server Control ........................................................ 564 Using the DataGrid Web Server Control ....................................................... 582

Summary .................................................................................................................. 608

Chapter 17 Building Real-World Web Applications ........ 609

Introducing the Job Board Application Specifications .............. 609 Under.standing the Database Schema ....................................................... 610 Developing the Online Job Board Application ................................. 611

Creating the Login.aspx Page ........................................................................ 612 Creating the Register.aspx Page ..................................................................... 615 Creating the Contact.aspx Page ..................................................................... 617 Creating the PostJob.aspx Page ..................................................................... 618 Creating the PostResume.aspx Page ............................................................. 620 Creating the DisplayData.aspx and Resumes.aspx Pages ........................... 623 Creating the dnjHeader.aspx Page ................................................................ 632 Running the Application ................................................................................ 633

Improving and Modifying the Application ............................................ 635 Summary ................................................................... · ............................................... 636

xvi

Page 16: Applied ADO.NET: Building Data-Driven

Contents

Chapter 18 Object-Relational Mapping in .NET ................ 637

Why Not Just Use a DataSet? ...................................................................... 638

Understanding Object Databases ................................................................ 639

Why Object Relational Mapping? ................................................................ 640

Creating the Basic Design of the Video Store Application ....... 640

Understanding the Basic Architecture .......................................................... 641

Creating the Database Design of the Video Store ........................................ 641

Creating the Data Object ............................................................................... 643

Creating the Mapped Object ......................................................................... 644

Creating the Data Access Component .......................................................... 648

Building the VideoTape Test Case ................................................................. 652

Using the User Component ........................................................................... 654

Creating the User Test Case ........................................................................... 659

Managing Dependencies ............................................................................... 661

Creating the Check In/Check Out Component ........................................... 663

SeeingHowltWorks ....................................................................................... 664

Making Design Tradeoffs ............................................................................. 665

Understanding Logic in Stored Procedures ................................................. 665

Understanding Component Isolation .......................................................... 666

Creating a Workaround on Part of the Problem ........................................... 667

Creating the VideoChecklnCheckOut Test Case .......................................... 670

Summary ................................................................................................................ 673

Chapter 19 Mapped Objects: Performance Considerations and Data Binding ..................... 675

Using Data Binding and Mapped Objects ................................................. 675

Directly Accessing a Bound Object's Properties .......................................... 678 Using Logic with Bound Objects ................................................................... 680

Understanding Problematic Master-Detail Relationships .............. 684

Working with Highly Nested Structures ....................................................... 685

Working with a Much Larger Tree ................................................................. 691

A Final Note on Tree Optimization ............................................................... 693

Working with Large Master-Detail Relationships ........................... 694

Implementing Lazy Loading ......................................................................... 695

Implementing an Incremental Lazy Loading Scheme ................................ 700

Loading the Detail When the Master Is Loaded ........................................... 705

Using a Near-Zero-Impact Caching Mechanism ...................................... 706

Summary .................................................................................................................. 708

xvii

Page 17: Applied ADO.NET: Building Data-Driven

Contents

Chapter 20 COM Interoperability and AOO.NET .................. 709

Exploring the .NET Interop Tools ........................................................... 710 Using Visual Studio .NET ............................................................................... 710 Using the Type Library Importer and Exporter (Tlbimp.exe) ..................... 711 Using the Type Library Exporter (Tlbexp.exe) ............................................. 712

Using the ADO Recordset in ADO. NET ..................................................... 712 Using ADOX with ADO.NET ............................................................................. 716 Accessing OLAP Server Data with ADO.NET .......................................... 718 Summary ................................................................................................................ 724

Chapter 21 Messaging .............................................................................. 725

Introducing Types of Queues ...................................................................... 725 Using User Queues ......................................................................................... 726

Using System Queues ..................................................................................... 726 Installing Message Queuing ...................................................................... 726 Using the System.Messaging Namespace ................................................. 727 Working with Message Queues .................................................................... 729

Using the MessageQueue Properties ............................................................ 729 Managing Queues UsingVS .NET ................................................................. 731 Retrieving Available Queues .......................................................................... 732 Filtering Queues Using MessageQueueCriteria ........................................... 734 Creating and Deleting Message Queues Programmatically ........................ 735

Creating a Sample Application ................................................................ 736 Creating a MessageQueue Instance .............................................................. 738 Setting a Queue's Path .................................................................................... 739 Sending and Receiving Messages .................................................................. 740 Walking Through Simple Messaging Application ........................................ 741

Working with Messages ................................................................................. 745

Creating and Removing Messages ................................................................ 745 Setting Queue and Message Priorities .......................................................... 746

Understanding Transactional Messaging .............................................. 747

Using the MessageQueueTransaction Class ................................................. 747 Creating Transactional Queues ..................................................................... 748 Sending and Receiving Transactional Messages .......................................... 748

Encrypting Messages ...................................................................................... 750 Summary ................................................................................................................ 752

xviii

Page 18: Applied ADO.NET: Building Data-Driven

Contents

Chapter 22 SQL Server and ADO.NET: Notes on Performance ................................................. 753

Improving SQL Server Performance ........................................................... 753

Using Indexes ................................................................................................. 753

Choosing Which Columns to Index .............................................................. 757

Understanding the SQL Server Profiler ........................................................ 758

Optimizing Automatically with the SQL Server Profiler .............................. 760

OptimizingYourTransact-SQL Queries for Performance ........................... 762

Avoiding Excessive Stored Procedure Recompilation ................................. 765

Avoiding Locks ................................................................................................ 766

Designing Your Tables for Optimal Performance ......................................... 766

Checking the Size of Database Pages ............................................................ 767

Understanding Denormalization .................................................................. 768

Understanding the Dangers of Database Design Slippage ......................... 768

Understanding ADO.NET Performance Issues and Using Best Practices ........................................................................... 769

Selecting Data Providers ................................................................................ 769

Writing a Generic Data Access Component ................................................. 770

Choosing a Development Mode: Designer vs. Manual ............................... 775

Retrieving Data: DataReader, XmlReader, and DataSet .............................. 775

Updating a Data Source: Command vs. DataSet ......................................... 776 Saving Data and Using GetChanges ............................................................. 777 Retrieving Data with the SELECT Statement ............................................... 777 Using Stored Procedures ................................................................................ 777 Using Connection Strings and Pooling ......................................................... 777

Summary ................................................................................................................ 778

Appendix A Relational Databases: Some Basic Concepts .................................................... 779

Understanding Normalization ...................................................................... 780

First Normal Form (lNF) ............................................................................... 780

Second Normal Form (2NF) .......................................................................... 782

Third Normal Form (3NF) ............................................................................. 784

Boyce-Codd Normal Form (BCNF) ............................................................... 785

Fourth Normal Form (4NF) ........................................................................... 785

Fifth Normal Form.(SNF or PJ /NF) ............................................................... 786

Introducing Sets, Cursors, and ADO.NET ............................................ 786

xix

Page 19: Applied ADO.NET: Building Data-Driven

Contents

Using Locking ................................................................................................... 788

Isolation Levels ............................................................................................... 788

Locking Modes ................................................................................................ 790

Summary ................................................................................................................ 792

Appendix B Commonly Used SQL Statements ............................. 793

Understanding SQL References .................................................................... 793

Using the SELECT Statement ........................................................................ 796

Using the UPDATE Statement ....................................................................... 802

Using the DELETE Statement ........................................................................ 802

Using the CREATE TABLE Statement ............................................................ 803 Using the DROP TABLE Statement ............................................................... 803 Using the TRUNCATE TABLE Statement ...................................................... 804 Using the INSERT Statement ......................................................................... 805 Using Joins and Aliases .................................................................................. 806

Understanding Views ...................................................................................... 807 Using SQL Server's SELECT • •• FOR XML Clause ...................................... 809 Summary .................................................................................................................. 810

Appendix C ADO.NET Frequently Asked Questions ............. 811

Summary .................................................................................................................. 845

Index .................................................................................................................... 847

XX

Page 20: Applied ADO.NET: Building Data-Driven

About the Authors

Mahesh Chand is a Microsoft .NET consultant, an author, and the founder of C# Corner (www. c-sharpcorner. com), one of the leading online community for .NET (C#, VB .NET, and ASP. NET) developers. He has a master's degree

in computer science and a bachelor's degree in mathe­matics, and he is a Microsoft Certified Professional in VC++. Mahesh is also the author of A Programmer's Guide

toADO.NETin C#(Apress, 2002).

David Talbot has worked in a variety of technologies including television set top boxes, license plate recogni­tion, and scalable Web applications. He has written a number of articles concerning .NET technologies and has

worked in various capacities on three books. He is cur­rently working as a development manager in the New Business Technologies group at FreeMarkets in Pittsburgh, Pennsylvania.

xxi

Page 21: Applied ADO.NET: Building Data-Driven

About the Technical Reviewer

Philip Pursglove is a developer with the Willis Group,

based in Ipswich, United Kingdom. He has worked with

every version ofVisual Basic from 3.0 onward. Philip was

one of the first developers in the UK to gain the Microsoft Certified Application Developer certification; he also

holds the Microsoft Certified Solution Developer certifi­

cation in addition to a degree in business information

systems. Philip writes for Pinnacle Publishing's Hardcore Visual Basic and SQL Server Professional magazines,

and he speaks at user group events in the UK. He maintains a Web site at

www. philippursglove. com and can be reached at phil@philippursglove. com.

xxili

Page 22: Applied ADO.NET: Building Data-Driven

Acknowledgments

FIRST, I wouLD like to thank Karen Watterson at Apress. I couldn't even think about

finishing this book without her timely expert comments and motivation. Second,

as always, project manager Tracy Brown Collins did a great job of managing the

entire project so we could finish it within the time constraints. Without a technical

reviewer, a book could never be published. Philip Pursglove did a good job of

improving the technical aspect of the book. Thanks also to Kim Wimpsett, the

copy editor, and Kari Brooks, the production manager, for their hard work and for

giving the book a professional look.

-Mahesh Chand

I would like to thank Andy Harris for convincing me to write my first book.

-David Talbot

XXV

Page 23: Applied ADO.NET: Building Data-Driven

Introduction

THIS BOOK IS for experienced developers who want to write desktop or Web-based

database applications in .NET. This book assumes you have some prior pro­

gramming knowledge of an object -oriented programming language such as C++,

Java, or Visual Basic; some basic concepts of database programming; and some

experience with previous versions ofVisual Studio (VS). This book also assumes

you know the basic concepts of .NET and how to install it.

The following sections briefly introduce this book's chapters.

Chapter 1: ((ADO.NET Basics}}

This chapter provides you with a high-level overview of ADO.NET. This chapter

covers the basics of ADO. NET, describes its advantages over current data access

technologies, and briefly introduces ADO.NET classes and namespaces. It also

shows you how to use ADO.NET classes and namespaces to write simple database

applications usingVS .NET (VS .NET). Finally, MicrosoftVS .NET provides

tremendous support for writing database applications in no time using its wizards

and utilities. This chapter also briefly introduces ADO. NET components and how

they fit in the model and work together.

Chapter 2: «oata Components in Visual Studio .NETJJ

The Visual Studio .NET (VS .NET) Integrated Development Environment (IDE)

provides design-time support to work with data components. In this chapter,

you'll learn how to use these data components in the VS .NET IDE at design-time

to create database applications. This chapter starts with the Server Explorer, a

useful tool for database applications. You'll focus on developing database applica­

tions quickly using data components in VS .NET without writing a lot of code.

You'll work through a step-by-step tutorial to help you develop and run a project.

The chapter also discusses the Connection, DataAdapter, Command, DataSet, and

DataView components in more detail. After finishing this chapter, you'll have a

good understanding of data components and how to work with them in VS .NET.

xxvii

Page 24: Applied ADO.NET: Building Data-Driven

Introduction

xxviii

Chapter 3: «ADO.NET in Disconnected Environments»

In this chapter, you'll get a broad view of the ADO. NET architecture and the basic building blocks of ADO. NET in a disconnected environment. This chapter plays a major role for later chapters as well. Actually, ADO.NET not only provides a way to work with databases, it also allows you to access various kinds of data sources and even in-memory representations of data. You'll learn how to write database applications without using a database. You'll also explore the System. Data and System.Data.COIIIDon namespace classes. Some of the common data objects covered in this chapter are Data Table, DataColumn, DataRow, and DataSet.

Chapter 4: «ADO.NET in Connected Environments»

This chapter examines ADO.NET functionality in a connected environment, which means you won't be storing data in memory. You'll be reading and storing data in data sources. You access data from a data source and save data back to the data source with the help of a bridge between the application and the data source; in ADO.NET this bridge is a data provider. ADO.NET provides many data providers for working with different data sources to make data access fast, reliable, and easy to use. Each data provider has data components (classes) that let you connect to a data source and read, write, add, delete, and update data. This chapter examines these components and shows how to use Wmdows data-bound controls to bind data with ADO.NET components.

Chapter s: «Handling ADO.NET Events»

Events are useful for notifying you when some action happens to an object. An event can have a method associated with it. Not too many books cover the ADO.NET events in details. This chapter shows you how you can handle events for ADO.NET objects. It covers almo$t every ADO.NET data component event and how to use them in your applications.

Chapter 6: «Integrating XML with ADO.NET»

This chapter begins with the introduction of the classes provided by the .NET Framework library to work with Extensible Markup Language (XML) documents. This chapter discusses how to read from and write to XML documents using the .NET Framework library classes. Mter that it discusses how to navigate through

Page 25: Applied ADO.NET: Building Data-Driven

. Introduction

XML documents. The chapter also discusses XML transformations. In addition,

this chapter covers the relationship between ADO. NET and XML and shows how

to mix them up and use rich ADO.NET database components to display and

manipulate XML data. Finally, this chapter covers the XPathNavigator class,

which navigates XML documents.

Chapter 7: «Data Binding and Windows Forms Data-Bound Controls»

Data-bound controls are not only ease to use, but they also provide many built-in

features that programmers will find useful. This chapter discusses the basics of

data binding and data-bound controls, as well as how to develop interactive

Graphical User Interface (GUI) database applications using these controls in

minimal time and with minimal effort. This chapter covers how to use Windows

controls such as the TextBox, Button, Label, CheckBox, ComboBox, List Box, and DataGrid

controls in the data-binding process and how to write your custom data-bound

applications to navigate through the records of a data source. In this chapter,

you'll learn some data-binding techniques that are hard to find in other

ADO.NET books.

Chapter 8: «constraints and Data Relations»

This chapter discusses constraints and data relations in detail. First, this chapter

starts with a discussion of constraints and how ADO. NET constraint objects

maintain data integrity. The second part of this chapter discusses data relations.

Chapter 9: «ADO.NET Exception Handling»

Exception and error handling is one of the most important parts of writing

reliable and error-prone applications. If you come from a C++ background,

you're probably familiar with different exceptional handling methods such as C++

exceptional handling, structured exceptional handling, and Microsoft Foundation

Classes (MFC) exceptions. If you come from a Visual Basic background, you're

probably familiar with the On Error statement. Besides the exception handling in

previous versions ofVC++ and Visual Basic, .NET i

xxix

Page 26: Applied ADO.NET: Building Data-Driven

Introduction

XXX

mplements exceptions in a different way, and all.NET-supported languages {C# and VB .NET) share the same mechanism. Now Visual Basic developers can enjoy

the same rich exception handling C++ developers have enjoyed. Discussing .NET exception handling is beyond the scope of this book; this chapter concentrates on ADO.NET exception handling classes.

Chapter 10: «working with the ODBC .NET Data Provider''

This chapter discusses the ODBC .NET data provider and how to work with various data sources such as Access, MySQL, Excel, and text using the ODBC data provider.

Chapter 11: «stored Procedures and Views»

Stored procedures and views are another important aspect of database programming. This chapter discusses how you can take advantage ofVS .NET tools to work with these objects.

Chapter 12: «oracle~ SQLXML~ and Other .NET Data Providers»

In this chapter, you'll see some more data providers-specifically, Oracle and SQLXML. In previous chapters, you learned how to work with other data providers, so working with the rest of them is just a piece of cake. All data providers implement a similar class hierarchy model with only a few changes. This chapter concentrates how to work with Oracle databases and how to access SQL Server using SQLXML.

Chapter 13: «Developing a Custom Data Provider»

ADO.NET is an extensible architecture that allows anyone, not just Microsoft, to create data providers for virtually any type of data source. This chapter covers how to create a data provider for pipe-delimited data files, which is a common file format, especially for Unix systems. This data provider plugs in to the ADO.NET architecture and provides all of the things you would expect from a data provider, including the ability to fill a DataSet and bind it to any GUI object.

Page 27: Applied ADO.NET: Building Data-Driven

Introduction

Chapter 14: «Developing Database Applications Using ASP.NETJJ

As the programming world moves toward the Internet these days, it's becoming

important for developers to be able to create Web applications and Web services.

The Microsoft .NET Framework enables you to develop, maintain, and deploy

reliable and high-performance Web applications and Web services. This chapter

starts with an overview of ASP.NET and how to install it, and it then shows how to

develop a simple Web application using VS .NET. Finally, it discusses Web Forms

controls and how to use them. The Web Form's DataGrid control is a useful control

to develop Web-based database applications. You can bind a DataSet to the

DataGrid control as you did for the Windows Form's Data Grid control. This chapter

discusses how to fill data to a DataGrid and how to develop powerful Web-based

database applications using the DataGrid control. It also discusses how to enable

paging in a DataGrid control. Finally, it shows you how to develop an ASP. NET

guest book for your Web site using ASP. NET.

Chapter 15: 11Using ADO. NET in XML Web Services}}

Web services provide a way to run a service on the Web and access its methods

using standard protocols, including Simple Object Access Protocol (SOAP), XML,

Web Service Description Language (WSDL), and Hypertext Transfer Protocol

(HTTP). Technically, a Web service is nothing more than an application that

exposes its interface over the Web to a client who wants to access the service's abil­

ities. The uses of a Web service include validating credit cards, searching for data

in a database, inserting an order into a shopping cart, and updating a guest list.

The sky is the limit on what you can have your Web service do. In the past, Jav­

aBeans, Component Object Model (COM) components, and other, nonstandard

service components handled these services, which required specialized formats or

extra, specialized components to exchange data with the client. But Web services

under .NET run by invoking methods in the service directly through HTTP or

SOAP, so someone wanting to run your Web service from their computer can

simply send an HTTP call to your service, passing the parameters in a standard

Uniform Resource Locator CURL). This chapter shows you how to use ADO.NET in

XML Web services.

xxxi

Page 28: Applied ADO.NET: Building Data-Driven

Introduction

xxxii

Chapter 16: «ASP.NET Server Controls and Data Binding"

Chapter 14 discussed some of the basics of data binding in Web Forms and ASP.NET data-bound controls. You also saw how to use data-bound controls in Web applications. Chapter 15 discussed how to develop data-driven Web services and how to access the functionality implemented in a Web service from Web Forms applications. This chapter extends the information in Chapter 14 and concentrates on the more practical aspect of data binding and Web Forms data­bound controls.

Chapter 17: «Building Real-World Web Applications"

Chapter 14 discussed the basics of ASP.NET and how to write data-driven Web applications using ASP.NET and ADO.NET. Chapter 16 discussed data binding in ASP. NET and ASP. NET server controls and how to use these controls to develop data-bound Web applications. This chapter uses the functionality discussed in those chapters. You'll see how you can write a real-world online job board where candidates can post their resumes, recruiters can post their jobs, recruiters can browse the available resumes, and job hunters can browse and apply for the available jobs online.

Chapter 18: «object-Relational Mapping in .NET"

Object-relational mapping is a commonly desired software architecture element on any platform because of the encapsulation and modeling of data behavior from a relational database into an object. Although you can use XML Schema Document (XSD) files to create objects from data, these objects are not easily extensible in regard to modeling data behavior. The technique discussed in this chapter extends the concept provided by Duwamish7 (a demo application from Microsoft) to create custom-built mapped objects.

Chapter 19: «Mapped Objects: Performance Considerations and Data Binding"

Building on the object-relational concepts discussed in Chapter 18, this chapter deals with the common problems encountered in a mapped system, including performance considerations and how to use data binding. Data binding is the

Page 29: Applied ADO.NET: Building Data-Driven

Introduction

preferred way to work with data in .NET, but you'll need to alter your code slightly when using mapped objects. In addition, performance is always a consideration in creating a scalable system, but often many of the things that improve performance can lead to an unmaintainable system design. In the performance part of the chapter, it discusses common performance problems such as managing large tree structures and balancing the ease of use that lazy loading can provide vs. reducing round trips to the database.

Chapter 20: «coM Interoperability with ADO.NET»

COM has been around for many years and is used by many Wmdows applications. Eventually .NET platform will replace COM, but until then you may need to develop COM components from .NET and access them from unmanaged code, or you may want to use COM components in .NET applications. COM interoperability (also referred to as COM Interop) enables you to use existing COM components in .NET applications or use .NET components in unmanaged code. This chapter shows you how to use ADO and other COM -based data access technologies through COM Interop in your .NET applications.

Chapter 21: «Messaging»

A messaging service is one of the most effective and popular mediums to commu­nicate between two machines. It doesn't matter if you're a high-tech developer, a stockbroker, a high-school student, or a businessperson. In some means, you probably use messaging services. Some of the common messaging services are electronic mail (email), instant messenger services, text messaging via phones, or messaging used in complex distributed applications. This chapter covers mes­saging and its related functionality defined in the .NET Framework Class Library, as well as how to use it in your applications.

Chapter 22: «sQL Server and ADO.NET: Notes on Performance»

Database performance has always been something of a black art consisting largely of obscure tricks. Although there's no single trick that will make your application scale, there are several tricks that can help you identify and address performance problems. This chapter covers those tricks. It also discusses some best practices to make sure you get most out of your code.

xxxiii

Page 30: Applied ADO.NET: Building Data-Driven

Introduction

xxxiv

Appendix A: «Relational Databases: Some Basic Concepts»

Appendix A covers some of the basics of databases, such as locking, cursors, and

normalization.

Appendix 8: ((Commonly Used SQL Statements»

SQL is a vital part of database programming. Appendix B is a quick reference to

SQL statements and shows you how to write various SQL statements.

Appendix C: «ADO.NET Frequently Asked Questions»

This appendix answers some of the commonly asked questions related to ADO.NET.

Most of these questions were originally asked on the discussion forums at C#

Corner (www. c- sharpcorner. com) or other news groups.