Distributed Data Applications with ASP.NET, Second Edition

ALEX HOMER AND DAVID SUSSMAN

APress Media, LLC Distributed Data Applications with ASP.NET, Second Edition Copyright © 2004 by Alex Homer and David Sussman Originally published by Apress in 2004

AlI 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-318-9 ISBN 978-1-4302-0661-3 (eBook) DOI 10.1007/978-1-4302-0661-3

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 Reviewers: Dan Green, John Godfrey, Maxime Bombardier, Christian Holm, Jeffrey Hasan, Paul Churchill, Phil Powers-De George, Fredrik Normen, Christophe Nasarre, Andrew Stopford, Larry Schoeneman, Sophie McQueen, David Schultz, Johan Normen Editorial Board: Steve Anglin, Dan Appleman, Gary Cornell, James Cox, Tony Davis, John Franklin, Chris Mills, Steven Rycroft, Dominic Shakeshaft, Julian Skinner, Martin Streicher, Iim Sumser, Karen Watterson, Gavin Wray, John Zukowski Assistant Publisher: Grace Wong Project Manager: Beth Christmas Copy Editor: Kim Wimpsett Production Manager: Kari Brooks Production Editor: JanetVail Proofreader: Linda Seifert Compositor: Diana Van Winkle, Van Winkle Design Indexer: Valerie Robbins Cover Designer: Kurt Krames Manufacturing Manager: Tom Debo1ski

In the United States: phone 1-800-SPRINGER, email [email protected]. or visit http://www.springer-ny . corn. Outside the United States: fax +49 6221 345229, email [email protected], or visit http://www.springer.de. For information on translations, please contact Apress directly at 2560 Ninth Street, Suite 219, Berkeley, CA 94710. Phone 510-549-5930, fax 510-549-5939, email [email protected], or visit http://www.apress.com. The information in this book is distributed on an "as is" basis, without warranty. Although every precaution has been taken in the preparation of this work, neither the author(s) nor Apress shall have any liability to any person or entity with respect to any 10ss 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 avai1able to readers at http://www.apress.comin the Downloads section. Contents at a Glance

About the Authors ...... xiii Introduction ...... xv

Chapter 1 The Distributed Application ...... 1

Chapter 2 Components and Data Access ...... 53

Chapter 3 Accessing XML Documents ...... 109

Chapter 4 The Application Plumbing ...... 143

Chapter 5 Working with Down-Level Clients ...... 199

Chapter 6 Working with Rich Clients ...... 261

Chapter 7 Remoting to .NET Clients ...... 347

Chapter 8 Updating Data in Down-Level Clients ...... 391

Chapter 9 Updating Remote Cached Data ...... 475

Chapter 10 Components for Updating Data ...... 527

Chapter 11 Rich Client Update Applications ...... 583

Chapter 12 Reconciling Update Errors ...... 647

Chapter 13 Updating Data from Remote .NET Applications ...... 715

Index ...... 765

iii Contents

About the Authors ...... xiii Introduction ...... xv

Chapter 1 The Distributed Application ...... 1

What Are Distributed Data Applications? ...... 2 Our Definition ...... 2 Why Do You Need to Distribute? ...... 3 How Can You Do ((Distributed}) on the Internet? ...... 5 Internet Protocols ...... 5 Internet Clients ...... 6 The Elements of a Distributed Application ...... 8 Client Devices and Client Applications ...... 10 Server-Side Data Stores ...... 12 Processing and Presenting Information ...... 14 Data Access Techniques Overview ...... 20 About "Relational" Data Access ...... 21 The ADO. NET Data Access Classes ...... 22 Understanding System.Xml ...... 32 Representing Data and Information ...... 33 The System.XrnI Classes ...... 37 Data Access and the n- Tier Model ...... 41 What Is the Data Being Used For? ...... 41 Some n -Tier Data Access Scenarios ...... 44 Summary ...... 51

Chapter 2 Components and Data Access ...... 53

