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

Beginning asp net 2.0 with c phần 1 pdf

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 (1.34 MB, 77 trang )


Beginning

ASP.NET 2.0 with C#
Chris Hart, John Kauffman, David Sussman, and Chris Ullman



Beginning

ASP.NET 2.0 with C#



Beginning

ASP.NET 2.0 with C#
Chris Hart, John Kauffman, David Sussman, and Chris Ullman


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, MA 01923, (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 PARTICULAR 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 PROFESSIONAL ASSISTANCE IS REQUIRED, THE SERVICES OF A COMPETENT PROFESSIONAL PERSON SHOULD BE SOUGHT. NEITHER THE PUBLISHER NOR THE AUTHOR SHALL BE LIABLE FOR DAMAGES 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, 1976TK5105.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.


About the Authors
Chris Hart
Chris normally works at Trinity Expert Systems Plc, based in Coventry (UK), but is currently on maternity 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 drumming. In addition to technical material, he manages to read the New Yorker magazine from cover-tocover 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 software. When not writing books or testing alpha and beta software, Dave can be found working with a variety 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 official 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.


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 contributed chapters to books on PHP, ColdFusion, JavaScript, Web Services, C#, XML, and other Internetrelated 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 selection 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 threeyear-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.


Credits
Senior Acquisitions Editor

Graphics and Production Specialists

Jim Minatel

Jennifer Click
Alicia B. South

Julie Trippetti

Development Editor
Brian Herrmann

Quality Control Technicians
Dan Maharry

John Greenough
Brian Walls

Production Editor

Project Coordinator

Felicia Robinson

Bill Ramsey

Copy Editor

Proofreading and Indexing

Kim Cofer

Techbooks

Technical Editor

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


Chris Ullman: All my love to my wife Kate and the boys.


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 controls 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!



Contents
Acknowledgments
Introduction
Chapter 1: An Introduction to ASP.NET 2.0 and the Wrox United Application
The Site You Will Build
ASP.NET 2.0 — A Powerful Tool to Build Dynamic Web Sites
Simple Solutions for Common Web Site Tasks
Consistency and Personalization
Navigation
Login, Security, and Roles
Connection to Data
Code
Componentization
Web Services
Performance and Caching
Errors and Exception Handling
Deployment
Development Tools

Where Does ASP.NET 2.0 Fit with Other Technology?

Exploring the Wrox United Application
Getting Started with Your Wrox United Site
VWD Express — A Development Environment
Introducing the ASP.NET Development Server
VWD’s Solution Explorer
Creating, Opening, and Using Web Sites and Pages with VWD
The Sample Code (Download) Directories
Running a Page
Design Surface
Toolbox
Properties Window
Error List Window
VWD’s Database Explorer

Summary
Exercises

ix
xxiii

1
3
4
5
5
5
5
6
6
6

6
6
7
7
7

7
8
10
10
11
11
13
14
15
16
18
20
22
24

25
25


Contents
Chapter 2: Site Design
General Design Objectives
Master and Content Pages
Creating a Master Page

Creating Content Pages
A Sample of Master and Content Pages
Using Cascading Style Sheets in a Master Page

Additional Capabilities of Master Pages
Multiple Levels of Master Pages
Master Pages Support Multiple Content Placeholders

Creating a Site Map
General Guidelines for Site Design
Standard Files for ASP.NET 2.0 Applications
Web.config Holds Settings for the Entire Site
Global.asax Holds Code for the Entire Site
Editing Site Configuration Through a Web Browser

Troubleshooting Site Design Errors
Summary
Exercises

Chapter 3: Page Design
Static Page Design
The World of HTML
From HTML to XHTML Code

Dynamic Content
Dynamic Client Code and Dynamic Server Code

Introduction to Server Controls
The Server Control Toolbox
What Are Server Controls?

Source View in VWD

Types of Server Controls
Standard Controls
HTML Controls
Navigation Controls

Summary
Exercises

xii

27
28
29
29
31
33
34

39
39
41

42
45
45
45
50
50


53
53
54

55
55
62
66

68
69

69
70
71
75

80
80
82
83

97
98


Contents
Chapter 4: Membership and Identity
Security Basics

Identity — Who Am I?
Authentication — This Is Who I Am
Authorization — This Is What I Can Do
Logging In to a Site

101
102
102
102
102
103

ASP.NET Security

103

Login Controls
Personalization
Membership
Authentication

103
117
120
125

Wrox United Security
Summary
Exercises


Chapter 5: Styling with Themes
Styling a Site
Style Attributes
CSS — Cascading Style Sheets
Themes
Applying Styling to a Site

Themes in Wrox United
Styling and Layout Best Practices
Usability
Accessibility

Summary
Exercises

128
131
132

133
133
134
138
147
165

167
172
172
172


173
174

Chapter 6: Events and Code

175

Web Server Architecture

175

HTTP Is Stateless

Server-Side Events
Adding Events to the Page
The Postback Architecture
What Events Are Available?
Which Events Should I Use?

Events Aren’t Triggered by Users Only

176

177
178
184
186
186


189

xiii


Contents
Indirect Events
Canceling Events
Global Events
Summary
Exercises

Chapter 7: Reading Data
Introducing Databases
Using ASP.NET 2.0’s Data Controls
Introducing Data Source Controls
Introducing Data-Bound Controls
Data Source Controls and Data-Bound Controls Work Together
Configuring Data Controls with VWD

Data Source Controls
The Basic Properties of Data Source Controls
Hiding the Connection String
Details of the Connection String and Provider

Data-Bound Controls

193
196
200

201
202

203
203
205
205
206
211
211

212
212
215
217

218

Data-Bound Selection Lists
The GridView Control
The DataList and Repeater Controls
The DetailsView and FormView Controls

218
225
231
239

Data Source Controls with Parameters
Multiple Data Controls Working Together

Working with XML Data

242
247
253

Reading XML Data

Binding Syntax
Summary
Exercises

Chapter 8: Writing Data
Introduction to Writing Data
Options for Writing Data
DataKeyNames

Changing Existing Records
Adding New Records
Deleting Records
Uploading Pictures
Improving the Upload of Pictures
Summary
Exercises

xiv

255

258

259
260

261
261
262
262

263
269
271
274
278
283
284


Contents
Chapter 9: Code
Variables and Data Types
Common Language Runtime Types
What Are All Those Curly Brackets and Semicolons For?
Declaring Variables
Assigning Values
Data Conversion
Null Values
Working with Strings
Working with Dates
Working with Arrays and Collections
Deciding Whether to Use Arrays or Collections

Enumerations
Constants

285
285
287
288
288
289
289
291
291
294
297
303
304
305

Statements

306

Operators
Decisions
Loops

306
312
316


Namespaces
Working with Classes
Creating Classes
Inheritance

326
327
328
338

Variable Scope and Lifetime
Generics
Summary
Exercises

343
345
346
346

Chapter 10: Componentization

347

The Separation of Code from Content
The Separation of Code from Design
Code-Behind

348
349

350

The Page Directive
Partial Classes
Event Handlers/Functions

350
351
351

Creating a Code-Behind File

352

Compilation in ASP.NET 2.0
The App_Code Folder

Data Layers
Two-Tier Applications
Three-Tier Applications
What’s New in ASP.NET 2.0
The Wrox United ObjectDataSource

356
357

357
357
358
359

364

xv


Contents
User Controls
User Control Structure
A Simple User Control
The Wrox United News User Control

Composite Controls
Assemblies and Custom Server Controls
Summary
Exercises

Chapter 11: Roles and Profiles
The Importance of Roles
Introducing Roles in Wrox United
Configuring Page-Level Authorization

367
369
370
375

379
379
380
381


383
384
385
396

Controlling Page Visibility

397

Working with Roles in Code
Enabling User Profiles
Building a Profile

404
405
406

Profiles in Wrox United
Storing Preferences

Managing Anonymous Shopping Carts
Summary
Exercises

408
416

422
423

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
Transmitting the Web Service
Returning the Response
Using the Response

431
431
433
435

The Structure of Your Web Service
Processing Directive

Namespaces
Public Class
Web Methods

Creating a Web Service
Testing Your Web Service
The WSDL Contract

xvi

435
435
436
436
436

438
441
443


Contents
Web Service Discovery
DISCO
UDDI
Discovering Your Web Service

444
445
445

445

Adding the Fixture Service to Your Application
Putting It All Together
Remote Web Services — PocketPC Application
Web Service Security

447
450
455
459

Encryption and Message-Based Security
Authentication and Access Controls for Services

459
459

Summary
Exercises

460
460

Chapter 13: E-Commerce

461

The E-Commerce Pipeline
The Product Catalog


462
463

The Structure of the Catalog
The Design of the Catalog
Implementation of the Catalog
The Product Item Page

The Shopping Cart
The Shopping Object
The Profile
The Shopping Cart Control

Checkout
Order Processing
Login
Address/Delivery Details
Credit Card Handling
How You Intend to Checkout

463
463
464
471

477
477
487
489


502
503
503
503
504
505

Secure Transactions
What Else Can You Do?
Summary
Exercises

520
520
521
521

Chapter 14: Performance

523

Simple Techniques
Object Disposal
Database Connections
Stored Procedures

523
524
527

527

xvii


Contents
Strongly Typed Collections
Session State
View State

Pages and Code
Data Binding and Postback
Object References
StringBuilder Versus String Concatenation
Picking the Right Collection

Caching
Page Caching

Designing for Performance
Web Server Hardware and Software

536
537
538

539
539
540
540

542

543
543

548
549

Testing Performance

549

Tracing
Stress Testing Tools
Performance Monitor

549
552
552

Summary
Exercises

Chapter 15: Dealing with Errors
Defensive Coding
Parameter Checking
Avoiding Assumptions
Query Parameters
Validation


Exception Handling

553
553

555
555
556
557
558
559

564

What Are Exceptions?
The Exception Object
How to Trap Exceptions
Logging Exceptions
Mailing Exceptions
Raising Exceptions

565
565
566
573
576
578

Exceptions Best Practices
Global Exception Handling

Custom Error Pages

579
579
581

Configuring Custom Error Pages

Debugging and Tracing
Using ASP.NET Tracing
Using the Debugger

Summary
Exercises

xviii

582

583
584
588

595
596


Contents
Chapter 16: Deployment, Builds, and Finishing Up
Site Deployment

Checklist
Compiling and Running Your Application
Publishing the Site
XCOPY Deployment
Common Problems Encountered When Deploying a Site

597
598
598
599
600
603
605

Testing and Maintenance

609

Testing Before and After
Maintenance

609
610

Where to Now?
References
Summary
Exercise

617

618
618
619

Appendix A: Exercise Answers

621

Appendix B: Setup

647

System Requirements
Processor
Operating System
RAM
Hard Disk
CD or DVD Drive
Display
Mouse

Visual Web Developer Express Installation
Web Site Folder Setup
IIS Setup (Optional)

Wrox United Installation
Network Service Enabling
Windows XP Home Edition Users Only
Checking the Installation with VWD and the ASP.NET Development Server
Checking the Installation with IIS


Troubleshooting

647
647
648
648
648
648
648
648

648
654
654

658
659
661
661
662

663

xix


Contents
Appendix C: Wrox United Database Design
Players and Matches

The
The
The
The
The

Players Table
Goals Table
Fixtures Table
MatchReports Table
Gallery Table

Standalone Tables
The Opponents Table
The News Table

Wrox United Store Tables
The Orders Table
The OrderLines Table
The Products Table

Appendix D: VWD Database Explorer
Opening the Database Explorer
Adding an Existing Database to the Database Explorer
Accessing Files
SQL Databases on a SQL Server (Including SQL Server Express)
Saving SQL Databases as an MDF File

665
666

666
667
668
669
669

669
669
670

670
670
671
672

673
673
673
674
675
676

Viewing Database Diagrams
Exploring a Table’s Structure
Observing and Editing Data of Existing Tables
Creating a New Database
Creating a New Table and Adding Data
Examining and Creating Views
Examining a Stored Procedure (SPROC)
Summary


677
681
682
683
683
684
689
690

Appendix E: CSS and HTML Quick Reference

691

Styling Pages and Controls
Creating Inline Styles
Linking Style Sheets to a Page
CSS Inheritance
CSS Styles
CSS Sizes
Fonts
Colors

xx

691
692
693
693
693

695
695
696


Contents
CSS Selectors
Floating Elements
Pseudo Classes

CSS Reference
Common HTML Tags by Category
Document Structure
Titles and Headings
Paragraphs and Lines
Text Styles
Lists
Tables
Links
Graphics, Objects, Multimedia, and Scripts
Forms
Frames

696
698
699

699
704
704

705
705
706
707
707
707
708
708
709

HTML Common Attributes to the CSS Property
Recommended Reading

709
711

Index

713

xxi



×