ASP.NET 1.1 Insider Solutions- P1

Chia sẻ: Thanh Cong | Ngày: | Loại File: PDF | Số trang:50

0
44
lượt xem
9
download

ASP.NET 1.1 Insider Solutions- P1

Mô tả tài liệu
  Download Vui lòng tải xuống để xem tài liệu đầy đủ

Bạn nhận được nhiều nhất từ ASP.NET? Trong khi rất dễ dàng để xây dựng các trang khá phức tạp một cách nhanh chóng và dễ dàng với ASP.NET, nếu bạn có được một kiến thức nhiều hơn thân mật của NET Framework. Như một toàn thể, bạn thực sự có thể tận dụng các tính năng tuyệt vời nó cung cấp.

Chủ đề:
Lưu

Nội dung Text: ASP.NET 1.1 Insider Solutions- P1

  1. TEAM LinG Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
  2. Alex Homer Dan Kent Dave Sussman Dan Whalin ASP.NET 1.1 800 East 96th Street, Indianapolis, Indiana 46240 TEAM LinG
  3. ASP.NET 1.1 Insider Solutions Associate Publisher Michael Stephens Copyright © 2004 by Sams Publishing All rights reserved. No part of this book shall be reproduced, stored in a Acquisitions Editor retrieval system, or transmitted by any means, electronic, mechanical, Neil Rowe photocopying, recording, or otherwise, without written permission from the publisher. No patent liability is assumed with respect to the use of the Development Editor information contained herein. Although every precaution has been taken Mark Renfrow in the preparation of this book, the publisher and author assume no responsibility for errors or omissions. Nor is any liability assumed for Managing Editor damages resulting from the use of the information contained herein. Charlotte Clapp International Standard Book Number: 0-672-32674-4 Project Editor Library of Congress Catalog Card Number: 2004091341 Dan Knott Printed in the United States of America Copy Editor First Printing: June 2004 Kitty Jarrett 07 06 05 04 4 3 2 1 Indexer Trademarks Heather McNeill All terms mentioned in this book that are known to be trademarks or service marks have been appropriately capitalized. Sams Publishing cannot Proofreader attest to the accuracy of this information. Use of a term in this book Katie Robinson should not be regarded as affecting the validity of any trademark or service mark. Technical Editors Dan Maharry Warning and Disclaimer Justin Rogers Every effort has been made to make this book as complete and as accurate as possible, but no warranty or fitness is implied. The information Team Coordinator provided is on an “as is” basis. The author and the publisher shall have Cindy Teeters neither liability nor responsibility to any person or entity with respect to any loss or damages arising from the information contained in this book. Designer Gary Adair Bulk Sales Page Layout Sams Publishing offers excellent discounts on this book when ordered in quantity for bulk purchases or special sales. For more information, please Bronkella Publishing contact U.S. Corporate and Government Sales 1-800-382-3419 corpsales@pearsontechgroup.com For sales outside of the U.S., please contact International Sales 1-317-428-3341 international@pearsontechgroup.com
  4. Contents at a Glance Introduction...............................................................................................1 Part I Web Form User Interfaces 1 Web Forms Tips and Tricks .........................................................................7 2 Cross-Page Posting ..................................................................................51 3 Loading Progress and Status Displays ......................................................75 4 Working with Nested List Controls ..........................................................109 Part II Reusability 5 Creating Reusable Content.....................................................................155 6 Client-Side Script Integration ..................................................................197 7 Design Issues for User Controls .............................................................243 8 Building Adaptive Controls......................................................................297 9 Page Templates .....................................................................................353 Part III Data Techniques 10 Relational Data-Handling Techniques.......................................................385 11 Working with XML Data ..........................................................................429 Part IV Hosting and Security 12 Side-by-Side Execution in ASP.NET ..........................................................479 13 Taking Advantage of Forms Authentication ...............................................499 14 Customizing Security..............................................................................537 Index ....................................................................................................561
  5. Table of Contents Introduction 1 Part I Web Form User Interfaces 1 Web Forms Tips and Tricks 7 Getting More from ASP.NET Validation Controls ..........................................8 Validating a RadioButtonList Control .................................................9 Validating a CheckBoxList Control ...................................................11 Validating Nonstandard Control Values ...........................................12 Using List and Validation Controls in a DataGrid Control ...................14 Taking Control of Content Layout in a DataGrid Control .............................31 Controlling the Width of Columns in a DataGrid Control ....................32 Using Multiple Edit Controls in a DataGrid Control Column ...............33 Controlling the Width of Edit Controls in a DataGrid Control ..............35 Providing Scrollable Content in a DataGrid Control ...........................36 Loading Controls Dynamically at Runtime .................................................38 The ASP.NET Control Tree ...............................................................38 Creating a DataGrid Control Dynamically at Runtime ........................41 Loading User Controls Dynamically at Runtime ................................46 Summary ...............................................................................................49 2 Cross-Page Posting 51 Techniques for Passing Values Between Pages .........................................52 Accessing Request Values in Another Page .....................................52 Changing the action Attribute of a Form ..........................................53 Redirecting Postbacks to the Target Page ........................................57 Client-Side Versus Server-Side Redirection ...............................................60 Exposing Values to Another Page via References ......................................62 The Event Handlers That Call the Server.Transfer Method .................63 The Public Properties in the Main Page ...........................................64 The Target Page for the Server.Transfer Method ...............................65 Changing the Method and Clearing the Request Collections .............67 The Server.Execute Method .....................................................................68 Capturing Output from the Server.Execute Method ...........................69 The Target Page for the Server.Execute Method ...............................70 Summary ...............................................................................................72
  6. 3 Loading Progress and Status Displays 75 Displaying a “Please Wait” Page ..............................................................76 A Simple “Please Wait” Example ....................................................77 Displaying a Progress Bar Graphic ...........................................................85 The Progress Bar Animated Graphic Files ........................................86 Displaying the Progress Bar Graphic ...............................................87 Implementing a Staged Page Load Process ..............................................92 The Steps in Implementing a Staged Page Load Process .................92 Status Information in ASP .NET and the XMLHTTP Object ...................93 The Staged Process Operation Page ...............................................94 The Staged Process Main Page in the Staged Loading Example ........98 Summary .............................................................................................107 4 Working with Nested List Controls 109 Displaying Related Data in Nested DataGrid Controls ..............................110 Declarative Nested Binding to a DataSet Instance .........................110 Filling Nested DataGrid Controls with a DataSet Instance ...............119 Declarative Nested Binding to a Custom Function ..........................125 Filling Nested DataGrid Controls from a DataReader Instance .........128 A Master/Detail Display with DataList and DataGrid Controls ..................134 Declaring the DataList and DataGrid Controls ................................135 Populating the DataList Control ....................................................140 Populating the DataGrid Control ....................................................143 Selecting a Row in the DataList Control ........................................143 Editing a Row in the DataGrid Control ...........................................145 Updating the Original Data in the Database ...................................149 Summary .............................................................................................150 Part II Reusability 5 Creating Reusable Content 155 Techniques for Creating Reusable Content .............................................156 Server-Side Include Files ..............................................................156 ASP.NET User Controls ..................................................................158 Custom Master Page and Templating Techniques ...........................162 ASP.NET Server Controls Built As .NET Assemblies .........................163 Using COM or COM+ Components via COM Interop ........................166 Building a ComboBox User Control .........................................................169 Design Considerations .................................................................169 The HTML for a Drop-Down Combo Box .........................................170
  7. vi ASP.NET 1.1 Insider Solutions The Structure and Implementation of the ComboBox User Control ...173 Outputting the Appropriate HTML ..................................................175 The ShowMembers Method ..........................................................176 Public Property Accessor Declarations ...........................................176 The Property Accessors for the ComboBox User Control .................178 The Page_Load Event Handler for the ComboBox Control ................183 Using the ComboBox Control .................................................................189 Populating the ComboBox Controls from an ArrayList Instance ........191 Displaying the Members of the ComboBox User Control .................192 Displaying Details of the Selected Item .........................................192 Setting the Properties of the ComboBox User Control ....................193 Populating the ComboBox Control ..........................................................194 Summary .............................................................................................196 6 Client-Side Script Integration 197 Client-Side Interaction on the Web .........................................................198 Client-Side Scripting in the Browser ..............................................199 CSS2 and Dynamic HTML .............................................................199 Selecting Your Target ...................................................................200 Version 6 Browser-Compatible Code Techniques ............................201 The Client-Side Code in the ComboBox User Control ......................203 Useful Client-Side Scripting Techniques ..................................................207 Buttons, Grids, and Client-Side Script ............................................208 Detecting and Trapping Keypress Events .......................................211 Creating a MaskedEdit Control .....................................................218 Using the MaskedEdit Control .......................................................224 Creating a One-Click Button ..........................................................230 Summary .............................................................................................240 7 Design Issues for User Controls 243 The Effect of User Controls on Design and Implementation .....................244 Converting the MaskedEdit Control Page to a User Control .............245 Adding Validation Controls to the MaskedEdit Control ....................251 Building a SpinBox User Control ............................................................254 The User Interface Declaration for the SpinBox Control ..................255 The Private and Public Members of the Control ..............................256 The Server-Side Code Within the SpinBox Control ..........................261 Integrating Client-Side Script Dialogs .....................................................267 How the Client Dialogs Example Works .........................................269 The clientdialog.ascx User Control ................................................269
  8. Contents vii Browser-Adaptive Script Dialogs .............................................................274 How the Adaptive Client Dialogs Example Works ............................276 Integrating Internet Explorer Dialog Windows ..........................................283 How the Modal Dialog Window Example Works ..............................285 The Internet Explorer showModalDialog Method .............................285 Browser-Adaptive Dialog Windows ..........................................................290 How the Browser-Adaptive Dialog Window Example Works ..............291 Summary .............................................................................................294 8 Building Adaptive Controls 297 The Advantages of Server Controls ........................................................298 The Basics of Building Server Controls ..................................................298 The Process of Building a Server Control .......................................299 The Life Cycle of ASP .NET Controls ................................................299 The Life Cycle of a Server Control .................................................300 Creating a Class for a Server Control ............................................301 Choosing and Extending a Base Class ..........................................302 Building a MaskedEdit Server Control ....................................................305 The MaskedEdit Control Class File ................................................305 Compiling and Testing the MaskedEdit Control ...............................312 Building a SpinBox Server Control ..........................................................315 The Standard SpinBox Control Class File .......................................316 Using an Adaptive SpinBox Control ...............................................334 Making the SpinBox Control Adaptive .....................................................335 Coping with Older and Nonstandard Browsers ...............................337 Adaptability Changes to the SpinBox Control Class ........................339 Testing and Using an Adaptive SpinBox Control .............................346 Installing a SpinBox Control in the GAC ..................................................348 Changes to the SpinBox Control Class File for GAC Installation ......349 Compiling the SpinBox Control Class File ......................................349 Installing the SpinBox Assembly into the GAC ................................350 Testing the GAC-Installed Control ..................................................351 Summary .............................................................................................352 9 Page Templates 353 Designing for Consistency .....................................................................354 Templating Solutions .............................................................................355 A Simple Layout Server Control ............................................................355 Custom Layout Control Output ......................................................357 Creating Content from a Custom Control .......................................358 Creating a Custom Layout Control .................................................360
  9. viii ASP.NET 1.1 Insider Solutions A Server Control That Uses Templates ...................................................365 Creating a Templated Server Control .............................................366 Creating Default Content for Templates ..................................................371 Creating Dynamic Regions for Page Content ...........................................372 Using a Custom Page Class for a Page Template ....................................373 Creating the Content and ContentPlaceHolder Controls ..................373 Creating a Custom Page Class .....................................................374 Creating a Master Page ................................................................378 Using a Custom Page Class .........................................................379 Using Custom Controls in Visual Studio .NET .........................................380 Summary .............................................................................................381 Part III Data Techniques 10 Relational Data-Handling Techniques 385 Using Parameters with SQL Statements and Stored Procedures ..............386 Using Submitted Values in a SQL Statement .................................386 Ordering of Stored Procedures and Query Parameters ....................392 Using Default Values in a Stored Procedure ...................................393 Filling a DataSet Instance With and Without a Schema ...........................400 Loading the Schema for a DataSet Instance ..................................400 The Sample Page for Filling a DataSet Instance .............................401 Writing Provider-Independent Data Access Code .....................................410 Dynamically Instantiating a .NET Framework Class .........................410 The Code in the Provider-Independent Data Access Sample Page ...411 Updating Multiple Rows by Using Changed Events ..................................415 The Edit and Cancel Buttons ........................................................418 Populating the DataGrid Control ....................................................419 Handling the ItemDataBound Event ...............................................420 Handling the Changed Events .......................................................422 Updating the Source Data ............................................................424 Creating the Client-Side Script to Highlight a Control ......................426 Summary .............................................................................................427 11 Working with XML Data 429 The Role of XML in ASP.NET ...................................................................430 XML API Pros and Cons ........................................................................430 The Forward-Only API: XmlTextReader ............................................431 The DOM API: XmlDocument .........................................................431 The Cursor-Style API: XPathNavigator .............................................432 The XML Serialization API: XmlSerializer ........................................432
  10. Contents ix Combining the XmlTextReader and XmlTextWriter Classes ........................433 Parsing XML Strings ..............................................................................437 Accessing XML Resources by Using the XmlResolver Class .....................438 XmlResolver, Evidence, and XslTransform ......................................439 Searching, Filtering, and Sorting XML Data .............................................442 Searching and Filtering XML Data .................................................442 Sorting XML Data ........................................................................446 Creating a Reusable XML Validation Class .............................................456 Converting Relational Data to XML .........................................................460 Customizing XML by Using the DataSet Class ................................461 Adding CDATA Sections into XML Documents .................................464 Simplifying Configuration by Using XML ..................................................466 Accessing Configuration Settings by Using XPathNavigator ..............467 Using XML Serialization ................................................................470 Summary .............................................................................................474 Part IV Hosting and Security 12 Side-by-Side Execution in ASP.NET 479 How Version 1.1 of the .NET Framework Is Distributed ............................480 How Installing a New Version of the .NET Framework Affects Existing Applications .......................................................................................481 Configuration Settings in machine.config .......................................481 The ASP .NET State Service and SQL Server State Service ...............481 The ASP .NET Process Account .......................................................482 Windows Performance Counters ...................................................482 Running Version 1.0 Applications on Version 1.1 of the .NET Framework ........................................................................482 Running Version 1.1 Applications on Version 1.0 ...........................488 How ASP.NET Selects the Runtime Version .............................................488 How to Specify the ASP.NET Version for Individual Applications ................489 Installing ASP.NET Without Updating Script Mappings .....................489 Using the aspnet_regiis.exe Tool to Configure Runtime Versions .....490 ASP.NET and IIS 6.0 on Windows Server 2003 .......................................492 IIS 6.0 Web Service Extensions ....................................................493 IIS 6.0 Application Pools ..............................................................494 Summary .............................................................................................497 13 Taking Advantage of Forms Authentication 499 Building a Reusable Sign-in Control .......................................................500 Hashing Passwords ..............................................................................506
  11. Helping Users Who Forget Their Passwords ............................................508 Persistent Authentication Cookies .........................................................514 Setting a Timeout ........................................................................515 Mandatory Expiration ...................................................................515 Using Forms Authentication in Web Farms ..............................................516 Using Elements to Implement Single Sign-in Systems ...................................................................................518 Cookieless Forms Authentication ...........................................................519 Creating a Hyperlink Control to Add the Authentication Ticket .........521 Protecting Non-ASP.NET Content ............................................................523 Supporting Role-Based Authorization with Forms Authentication ...............526 Using Multiple Sign-in Pages .................................................................528 Dealing with Failed Authorization ............................................................530 Listing Signed-in Users .........................................................................531 Forcibly Signing Out a User ....................................................................533 Summary .............................................................................................535 14 Customizing Security 537 Building a Custom Authentication Module ..............................................538 What Is an Authentication Module? ...............................................538 Building a Custom Identity Class ..................................................538 Building the HTTP Module ............................................................540 Running Authentication Modules in Tandem ...................................542 Building a Custom Authorization Module ................................................543 Running Authorization Modules in Tandem .....................................545 Trust Levels ..........................................................................................546 Using One of the Preconfigured Trust Levels ..................................546 Forcing an Application to Use a Trust Level ....................................548 Creating Custom Trust Levels .......................................................549 Recommended Use of Permissions ...............................................556 Summary .............................................................................................559 Index 561
  12. About the Authors Alex Homer began his love/hate relationship with computers in 1980, with the Altair and Sinclair Z80, and he now lives and works in the idyllic rural surroundings of the Derbyshire Dales in England. Alex has written or contributed to more than 30 books on Web development topics for major publishers. He is a Microsoft MVP and INETA member, and he speaks regularly at conferences around the world. In what spare time is left, he runs his own software and consulting company, Stonebroom Limited (http://stonebroom.com). Dave Sussman is a freelance writer, trainer, and consultant who lives in a rural village in England. He spends most of his time in betaland, a strange place inhabited by test software that changes daily and where there only seem to be 12 hours in a day. He strongly believes in the Douglas Adams view of deadlines. He can be contacted at davids@ipona.com. Dan Wahlin, a Microsoft MVP, is the president of Wahlin Consulting and founded the XML for ASP.NET Developers Web site (www.XMLforASP.NET), which focuses on using XML and Web services in the .NET platform. In addition to consulting, Dan is also a corpo- rate trainer/speaker, and he teaches XML and .NET training courses around the United States. Dan coauthored ASP.NET: Tips, Tutorials, and Code and authored XML for ASP.NET Developers (both from Sams Publishing). Dan Kent currently edits the Evolution series for Sams Publishing, builds sites that support community regeneration, and performs cutting-edge video shows as half of VJ duo Syzygy. After studying artificial intelligence, he went on to become part of the dot-com bubble, building online community sites that empowered newcomers to the Web to create Web presences. He decided to leave frontline programming and concentrate on passing on some of his know-how. His desire to be involved with books was kindled by some work as a technical reviewer for Wrox, which he went on to as a technical editor. While at Wrox, Dan developed the Problem-Design-Solution concept, which pioneered the approach of presenting readers with real-world solutions in the context of real applications. He also worked with the Microsoft ASP.NET team to help programmers learn more about the fantastic technology they created and contributed as an author to the highly respected Professional ASP.NET Security, now sadly out of print. Two years, four job titles, and far too many books later, Dan decided to leave Wrox.
  13. We Want to Hear from You! As the reader of this book, you are our most important critic and commentator. We value your opinion and want to know what we’re doing right, what we could do better, what areas you’d like to see us publish in, and any other words of wisdom you’re willing to pass our way. As an associate publisher for Sams Publishing, I welcome your comments. You can email or write me directly to let me know what you did or didn’t like about this book— as well as what we can do to make our books better. Please note that I cannot help you with technical problems related to the topic of this book. We do have a User Services group, however, where I will forward specific technical questions related to the book. When you write, please be sure to include this book’s title and author as well as your name, email address, and phone number. I will carefully review your comments and share them with the author and editors who worked on the book. Email: feedback@samspublishing.com Mail: Michael Stephens Associate Publisher Sams Publishing 800 East 96th Street Indianapolis, IN 46240 USA For more information about this book or another Sams Publishing title, visit our Web site at www.samspublishing.com. Type the ISBN (0672326744) or the title of the book into the Search field to find the page you’re looking for.
  14. Introduction Are you getting the most from ASP.NET? While it’s easy to build quite complex pages quickly and easily with ASP.NET, if you acquire a more intimate knowledge of the .NET Framework as a whole, you can really take advantage of the great features it provides. This book explores some of the more advanced topics that help you to build better, more effi- cient, and more attractive Web pages and Web applications. In fact, many of the examples in this book are designed to illustrate and provide solutions for questions and problems that appear regularly on the ASP.NET forums and newsgroups. What This Book Covers Topics include getting more from the DataGrid control, creating reusable content as both user and server controls, using page templating and cross-page posting, building secure applica- tions, validating user input, integrating client-side script, providing great cross-browser support, and much more. The book is divided into four sections: ■ Part I, “Web Form User Interfaces,” is a combination of many useful techniques for solving issues that ASP.NET developers regularly face. The chapters in this part include tips and tricks with Web forms and information on cross-page posting, displaying progress and status information, and working with nested ASP.NET list controls. n Part II, “Reusability,” demonstrates how you can create reusable content for Web pages and applications. Topics include client-side script integration; user and server control design and construction; adaptive controls; and master pages, templates, and page subclassing techniques. n Part III, “Data Techniques,” covers some of the issues that you should think about when working with both relational and XML data, including tips and tricks, protecting your server, and performance. n Part IV, “Hosting and Security,” covers topics that are mainly concerned with installing, setting up, and using ASP.NET. This includes side-by-side execution of different versions, ASP.NET forms authentication, and general security configuration issues. Who This Book Is For This book is for developers who are using ASP.NET and have a reasonable grasp of the basic topics for building Web pages and Web applications in ASP.NET. It is not designed to act as a
  15. 2 Introduction beginner’s guide or as a comprehensive reference to all the techniques available in ASP.NET. However, the topics that it does cover are introduced in sufficient depth that a reasonably experienced ASP.NET user will be able to learn and take advantage of the techniques described. For example, Chapter 5, “Creating Reusable Content,” explains what user and server controls are and how to build them—in such a way that the reader does not need to have any prior experience of these topics. It describes and illustrates properties and methods, how to expose functionality from a control, and how to use that control in Web pages and applications. What You Need to Use This Book This book covers ASP.NET 1.1, and you must be running this version of ASP.NET to use the sample code that is available for download. The examples are not designed for use in Visual Studio .NET, which means that you can use them (and edit them to suit your own projects) in tools such as Web Matrix or in any text editor. You can, of course, convert them yourself to run within Visual Studio .NET if you wish. All the sample code for this book can be downloaded from the Sams Web site at www.samspublishing.com. It is also available at www.daveandal.net/books/6744/, where you can run many of the examples online without needing to download them and install them on your own server. Many of the examples in this book rely on a database server to provide values for the pages. The database used in the book is the sample Northwind database provided with SQL Server and MSDE, and a suitable Access database is included with the downloadable samples for the book as well. You can use a different database server if you prefer, provided that you have a managed provider for the .NET Framework available, and you must edit the connections strings in the web.config file to specify your database server. Other than that, you can run the examples and experiment with the techniques they illus- trate without requiring any other special software or hardware. Conventions Used in This Book Special conventions are used to help you get the most from this book and from Web markup. Text Conventions Various typefaces in this book identify terms and other special objects. n Screen messages, code listings, and command samples appear in monospace type. n Uniform Resource Locators (URLs) used to identify pages on the Web and values for HTML attributes also appear in monospace type.
  16. Introduction 3 n Terms that are defined in the text appear in italics. Italics are sometimes used for emphasis, too. n In code lines, placeholders for variables are indicated by using italic monospace type. n User input information will appear in bold monospace type. Special Elements Throughout this book, you’ll find best practices, sidebars, and cross-references. Sidebars for More Information These elements provide a variety of infor- Sidebars are designed to provide information mation, ranging from warnings you that is ancillary to the topic being discussed. Read these if you want to learn more about shouldn’t miss to ancillary information an application or a task. that will enrich your learning experience: BEST PRACTICE Best Practices Bets practices are designed to help you decide which is the best way to approach the task being discussed and which is the best way to make use of the technology or maximize its benefits.
  17. PART I Web Form User Interfaces 1 Web Forms Tips and Tricks 2 Cross-Page Posting 3 Loading Progress and Status Displays 4 Working with Nested List Controls
  18. 1 IN THIS CHAPTER Getting More from ASP.NET Validation Controls 8 Web Forms BEST PRACTICE: Protecting Your Pages from Spoofing Tips and Tricks Attacks BEST PRACTICE: 12 Displaying the Correct Currency Symbol 21 BEST PRACTICE: We start this chapter by looking at some Selecting the Current Value in a Nested of the more unusual ways you can use the List Control 27 ASP.NET validation controls, such as within a list control—something that comes up BEST PRACTICE: regularly on ASP.NET mailing lists and Using a Stored Procedure to Update the forums. Data Store 30 Next, we take a brief look at creating some- Taking Control of Content Layout in a thing other than the standard layout in a DataGrid Control 31 DataGrid control. We show a couple exam- BEST PRACTICE: ples that demonstrate how you can specify Setting the Width of All the Columns 33 the width of the columns, expose more than one editable value in a column, and Loading Controls Dynamically at display long text strings in scrollable cells. Runtime 38 Finally, we look at a topic that seems to Summary 49 regularly cause problems for users: creating instances of controls dynamically when a page is loaded. This technique can provide far more flexibility than just declaring all the controls within the HTML section of the page, but it means you have to be fairly organized when developing the page—and remember to re-create all the controls in the correct order on each postback.
Đồng bộ tài khoản