Tải bản đầy đủ (.pdf) (769 trang)

Beginning ASP.NET 2.0 with C# ppt

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (21.45 MB, 769 trang )

Beginning
ASP.NET 2.0 with C#
Chris Hart, John Kauffman, David Sussman, and Chris Ullman
01_042583 ffirs.qxd 4/4/06 2:38 PM Page iii
01_042583 ffirs.qxd 4/4/06 2:38 PM Page ii
Beginning
ASP.NET 2.0 with C#
01_042583 ffirs.qxd 4/4/06 2:38 PM Page i
01_042583 ffirs.qxd 4/4/06 2:38 PM Page ii
Beginning
ASP.NET 2.0 with C#
Chris Hart, John Kauffman, David Sussman, and Chris Ullman
01_042583 ffirs.qxd 4/4/06 2:38 PM Page iii
Beginning ASP.NET 2.0 with C#
Published by
Wiley Publishing, Inc.
10475 Crosspoint Boulevard
Indianapolis, IN 46256
www.wiley.com
Copyright © 2006 by Wiley Publishing, Inc., Indianapolis, Indiana
Published simultaneously in Canada
ISBN-13: 978-0-470-04258-8
ISBN-10: 0-470-04258-3
Manufactured in the United States of America
10 9 8 7 6 5 4 3 2 1
1B/SQ/QU/QW/IN
No part of this publication may be reproduced, stored in a retrieval system or transmitted in any form or by any means, electronic,
mechanical, photocopying, recording, scanning or otherwise, except as permitted under Sections 107 or 108 of the 1976 United States
Copyright Act, without either the prior written permission of the Publisher, or authorization through payment of the appropriate
per-copy fee to the Copyright Clearance Center, 222 Rosewood Drive, Danvers, MA01923, (978) 750-8400, fax (978) 646-8600.


Requests to the Publisher for permission should be addressed to the Legal Department, Wiley Publishing, Inc., 10475 Crosspoint Blvd.,
Indianapolis, IN 46256, (317) 572-3447, fax (317) 572-4355, or online at />LIMIT OF LIABILITY/DISCLAIMER OF WARRANTY: THE PUBLISHER AND THE AUTHOR MAKE NO REPRESENTATIONS
OR WARRANTIES WITH RESPECT TO THE ACCURACY OR COMPLETENESS OF THE CONTENTS OF THIS WORK AND
SPECIFICALLY DISCLAIM ALL WARRANTIES, INCLUDING WITHOUT LIMITATION WARRANTIES OF FITNESS FOR A PAR-
TICULAR PURPOSE. NO WARRANTY MAY BE CREATED OR EXTENDED BY SALES OR PROMOTIONAL MATERIALS. THE
ADVICE AND STRATEGIES CONTAINED HEREIN MAY NOT BE SUITABLE FOR EVERY SITUATION. THIS WORK IS SOLD
WITH THE UNDERSTANDING THAT THE PUBLISHER IS NOT ENGAGED IN RENDERING LEGAL, ACCOUNTING, OR
OTHER PROFESSIONAL SERVICES. IF PROFESSIONALASSISTANCE IS REQUIRED, THE SERVICES OF A COMPETENT PRO-
FESSIONAL PERSON SHOULD BE SOUGHT. NEITHER THE PUBLISHER NOR THE AUTHOR SHALL BE LIABLE FOR DAM-
AGES ARISING HEREFROM. THE FACT THAT AN ORGANIZATION OR WEBSITE IS REFERRED TO IN THIS WORK AS A
CITATION AND/OR A POTENTIAL SOURCE OF FURTHER INFORMATION DOES NOT MEAN THAT THE AUTHOR OR THE
PUBLISHER ENDORSES THE INFORMATION THE ORGANIZATION OR WEBSITE MAY PROVIDE OR RECOMMENDATIONS
IT MAY MAKE. FURTHER, READERS SHOULD BE AWARE THAT INTERNET WEBSITES LISTED IN THIS WORK MAY HAVE
CHANGED OR DISAPPEARED BETWEEN WHEN THIS WORK WAS WRITTEN AND WHEN IT IS READ.
For general information on our other products and services please contact our Customer Care Department within the United States
at (800) 762-2974, outside the United States at (317) 572-3993 or fax (317) 572-4002.
Library of Congress Cataloging-in-Publication Data:
Beginning ASP.net 2.0 with C# / Chris Hart [et al.].
p. cm.
Includes index.
ISBN-13: 978-0-470-04258-8 (paper/website)
ISBN-10: 0-470-04258-3 (paper/website)
1. Active server pages. 2. Web sites—Design. 3. Microsoft .NET. 4. C# (Computer program language) I. Hart, Chris, 1976-
TK5105.8885.A26B4535 2006
005.2'76—dc22
2006007661
Trademarks: Wiley, the Wiley logo, Wrox, the Wrox logo, Programmer to Programmer, and related trade dress are trademarks or
registered trademarks of John Wiley & Sons, Inc. and/or its affiliates, in the United States and other countries, and may not be
used without written permission. All other trademarks are the property of their respective owners. Wiley Publishing, Inc., is not
associated with any product or vendor mentioned in this book.

