Wrox Programmer to Programmer Beginning ASP.NET 3.5 In C# ... · Kathryn Duggan David Parise Rachel...

30
Updates, source code, and Wrox technical support at www.wrox.com Beginning ASP.NET 3.5 In C# and VB Imar Spaanjaars Wrox Programmer to Programmer TM

Transcript of Wrox Programmer to Programmer Beginning ASP.NET 3.5 In C# ... · Kathryn Duggan David Parise Rachel...

Page 1: Wrox Programmer to Programmer Beginning ASP.NET 3.5 In C# ... · Kathryn Duggan David Parise Rachel Gunn Indexer Melanie Belkin 87593ffirs.qxd:WroxPro 1/29/08 12:47 AM Page ix. 87593ffirs.qxd:WroxPro

Updates, source code, and Wrox technical support at www.wrox.com

Beginning

ASP.NET 3.5In C# and VBImar Spaanjaars

spine=1.536"

www.wrox.com

$44.99 USA$48.99 CAN

Wrox Beginning guides are crafted to make learning programming languages and technologies easier than you think, providing a structured, tutorial format that will guide you through all the techniques involved.

Recommended Computer Book

Categories

Web Development

ASP.NET

ISBN: 978-0-470-18759-3

To build effective and eye-catching database-driven web sites, you must first have a solid framework on which to run your web pages as well as a rich environment in order to create and program these web pages. Microsoft’s ASP.NET 3.5 and Visual Web Developer™ 2008 combine forces to provide you with the ultimate platform on which you can create dynamic and interactive web applications.

Popular Wrox author Imar Spaanjaars begins by demonstrating how to obtain and install Visual Web Developer. With each successive chapter, he introduces you to new technologies that build on knowledge gained from previous chapters. You’ll learn that both ASP.NET 3.5 and Visual Web Developer now come with an extensive set of tools that will help you smoothly program your web applications. With the knowledge you gain from this book, you will be able to create feature-rich, database-driven, interactive web sites.

What you will learn from this book● Ways that ASP.NET Server controls allow you to create complex web

sites with very little code● How to use the extensive set of CSS tools that help you design your

web pages● How to program responsive and interactive web pages with either C#

or Visual Basic®● How to work with databases to create rich, data-driven web pages● How you can easily create a centralized and maintainable site design● How to secure your web site, providing login functionality and role-based

access to content

Who this book is forThis book is for anyone who wants to build rich and interactive web sites that run on the Microsoft platform. No prior experience in web development is assumed.

Enhance Your KnowledgeAdvance Your Career

Beginning

ASP.NET 3.5 In C# and VB

Spaanjaars

BeginningAS

P.NE

T 3.5In C# and VB

Wrox Programmer to Programmer TMWrox Programmer to Programmer TM

Page 2: Wrox Programmer to Programmer Beginning ASP.NET 3.5 In C# ... · Kathryn Duggan David Parise Rachel Gunn Indexer Melanie Belkin 87593ffirs.qxd:WroxPro 1/29/08 12:47 AM Page ix. 87593ffirs.qxd:WroxPro

87593ffirs.qxd:WroxPro 1/29/08 12:47 AM Page ii

Page 3: Wrox Programmer to Programmer Beginning ASP.NET 3.5 In C# ... · Kathryn Duggan David Parise Rachel Gunn Indexer Melanie Belkin 87593ffirs.qxd:WroxPro 1/29/08 12:47 AM Page ix. 87593ffirs.qxd:WroxPro

Beginning

ASP.NET 3.5

Chapter 1: Getting Started with ASP.NET 3.5 . . . . . . . . . . . . . . . . . . . . . . . . . 1Chapter 2: Building an ASP.NET Web Site . . . . . . . . . . . . . . . . . . . . . . . . . . . 33Chapter 3: Designing Your Web Pages . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 63Chapter 4: Working with ASP.NET Controls . . . . . . . . . . . . . . . . . . . . . . . . . 103Chapter 5: Programming Your ASP.NET Web Pages . . . . . . . . . . . . . . . . . . . 135Chapter 6: Creating Consistent Looking Web Sites . . . . . . . . . . . . . . . . . . . 193Chapter 7: Navigation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 235Chapter 8: User Controls . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 267Chapter 9: Validating User Input. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 291Chapter 10: ASP.NET AJAX . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 321Chapter 11: Introduction to Databases. . . . . . . . . . . . . . . . . . . . . . . . . . . . 353Chapter 12: Displaying and Updating Data . . . . . . . . . . . . . . . . . . . . . . . . . 383Chapter 13: LINQ. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 425Chapter 14: Presenting Data — Advanced Topics . . . . . . . . . . . . . . . . . . . . 475Chapter 15: Security in Your ASP.NET 3.5 Web Site . . . . . . . . . . . . . . . . . . 517Chapter 16: Personalizing Web Sites . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 557Chapter 17: Exception Handling, Debugging, and Tracing . . . . . . . . . . . . . . 591Chapter 18: Deploying Your Web Site . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 631Appendix A: Exercise Answers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 665Appendix B: Configuring SQL Server 2005 . . . . . . . . . . . . . . . . . . . . . . . . . 687Index . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 707

87593ffirs.qxd:WroxPro 1/29/08 12:47 AM Page i

Page 4: Wrox Programmer to Programmer Beginning ASP.NET 3.5 In C# ... · Kathryn Duggan David Parise Rachel Gunn Indexer Melanie Belkin 87593ffirs.qxd:WroxPro 1/29/08 12:47 AM Page ix. 87593ffirs.qxd:WroxPro

87593ffirs.qxd:WroxPro 1/29/08 12:47 AM Page ii