Different Types of ((Component}) ...... 54 .NET Components ...... 54 COM and COM+ Components ...... 58 User Controls ...... 59 Include Files ...... 63 Server Controls ...... 64 Accessing and Exposing Data ...... 64 Delivering Data to Rich Clients ...... 64 Managing Data for Down-Level Clients ...... 65 Displaying XML Data ...... 65

v Contents

Working with the DataSet Object ...... 66 The Structure of the DataSet Object ...... 66 When Should You Use a DataSet? ...... 69 Relational Data Access Component Examples ...... 70 Setting Up the Examples ...... 70 Accessing and Returning Relational Data ...... 72 Summary ...... 107

Chapter 3 Accessing XML Documents ...... 109

Introducing the XML Data Access Component Examples ...... 109 Accessing and Returning Relational Data ...... 110 Using the SupplierListXml Data Access Component ...... 111 Returning an XmITextReader Reference ...... 112 Returning an XmlValidatingReader Reference ...... 11 8 Returning a DataSet Object ...... 123 Returning a Custom Array Reference ...... 126 Returning an ArrayList Reference ...... 130 Returning an XML String ...... 133 Returning an XmIDocument Object ...... 135 Returning anXPathDocument Object ...... 137 Summary ...... 141

Chapter 4 The Application Plumbing ...... 143

Overview of Client-Side Techniques ...... 144 Available Client-Side Programming Techniques ...... 144 Choosing Client Support ...... 145 Remoting Data to the Client ...... 151 Remoting Relational Data to the Client ...... 151 Remoting XML Data to the Client ...... 154 Running the .NET Framework on the Client ...... 157 Using ASP. NET Sessions ...... 172 Sessions Configuration in ASP. NET ...... 172 Checking for Session Support ...... 175 Munging URLs for Session Support ...... 176 Client Detection Example ...... 177 Overview of the Process ...... 177 Detecting the Client Type ...... 178 The default.aspxPage ...... 182 Detection Errors and Unsupported Clients ...... 184 Checking for Client-Side Scripting Support ...... 1 84

vi Contents

Redirecting the Client If Scripting Is Enabled ...... 185 The Device-Specific Home Pages ...... 186 Viewing the Results ...... 191 Summary ...... 196

Chapter 5 Working with Down-Level Clients ...... 199

A Mul tiple-Client Order List Application ...... 200 The User Interface ...... 201 Detecting the Client Type ...... 202 The Data Access Tier ...... 206 Maximizing Efficiency Through Data Caching ...... 206 The Order List Application: The HTML Version ...... 207 The Outline Process ...... 208 Searching for Customers ...... 209 Displaying a List of Customers ...... 211 Displaying a List of Orders ...... 220 Displaying the Order Details ...... 229 The Order List Application: The Mobile Version ...... 235 The Outline Process ...... 236 Fetching Data from the Server ...... 238 The Mobile Page Content ...... 242 Summary ...... 259

Chapter 6 Working with Rich Clients ...... 261

Working wi th XML ...... 262 Why XSL and XSLT? ...... 262 Exposing and Delivering niL ...... 262 Using XML in 5 and Higher ...... 264 Building the Middle Tier ...... 264 Selecting a Customer ...... 271 Selecting an Order ...... 285 Viewing Order Details ...... 293 Extracting the Order Details ...... 294 Using Web Services in Internet Explorer 5 and Higher ...... 297 Looking at the Customer Data Web Service ...... 298 Testing a Web Service ...... 300 Building the Middle Tier ...... 302 The Internet Explorer 5 WebService Behavior ...... 305

vii Contents

Building the Hypertext Application Example ...... 310 Running the Example Hypertext Application ...... 311 Loading the XML Data ...... 313 Building the Middle Tier ...... 314 The HTA Page Content ...... 316 Selecting an Order ...... 323 Working with Delimited Text Data ...... 324 Why Use Delimited Text Data? ...... 324 Remember the TDC? ...... 324 Building the Middle Tier ...... 325 Selecting a Customer ...... 331 Selecting and Viewing an Order ...... 338 Client -Side Data Binding with XML Anyone? ...... 345 Summary ...... 345