Wiley also publishes its books in a variety of electronic formats. Some content that appears in print may not be available in
electronic books.
01_042583 ffirs.qxd 4/4/06 2:38 PM Page iv
About the Authors
Chris Hart
Chris normally works at Trinity Expert Systems Plc, based in Coventry (UK), but is currently on mater-
nity leave. She’s worked on several major .NET, SharePoint, and CMS applications. She enjoys having a
job where she gets to learn and play with new technologies on a regular basis, often working on-site
with customers. She’s been using .NET since the pre-Alpha days, and yet still enjoys the fun of working
with beta software.
Chris lives in Birmingham (UK, not Alabama) with her extremely understanding husband James and
baby Nathan, and is discovering that motherhood is more challenging than developing a CMS system
for a major client. She’s currently trying to work out how to make the home network toddlerproof.
I’d like to thank James for being so understanding — this was the hardest one yet, and you were great.
Thanks also to my brother Rob for your inspiring creativity — best of luck in your final year at Uni.
Thanks to Lou for designing the Wrox United site, and for being such a fantastic friend. Finally, thanks
to Nathan for waiting eight more days after I finished my final drafts before arriving into the world.
Chris Hart contributed Chapters 3–5 and 11 and Appendix C to this book.
John Kauffman
John Kauffman was born in Philadelphia, the son of a chemist and a nurse. He received his degrees from
The Pennsylvania State University, the colleges of Science and Agriculture. His early research was for
Hershey foods in the genetics of the chocolate tree and the molecular biology of chocolate production.
Since 1993 John has focused on explaining technology in the classroom and in books.
In his spare time, John is an avid sailor and youth sailing coach. He also enjoys jazz music and drum-
ming. In addition to technical material, he manages to read the New Yorker magazine from cover-to-
cover each week.
John Kauffman contributed Chapters 1, 2, 7, and 8 and Appendix D to this book.
Dave Sussman
Dave Sussman is an independent trainer, consultant, and writer, who inhabits that strange place called beta
land. It’s full of various computers, multiple boot partitions, VPC images, and very occasionally, stable soft-