Page 5: Wrox Programmer to Programmer Beginning ASP.NET 3.5 In C# ... · Kathryn Duggan David Parise Rachel Gunn Indexer Melanie Belkin 87593ffirs.qxd:WroxPro 1/29/08 12:47 AM Page ix. 87593ffirs.qxd:WroxPro

Beginning

ASP.NET 3.5In C# and VB

Imar Spaanjaars

87593ffirs.qxd:WroxPro 1/29/08 12:47 AM Page iii

Page 6: Wrox Programmer to Programmer Beginning ASP.NET 3.5 In C# ... · Kathryn Duggan David Parise Rachel Gunn Indexer Melanie Belkin 87593ffirs.qxd:WroxPro 1/29/08 12:47 AM Page ix. 87593ffirs.qxd:WroxPro

Beginning ASP.NET 3.5: In C# and VBPublished byWiley Publishing, Inc.10475 Crosspoint BoulevardIndianapolis, IN 46256www.wiley.com

Copyright © 2008 by Wiley Publishing, Inc., Indianapolis, Indiana

Published simultaneously in Canada

ISBN: 978-0-470-18759-3

Manufactured in the United States of America

10 9 8 7 6 5 4 3 2 1

Library of Congress Cataloging-in-Publication Data

Spaanjaars, Imar.Beginning ASP.NET 3.5 / Imar Spaanjaars.

p. cm.Includes index.ISBN 978-0-470-18759-3 (pbk. : web)1. Active server pages. 2. Web sites—Design. 3. Microsoft .NET. I. Title.TK5105.8885.A26S6815 2006005.2'76—dc22

2007052406

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 authorizationthrough 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 LegalDepartment, Wiley Publishing, Inc., 10475 Crosspoint Blvd., Indianapolis, IN 46256, (317) 572-3447, fax (317) 572-4355, oronline at http://www.wiley.com/go/permissions.

Limit of Liability/Disclaimer of Warranty: The publisher and the author make no representations or warranties withrespect to the accuracy or completeness of the contents of this work and specifically disclaim all warranties, includingwithout limitation warranties of fitness for a particular purpose. No warranty may be created or extended by sales orpromotional materials. The advice and strategies contained herein may not be suitable for every situation. This work issold with the understanding that the publisher is not engaged in rendering legal, accounting, or other professional serv-ices. If professional assistance is required, the services of a competent professional person should be sought. Neither thepublisher nor the author shall be liable for damages arising herefrom. The fact that an organization or Website is referredto in this work as a citation and/or a potential source of further information does not mean that the author or the pub-lisher 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 whenthis work was written and when it is read.

For general information on our other products and services please contact our Customer Care Department within theUnited 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, Wrox Programmer to Programmer, and related trade dress aretrademarks or registered trademarks of John Wiley & Sons, Inc. and/or its affiliates, in the United States and other coun-tries, 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 avail-able in electronic books.

87593ffirs.qxd:WroxPro 1/29/08 12:47 AM Page iv

Page 7: Wrox Programmer to Programmer Beginning ASP.NET 3.5 In C# ... · Kathryn Duggan David Parise Rachel Gunn Indexer Melanie Belkin 87593ffirs.qxd:WroxPro 1/29/08 12:47 AM Page ix. 87593ffirs.qxd:WroxPro

To my dad — I know you’d be proud

87593ffirs.qxd:WroxPro 1/29/08 12:47 AM Page v

Page 8: Wrox Programmer to Programmer Beginning ASP.NET 3.5 In C# ... · Kathryn Duggan David Parise Rachel Gunn Indexer Melanie Belkin 87593ffirs.qxd:WroxPro 1/29/08 12:47 AM Page ix. 87593ffirs.qxd:WroxPro

87593ffirs.qxd:WroxPro 1/29/08 12:47 AM Page vi

Page 9: Wrox Programmer to Programmer Beginning ASP.NET 3.5 In C# ... · Kathryn Duggan David Parise Rachel Gunn Indexer Melanie Belkin 87593ffirs.qxd:WroxPro 1/29/08 12:47 AM Page ix. 87593ffirs.qxd:WroxPro

About the AuthorImar Spaanjaars graduated in Leisure Management at the Leisure Management School in the Netherlands,but he quickly changed his career path into the Internet world.

After working for a large corporation and doing some freelance work, he now works for Design IT(www.designit.nl), an IT company in the Netherlands specializing in Internet and intranet applica-tions built with Microsoft technologies like ASP.NET 3.5. As a technical director and software designer,he’s responsible for designing and building medium- to large-scaled e-commerce web sites and portals.

He’s also the tech lead for Dynamicweb Nederland, the Dutch branch of the popular Danish ContentManagement System Dynamicweb (www.dynamicweb.nl).

Imar has written books on ASP.NET 2.0 and Macromedia Dreamweaver, all published under the Wroxbrand. He is also one of the top contributors to the Wrox Community Forum at p2p.wrox.com, where he shares his knowledge with fellow programmers.

Imar lives in Utrecht, the Netherlands, with his girlfriend, Fleur. You can contact him through his personalweb site at http://imar.spaanjaars.com.

87593ffirs.qxd:WroxPro 1/29/08 12:47 AM Page vii

Page 10: Wrox Programmer to Programmer Beginning ASP.NET 3.5 In C# ... · Kathryn Duggan David Parise Rachel Gunn Indexer Melanie Belkin 87593ffirs.qxd:WroxPro 1/29/08 12:47 AM Page ix. 87593ffirs.qxd:WroxPro

87593ffirs.qxd:WroxPro 1/29/08 12:47 AM Page viii

Page 11: Wrox Programmer to Programmer Beginning ASP.NET 3.5 In C# ... · Kathryn Duggan David Parise Rachel Gunn Indexer Melanie Belkin 87593ffirs.qxd:WroxPro 1/29/08 12:47 AM Page ix. 87593ffirs.qxd:WroxPro