Chapter 7 Remoting to . NET Clients ...... 347

Remoting Refresher ...... 348 Remoting Objects ...... 348 The Remotable Object Class ...... 349 The Remote Server ...... 349 The Remote Client ...... 352 Deploying the Objects ...... 356 The Windows Application ...... 356 The Design Choices ...... 359 Remoting Data to Windows Applications ...... 359 Building the Windows Application ...... 360 Creating the Web Services ...... 364 Incremental Downloads ...... 368 Creating a Downloadable Form ...... 368 Loading the Form Dynamically ...... 369 The Download Cache ...... 372 Strong Named Assemblies and the Download Cache ...... 374 Deployment ...... 374 Security ...... 375 Security Policy ...... 377 Modifying the Security Policy ...... 379 Checking Permissions ...... 386 Dynamic Applications ...... 388 Summary ...... 389

viii Contents

Chapter 8 Updating Data in Down-Level Clients ...... 391

Updating Data Stores: An Overview ...... 392 Making the Process As Efficient As Possible ...... 392 Measuring the Results and Providing Feedback ...... 394 Controlling Access to Protect the Data ...... 394 Controlling Concurrent Data Updates ...... 395 Data Update Techniques in .NET ...... 397 Using Transactions While Updating Data ...... 404 Managing Concurrency While Updating ...... 408 Data Update Example for HTML 3.2 Clients ...... 412 An Overview of the Application ...... 413 Displaying and Editing Orders ...... 418 Displaying and Editing the Order Contents ...... 452 Data Update Example for Mobile Devices ...... 467 The Application Design ...... 467 Viewing the Application ...... 469 Summary ...... 473

Chapter 9 Updating Remote Cached Data ...... 475

Reviewing the Architecture ...... 476 Caching Updates on the Client ...... 477 Getting Updates Back to the Server ...... 478 Loading a DataSet ...... 480 Executing the Update Process ...... 498 Providing Feedback from the Update Process ...... 499 The Update Process in Detail ...... 503 A Data Update Process Example ...... 505 Summary ...... 525

Chapter 10 Components for Updating Data ...... 527

The UpdateDataSet Component ...... 528 Enabling Tracing from Within a Component ...... 528 Writing to the Trace Object ...... 530 The Common Methods in the Component ...... 532 Managing IDENTITY Columns for Inserted Rows ...... 533 The UpdateAlIOrderDetails Method ...... 549 Creating the Parameterized Command Objects ...... 563

ix Contents

Using the UpdateDataSet Component ...... 570 Filling the DataSet ...... 572 Editing Some RowValues ...... 573 Changing the Underlying Database Values Concurrently ...... 575 Performing the Update ...... 577 Displaying the Update Errors ...... 578 Deleting the New Rows You Added ...... 580 Viewing the Trace Information ...... 581 Summary ...... 582

Chapter 11 Rich Client Update Applications ...... 583

How This Chapter Is Organized ...... 584 An Overview of the Application ...... 585 The Process in Outline ...... 586 Checking for Concurrency Errors ...... 587 The Middle Tier ASP. NET Page ...... 587 Getting the Data from the Data Access Tier ...... 588 Exposing the Data to the Client ...... 588 Loading the Di ffgrams on the Client ...... 589 Loading the Orders Data ...... 590 Loading the Shippers Data ...... 591 Loading the Products Data ...... 593 Editing a .NET DataSet Diffgram ...... 594 Viewing the Updated Diffgram ...... 595 The Updated Diffgram Format ...... 598 The edit-orders. aspx Page Code and HTML ...... 603 Creating the List of Orders ...... 603 Posting the Updated Diffgram to the Server ...... 605 Displaying Details of the Selected Order ...... 609 Creating the List of Order Lines ...... 616 Creating the Update Line and Delete Line Buttons ...... 618 It's Time to Talk Dirty ...... 618 Updating the Orders Diffgram ...... 620 Summary ...... 644