ware. When not writing books or testing alpha and beta software, Dave can be found working with a vari-
ety of clients helping to bring ASP.NET projects into fruition. He is a Microsoft MVP, and a member of the
ASP Insiders and INETA Speakers Bureau. You can find more details about Dave and his books at his offi-
cial website (
www.ipona.com) or the site he shares with Alex Homer ().
Dave Sussman contributed Chapters 6, 9, 14, and 15 and Appendix E to this book.
01_042583 ffirs.qxd 4/4/06 2:38 PM Page v
Chris Ullman
Chris Ullman is a freelance web developer and technical author who has spent many years stewing in
ASP/ASP.NET, like a teabag left too long in the pot. Coming from a Computer Science background, he
started initially as a UNIX/Linux guru, who gravitated towards MS technologies during the summer of
ASP (1997). He cut his teeth on Wrox Press ASP guides, and since then, he has written on over 20 books,
most notably as lead author for Wrox’s bestselling Beginning ASP/ASP.NET 1.x series, and has con-
tributed chapters to books on PHP, ColdFusion, JavaScript, Web Services, C#, XML, and other Internet-
related technologies too esoteric to mention, now swallowed up in the quicksands of the dot.com boom.
Quitting Wrox as a full-time employee in August 2001, he branched out into VB.NET/C# programming
and ASP.NET development and started his own business, CUASP Consulting Ltd, in April 2003. He
maintains a variety of sites from
www.cuasp.co.uk, his “work” site, to www.atomicwise.com, a selec-
tion of his writings on music and art. The birth of his twins Jay and Luca in February 2005 took chaos to
a new level. He now divides his time between protecting the twins from their over-affectionate three-
year-old brother Nye, composing electronic sounds on bits of dilapidated old keyboards for his music
project Open E, and tutoring his cats in the art of peaceful co-existence and not violently mugging each
other on the stairs.
Chris Ullman contributed Chapters 10, 12, 13, and 16 and Appendix B to this book.
01_042583 ffirs.qxd 4/4/06 2:38 PM Page vi
Credits
Senior Acquisitions Editor
Jim Minatel
Development Editor

Brian Herrmann
Technical Editor
Dan Maharry
Production Editor
Felicia Robinson
Copy Editor
Kim Cofer
Editorial Manager
Mary Beth Wakefield
Production Manager
Tim Tate
Vice President and Executive Group Publisher
Richard Swadley
Vice President and Executive Publisher
Joseph B. Wikert
Graphics and Production Specialists
Jennifer Click
Alicia B. South
Julie Trippetti
Quality Control Technicians
John Greenough
Brian Walls
Project Coordinator
Bill Ramsey
Proofreading and Indexing
Techbooks
01_042583 ffirs.qxd 4/4/06 2:38 PM Page vii
Chris Ullman: All my love to my wife Kate and the boys.
01_042583 ffirs.qxd 4/4/06 2:38 PM Page viii
Acknowledgments

Chris Hart
I’d like to thank James for sharing me with a laptop while I wrote this book—this was the hardest one
yet, and you were great. Thanks also to my brother Rob for your inspiring creativity—best of luck in
your final year at Uni. Finally, big thanks to Lou for designing the Wrox United site, and for being such a
fantastic friend.
John Kauffman
I gratefully acknowledge the help of the Microsoft ASP.NET 2.0 development team, particularly Bradley
Millington. It was Brad who first demonstrated the enormous capability of the ASP.NET 2.0 data con-
trols to me and has continued to tutor me in the best use of the code his team developed. I also deeply
appreciate the ongoing advice and friendship of my co-author Dave Sussman.
Dave Sussman
I would like to thank everyone on the ASP.NET team for supplying interim builds and answering many
questions; Dan Maharry for his invaluable reviewing; and Brian Herrmann for coping admirably with
not only my writing, but also my occasional stroppy fits.
Chris Ullman
Thanks to everyone on the author team (Dave, Chris, and John) for being available for my Messenger
and email queries, thanks to Dan for being an honest reviewer and always ready with good advice, and
thanks to Jim and Brian for being patient on the chapters—I got there eventually!
01_042583 ffirs.qxd 4/4/06 2:38 PM Page ix
01_042583 ffirs.qxd 4/4/06 2:38 PM Page x
Contents
Acknowledgments ix
Introduction xxiii
Chapter 1: An Introduction to ASP.NET 2.0 and the Wrox United Application 1
The Site You Will Build 3
ASP.NET 2.0 — A Powerful Tool to Build Dynamic Web Sites 4
Simple Solutions for Common Web Site Tasks 5
Consistency and Personalization 5
Navigation 5
Login, Security, and Roles 5

