Wiley Beginning ASP Dot NET 2 0 Nov 2005 ISBN 0764588508 pdf

  TEAM LinG

  Beginning ASP.NET 2 .0

  

Beginning ASP.NET 2 .0

Chris Hart, John Kauffman, Dave Sussman, and Chris Ullman

  Beginning ASP.NET 2 .0

  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-7645-8850-1

  ISBN-10: 0-7645-8850-8 Manufactured in the United States of America 10 9 8 7 6 5 4 3 2 1

  1B/SW/RQ/QV/IN Library of Congress Cataloging-in-Publication Data is available from the Publisher. 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 permis- sion 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 http://www. wiley.com/go/permissions .

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 HERE- FROM. 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 DISAP- PEARED 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.

  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.

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

  About the Authors Chris Hart

  Chris works full-time as a developer at Trinity Expert Systems Plc, based in Coventry (UK), where 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, as she tries to fit writing alongside her hectic job and her attempts at gardening. She collects computers in much the same way as some old ladies collect cats.

  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 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 Web site (www.ipona.com) or the site he shares with Alex Homer (http://dave andal.net ).

  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 toward MS technologies during the summer of ASP (1997). He cut his teeth on Wrox Press ASP guides, and since then he has written on more than 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 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 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 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 coexistence, 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

  Richard Swadley

  Indexing

  Sossity R. Smith

  Proofreading

  Leeann Harney

  Quality Control Technician

  Andrea Dahl Carrie Foster Lauren Goddard Denny Hager Joyce Haughey Jennifer Heleine Stephanie D. Jumper Lynsey Osborn Alicia B. South

  Graphics and Production Specialists

  Ryan Steffen

  Project Coordinator

  Joseph B. Wikert

  Vice President and Publisher

  Vice President & Executive Group Publisher

  Jim Minatel

  Tim Tate

  Production M anager

  Mary Beth Wakefield

  Editorial M anager

  Kim Cofer

  Copy Editor

  Felicia Robinson

  Production Editor

  Dan Maharry

  Technical Editor

  Brian Herrmann

  Development Editor

  TECHBOOKS Production Services

  Contents

Acknowledgments xx

i Introduction xxiii Who This Book Is For xxiii What This Book Covers xxiv

  Chapte r 1 : An Intro duc tio n to AS P.NET 2 .0 and the Wro x Unite d Applic atio n xxiv Chapte r 2 : S ite De s ign xxiv Chapte r 3 : Page De s ign xxiv Chapte r 4 : Me mbe rs hip and Ide ntity xxv Chapte r 5 : S tyling with The me s xxv Chapte r 6 : Eve nts and Co de xxv Chapte r 7 : Re ading Data xxv Chapte r 8 : Writing Data xxv Chapte r 9 : Co de xxv Chapte r 1 0 : Co mpo ne ntizatio n xxv Chapte r 1 1 : Ro le s and Pro file s xxvi Chapte r 1 2 : We b S e rvic e s xxvi Chapte r 1 3 : E-Co mme rc e xxvi Chapte r 1 4 : Pe rfo rmanc e xxvi Chapte r 1 5 : De aling with Erro rs xxvi Chapte r 1 6 : De plo yme nt, Builds , and Finis hing Up xxvi

  How This Book Is Structured xxv ii What You Need to Use This Book xxv ii

  

Conventions xxv

ii Source Code xxv iii Errata xxv iii

p2 p.wrox.com xx

ix

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 Co ns is te nc y and Pe rs o nalizatio n

  5 Navigatio n

  5 Lo gin, S e c urity, and Ro le s

  5 Co nne c tio n to Data

  6 Co de

  6 Co nte nts Co mpo ne ntizatio n 6 We b S e rvic e s

  6 Pe rfo rmanc e and Cac hing

  7 Erro rs and Exc e ptio n Handling

  7 De plo yme nt

  7 De ve lo pme nt To o ls

  7 Where Does ASP.NET 2 .0 Fit with Other Technology?

  8 Exploring the Wrox United Application

  9 Getting Started with Your Wrox United Site 1 0

  VWD Express — A Development Environment 1 0 Intro duc ing Cas s ini

  1 1

  VWD’s S o lutio n Explo re r 1 1 Cre ating, Ope ning, and Us ing We b S ite s and Page s with VWD 1 4

  The S ample Co de Dire c to rie s 1 4 Running a Page 1 6 De s ign S urfac e 1 7 To o lbo x 1 8 Pro pe rtie s Windo w 2 1 Erro r Lis t Windo w 2 2

  VWD’s Databas e Explo re r 2 5

  Summary 2 6 Exercises 2 6

Chapter 2 : Site Design

  2 9 General Design Objectives 3 0 M aster and Content Pages 3 1

  Cre ating a Mas te r Page 3 1 Cre ating Co nte nt Page s 3 3 A S ample o f Mas te r and Co nte nt Page s 3 5 Us ing Cas c ading S tyle S he e ts in a Mas te r Page 3 6

  Additional Capabilities of M aster Pages 4 2

  Multiple Le ve ls o f Mas te r Page s 4 2 Mas te r Page s S uppo rt Multiple Co nte nt Plac e ho lde rs 4 3

  Creating a Site M ap 4 4 General Guidelines for Site Design 4 7 Standard Files for ASP.NET 2 .0 Applications 4 7

  We b.c o nfig Ho lds S e ttings fo r the Entire S ite 4 8 Glo bal.as ax Ho lds Co de fo r the Entire S ite 5 2 Editing S ite Co nfiguratio n Thro ugh a We b Bro ws e r 5 2

  Troubleshooting Site Design Errors 5 5 Summary 5 5 Exercises 5 6 xii

  Co nte nts Chapter 3 : Page Design

  5 7 Static Page Design 5 7 The World of HTM L 6 5

  Fro m HTML to XHTML Co de 6 8

  Dynamic Content 7 0

  Dynamic Clie nt Co de and Dynamic S e rve r Co de 7 1 Introduction to Server Controls

  7 2 The S e rve r Co ntro l To o lbo x

  7 2 What Are S e rve r Co ntro ls ? 7 3 S o urc e Vie w in VWD 7 8

  Types of Server Controls 8 3

  S tandard Co ntro ls 8 3 HTML Co ntro ls 8 4 Navigatio n Co ntro ls 8 6

  

Summary 1 0 2

Exercises 1 0 3

Chapter 4 : M embership and Identity

  1 0 5 Security Basics 1 0 6

  Ide ntity — Who Am I? 1 0 6 Authe ntic atio n — This Is Who I Am 1 0 6 Autho rizatio n — This Is What I Can Do 1 0 6 Lo gging In to a S ite 1 0 7

  ASP.NET Security 1 0 7

  Lo gin Co ntro ls 1 0 7 Pe rs o nalizatio n 1 2 1 Me mbe rs hip 1 2 4 Authe ntic atio n 1 3 0

  Wrox United Security 1 3 2

  

Summary 1 3 6

Exercises 1 3 6

Chapter 5 : Styling with Themes

  1 3 7 Styling a Site 1 3 7

  S tyle Attribute s 1 3 8 CS S — Cas c ading S tyle S he e ts 1 4 2 The me s 1 5 1 Applying S tyling to a S ite 1 6 8

  Themes in Wrox United 1 7 1 xiv Co nte nts

  Styling and Layout Best Practices 1 7 7

  2 1 0 Using ASP.NET 2 .0 ’s Data Controls 2 1 1

  Data-Bo und S e le c tio n Lis ts 2 2 4 The GridVie w Co ntro l 2 3 0 The DataLis t and Re pe ate r Co ntro ls 2 3 6 The De tails Vie w and Fo rmVie w Co ntro ls 2 4 4

  Data-Bound Controls 2 2 4

  The Bas ic Pro pe rtie s o f Data S o urc e Co ntro ls 2 1 8 Hiding the Co nne c tio n S tring 2 2 1 De tails o f the Co nne c tio n S tring and Pro vide r 2 2 3

  Data Source Controls 2 1 7

  Co nfiguring Data Co ntro ls with VWD 2 1 7

  Intro duc ing Data S o urc e Co ntro ls 2 1 1 Intro duc ing Data-Bo und Co ntro ls 2 1 2 Data S o urc e Co ntro ls and Data-Bo und Co ntro ls Wo rk To ge the r 2 1 6

  Chapter 7 : Reading Data 2 0 9 Introducing Databases

  Us ability 1 7 7 Ac c e s s ibility 1 7 8

  Events Aren’t Triggered by Users Only 1 9 5 Indirect Events 2 0 0 Canceling Events 2 0 3 Global Events 2 0 6 Summary 2 0 7 Exercises 2 0 8

  The Po s tbac k Arc hite c ture 1 9 0 What Eve nts Are Available ? 1 9 1 Whic h Eve nts S ho uld I Us e ? 1 9 3

  1 8 3 Adding Events to the Page 1 8 4

  1 8 2 Server-Side Events

  1 8 1 HTTP Is S tate le s s

  Chapter 6 : Events and Code 1 8 1 Web Server Architecture

  Summary 1 7 9 Exercises 1 7 9

  Data Source Controls with Parameters 2 4 7

  Co nte nts

M ultiple Data Controls Working Together 2 5 2

Working with XM L Data

  2 5 8 Re ading XML Data

  2 6 0 Binding Syntax

  2 6 2

Summary 2 6 3

Exercises 2 6 4

  Chapter 8 : Writing Data 2 6 5 Introduction to Writing Data

  2 6 5 Optio ns fo r Writing Data

  2 6 6 DataKe yName s 2 6 6 Changing Existing Records

  2 6 7 Adding New Records 2 7 3 Deleting Records 2 7 5 Uploading Pictures 2 7 8 Improving the Upload of Pictures 2 8 1

  

Summary 2 8 6

Exercises 2 8 7

Chapter 9 : Code

  2 8 9 Variables and Data Types 2 8 9

  Co mmo n Language Runtime Type s 2 9 1 De c laring Variable s 2 9 2 As s igning Value s 2 9 2 Data Co nve rs io n 2 9 3 Null Value s 2 9 5 Wo rking with S trings 2 9 5 Wo rking with Date s 2 9 7 Wo rking with Arrays and Co lle c tio ns 3 0 1 De c iding Whe the r to Us e Arrays o r Co lle c tio ns 3 0 7

  Enume ratio ns 3 0 7 Co ns tants 3 0 9

  

Statements 3 1 0

Ope rato rs

  3 1 0 De c is io ns 3 1 7 Lo o ps 3 2 0

  

Namespaces 3 2 8

Working with Classes 3 2 9

  Cre ating Clas s e s 3 3 0 Inhe ritanc e 3 3 9 Co nte nts Variable Scope and Lifetime

  3 4 4 Generics 3 4 5 Summary 3 4 6 Exercises 3 4 7

  Chapter 1 0 : Componentization 3 4 9 The Separation of Code from Content

  3 5 0 The Separation of Code from Design 3 5 1 Code-Behind 3 5 2

  The Page Dire c tive 3 5 2 Partial Clas s e s 3 5 3 Eve nt Handle rs / Func tio ns 3 5 3

  Creating a Code-Behind File 3 5 4

  Co mpilatio n in AS P.NET 2 .0 3 5 7 The App_Co de Fo lde r 3 5 9

  Data Layers 3 5 9

  Two -Tie r Applic atio ns 3 5 9 Thre e -Tie r Applic atio ns 3 6 0 What’s Ne w in AS P.NET 2 .0 3 6 1 The Wro x Unite d Obje c tDataS o urc e 3 6 7

  User Controls 3 7 0

  Us e r Co ntro l S truc ture 3 7 2 A S imple Us e r Co ntro l 3 7 3 The Wro x Unite d Ne ws Us e r Co ntro l 3 7 7

  Composite Controls 3 8 2 Assemblies and Custom Server Controls 3 8 2 Summary 3 8 3 Exercises 3 8 3

  Chapter 1 1 : Roles and Profiles 3 8 5 The Importance of Roles

  3 8 6 Introducing Roles in Wrox United 3 8 7 Configuring Page-Level Authorization 3 9 7

  Co ntro lling Page Vis ibility 3 9 9

  Working with Roles in Code 4 0 6 Enabling User Profiles 4 0 7 Building a Profile 4 0 8

  Pro file s in Wro x Unite d 4 1 0 S to ring Pre fe re nc e s 4 1 8

  M anaging Anonymous Shopping Carts 4 2 4 Summary 4 2 5 Exercises 4 2 6 xvi

  Co nte nts

Chapter 1 2 : Web Services

DIS CO

  Adding the Fixture Service to Your Application 4 5 1 Putting It All Together 4 5 4 Remote Web Services — PocketPC Application 4 5 8 Web Service Security 4 6 3

  The S ho pping Obje c t 4 8 2 The Pro file 4 9 0 The S ho pping Cart Co ntro l 4 9 2

  The Shopping Cart 4 8 1

  The S truc ture o f the Catalo g 4 6 7 The De s ign o f the Catalo g 4 6 7 Imple me ntatio n o f the Catalo g 4 6 8 The Pro duc t Ite m Page 4 7 5

  4 6 5 The E-Commerce Pipeline 4 6 6 The Product Catalog 4 6 7

  

Summary 4 6 4

Exercises 4 6 4

  Enc ryptio n and Me s s age -Bas e d S e c urity 4 6 3 Authe ntic atio n and Ac c e s s Co ntro ls fo r S e rvic e s 4 6 3

  4 4 8 UDDI 4 4 8 Dis c o ve ring Yo ur We b S e rvic e 4 4 8

  4 2 7 Looking at Web Services 4 2 8

  Web Service Discovery 4 4 7

  The WS DL Co ntrac t 4 4 6

  Creating a Web Service 4 4 1 Testing Your Web Service 4 4 4

  Pro c e s s ing Dire c tive 4 3 8 Name s pac e s 4 3 9 Public Clas s 4 3 9 We b Me tho ds 4 3 9

  The Structure of Your Web Service 4 3 8

  Calling the We b S e rvic e 4 3 3 Trans mitting the We b S e rvic e 4 3 4 Re turning the Re s po ns e 4 3 6 Us ing the Re s po ns e 4 3 8

  The Life Cycle of a Web Service 4 3 3

  Co ns uming a Third-Party We b S e rvic e 4 2 9

Chapter 1 3 : E-Commerce

  xviii Curre nt He ad Co nte nts

  Page Cac hing 5 4 7

  5 5 9 Parame te r Che c king

  Chapter 1 5 : Dealing with Errors 5 5 9 Defensive Coding

  Summary 5 5 7 Exercises 5 5 7

  Trac ing 5 5 4 S tre s s Te s ting To o ls 5 5 6 Pe rfo rmanc e Mo nito r 5 5 7

  Testing Performance 5 5 3

  We b S e rve r Hardware and S o ftware 5 5 3

  Designing for Performance 5 5 2

  Caching 5 4 7

  Checkout 5 0 5 Orde r Pro c e s s ing

  Data Binding and Po s tbac k 5 4 3 Obje c t Re fe re nc e s 5 4 4 S tringBuilde r Ve rs us S tring Co nc ate natio n 5 4 4 Pic king the Right Co lle c tio n 5 4 6

  Pages and Code 5 4 3

  5 2 8 Databas e Co nne c tio ns 5 3 1 S to re d Pro c e dure s 5 3 1 S tro ngly Type d Co lle c tio ns 5 4 0 S e s s io n S tate 5 4 1 Vie w S tate 5 4 2

  5 2 7 Obje c t Dis po s al

  Chapter 1 4 : Performance 5 2 7 Simple Techniques

  Secure Transactions 5 2 3 What Else Can You Do? 5 2 4 Summary 5 2 4 Exercises 5 2 5

  5 0 6 Lo gin 5 0 6 Addre s s / De live ry De tails 5 0 6 Cre dit Card Handling 5 0 7 Ho w Yo u Inte nd to Che c ko ut 5 0 8

  5 6 0 Avo iding As s umptio ns 5 6 1 Que ry Parame te rs 5 6 2 Validatio n 5 6 3

  Co nte nts Exception Handling

  5 6 8 What Are Exc e ptio ns ?

  5 6 9 The Exc e ptio n Obje c t 5 6 9 Ho w to Trap Exc e ptio ns 5 7 0 Lo gging Exc e ptio ns 5 7 6 Mailing Exc e ptio ns 5 8 0 Rais ing Exc e ptio ns 5 8 2

  Exceptions Best Practices 5 8 2 Global Exception Handling 5 8 3 Custom Error Pages 5 8 5

  Co nfiguring Cus to m Erro r Page s 5 8 5

  Debugging and Tracing 5 8 7

  Us ing AS P.NET Trac ing 5 8 7 Us ing the De bugge r 5 9 2

  

Summary 5 9 9

Exercises 6 0 0

Chapter 1 6 : Deployment, Builds, and Finishing Up 6 0 1 Site Deployment

  6 0 2 Che c klis t

  XCOPY De plo yme nt 6 0 9 Co mmo n Pro ble ms Enc o unte re d Whe n De plo ying a S ite 6 1 1

  Testing and M aintenance 6 1 5

  Te s ting Be fo re and Afte r 6 1 5 Mainte nanc e 6 1 6

  Where To Now? 6 2 3

  

References 6 2 3

Summary 6 2 4

Exercises 6 2 4

Appendix A: Exercise Answers

  6 2 5 Appendix B: Setup 6 5 3

  

Appendix C: Wrox United Database Design 6 7 1

  6 0 2 Co mpiling and Running Yo ur Applic atio n 6 0 3 Publis hing the S ite 6 0 4 Co nte nts Appendix D: VWD Database Explorer

  6 7 9

Appendix E: CSS and HTM L Quick Reference 6 9 9

Index

  7 2 3 xx

  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 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 e-mail 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!

  

I nt roduct i on

  Many different technologies are available today for developing complex web sites and web applications, and with so many to choose from, it’s great that there’s one technology in particular that stands out from the crowd and is such a joy to use. ASP.NET 2.0 is a fantastic technology that enables you to develop web sites and applications with very little hassle. Developing web applications was never this easy, yet even though it may appear simple, there is real power and depth to this technology that enables it to host even the most complex applications available today.

  With every new release from Microsoft comes a new way of thinking, new technologies designed to make your life easier, and the best-ever programming experience; ASP.NET 2.0 is no exception to this rule. Whether you have developed web applications before, or if you are completely new to the world of web development, there’s a lot to learn about this particular version of the technology.

  Built on top of version 2.0 of the .NET Framework, ASP.NET 2.0 extends on the functionality first seen in ASP.NET 1.0 and 1.1. At its core, you have a control-based, event- driven architecture, which means that you have the ability to add small blocks of code to a page, and see dynamic results with minimal effort, and you can react to user input to provide a smooth and intuitive user experience.

  The biggest change since the previous edition of ASP.NET is in the amount of code you have to write— the ASP.NET team aimed for a 70% reduction in the amount of code you write, and having spent time myself working with ASP.NET 2.0 in the field, even if this claim does sound somewhat large, the reduc- tion in time spent with fingers on keys is very noticeable. The mundane and repetitive tasks that you would have previously had to complete have been simplified. For example, providing user login func- tionality to a site is now a very swift process—adding a few controls to a page and setting up some user accounts is pretty much all you need to do to get basic user login functionality implemented on a site, and personalizing the user experience is just a step away from there! Now add the new development environment designed for building ASP.NET 2.0 applications, Visual Web Developer (available on its own, or as part of Visual Studio 2005), and you will find building dynamic, feature-rich applications to be a fast, smooth process.

  Visual Web Developer is a new innovation from Microsoft, and was developed mostly in response to developer demand. Previous editions of Visual Studio .NET were not great when it came to web pro- gramming, and you’d often find your code had been “fixed” for you behind the scenes because your HTML came out looking very different thanthe way it went in originally! Visual Web Developer has a fantastic HTML editing environment, and a really smooth and intuitive interface for developing com- plex ASP.NET applications. Best of all, it’s a low-cost product, which makes it accessible to a wide audi- ence who may not be able to afford the complete Visual Studio package.

  W ho This Book I s For

  This book teaches you how to program web applications in ASP.NET 2.0 that can display data stored in a database, provide a personalized user experience to your users, and even offer shopping functionality. Intro duc tio n

  All of these sorts of web applications can be developed using ASP.NET 2.0, so if these are the sorts of applications that you are interested in developing, then this is a great place to start! This book is for anyone new to web programming, or who has a small amount of knowledge of web pro- gramming concepts. Maybe you want to start a career as a web developer? Or perhaps you just want to learn how to use some cool server-side technology to put together some sites in your spare time? In either case, this book teaches you what you need to know, and gives you a good feel for how the tech- nology works, how to use the Visual Web Developer environment to speed up your development, and to give you total control over the development process. The early chapters in this book ease you into the world of ASP.NET development, and if you already have some knowledge of programming, you will find these early chapters a swift and pleasant read. Note, though, that ASP.NET 2.0 has a lot of neat tricks and tools at its disposal, and we’ll be introducing these throughout the book. As with other Wrox Beginning books, you should find that the concepts dis- cussed in one chapter are then used and extended in other chapters.

  W ha t This Book Cove rs

  This book teaches you ASP.NET 2.0, with the help of the Visual Web Developer IDE (Integrated Development Environment). Working through this book, you will learn how to develop powerful data- driven web applications, and even to expose functionality using web services. Here’s how the book shapes up over the next 16 chapters.

  Chapter 1 : An Introduction to ASP.NET 2 .0 and the Wrox United Application This chapter provides an overview of ASP.NET 2.0 and the Visual Web Developer environment, and

  gives you a chance to create and run a simple page. You’ll also learn about the Wrox United sample web site, which is used in examples throughout the book to demonstrate different aspects of ASP.NET 2.0.

  Chapter 2 : Site Design Now that you’ve gained some familiarity with creating simple pages, this chapter discusses the concept

  of site design, and introduces the concept of a Master page, which can be used to provide a consistent look for all pages on a site. It also introduces Web.config and Global.asax —two important ASP.NET files that control the behavior of a site, and the concept of a site map, for defining a site page hierarchy.

  Chapter 3 : Page Design This chapter starts by providing a quick crash-course (or a refresher course as the case may be) in HTML

  and XHTML development, and introduces the crucial concept of server controls. The chapter continues by demonstrating several of the built-in server controls in action to provide navigation functionality on a site.

  xxiv

  Intro duc tio n

  Chapter 4 : M embership and Identity One of the big new features of ASP.NET 2.0 is the addition of the Login server controls, so this chapter

  introduces these controls, alongside discussions of how to create user accounts, how to configure roles, and how to enable login functionality on a site.

  Chapter 5 : Styling with Themes Once the functionality of a site has been developed, it’s important to make a site look and feel the right

  way. This chapter introduces CSS style sheets, and integrates them into the discussion of ASP.NET’s Theme functionality, making it simple to keep your functionality and your site styling cleanly separated—great for future maintainability!

  Chapter 6 : Events and Code Reacting to events involves writing code, so this chapter talks about server-side coding concepts and

  how web servers work. It walks you through the basics of HTTP so that you will gain an understanding of the postback, and how you can write code to handle postback events.

  Chapter 7 : Reading Data Developing a site will almost always involve reading data stored in a database, and displaying that data

  on the screen, so this chapter talks about how you can use ASP.NET controls (such as the GridView ,

  DataLists , and DetailsView controls) to connect to a database and display data. This chapter also dis- cusses reading data stored in an XML file.

  Chapter 8 : Writing Data The storing and updating of data is the next topic to be covered in this book, and in this chapter, you’ll

  learn some useful techniques for safely updating the data stored in the database using parameters and referring to data using keys that uniquely identify items in a database.

  Chapter 9 : Code This chapter teaches you the fundamental programming concepts that you will need to understand if

  you are to become a fully fledged .NET developer. It starts by taking you through basic variables and data types, before looking at collections, statements, operators, branches, and loops. Then it introduces some object orientation and talks about classes, properties, methods, and simple class design principles.

  Chapter 1 0 : Componentization Having learned all about the principles of code in the previous chapter, this chapter takes those building

  blocks and talks about creating pages with separate code files, and about how to design applications with logic stored in different classes or files. This chapter also introduces the concept of user controls, which are great for storing pieces of code that can be reused across pages on a site. Intro duc tio n

  Chapter 1 1 : Roles and Profiles Following on from simple user accounts and roles as introduced in Chapter 4, this chapter builds on the

  concept of site design, and changing the appearance of a site depending on which user is accessing the site. This chapter also looks at storing user profiles and populating profiles in code, as well as switching the theme used on a site according to user preferences.

  Chapter 1 2 : Web Services At this stage in the book, you’ll have gained sufficient experience with ASP.NET 2.0 and coding that you

  should now be ready to enter the world of web services. First, you’ll learn how to consume a third-party web service, and use that functionality on a page. Next, you’ll get the chance to build your own web ser- vices, and you’ll learn about proxies and WSDL.

  Chapter 1 3 : E-Commerce Adding e-commerce functionality to a site can be a bit tricky, so this chapter walks you through the

  e-commerce facilities built into the Wrox United sample application, looking at how to implement a product catalog, and build a shopping cart system that links in to user’s profiles.

  Chapter 1 4 : Performance You may find your rather lovely web applications may crawl to a halt if you haven’t quite tweaked them

  the right way to make them perform well under heavy loading, so this chapter talks about many of the different ways you can enhance the performance of an application. This includes concepts such as dis- posing of objects, using stored procedures, and making efficient use of caching.

  Chapter 1 5 : Dealing with Errors Errors happen whenever you develop any application, so this chapter talks you through some of the

  most common ways to handle errors, how to trap exceptions, and how to present custom error pages to users of your site. After all, they don’t need to know that your database server collapsed, but they would like to know, if the site is down, that faults will be rectified shortly. You can then use some of the excel- lent debugging and tracing functionality available in ASP.NET.

  Chapter 1 6 : Deployment, Builds, and Finishing Up The final chapter of the book talks you through the ideal way to deploy a finished web application to a

  live server. The application used as an example is the Wrox United application, which you can publish using both the Visual Web Developer tools and what’s known as XCOPY deployment. This chapter also looks at testing the deployment and looking out for common deployment problems. The final part of the chapter reviews the different parts of the Wrox United application, and recaps where each part of the application was discussed in the book. Finally, we’ll give you some pointers as to where you can head next to further your ASP.NET development career!

  xxvi

  Intro duc tio n How This Book I s St ruc t ure d

  This book takes time to explain concepts step-by-step, using worked examples and detailed explana- tions, to tell the story of how to develop ASP.NET applications. Each chapter assumes knowledge devel- oped in previous chapters, so you will likely find a front-to-back study approach works best to understand the concepts explained. Four authors worked on this book as a team, and we all worked quite closely together (with some great editorial support), to give you a steady and complete tutorial of the basics of developing ASP.NET applications.

  W ha t You Ne e d t o Use This Book

  To gain the most from this book, you should have the following software installed on your system: ❑ A minimum of Windows XP Home Edition as your operating system ❑ Microsoft Visual Web Developer ❑ Microsoft SQL Server 2005 Express Edition

  Because Visual Web Developer includes the .NET Framework and ASP.NET 2.0, these three pieces of software are all you will need to develop ASP.NET applications.

  Conve nt ions

  To help you get the most from the text and keep track of what’s happening, we’ve used a number of con- ventions throughout the book.

  Try It Out The Try It Out is an exercise you should work through, following the text in the book.

  1. They usually consist of a set of steps.

  2. Each step has a number.

  3. Follow the steps through with your copy of the code.

  How It Works After each Try It Out, the code you’ve typed will be explained in detail.

  

Boxes like this one hold important, not-to-be forgotten information that is directly

relevant to the surrounding text.

  Tips, hints, tricks, and asides to the current discussion are offset and placed in italics like this. Intro duc tio n

  As for styles in the text: ❑ We italicize new terms and important words when we introduce them.

  ❑ We show keyboard strokes like this: Ctrl+A. ❑ We show file names, URLs, and code within the text like so: persistence.properties . ❑ We present code in two different ways:

In code examples we highlight new and important code with a gray background.

  

The gray highlighting is not used for code that’s less important in the present

context, or has been shown before.

  Sourc e Code

  As you work through the examples in this book, you may choose either to type in all the code manually or to use the source code files that accompany the book. All of the source code used in this book is avail- able for download at http://www.wrox.com . Once at the site, simply locate the book’s title (either by using the Search box or by using one of the title lists) and click the Download Code link on the book’s detail page to obtain all the source code for the book.

  Because many books have similar titles, you may find it easiest to search by ISBN; for this book the ISBN is 0-7645-8850-8.

  Once you download the code, just decompress it with your favorite compression tool. Alternatively, you can go to the main Wrox code download page at http://www.wrox.com/dynamic/books/

  download.aspx to see the code available for this book and all other Wrox books.

  Erra t a

  We make every effort to ensure that there are no errors in the text or in the code. However, no one is per- fect, and mistakes do occur. If you find an error in one of our books, like a spelling mistake or faulty piece of code, we would be very grateful for your feedback. By sending in errata you may save another reader hours of frustration and at the same time you will be helping us provide even higher-quality information. To find the errata page for this book, go to http://www.wrox.com and locate the title using the Search box or one of the title lists. Then, on the book details page, click the Book Errata link. On this page you can view all errata that has been submitted for this book and posted by Wrox editors. A complete book list including links to each book’s errata is also available at www.wrox.com/misc-pages/booklist.

  shtml .

  If you don’t spot “your” error on the Book Errata page, go to www.wrox.com/contact/techsupport.

  

shtml and complete the form there to send us the error you have found. We’ll check the information

  and, if appropriate, post a message to the book’s errata page and fix the problem in subsequent editions of the book.

  xxviii

  Intro duc tio n p2 p. w rox . c om

  For author and peer discussion, join the P2P forums at p2p.wrox.com . The forums are a web-based sys- tem for you to post messages relating to Wrox books and related technologies and interact with other readers and technology users. The forums offer a subscription feature to e-mail you topics of interest of your choosing when new posts are made to the forums. Wrox authors, editors, other industry experts, and your fellow readers are present on these forums. At http://p2p.wrox.com you will find a number of different forums that will help you not only as you read this book, but also as you develop your own applications. To join the forums, just follow these steps:

  1 . Go to p2p.wrox.com and click the Register link.

  2. Read the terms of use and click Agree.

  3. Complete the required information to join as well as any optional information you wish to pro- vide and click Submit.

  

4. You will receive an e-mail with information describing how to verify your account and com-

plete the joining process.

  

You can read messages in the forums without joining P2P but in order to post your own messages, you

must join.

  Once you join, you can post new messages and respond to messages other users post. You can read mes- sages at any time on the web. If you would like to have new messages from a particular forum e-mailed to you, click the Subscribe to this Forum icon by the forum name in the forum listing. For more information about how to use the Wrox P2P, be sure to read the P2P FAQs for answers to ques- tions about how the forum software works as well as many common questions specific to P2P and Wrox books. To read the FAQs, click the FAQ link on any P2P page.

1 An I nt roduct i on t o ASP. NET 2 . 0 a nd t he Wrox Uni t e d Appl i ca t i on

  At the end of the twentieth century something unprecedented happened to computers. Previously relegated to the realm of the bedroom and dedicated hobbyists who never saw the light of day, the explosion of the Internet lead to computers acquiring a glamour, an aura of excitement that had never been associated with them before. Prior to the 1990s it was almost embarrassing to admit you worked with computers, and then suddenly everyone wanted one. Every business had to be attached to the Internet, and many families wanted their own web site. If you had to name one piece of technology that became synonymous with the explosion, it was undoubtedly the web browser. However, without anything to view on a web browser, it becomes virtually useless. You need information, and like mushrooms sprouting up in a woodland, hundreds of web sites on every imaginable subject were born.

  The late ‘90s were a time of vast upheaval. Business empires were founded on the simplest ideas — a search engine (Google) or an online store for buying books (Amazon). Everyone wanted to know how to build a web site for themselves. HTML (HyperText Markup Language) enabled them to do that, but it was soon obvious that it only went so far. You could display pictures and text, but what happened if you wanted more than that? What happened if you wanted a site that was reactive, that received information from your users and was automatically updated without someone having to beaver away writing new web pages every time? What if you wanted to attach a database to the Internet, or you wanted to display a stock catalogue, or you wanted to personal- ize your site to everyone who visited it, or you just wanted it to look good for your family and friends who visited it? The race was on and several competing technologies were created for doing this, including CGI, PHP, and Java. Microsoft’s own entry into the race was ASP and what made it particularly attractive was that it was simpler to pick up and learn than most of its rivals, but it also had some exciting features — the ability to store details of users as they moved through pages on a web site, and controls such as calendars and ad rotators that you could just stick into your pages like HTML tags. ASP was a huge success. Microsoft went one further; it created the .NET Framework, and Chapte r 1

  ASP.NET became a “grown up” version of its ASP technology, using its mature programming languages