Chapter 12 Reconciling Update Errors ...... 647

Reconciling Update Errors in Overview ...... 648 A Summary of the Process ...... 648 The Error Reporting and Reconciliation Process ...... 649 Displaying Trace Information ...... 654

x Contents

The Reconciliation Process in Detail ...... 655 The reconcile-changes.aspx Page ...... 656 The HTML Form and Hyperlinks ...... 656 Collecting the Posted Values ...... 657 Loading the Edited Diffgram ...... 659 Editing the DataSet Contents for a Postback ...... 665 Updating the Database from the DataSet ...... 666 Checking for Errors After the Update Process ...... 667 Getting a Diffgram As a String from a DataSet ...... 669 Displaying the Errors and Reconciliation Options ...... 671 Editing the Values in the DataSet Tables ...... 683 Rich Client Updates via a Web Service ...... 688 The Issues and Work-Arounds ...... 689 The Middle Tier Web Service Component ...... 689 TheWeb Service Client Application ...... 692 Other Rich Client Update Techniques ...... 709 Rich Client Updates Using Delimited Data ...... 710 Hypertext Application Updates ...... 712 Summary ...... 713

Chapter 13 Updating Data from Remote . NET Applications ...... 715

The Application ...... 716 The Orders Method ...... 717 The Lookups Method ...... 719 The UpdateOrders Method ...... 720 The New Editable Orders Form ...... 721 DataGrids and TableStyles ...... 722 Wmdows Forms Data Binding ...... 723 Maintaining the Current Row ...... 727 Handling the PositionChanged Event ...... 728 The Code So Far...... 729 Handling Data Changes ...... 731 Adding Rows ...... 732 Deleting Rows ...... 732 Cancelling Edits ...... 733 Flushing Changes to the Database ...... 735 Handling Concurrency Conflicts ...... 738 The ErrorProvider Object ...... 739 The Error Handling Form ...... 740 Identifying Errors ...... 742

xi Contents

Changing the View ...... 748 Correcting Errors ...... 752 Navigation ...... 757 Handling Deleted Rows ...... 758 Correcting Errors in Deleted Rows ...... 759 Saving the Corrected Data ...... 761 The Application in Practice ...... 762 Summary ...... 763 Epilogue ...... 764

Index ...... 765

xii About the Authors

Alex Homer is a computer geek and Web developer with a passion for ASP.NET. Although he has to spend some time doing real work (a bit of consultancy and training and the occasional conference session), most of his days are absorbed in playing with the latest Web technology and then writing about it. living in the picturesque wilderness of the Derbyshire Dales in England, he's well away from the demands of the real world-with only an Internet connection to maintain some distant representation of normality. But, hey, what else could you want from life? You can contact Alex through his own software company, Stonebroom limited, [email protected].

Dave Sussman is a hacker in the traditional sense of the word. That's someone who likes playing with code and figuring out how things work, which is why he spends much of his life working with beta software. Luckily, this coincides with writing about new technologies, giving him an output for his poor English and grammar. He lives in a small village in the Oxfordshire countryside. Like many programmers everywhere, he has an expensive hi-fi, a big Tv; and no life. You can contact Dave through his own company, ipona Limited, at [email protected].

xiii Introduction

ASRNET IS A HUGE ADVANCE from previous incarnations of ASP, with one of its goals being pure HTML output that achieves maximum cross-browser compatibility. The server-side event architecture tends to engender this approach, but amid the first flush of excitement it's often forgotten that there's still a place for rich clients and handling data in a multitude of places. Distributed data -driven applications aren't new, but the range of possibilities and ease of development have both increased with the introduction of .NET. This book approaches data management and data applications from several different points of view:

• Understanding the new .NET data management philosophy for both rela• tional and XML data

• Grasping the different techniques that it encompasses and how they relate to real-world requirements

• Exploring the application architecture and design implications of the .NET data management classes