Connection to Data 6
Code 6
Componentization 6
Web Services 6
Performance and Caching 6
Errors and Exception Handling 7
Deployment 7
Development Tools 7
Where Does ASP.NET 2.0 Fit with Other Technology? 7
Exploring the Wrox United Application 8
Getting Started with Your Wrox United Site 10
VWD Express — A Development Environment 10
Introducing the ASP.NET Development Server 11
VWD’s Solution Explorer 11
Creating, Opening, and Using Web Sites and Pages with VWD 13
The Sample Code (Download) Directories 14
Running a Page 15
Design Surface 16
Toolbox 18
Properties Window 20
Error List Window 22
VWD’s Database Explorer 24
Summary 25
Exercises 25
02_042583 ftoc.qxd 4/4/06 2:39 PM Page xi
xii
Contents
Chapter 2: Site Design 27
General Design Objectives 28
Master and Content Pages 29

Creating a Master Page 29
Creating Content Pages 31
A Sample of Master and Content Pages 33
Using Cascading Style Sheets in a Master Page 34
Additional Capabilities of Master Pages 39
Multiple Levels of Master Pages 39
Master Pages Support Multiple Content Placeholders 41
Creating a Site Map 42
General Guidelines for Site Design 45
Standard Files for ASP.NET 2.0 Applications 45
Web.config Holds Settings for the Entire Site 45
Global.asax Holds Code for the Entire Site 50
Editing Site Configuration Through a Web Browser 50
Troubleshooting Site Design Errors 53
Summary 53
Exercises 54
Chapter 3: Page Design 55
Static Page Design 55
The World of HTML 62
From HTML to XHTML Code 66
Dynamic Content 68
Dynamic Client Code and Dynamic Server Code 69
Introduction to Server Controls 69
The Server Control Toolbox 70
What Are Server Controls? 71
Source View in VWD 75
Types of Server Controls 80
Standard Controls 80
HTML Controls 82
Navigation Controls 83

Summary 97
Exercises 98
02_042583 ftoc.qxd 4/4/06 2:39 PM Page xii
xiii
Contents
Chapter 4: Membership and Identity 101
Security Basics 102
Identity — Who Am I? 102
Authentication — This Is Who I Am 102
Authorization — This Is What I Can Do 102
Logging In to a Site 103
ASP.NET Security 103
Login Controls 103
Personalization 117
Membership 120
Authentication 125
Wrox United Security 128
Summary 131
Exercises 132
Chapter 5: Styling with Themes 133
Styling a Site 133
Style Attributes 134
CSS — Cascading Style Sheets 138
Themes 147
Applying Styling to a Site 165
Themes in Wrox United 167
Styling and Layout Best Practices 172
Usability 172
Accessibility 172
Summary 173

Exercises 174
Chapter 6: Events and Code 175
Web Server Architecture 175
HTTP Is Stateless 176
Server-Side Events 177
Adding Events to the Page 178
The Postback Architecture 184
What Events Are Available? 186
Which Events Should I Use? 186
Events Aren’t Triggered by Users Only 189
02_042583 ftoc.qxd 4/4/06 2:39 PM Page xiii
xiv
Contents
Indirect Events 193
Canceling Events 196
Global Events 200
Summary 201
Exercises 202
Chapter 7: Reading Data 203
Introducing Databases 203
Using ASP.NET 2.0’s Data Controls 205
Introducing Data Source Controls 205
Introducing Data-Bound Controls 206
Data Source Controls and Data-Bound Controls Work Together 211
Configuring Data Controls with VWD 211
Data Source Controls 212
The Basic Properties of Data Source Controls 212
Hiding the Connection String 215
Details of the Connection String and Provider 217
Data-Bound Controls 218