CreditsAcquisitions DirectorJim Minatel

Development EditorBrian Herrmann

Lead Technical EditorPeter Lanoie

Technical EditorsAlexei GorkovJohn DunaganRobert Searing

Editorial ManagerMary Beth Wakefield

Production ManagerTim Tate

Vice President and Executive Group PublisherRichard Swadley

Vice President and Executive PublisherJoseph B. Wikert

Project Coordinator, CoverLynsey Stanford

CompositorLaurie Stewart, Happenstance Type-O-Rama

ProofreadersKathryn DugganDavid PariseRachel Gunn

IndexerMelanie Belkin

87593ffirs.qxd:WroxPro 1/29/08 12:47 AM Page ix

Page 12: Wrox Programmer to Programmer Beginning ASP.NET 3.5 In C# ... · Kathryn Duggan David Parise Rachel Gunn Indexer Melanie Belkin 87593ffirs.qxd:WroxPro 1/29/08 12:47 AM Page ix. 87593ffirs.qxd:WroxPro

87593ffirs.qxd:WroxPro 1/29/08 12:47 AM Page x

Page 13: Wrox Programmer to Programmer Beginning ASP.NET 3.5 In C# ... · Kathryn Duggan David Parise Rachel Gunn Indexer Melanie Belkin 87593ffirs.qxd:WroxPro 1/29/08 12:47 AM Page ix. 87593ffirs.qxd:WroxPro

Acknowledgments

Writing a book is probably one of the most exhausting but fun and rewarding things I have ever done.During writing you have to invest a lot of time and effort to put your ideas down into something that is worth reading by others. After the hard work is done and the book is written, the reward comes fromreaders like you who send me e-mails, contact me through my web site, or participate in the online dis-cussion forums at p2p.wrox.com to discuss the book.

As Norman Mailer put it, writing a book is the closest that men ever get to childbearing. Although I thinkthere is probably some truth in that statement, I also realize there is one big difference: writing a book isnot something you have to do on your own. Although only my name is on the cover, I owe a lot to manypeople who helped me write this book.

First of all I’d like to thank Jim Minatel from Wiley for asking me to pick up this project and having faithin my ability to bring it to a good end. I would also like to thank Brian Herrmann for his editorial work. Iknow it wasn’t always easy with the number of reviewers we had, but I think it turned out pretty well.

I am very thankful for the work done by the technical editors on this book: Alexei, John, and Rob —thanks, guys, for all your hard work! I particularly want to thank the lead technical editor, Peter Lanoie,who has made a major contribution, both in shaping the direction of the book and in assuring its technicalaccuracy. Thank you, Peter!

I am also very glad for the support I got from the people at Design IT. Thanks to all who have reviewedmy work and participated in my discussions on the book’s direction.

Another person I owe a lot to is Anne Ward from Blue Violet, a UK-based web and graphic design com-pany. Anne has done most of the designs used in this book, which I highly appreciate. Thanks, Anne!The concert pictures you see in this book come from her good friend Nigel D. Nudds, who kindly let meuse pictures from his collection.

Finally, I would like to thank my lovely girlfriend, Fleur. You may get tired of hearing it, but I reallyappreciate the support you have given me throughout this project. I couldn’t — and wouldn’t — havedone it without you!

87593ffirs.qxd:WroxPro 1/29/08 12:47 AM Page xi

Page 14: Wrox Programmer to Programmer Beginning ASP.NET 3.5 In C# ... · Kathryn Duggan David Parise Rachel Gunn Indexer Melanie Belkin 87593ffirs.qxd:WroxPro 1/29/08 12:47 AM Page ix. 87593ffirs.qxd:WroxPro

87593ffirs.qxd:WroxPro 1/29/08 12:47 AM Page xii

Page 15: Wrox Programmer to Programmer Beginning ASP.NET 3.5 In C# ... · Kathryn Duggan David Parise Rachel Gunn Indexer Melanie Belkin 87593ffirs.qxd:WroxPro 1/29/08 12:47 AM Page ix. 87593ffirs.qxd:WroxPro

Contents

Acknowledgments xiIntroduction xxiii

Chapter 1: Getting Started with ASP.NET 3.5 1

Microsoft Visual Web Developer 2Getting Visual Web Developer 3Installing Visual Web Developer Express Edition 3

Creating Your First ASP.NET 3.5 Web Site 5An Introduction to ASP.NET 3.5 9

Understanding HTML 10A First Look at ASP.NET Markup 14

A Tour of the IDE 15The Main Development Area 15Informational Windows 21

Customizing the IDE 22Rearranging Windows 22Modifying the Toolbox 23Customizing the Document Window 25Customizing Toolbars 25Customizing Keyboard Shortcuts 26Resetting Your Changes 27

The Sample Application 28Practical Tips on Visual Web Developer 30Summary 30Exercises 31

Chapter 2: Building an ASP.NET Web Site 33

Creating Web Sites with VWD 2008 34Different Project Types 34Choosing the Right Web Site Template 35Creating and Opening a New Web Site 36

Working with Files in Your Web Site 39The Many File Types of an ASP.NET 3.5 Web Site 39Adding Existing Files 43

87593ftoc.qxd:WroxPro 1/25/08 11:31 AM Page xiii

Page 16: Wrox Programmer to Programmer Beginning ASP.NET 3.5 In C# ... · Kathryn Duggan David Parise Rachel Gunn Indexer Melanie Belkin 87593ffirs.qxd:WroxPro 1/29/08 12:47 AM Page ix. 87593ffirs.qxd:WroxPro

xiv