• Designing distributed data -driven ASP.NET applications that benefit from the new data management techniques

• Examining the rich-client philosophy and how .NET can be used to bring this about

• Demonstrating how easy it is to take advantage of several different types of client device, providing the best user experience possible for each one

Many books describe the basic techniques for working with data in ASP.NET. However, this book goes not just a step further but in fact takes you on a complete journey by exploring how to provide the user with the best possible client-side experience when working with data. It also focuses on the server-side design and development process, such as using the n-tier architecture in your applications, and specific techniques such as correctly managing updates to a data store by multiple concurrent users.

xv Introduction

In this book, we assume a basic grasp of ASP. NET and the general data access techniques that the .NET Framework makes available (although we do provide some grounding to reinforce the important aspects). Where this book really is different, however, is that it's wholly aimed at seeing how you can actually build useful, interactive, and efficient distributed applications.

What This Book Is

This book is all of the following:

• It's a voyage of exploration through almost all aspects of building ASP. NET applications that handle data and work across the Internet (or other HTTP networks such as an intranet).

• It's a practical approach to building task-specific components, Web pages, and Web applications based on a server running ASP. NET.

• It's a demonstration of what's possible with ASP.NET, without requiring spe• cial expertise, long development times, or complex third-party components.

• It's focused on n-tier architecture design and the way it can be coded, using SQL Server as a data source and simple Web server hardware.

• It's clearly divided into chapters and sections that cover all the relevant theory and practice for the different parts of the sample application that's developed throughout the entire book.

• It's a source of useful techniques and snippets of code that can be reused in your own applications.

• It's written using mainly Visual Basic .NET (VB .NET) for the code listings. However, C# versions of the samples are available for download as well as VB .NET versions.

• A useful and enjoyable read (we hope).

xvi Introduction

What This Book Isn't

This book is none of the following:

• It's not an academic text or a theory-oriented book. We describe the work• ings of the application in down-to-earth language, use technical terms only where necessary, and try to avoid any off-topic discussion and irrelevancies.

• It's not a reference book in the sense that techniques we use are described where they fit into the application rather than as alphabetically organized tables.

• It's not a book about hardware performance, server optimization, or soft• ware security. We'll attempt to show how you can get the best performance from your systems when designing applications, but we won't be delving into these other areas.

• It's not a book about SQL programming, data storage theory, or complex back-end systems. The techniques we use are designed to be easily translat• able to any back-end system that ASP.NET can access.

• It's not a book for system administrators or database administrators. It's about programming and aimed at developers fluent in ASP.NET.

• It's not a detective story.

What This Book Covers

This book concentrates on using ASP. NET versions 1.0 and 1.1 for building appli• cations for Internet or intranet use and looking at the possibilities that rich clients bring to both application design and a better user experience. There often appears to be confusion over how the .NET data management and page-processing mod• els fit into the overall distributed application architecture, how it changes this, and how it provides exciting new opportunities. So we'll spend some time exploring the whole architecture and design issue, and you'll see how it can be addressed in different ways. In particular, throughout the whole book, we attempt to provide inspiration through a range of ideas on how data can be used to drive Web applications and how that data can be most effectively utilized at each level of the design. Web applications will usually benefit from the encapsulation of business rules into

xvii Introduction