Data-Bound Selection Lists 218
The GridView Control 225
The DataList and Repeater Controls 231
The DetailsView and FormView Controls 239
Data Source Controls with Parameters 242
Multiple Data Controls Working Together 247
Working with XML Data 253
Reading XML Data 255
Binding Syntax 258
Summary 259
Exercises 260
Chapter 8: Writing Data 261
Introduction to Writing Data 261
Options for Writing Data 262
DataKeyNames 262
Changing Existing Records 263
Adding New Records 269
Deleting Records 271
Uploading Pictures 274
Improving the Upload of Pictures 278
Summary 283
Exercises 284
02_042583 ftoc.qxd 4/4/06 2:39 PM Page xiv
xv
Contents
Chapter 9: Code 285
Variables and Data Types 285
Common Language Runtime Types 287
What Are All Those Curly Brackets and Semicolons For? 288
Declaring Variables 288

Assigning Values 289
Data Conversion 289
Null Values 291
Working with Strings 291
Working with Dates 294
Working with Arrays and Collections 297
Deciding Whether to Use Arrays or Collections 303
Enumerations 304
Constants 305
Statements 306
Operators 306
Decisions 312
Loops 316
Namespaces 326
Working with Classes 327
Creating Classes 328
Inheritance 338
Variable Scope and Lifetime 343
Generics 345
Summary 346
Exercises 346
Chapter 10: Componentization 347
The Separation of Code from Content 348
The Separation of Code from Design 349
Code-Behind 350
The Page Directive 350
Partial Classes 351
Event Handlers/Functions 351
Creating a Code-Behind File 352
Compilation in ASP.NET 2.0 356

The App_Code Folder 357
Data Layers 357
Two-Tier Applications 357
Three-Tier Applications 358
What’s New in ASP.NET 2.0 359
The Wrox United ObjectDataSource 364
02_042583 ftoc.qxd 4/4/06 2:39 PM Page xv
xvi
Contents
User Controls 367
User Control Structure 369
A Simple User Control 370
The Wrox United News User Control 375
Composite Controls 379
Assemblies and Custom Server Controls 379
Summary 380
Exercises 381
Chapter 11: Roles and Profiles 383
The Importance of Roles 384
Introducing Roles in Wrox United 385
Configuring Page-Level Authorization 396
Controlling Page Visibility 397
Working with Roles in Code 404
Enabling User Profiles 405
Building a Profile 406
Profiles in Wrox United 408
Storing Preferences 416
Managing Anonymous Shopping Carts 422
Summary 423
Exercises 423

Chapter 12: Web Services 425
Looking at Web Services 426
Consuming a Third-Party Web Service 427
The Life Cycle of a Web Service 430
Calling the Web Service 431
Transmitting the Web Service 431
Returning the Response 433
Using the Response 435
The Structure of Your Web Service 435
Processing Directive 435
Namespaces 436
Public Class 436
Web Methods 436
Creating a Web Service 438
Testing Your Web Service 441
The WSDL Contract 443
02_042583 ftoc.qxd 4/4/06 2:39 PM Page xvi
xvii
Contents
Web Service Discovery 444
DISCO 445
UDDI 445
Discovering Your Web Service 445
Adding the Fixture Service to Your Application 447
Putting It All Together 450
Remote Web Services — PocketPC Application 455
Web Service Security 459
Encryption and Message-Based Security 459
Authentication and Access Controls for Services 459
Summary 460

Exercises 460
Chapter 13: E-Commerce 461
The E-Commerce Pipeline 462
The Product Catalog 463
The Structure of the Catalog 463
The Design of the Catalog 463
Implementation of the Catalog 464
The Product Item Page 471
The Shopping Cart 477
The Shopping Object 477
The Profile 487
The Shopping Cart Control 489
Checkout 502
Order Processing 503
Login 503
Address/Delivery Details 503
Credit Card Handling 504
How You Intend to Checkout 505
Secure Transactions 520
What Else Can You Do? 520
Summary 521
Exercises 521
Chapter 14: Performance 523
Simple Techniques 523
Object Disposal 524
Database Connections 527
Stored Procedures 527
02_042583 ftoc.qxd 4/4/06 2:39 PM Page xvii
xviii
Contents