Contents

Organizing Your Site 44Special File Types 46

Working with Web Forms 47The Different Views on Web Forms 47Choosing between Code Behind and Pages with Inline Code 48Adding Markup to Your Page 53Connecting Pages 59

Practical Tips on Working with Web Forms 61Summary 61Exercises 62

Chapter 3: Designing Your Web Pages 63

Why Do You Need CSS? 63Problems of HTML Formatting 64How CSS Fixes Formatting Problems 65

An Introduction to CSS 65CSS — The Language 69The Style Sheet 69Adding CSS to Your Pages 80

Working with CSS in Visual Web Developer 82Creating New Styles in External Style Sheets 83Creating Embedded and Inline Style Sheets 88Applying Styles 94Managing Styles 96

Practical Tips on Working with CSS 99Summary 100Exercises 100

Chapter 4: Working with ASP.NET Controls 103

Introduction to Server Controls 103A Closer Look at ASP.NET Server Controls 107

Defining Controls in Your Pages 108Common Properties for All Controls 108

Types of Controls 110Standard Controls 111HTML Controls 124Data Controls 124Validation Controls 125Navigation Controls 125Login Controls 125

87593ftoc.qxd:WroxPro 1/25/08 11:31 AM Page xiv

Page 17: Wrox Programmer to Programmer Beginning ASP.NET 3.5 In C# ... · Kathryn Duggan David Parise Rachel Gunn Indexer Melanie Belkin 87593ffirs.qxd:WroxPro 1/29/08 12:47 AM Page ix. 87593ffirs.qxd:WroxPro

xv

Contents

Ajax Extensions 125WebParts 125

The ASP.NET State Engine 126What Is State and Why Is It Important? 126How the State Engine Works 127Not All Controls Rely on ViewState 131A Note About ViewState and Performance 131

Practical Tips on Working with Controls 132Summary 132Exercises 133

Chapter 5: Programming Your ASP.NET Web Pages 135

Introduction to Programming 136Data Types and Variables 136

Converting Data Types 140Using Arrays and Collections 142

Statements 146Operators 147Making Decisions 154Loops 161

Organizing Code 164Methods: Functions and Subroutines 165The App_Code Folder 167Organizing Code with Namespaces 171Writing Comments 173

Object Orientation Basics 176Important OO Terminology 176Events 188

Practical Tips on Programming 189Summary 190Exercises 191

Chapter 6: Creating Consistent Looking Web Sites 193

Consistent Page Layout with Master Pages 194Creating Master Pages 196Creating Content Pages 198

Using a Centralized Base Page 203An Introduction to the ASP.NET Page Life Cycle 204Implementing the Base Page 206Creating Reusable Page Templates 210

87593ftoc.qxd:WroxPro 1/25/08 11:31 AM Page xv

Page 18: Wrox Programmer to Programmer Beginning ASP.NET 3.5 In C# ... · Kathryn Duggan David Parise Rachel Gunn Indexer Melanie Belkin 87593ffirs.qxd:WroxPro 1/29/08 12:47 AM Page ix. 87593ffirs.qxd:WroxPro

xvi

Contents

Themes 214Different Types of Themes 215Choosing Between Theme and StyleSheetTheme 215Applying Themes 215Extending Themes 219Dynamically Switching Themes 222

Skins 228Creating a Skin File 229Named Skins 231A Final Note on Skins 232

Practical Tips on Creating Consistent Pages 232Summary 233Exercises 234

Chapter 7: Navigation 235

Different Ways to Move around Your Site 236Understanding Absolute and Relative URLs 236Understanding Default Documents 240

Using the Navigation Controls 241Architecture of the Navigation Controls 242Examining the Web.sitemap File 242Using the Menu Control 244Using the TreeView Control 253Using the SiteMapPath Control 257

Programmatic Redirection 259Programmatically Redirecting the Client to a Different Page 259Server-Side Redirects 261

Practical Tips on Navigation 264Summary 264Exercises 265

Chapter 8: User Controls 267

Introduction to User Controls 267Creating User Controls 268Adding User Controls to a Content Page or Master Page 271Site-Wide Registration of User Controls 274User Control Caveats 275

Adding Logic to Your User Controls 277Creating Your Own Data Types for Properties 277

87593ftoc.qxd:WroxPro 1/25/08 11:31 AM Page xvi

Page 19: Wrox Programmer to Programmer Beginning ASP.NET 3.5 In C# ... · Kathryn Duggan David Parise Rachel Gunn Indexer Melanie Belkin 87593ffirs.qxd:WroxPro 1/29/08 12:47 AM Page ix. 87593ffirs.qxd:WroxPro

xvii

Contents

Implementing ViewState Properties 283ViewState Considerations 288

Practical Tips on User Controls 289Summary 289Exercises 290

Chapter 9: Validating User Input 291

Gathering Data from the User 292Validating User Input in Web Forms 293

Processing Data at the Server 307Sending E-mail from Your Web Site 307Reading from Text Files 313

Practical Tips on Validating Data 318Summary 318Exercises 319

Chapter 10: ASP.NET AJAX 321

Introducing Ajax 322Using ASP.NET AJAX in Your Projects 323

Creating Flicker-Free Pages 323Providing Feedback to Users 328Using the Timer Control 332

Using Web Services in Ajax Web Sites 337What Are Web Services? 337Creating Web Services 338Using Web Services in Your Ajax Web Site 342This Is Just the Beginning 349

Practical Ajax Tips 349Summary 350Exercises 351

Chapter 11: Introduction to Databases 353

What Is a Database? 354Different Kinds of Relational Databases 355Using SQL to Work with Database Data 355

Retrieving and Manipulating Data 358Creating Your Own Tables 371