components, and the .NET Framework provides ways to build several types of components. So we'll show both the construction and use of these. There's no specific focus in this book on Windows Forms or executable appli• cations or on the client-server environment in which they normally reside. How• ever, to work really well in a distributed Web-based environment, the client can benefit from the use ofWindows Forms or other client -side executables that access the server in conjunction with an ASP.NET-based application. Again, we'll demonstrate this in the book. There are many development environments for ASP.NET applications and components already available and "on the way." The primary one is Visual Studio .NET. Traditionally, ASP pages have been built in a text editor or text-based tool, and because this book concentrates on the code rather than the tool used to cre• ate it, we predominantly use just a text editor to develop ASP.NET pages. However, the features ofVisual Studio .NET for building components and Windows Forms applications is covered where appropriate. Most of the code in the book is Visual Basic .NET because this gives the best opportunity for all developers. Even if you prefer to work in C# (or another lan• guage), you should be able to follow the VB .NET code quite easily. The alternative of providing listings and descriptions of the code for both languages would have meant we could get a lot less into the book overall, reducing the features we could cover and the techniques we could describe. However, the downloadable samples are provided in both VB .NET and C#. Of course, the client-side code we use in the browser isn't a .NET language. Predominantly we use JavaScript, though one example uses client -side VBScript to demonstrate that it can be done. We also use a mixture of notations in our code. You'll see Hungarian notation in many places, which is aimed at making it easy to follow the code by clearly showing to which data type each variable refers. However, under .NET, Microsoft suggests that we should all move away from this notation style-but they don't say what we should move to instead. You can send suggestions or comments to the authors (via our usual feedback address [email protected]) if you feel strongly about any other issue we've brought up here or throughout the remainder of the book.

Who Is This Book For?

This book is for developers who want to learn ASP.NET for building distributed data-driven applications, especially where they have a requirement for displaying and processing data in a wide range of different ways. In other words, it's for devel• opers who require more than just simple "read and update" scenarios but instead must tackle building truly distributed applications.

xviii Introduction

What You Need to Use This Book

We'd like to think that you have a passion for ASP.NET, but in reality there may be one or two people who just use it because they have to do so. Either way, ASP.NET is what this book is about, and what we expect you to be familiar with. You'll also need to have some database experience and the appropriate software and hard• ware available. We summarize all the requirements in the next two sections.

Prerequisite Knowledge and Experience

This book is aimed at developers who have learned about .NET, and in particular ASP.NET, and are probably experienced in Web application development using previous versions of ASP. However, knowledge ofWeb application fundamentals (perhaps from another environment) and a firm grasp of the basics of ASP. NET will suffice. Also, knowledge of programming using VB .NET (or at least a reasonable grasp ofVB .NET as it relates to the predecessorVBScript) will be useful. If you're fluent in C# and prefer to use that, the techniques we demonstrate can easily be imple• mented in that (or any other) .NET language. The downloadable samples files are supplied in both VB and C# versions. You can download the sample files from http://www • apress. com or http://www.daveanda1.net!books/4923/. You can also run most of the samples online on our own server at http://www.daveanda1.net!books/4923/.

Development Tools and Runtime Environment

Basically, all you need is a text editor and a server running version 1.0 or 1.1 of the .NET Framework. However, you'll also need to obtain and install the Microsoft Mobile Internet Toolkit (MMIT) to be able to run all the examples. To get the .NET Framework, go to http://msdn.microsoft . com/net!. Get the MIT from http://msdn.microsoft . com/vstudio/nextgen/device/ mi tdefault. asp. A database server is also required-though it can be on the same server as the .NET Framework. The database used in the book is Microsoft SQL Server, but you can use any database to which you can connect from ASP. NET and within which you can create stored procedures. You can use .NET to create and compile the .NET components, but it's not a requirement because you can compile the class files from the command line instead (we provide simple batch files with the sample

xix Introduction

code to make this easier). VS .NET isn't our main development environment for ASP.NET pages because we use inline format rather than the code-behind format that VS .NET demands. For the Windows Forms application, we do use Visual Studio .NET although the downloadable code will work without it. However, you won't be able to view the design of the forms. Information about Visual Studio is available from http://msdn.microsoft . coml vstudiol. To test the pages in different environments, you might want to install several browsers. We tested the code in Opera and Netscape Navigator, as well as the Nokia mobile phone emulator. Navigator is available from http://home.netscape . coml computingl downloadl index. . Opera is available from http://www.opera.com/. The Deck-It emulator is available from http://www.pyweb.com/tools/ . The Nokia toolkit is available from http://forum . nokia. com/. The Openwave toolkit is available from http: I lopenwave. com/.

xx