Strongly Typed Collections 536
Session State 537
View State 538
Pages and Code 539
Data Binding and Postback 539
Object References 540
StringBuilder Versus String Concatenation 540
Picking the Right Collection 542
Caching 543
Page Caching 543
Designing for Performance 548
Web Server Hardware and Software 549
Testing Performance 549
Tracing 549
Stress Testing Tools 552
Performance Monitor 552
Summary 553
Exercises 553
Chapter 15: Dealing with Errors 555
Defensive Coding 555
Parameter Checking 556
Avoiding Assumptions 557
Query Parameters 558
Validation 559
Exception Handling 564
What Are Exceptions? 565
The Exception Object 565
How to Trap Exceptions 566
Logging Exceptions 573
Mailing Exceptions 576

Raising Exceptions 578
Exceptions Best Practices 579
Global Exception Handling 579
Custom Error Pages 581
Configuring Custom Error Pages 582
Debugging and Tracing 583
Using ASP.NET Tracing 584
Using the Debugger 588
Summary 595
Exercises 596
02_042583 ftoc.qxd 4/4/06 2:39 PM Page xviii
xix
Contents
Chapter 16: Deployment, Builds, and Finishing Up 597
Site Deployment 598
Checklist 598
Compiling and Running Your Application 599
Publishing the Site 600
XCOPY Deployment 603
Common Problems Encountered When Deploying a Site 605
Testing and Maintenance 609
Testing Before and After 609
Maintenance 610
Where to Now? 617
References 618
Summary 618
Exercise 619
Appendix A: Exercise Answers 621
Appendix B: Setup 647
System Requirements 647

Processor 647
Operating System 648
RAM 648
Hard Disk 648
CD or DVD Drive 648
Display 648
Mouse 648
Visual Web Developer Express Installation 648
Web Site Folder Setup 654
IIS Setup (Optional) 654
Wrox United Installation 658
Network Service Enabling 659
Windows XP Home Edition Users Only 661
Checking the Installation with VWD and the ASP.NET Development Server 661
Checking the Installation with IIS 662
Troubleshooting 663
02_042583 ftoc.qxd 4/4/06 2:39 PM Page xix
xx
Contents
Appendix C: Wrox United Database Design 665
Players and Matches 666
The Players Table 666
The Goals Table 667
The Fixtures Table 668
The MatchReports Table 669
The Gallery Table 669
Standalone Tables 669
The Opponents Table 669
The News Table 670
Wrox United Store Tables 670

The Orders Table 670
The OrderLines Table 671
The Products Table 672
Appendix D: VWD Database Explorer 673
Opening the Database Explorer 673
Adding an Existing Database to the Database Explorer 673
Accessing Files 674
SQL Databases on a SQL Server (Including SQL Server Express) 675
Saving SQL Databases as an MDF File 676
Viewing Database Diagrams 677
Exploring a Table’s Structure 681
Observing and Editing Data of Existing Tables 682
Creating a New Database 683
Creating a New Table and Adding Data 683
Examining and Creating Views 684
Examining a Stored Procedure (SPROC) 689
Summary 690
Appendix E: CSS and HTML Quick Reference 691
Styling Pages and Controls 691
Creating Inline Styles 692
Linking Style Sheets to a Page 693
CSS Inheritance 693
CSS Styles 693
CSS Sizes 695
Fonts 695
Colors 696
02_042583 ftoc.qxd 4/4/06 2:39 PM Page xx
xxi
Contents
CSS Selectors 696

Floating Elements 698
Pseudo Classes 699
CSS Reference 699
Common HTML Tags by Category 704
Document Structure 704
Titles and Headings 705
Paragraphs and Lines 705
Text Styles 706
Lists 707
Tables 707
Links 707
Graphics, Objects, Multimedia, and Scripts 708
Forms 708
Frames 709
HTML Common Attributes to the CSS Property 709
Recommended Reading 711
Index 713
02_042583 ftoc.qxd 4/4/06 2:39 PM Page xxi
02_042583 ftoc.qxd 4/4/06 2:39 PM Page xxii

×