Data Types in SQL Server 371

87593ftoc.qxd:WroxPro 1/25/08 11:31 AM Page xvii

Page 20: Wrox Programmer to Programmer Beginning ASP.NET 3.5 In C# ... · Kathryn Duggan David Parise Rachel Gunn Indexer Melanie Belkin 87593ffirs.qxd:WroxPro 1/29/08 12:47 AM Page ix. 87593ffirs.qxd:WroxPro

xviii

Contents

Understanding Primary Keys and Identities 373Creating Relationships Between Tables 377

Practical Database Tips 380Summary 381Exercises 381

Chapter 12: Displaying and Updating Data 383

Data Controls 383Data-Bound Controls 384Data Source Controls 386

Data Source and Data-Bound Controls Working Together 386Displaying and Editing Data with GridView 386Inserting Data with DetailsView 392Storing Your Connection Strings in web.config 395Filtering Data 397

Customizing the Appearance of the Data Controls 403Configuring Columns or Fields of Data-Bound Controls 403

Updating and Inserting Data 409Using DetailsView to Insert and Update Data 409

Practical Tips for Displaying and Updating Data 422Summary 423Exercises 423

Chapter 13: LINQ 425

Introducing LINQ 426Different Types of LINQ 427

Introducing LINQ to SQL 427Mapping Your Data Model to an Object Model 428

Introducing Query Syntax 433Standard Query Operators 433Shaping Data with Anonymous Types 437

Using Server Controls with LINQ Queries 443New Controls Introduced in ASP.NET 3.5 443A Few Notes about Performance 471

Practical LINQ Tips 472Summary 472Exercises 473

87593ftoc.qxd:WroxPro 1/25/08 11:31 AM Page xviii

Page 21: Wrox Programmer to Programmer Beginning ASP.NET 3.5 In C# ... · Kathryn Duggan David Parise Rachel Gunn Indexer Melanie Belkin 87593ffirs.qxd:WroxPro 1/29/08 12:47 AM Page ix. 87593ffirs.qxd:WroxPro

xix

Contents

Chapter 14: Presenting Data — Advanced Topics 475

Formatting Your Controls Using Styles 476An Introduction to Styles 477Combining Styles, Themes, and Skins 481

Handling Events 485The ASP.NET Page and Controls Life Cycles Revisited 485Handling Errors that Occur in the Data Source Controls 498

Caching 502Common Pitfalls with Caching Data 503Different Ways to Cache Data in ASP.NET Web Applications 505

Practical Data Tips 513Summary 514Exercises 515

Chapter 15: Security in Your ASP.NET 3.5 Web Site 517

Introducing Security 518Identity: Who Are You? 518Authentication: How Can You Prove Who You Are? 518Authorization: What Are You Allowed to Do? 518An Introduction to the ASP.NET Application Services 519

Introducing the Login Controls 520The Login Controls 525Configuring Your Web Application 537

The Role Manager 541Configuring the Role Manager 541Managing Users with the WSAT 542Configuring the Web Application to Work with Roles 546Programmatically Checking Roles 551

Practical Security Tips 554Summary 555Exercises 555

Chapter 16: Personalizing Web Sites 557

Understanding Profile 558Configuring the Profile 558Using the Profile 565

87593ftoc.qxd:WroxPro 1/25/08 11:31 AM Page xix

Page 22: Wrox Programmer to Programmer Beginning ASP.NET 3.5 In C# ... · Kathryn Duggan David Parise Rachel Gunn Indexer Melanie Belkin 87593ffirs.qxd:WroxPro 1/29/08 12:47 AM Page ix. 87593ffirs.qxd:WroxPro

xx

Contents

Other Ways of Dealing with Profile 583Anonymous Identification 583Cleaning Up Old Anonymous Profiles 584Looking at Other Users’ Profiles 585

Practical Personalization Tips 589Summary 589Exercises 590

Chapter 17: Exception Handling, Debugging, and Tracing 591

Exception Handling 592Different Types of Errors 592Catching and Handling Exceptions 594Global Error Handling and Custom Error Pages 601

The Basics of Debugging 607Tools Support for Debugging 611

Moving around in Debugged Code 611Debugging Windows 612

Debugging Client-Side Script 618Tracing Your ASP.NET Web Pages 621

Using the Standard Tracing Capabilities 622Adding Your Own Information to the Trace 626Tracing and Performance 628A Security Warning 628

Practical Debugging Tips 628Summary 629Exercises 630

Chapter 18: Deploying Your Web Site 631

Preparing Your Web Site for Deployment 632Avoiding Hardcoded Settings 632

Copying Your Web Site 639Creating a Simple Copy of Your Web Site 639Publishing Your Web Site 642

Running Your Site under IIS 643Installing and Configuring the Web Server 643Understanding Security in IIS 651NTFS Settings for Planet Wrox 652Troubleshooting Web Server Errors 656

87593ftoc.qxd:WroxPro 1/25/08 11:31 AM Page xx

Page 23: Wrox Programmer to Programmer Beginning ASP.NET 3.5 In C# ... · Kathryn Duggan David Parise Rachel Gunn Indexer Melanie Belkin 87593ffirs.qxd:WroxPro 1/29/08 12:47 AM Page ix. 87593ffirs.qxd:WroxPro

xxi

Contents

Moving Data to a Remote Server 657Using the Database Publishing Wizard 658Recreating the Database 660

The Deployment Checklist 661What’s Next 662Summary 663Exercises 664

Appendix A: Exercise Answers 665

Appendix B: Configuring SQL Server 2005 687

Configuring SQL Server 2005 687Terminology and Concepts 688Using SQL Server Management Studio 689Enabling Remote Connections in SQL Server 690Connecting Your Application to SQL Server 2005 693

Configuring Application Services 701Configuring Your Database for the Application Services 702Overriding the LocalSqlServer Connection String 703Overriding the Settings of the Application Services 704

Index 707

87593ftoc.qxd:WroxPro 1/25/08 11:31 AM Page xxi

Page 24: Wrox Programmer to Programmer Beginning ASP.NET 3.5 In C# ... · Kathryn Duggan David Parise Rachel Gunn Indexer Melanie Belkin 87593ffirs.qxd:WroxPro 1/29/08 12:47 AM Page ix. 87593ffirs.qxd:WroxPro

87593flast.qxd:WroxPro 1/28/08 8:56 AM Page xxii

Page 25: Wrox Programmer to Programmer Beginning ASP.NET 3.5 In C# ... · Kathryn Duggan David Parise Rachel Gunn Indexer Melanie Belkin 87593ffirs.qxd:WroxPro 1/29/08 12:47 AM Page ix. 87593ffirs.qxd:WroxPro

Introduction

To build effective and attractive database-driven web sites, you need two things: a solid and fast frame-work to run your web pages on and a rich and extensive environment to create and program these webpages. With ASP.NET 3.5 and Visual Web Developer 2008 you get both. Together they form the platformto create dynamic and interactive web applications.

ASP.NET 3.5 builds on top of its popular predecessor ASP.NET 2.0. While maintaining backward compati-bility with sites built using this older version, the Microsoft .NET Framework 3.5 in general and ASP.NET3.5 in particular add a lot of new, compelling features to the mix.

Continuing the path of “less code” that was entered with the 2.0 version of the .NET Framework,ASP.NET 3.5 lets you accomplish more with even less code. New features like LINQ that are added tothe .NET Frame work allow you to access a database with little to no handwritten code. The integrationof Microsoft ASP.NET Ajax into the ASP.NET Framework and Visual Web Developer means you can nowcreate fast-responding and spiffy web interfaces simply by dragging a few controls onto your page andsetting a few properties. This book gives you an in-depth look at both of these technologies.

The support for Cascading Style Sheets (CSS), the language to lay out and format web pages, has under-gone a major overhaul in Visual Web Developer. The design-time support, that shows you how a pagewill eventually look in the browser, has been vastly improved. Additionally, Visual Web Developer nowships with a lot of tools that make writing CSS a breeze.

However, drag-and-drop support and visual tools are not the only things you’ll learn from this book.ASP.NET 3.5 and Visual Web Developer 2008 come with a great and extensive set of tools to help youprogram your web applications. These tools range from the new LINQ syntax that allows you to querydata and databases in your web applications, to the vastly improved debugging capabilities that allowyou to debug your application from client-side JavaScript all the way up into your server-side code, allwith the same familiar user interface, commands, and actions.

Under the hood, ASP.NET 3.5 makes use of the same run time as version 2.0. This ensures a great back-ward compatibility with that version, which means that ASP.NET 2.0 applications continue to run underthe new framework. But don’t be fooled by the fact that the run time hasn’t changed. Although the tech-nical underpinnings needed to execute your web application haven’t changed, the .NET 3.5 Frameworkand ASP.NET add a lot of new features, as you’ll discover in this book.

Probably the best thing about Visual Web Developer 2008 is its price: it’s available for free. Althoughthe commercial versions of Visual Studio 2008 ship with Visual Web Developer, you can also downloadand install the free Express Edition. This makes Visual Web Developer 2008 and ASP.NET 3.5 probablythe most attractive and compelling web development technologies available today.

87593flast.qxd:WroxPro 1/28/08 8:56 AM Page xxiii

Page 26: Wrox Programmer to Programmer Beginning ASP.NET 3.5 In C# ... · Kathryn Duggan David Parise Rachel Gunn Indexer Melanie Belkin 87593ffirs.qxd:WroxPro 1/29/08 12:47 AM Page ix. 87593ffirs.qxd:WroxPro

Introduction

xxiv

Whom This Book Is ForThis book is for anyone who wants to learn how to build rich and interactive web sites that run on theMicrosoft platform. With the knowledge you gain from this book, you create a great foundation to buildany type of web site, ranging from simple hobby-related web sites to sites you may be creating for com-mercial purposes.

Anyone new to web programming should be able to follow along because no prior background in webdevelopment is assumed. The book starts at the very beginning of web development by showing you howto obtain and install Visual Web Developer. The chapters that follow gradually introduce you to new tech-nologies, building on top of the knowledge gained in the previous chapters.

Do you have a strong preference for Visual Basic over C# or the other way around? Or do you thinkboth languages are equally cool? Or maybe you haven’t made up your mind yet and want to learn bothlanguages? Either way, you’ll like this book because all code examples are presented in both languages!

Even if you’re already familiar with previous versions of ASP.NET, with the 1.x versions in particular,you may gain a lot from this book. Although many concepts from ASP.NET 2.0 are brought forward intoASP.NET 3.5, you’ll discover there’s a host of new stuff to be found in this book, including an introduc-tion to LINQ, the new CSS and JavaScript debugging tools, new ASP.NET controls, and integrated sup-port for ASP.NET Ajax.

What This Book CoversThis book teaches you how to create a feature-rich, data-driven, and interactive web site. Although thisis quite a mouthful, you’ll find that with Visual Web Developer 2008 this isn’t as hard as it seems. You’llsee the entire process of building a web site, from installing Visual Web Developer 2008 in Chapter 1all the way up to putting your web application on a live server in Chapter 18. The book is divided into 18 chapters, each dealing with a specific subject.

❑ Chapter 1, “Getting Started with ASP.NET 3.5.” In this chapter you’ll see how to obtain andinstall Visual Web Developer 2008. You’ll get instructions for downloading and installing thefree edition of Visual Web Developer 2008, called the Express Edition. You are also introduced to HTML, the language behind every web page. The chapter closes with an overview of the customization options that Visual Web Developer gives you.

❑ Chapter 2, “Building an ASP.NET Web Site.” This chapter shows you how to create a new web site and how to add new elements like pages to it. Besides learning how to create a well-structured site, you also see how to use the numerous tools in Visual Web Developer to createHTML and ASP.NET pages.

❑ Chapter 3, “Designing Your Web Pages.” Visual Web Developer comes with a host of tools that allow you to create well-designed and attractive web pages. In this chapter, you see how to make good use of these tools. Additionally, you learn about CSS, the language that is used toformat web pages.

❑ Chapter 4, “Working with ASP.NET Controls.” ASP.NET Server Controls are one of the mostimportant concepts in ASP.NET. They allow you to create complex and feature-rich web siteswith very little code. This chapter introduces you to the large number of server controls that are available, explains what they are used for, and shows you how to use them.

87593flast.qxd:WroxPro 1/28/08 8:56 AM Page xxiv

Page 27: Wrox Programmer to Programmer Beginning ASP.NET 3.5 In C# ... · Kathryn Duggan David Parise Rachel Gunn Indexer Melanie Belkin 87593ffirs.qxd:WroxPro 1/29/08 12:47 AM Page ix. 87593ffirs.qxd:WroxPro

Introduction

xxv

❑ Chapter 5, “Programming Your ASP.NET Web Pages.” Although the built-in CSS tools and theASP.NET Server Controls can get you a long way in creating web pages, you are likely to use aprogramming language to enhance your pages. This chapter serves as an introduction to pro-gramming with a strong focus on programming web pages. Best of all: all the examples you seein this chapter (and the rest of the book) are in both Visual Basic and C#, so you can choose thelanguage you like best.

❑ Chapter 6, “Creating Consistent Looking Web Sites.” Consistency is important to give your website an attractive and professional appeal. ASP.NET helps you create consistent-looking pagesthrough the use of master pages, which allow you to define the global look and feel of a page.Skins and themes help you to centralize the looks of controls and other visual elements in yoursite. You also see how to create a base page that helps to centralize programming code that youneed on all pages in your site.

❑ Chapter 7, “Navigation.” To help your visitors find their way around your site, ASP.NET comeswith a number of navigation controls. These controls are used to build the navigation structureof your site. They can be connected to your site’s central site map that defines the pages in yourweb site. You also learn how to programmatically send users from one page to another.

❑ Chapter 8, “User Controls.” User controls are reusable page fragments that can be used in multi-ple web pages. As such, they are great for repeating content like menus, banners, and so on. In thischapter, you learn how to create and use user controls and enhance them with some programmaticintelligence.

❑ Chapter 9, “Validating User Input.” A large part of interactivity in your site is defined by theinput of your users. This chapter shows you how to accept, validate, and process user input usingASP.NET Server Controls. Additionally, you see how to send e-mail from your ASP.NET web appli-cation and how to read from text files.

❑ Chapter 10, “ASP.NET Ajax.” Microsoft ASP.NET Ajax allows you to create good-looking, flicker-free web pages that close the gap between traditional desktop applications and web applications.In this chapter you learn how to use the built-in Ajax features to enhance the presence of your webpages, resulting in a smoother interaction with the web site.

❑ Chapter 11, “Introduction to Databases.” Understanding how to use databases is critical tobuilding modern web sites, as most modern web sites require the use of a database. You’ll learnthe basics of SQL, the query language that allows you to access and alter data in a database. Inaddition, you are introduced to the database tools found in Visual Web Developer that help youcreate and manage your SQL Server databases.

❑ Chapter 12, “Displaying and Updating Data.” Building on the knowledge you gained in theprevious chapter, this chapter shows you how to use the ASP.NET data-bound and data sourcecontrols to create a rich interface that enables your users to interact with the data in the databasethat these controls target.

❑ Chapter 13, “LINQ.” LINQ is Microsoft’s new solution for accessing objects, databases, XML, andmore. In this chapter you’ll see how to use LINQ to SQL to access SQL Server databases. Instead ofwriting a lot of manual code, you create a bunch of LINQ objects that do the heavy work for you.This chapter shows you what LINQ is all about, how to use the visual LINQ designer built intoVisual Web Developer, and how to write LINQ queries to get data in and out of your SQL Serverdatabase.

❑ Chapter 14, “Presenting Data: Advanced Topics.” While earlier chapters focused mostly on thetechnical foundations of working with data, this chapter looks at the same topic from a front-end perspective. You see how to change the visual appearance of your data through the use of

87593flast.qxd:WroxPro 1/28/08 8:56 AM Page xxv

Page 28: Wrox Programmer to Programmer Beginning ASP.NET 3.5 In C# ... · Kathryn Duggan David Parise Rachel Gunn Indexer Melanie Belkin 87593ffirs.qxd:WroxPro 1/29/08 12:47 AM Page ix. 87593ffirs.qxd:WroxPro

Introduction

xxvi

control styles. You also see how to interact with the data-bound controls and how to speed upyour application by keeping a local copy of frequently accessed data.

❑ Chapter 15, “Security in Your ASP.NET 3.5 Web Site.” Although presented quite late in thebook, security is a first-class, important topic. This chapter shows you how to make use of thebuilt-in ASP.NET features related to security. You learn about a number of application servicesthat facilitate security. You also learn about how to let users sign up for an account on your website, how to distinguish between anonymous and logged-on users, and how to manage the usersin your system.

❑ Chapter 16, “Personalizing Web Sites.” Building on the security features introduced inChapter 15, this chapter shows you how to create personalized web pages with content tar-geted at individual users. You see how to configure and use the ASP.NET Profile that enablesyou to store personalized data for known and anonymous visitors.

❑ Chapter 17, “Exception Handling, Debugging, and Tracing.” In order to understand, improve,and fix the code you write for your ASP.NET web pages you need good debugging tools. VisualWeb Developer ships with great debugging support that enables you to diagnose the state of yourapplication at run time, helping you to find and fix problems before your users do.

❑ Chapter 18, “Deploying Your Web Site.” By the end of the book, you should have a web site thatis ready to be shown to the world. But how exactly do you do that? What are the things you needto know and understand to put your web site out in the wild? This chapter gives the answers andprovides you with a good look at configuring different production systems in order to run yourfinal web site.

How This Book Is StructuredThis book takes the time to explain concepts step-by-step using working examples and detailed explana-tions. Using the famous Wrox Try It Out and How It Works sections, you are guided through a task stepby step, detailing important things as you progress through the task. Each Try It Out task is followed bya detailed How It Works section that explains the steps you performed in the exercise.

At the end of each chapter, you find exercises that help you test the knowledge you gained in this chapter.You’ll find the answers to each question in Appendix A at the end of this book. Don’t worry if you don’tknow all the answers to the questions. Later chapters do not assume you followed and carried out thetasks from the exercise sections of previous chapters.

What You Need to Use This BookThis book assumes you have a system that meets the following requirements:

❑ Capable of running Visual Web Developer. For the exact system requirements, consult the readmefile that comes with the software.

❑ Running Windows XP Professional Edition, Windows Vista (at least the Home Premium edition),or one of the server editions of Windows.

87593flast.qxd:WroxPro 1/28/08 8:56 AM Page xxvi

Page 29: Wrox Programmer to Programmer Beginning ASP.NET 3.5 In C# ... · Kathryn Duggan David Parise Rachel Gunn Indexer Melanie Belkin 87593ffirs.qxd:WroxPro 1/29/08 12:47 AM Page ix. 87593ffirs.qxd:WroxPro

Although you should be able to follow along with most exercises using Windows XP Home or WindowsVista Basic, some of the chapters in this book require the use of IIS, Microsoft’s web server, which onlyships with the Windows versions in the requirements list.

The first chapter shows you how to obtain and install Visual Web Developer 2008, which in turn installsthe Microsoft .NET Framework version 3.5 and SQL Server 2005 Express Edition; all you need is a goodoperating system and the drive to read this book!

ConventionsTo help you get the most from the text and keep track of what’s happening, a number of conventions areused throughout the book.

Try It Out ConventionsThe 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.

4. Then read the How It Works section to find out what’s going on.

How It WorksAfter each Try It Out, the actions you carried out and the code you’ve typed in will be explained in detail.

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

As for styles in the text:

❑ New terms and important words are italicized when they are introduced.

❑ URLs and code within the text are presented like this: Request.QueryString.Get(“Id”)

❑ Menu items that require you to click multiple submenus have a special symbol that looks likethis: ➪ . For example: File ➪ New ➪ Folder.

❑ Code or content irrelevant to the discussion is either left out completely or replaced with threesubsequent dots, like this:

<tr><td style=”white-space: nowrap;”>

Boxes like this one hold important, not-to-be forgotten information that is directlyrelevant to the surrounding text.

Introduction

xxvii

87593flast.qxd:WroxPro 1/28/08 8:56 AM Page xxvii

Page 30: Wrox Programmer to Programmer Beginning ASP.NET 3.5 In C# ... · Kathryn Duggan David Parise Rachel Gunn Indexer Melanie Belkin 87593ffirs.qxd:WroxPro 1/29/08 12:47 AM Page ix. 87593ffirs.qxd:WroxPro

... Menu items go here; not shown</td>

</tr>

The three dots are used regardless of the programming language used in the example, so you’llsee it for C#, Visual Basic, HTML, CSS, and JavaScript. When you see it in code you’re instructedto type into the code editor, you can simply skip the three dots and anything that follows themon the same line.

❑ Code shown for the first time, or other relevant code, is in the following format:

Dim albumOwner As StringalbumOwner = “Imar”lblOwner.Text = albumOwner

By contrast, less important code, or code that you have seen before, looks like this:

albumOwner = “Imar”

❑ Text that appears on screen often has Each Word Start With A Capital Letter, even though theoriginal screen text uses a different capitalization. This is done to make the screen text stand out from the rest of the text.

Source CodeAs you work through the examples in this book, you may choose either to type in all the code manuallyor 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 www.wrox.com. Once at the site, locate the book’s title (either by using the Searchbox or by using one of the title lists) and click the Download Code link on the book’s detail page to obtainall 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 ISBNis 978-0-470-18759-3.

You can download the full source for this book as a single file that you can decompress with yourfavorite decompression tool. If you extract the source, make sure you maintain the original folder struc-ture that is part of the code download. The different decompression tools use different names for thisfeature, but look for a feature like Use Folder Names or Maintain Directory Structure. Once you haveextracted the files from the code download, you should end up with a folder called Source and a foldercalled Resources. Then create a new folder in the root of your C drive, call it BegASPNET, and move theSource and Resources folders into this new folder so you end up with folders like C:\BegASPNET\Sourceand C:\BegASPNET\Resources. The source folder contains the source for each of the 18 chapters ofthis book and the final version of the PlanetWrox application that you’ll work on throughout this book.The Resources folder contains files you need during some of the exercises in this book. If everythingturned out correctly, you should end up with the structure shown in Figure I-1.

Introduction

xxviii

87593flast.qxd:WroxPro 8/13/08 4:07 PM Page xxviii