Upload
matthew-macdonald
View
216
Download
2
Embed Size (px)
Citation preview
THE EXPERTS VOICE IN .NET
Beginning
ASP.NET 4in C# 2010
Matthew MacDonald
Start your journey with the fundamentals of building ASP.NET websites
Beginning ASP.NET 4 in C# 2010
Matthew MacDonald
Beginning ASP.NET in C# 2010
Copyright 2010 by Matthew MacDonald
All rights reserved. No part of this work may be reproduced or transmitted in any form or by any means, electronic or mechanical, including photocopying, recording, or by any information storage or retrieval system, without the prior written permission of the copyright the publisher.
ISBN-13 (pbk): 978-1-4302-2608-6
ISBN-13 (electronic): 978-1-4302-2609-3
Printed and bound in the United States of America 9 8 7 6 5 4 3 2 1
Trademarked names, logos, and images may appear in this book. Rather than use a trademark symbol with every occurrence of a trademarked name, logo, or image we use the names, logos, and images only in an editorial fashion and to the benefit of the trademark owner, with no intention of infringement of the trademark.
The use in this publication of trade names, trademarks, service marks, and similar terms, even if they are not identified as such, is not to be taken as an expression of opinion as to whether or not they are subject to proprietary rights.
President and Publisher: Paul Manning Lead Editor: Ewan Buckingham Technical Reviewer: Damien Foggon Editorial Board: Clay Andres, Steve Anglin, Mark Beckner, Ewan Buckingham, Gary Cornell,
Jonathan Gennick, Jonathan Hassell, Michelle Lowman, Matthew Moodie, Duncan Parkes, Jeffrey Pepper, Frank Pohlmann, Douglas Pundick, Ben Renow-Clarke, Dominic Shakeshaft, Matt Wade, Tom Welsh
Coordinating Editor: Anne Collett Copy Editor: Kim Wimpsett Compositor: Mary Sudul Indexer: BIM Indexing & Proofreading Services Artist: April Milne Cover Designer: Anna Ishchenko
Distributed to the book trade worldwide by Springer Science+Business Media, LLC., 233 Spring Street, 6th Floor, New York, NY 10013. Phone 1-800-SPRINGER, fax (201) 348-4505, e-mail [email protected], or visit www.springeronline.com.
For information on translations, please e-mail [email protected], or visit www.apress.com.
Apress and friends of ED books may be purchased in bulk for academic, corporate, or promotional use. eBook versions and licenses are also available for most titles. For more information, reference our Special Bulk SaleseBook Licensing web page at www.apress.com/info/bulksales.
The information in this book is distributed on an as is basis, without warranty. Although every precaution has been taken in the preparation of this work, neither the author(s) nor Apress shall have any liability to any person or entity with respect to any loss or damage caused or alleged to be caused directly or indirectly by the information contained in this work.
mailto:[email protected]:[email protected]://www.springeronline.commailto:[email protected]://www.apress.comhttp://www.apress.com/info/bulksales
For my wonderful family,
Faria, Maya, and Brenna
CONTENTS
v
Contents
About the Author .................................................................................................. xxv About the Technical Reviewer ............................................................................. xxvi Acknowledgments .............................................................................................. xxvii Introduction ....................................................................................................... xxviii
Part 1: Introducing .NET ...........................................................................................1
Chapter 1: The .NET Framework ..........................................................................3 The Evolution of Web Development .................................................................................3
HTML and HTML Forms ..........................................................................................................................3
Server-Side Programming ......................................................................................................................6
Client-Side Programming .......................................................................................................................7
The .NET Framework .......................................................................................................9 C#, VB, and the .NET Languages ..........................................................................................................11 The Common Language Runtime .........................................................................................................13 The .NET Class Library..........................................................................................................................14 Visual Studio.........................................................................................................................................15
The Last Word................................................................................................................16
Chapter 2: The C# Language ..............................................................................17 The .NET Languages ......................................................................................................17 C# Language Basics ......................................................................................................18
Case Sensitivity ....................................................................................................................................18 Commenting .........................................................................................................................................18 Statement Termination.........................................................................................................................19
CONTENTS
vi
Blocks...................................................................................................................................................20
Variables and Data Types ..............................................................................................20 Assignment and Initializers ..................................................................................................................22
Strings and Escaped Characters ..........................................................................................................24
Arrays ...................................................................................................................................................24
Enumerations .......................................................................................................................................26
Variable Operations .......................................................................................................27 Advanced Math.....................................................................................................................................29
Type Conversions .................................................................................................................................29
Object-Based Manipulation ...........................................................................................31 The String Type ....................................................................................................................................32
The DateTime and TimeSpan Types .....................................................................................................34
The Array Type......................................................................................................................................36
Conditional Logic ...........................................................................................................37 The if Statement ...................................................................................................................................38
The switch Statement...........................................................................................................................39
Loops .............................................................................................................................40 The for Loop..........................................................................................................................................40
The foreach Loop..................................................................................................................................41
The while loop ......................................................................................................................................42
Methods.........................................................................................................................43 Parameters ...........................................................................................................................................44
Method Overloading .............................................................................................................................45
Optional and Named Parameters..........................................................................................................46
Delegates..............................................................................................................................................47
The Last Word................................................................................................................48
Chapter 3: Types, Objects, and Namespaces .....................................................49 The Basics About Classes..............................................................................................49
Static Members ....................................................................................................................................50
A Simple Class......................................................................................................................................51
CONTENTS
vii
Building a Basic Class ...................................................................................................51 Creating an Object ................................................................................................................................53
Adding Properties .................................................................................................................................54
Automatic Properties ............................................................................................................................56
Adding a Method ..................................................................................................................................56
Adding a Constructor ............................................................................................................................57
Adding an Event....................................................................................................................................59
Testing the Product Class.....................................................................................................................60
Value Types and Reference Types.................................................................................63 Assignment Operations ........................................................................................................................63
Equality Testing ....................................................................................................................................64
Passing Parameters by Reference and by Value ..................................................................................64
Reviewing .NET Types ..........................................................................................................................65
Understanding Namespaces and Assemblies................................................................67 Using Namespaces ...............................................................................................................................68
Importing Namespaces.........................................................................................................................69
Assemblies ...........................................................................................................................................70
Advanced Class Programming.......................................................................................71 Inheritance............................................................................................................................................71
Static Members ....................................................................................................................................73
Casting Objects.....................................................................................................................................74
Partial Classes ......................................................................................................................................76
Generics................................................................................................................................................77
The Last Word................................................................................................................79
Part 2: Developing ASP.NET Applications...............................................................81
Chapter 4: Visual Studio.....................................................................................83 The Promise of Visual Studio .........................................................................................83 Creating Websites..........................................................................................................84
Creating an Empty Web Application .....................................................................................................85
CONTENTS
viii
Websites and Web Projects ..................................................................................................................89
The Hidden Solution Files .....................................................................................................................90
The Solution Explorer ...........................................................................................................................91
Adding Web Forms ...............................................................................................................................92
Migrating a Website from a Previous Version of Visual Studio.............................................................93
Designing a Web Page...................................................................................................95 Adding Web Controls ............................................................................................................................96
The Properties Window ........................................................................................................................98
The Anatomy of a Web Form .......................................................................................100 The Web Form Markup .......................................................................................................................100
The Page Directive..............................................................................................................................101
The Doctype........................................................................................................................................102
The Essentials of XHTML ....................................................................................................................104
Writing Code ................................................................................................................110 The Code-Behind Class ......................................................................................................................110 Adding Event Handlers .......................................................................................................................110 Outlining .............................................................................................................................................112 IntelliSense .........................................................................................................................................113 Code Formatting and Coloring ............................................................................................................117
Visual Studio Debugging..............................................................................................118 The Visual Studio Web Server ............................................................................................................118
Single-Step Debugging.......................................................................................................................119
Variable Watches................................................................................................................................124
The Last Word..............................................................................................................125
Chapter 5: Web Form Fundamentals................................................................127 The Anatomy of an ASP.NET Application .....................................................................127
ASP.NET File Types.............................................................................................................................128
ASP.NET Application Directories.........................................................................................................129
Introducing Server Controls .........................................................................................130 HTML Server Controls.........................................................................................................................131
CONTENTS
ix
Converting an HTML Page to an ASP.NET Page..................................................................................131
View State ..........................................................................................................................................134
The HTML Control Classes..................................................................................................................135
Adding the Currency Converter Code .................................................................................................138
Event Handling....................................................................................................................................140
Behind the Scenes with the Currency Converter................................................................................142
Error Handling.....................................................................................................................................144
Improving the Currency Converter...............................................................................144 Adding Multiple Currencies ................................................................................................................145
Storing Information in the List ............................................................................................................146
Adding Linked Images ........................................................................................................................147
Setting Styles .....................................................................................................................................150
A Deeper Look at HTML Control Classes......................................................................151 HTML Control Events ..........................................................................................................................151
Advanced Events with the HtmlInputImage Control ...........................................................................152
The HtmlControl Base Class ...............................................................................................................154
The HtmlContainerControl Class.........................................................................................................155
The HtmlInputControl Class ................................................................................................................155
The Page Class ............................................................................................................156 Sending the User to a New Page ........................................................................................................157
HTML Encoding...................................................................................................................................158
Application Events .......................................................................................................160 The global.asax File............................................................................................................................161
Additional Application Events .............................................................................................................162
ASP.NET Configuration ................................................................................................163 The web.config File ............................................................................................................................163
Nested Configuration ..........................................................................................................................164
Storing Custom Settings in the web.config File .................................................................................166
The Website Administration Tool (WAT) .............................................................................................168
The Last Word..............................................................................................................170
CONTENTS
x
Chapter 6: Web Controls ..................................................................................173 Stepping Up to Web Controls . .....................................................................................173
Basic Web Control Classes . .................................................................................................................174
The Web Control Tags...........................................................................................................................175
Web Control Classes . ..................................................................................................176 The WebControl Base Class..................................................................................................................177
Units . ....................................................................................................................................................179
Enumerations .......................................................................................................................................179
Colors . ..................................................................................................................................................180
Fonts. ....................................................................................................................................................181
Focus . ...................................................................................................................................................183
The Default Button................................................................................................................................183
List Controls. ...............................................................................................................184 Multiple-Select List Controls . ..............................................................................................................185
The BulletedList Control .......................................................................................................................187
Table Controls. ............................................................................................................188 Web Control Events and AutoPostBack . .....................................................................193
How Postback Events Work. ................................................................................................................197
The Page Life Cycle ..............................................................................................................................198
A Simple Web Page. ....................................................................................................201 Improving the Greeting Card Generator. ..............................................................................................206
Generating the Cards Automatically . ...................................................................................................208
The Last Word. ............................................................................................................211
Chapter 7: Error Handling, Logging, and Tracing.............................................213 Common Errors. ..........................................................................................................213 Exception Handling . ....................................................................................................215
The Exception Class .............................................................................................................................215
The Exception Chain .............................................................................................................................217
CONTENTS
xi
Handling Exceptions ....................................................................................................218 Catching Specific Exceptions .............................................................................................................219
Nested Exception Handlers.................................................................................................................221
Exception Handling in Action..............................................................................................................222
Mastering Exceptions .........................................................................................................................224
Throwing Your Own Exceptions ...................................................................................224 Logging Exceptions......................................................................................................229
Viewing the Windows Event Logs.......................................................................................................229
Writing to the Event Log .....................................................................................................................232
Custom Logs.......................................................................................................................................234
A Custom Logging Class .....................................................................................................................236
Retrieving Log Information .................................................................................................................237
Page Tracing................................................................................................................239 Enabling Tracing.................................................................................................................................240
Tracing Information ............................................................................................................................240
Writing Trace Information...................................................................................................................246
Application-Level Tracing...................................................................................................................250
The Last Word..............................................................................................................252
Chapter 8: State Management .........................................................................253 The Problem of State ...................................................................................................253 View State....................................................................................................................253
The ViewState Collection....................................................................................................................254
A View State Example.........................................................................................................................254
Making View State Secure .................................................................................................................255
Retaining Member Variables ..............................................................................................................257
Storing Custom Objects ......................................................................................................................259
Transferring Information Between Pages ....................................................................260 Cross-Page Posting ............................................................................................................................260
The Query String.................................................................................................................................265
CONTENTS
xii
Cookies ........................................................................................................................269 A Cookie Example ...............................................................................................................................271
Session State...............................................................................................................272 Session Tracking ................................................................................................................................272
Using Session State............................................................................................................................273
A Session State Example....................................................................................................................274
Session State Configuration ........................................................................................277 Cookieless ..........................................................................................................................................278
Timeout...............................................................................................................................................281
Mode...................................................................................................................................................281
Application State..........................................................................................................286 An Overview of State Management Choices................................................................288 The Last Word..............................................................................................................290
Part 3: Building Better Web Forms .......................................................................291
Chapter 9: Validation .......................................................................................293 Understanding Validation.............................................................................................293
The Validation Controls.......................................................................................................................294
Server-Side Validation........................................................................................................................295
Client-Side Validation .........................................................................................................................295
The Validation Controls................................................................................................295 A Simple Validation Example ..............................................................................................................297
Other Display Options .........................................................................................................................299
Manual Validation ...............................................................................................................................302
Validating with Regular Expressions ..................................................................................................304
A Validated Customer Form................................................................................................................308
Validation Groups................................................................................................................................313
The Last Word..............................................................................................................314
CONTENTS
xiii
Chapter 10: Rich Controls ................................................................................315 The Calendar................................................................................................................315
Formatting the Calendar.....................................................................................................................317
Restricting Dates ................................................................................................................................319
The AdRotator ..............................................................................................................323 The Advertisement File.......................................................................................................................323
The AdRotator Class ...........................................................................................................................325
Pages with Multiple Views...........................................................................................326 The MultiView Control ........................................................................................................................328
The Wizard Control .............................................................................................................................333
The Last Word..............................................................................................................341
Chapter 11: User Controls and Graphics ..........................................................343 User Controls ...............................................................................................................343
Creating a Simple User Control ..........................................................................................................344
Independent User Controls .................................................................................................................347
Integrated User Controls.....................................................................................................................349
User Control Events ............................................................................................................................352
Passing Information with Events ........................................................................................................354
Dynamic Graphics........................................................................................................357 Basic Drawing ....................................................................................................................................357
Drawing a Custom Image ...................................................................................................................360
Placing Custom Images Inside Web Pages.........................................................................................361
Image Format and Quality ..................................................................................................................363
The Last Word..............................................................................................................366
Chapter 12: Styles, Themes, and Master Pages...............................................367 Styles ...........................................................................................................................367
Style Types .........................................................................................................................................368
Creating a Basic Inline Style...............................................................................................................368
Creating a Style Sheet ........................................................................................................................377
CONTENTS
xiv
Applying Style Sheet Rules.................................................................................................................380
Themes ........................................................................................................................383 How Themes Work .............................................................................................................................383
Applying a Simple Theme...................................................................................................................385
Handling Theme Conflicts...................................................................................................................386
Creating Multiple Skins for the Same Control ....................................................................................388
More Advanced Skins.........................................................................................................................389
Master Page Basics .....................................................................................................391 A Simple Master Page and Content Page ...........................................................................................392
How Master Pages and Content Pages Are Connected ......................................................................396
A Master Page with Multiple Content Regions ...................................................................................398
Default Content...................................................................................................................................401
Master Pages and Relative Paths .......................................................................................................402
Advanced Master Pages ..............................................................................................403 Style-Based Layouts...........................................................................................................................403
Code in a Master Page........................................................................................................................408
Interacting with a Master Page Programmatically .............................................................................409
The Last Word..............................................................................................................410
Chapter 13: Website Navigation.......................................................................411 Site Maps.....................................................................................................................411
Defining a Site Map ............................................................................................................................412
Seeing a Simple Site Map in Action....................................................................................................416
Binding an Ordinary Page to a Site Map.............................................................................................416
Binding a Master Page to a Site Map .................................................................................................418
Binding Portions of a Site Map ...........................................................................................................420
The SiteMap Class ..............................................................................................................................425
URL Mapping and Routing ...........................................................................................427 URL Mapping ......................................................................................................................................428
URL Routing ........................................................................................................................................428
CONTENTS
xv
The SiteMapPath Control .............................................................................................430 Customizing the SiteMapPath ............................................................................................................431
Using SiteMapPath Styles and Templates ..........................................................................................432
Adding Custom Site Map Information.................................................................................................434
The TreeView Control...................................................................................................435 TreeView Properties ...........................................................................................................................436
TreeView Styles ..................................................................................................................................438
The Menu Control ........................................................................................................442 Menu Styles........................................................................................................................................444
Menu Templates .................................................................................................................................445
The Last Word..............................................................................................................448
Part 4: Working with Data ....................................................................................449
Chapter 14: ADO.NET Fundamentals ................................................................451 Understanding Databases............................................................................................451 Configuring Your Database ..........................................................................................453
SQL Server Express ............................................................................................................................453
Browsing and Modifying Databases in Visual Studio .........................................................................454
The sqlcmd Command-Line Tool ........................................................................................................457
SQL Basics...................................................................................................................458 Running Queries in Visual Studio .......................................................................................................459
The Select Statement .........................................................................................................................461
The SQL Update Statement.................................................................................................................463
The SQL Insert Statement...................................................................................................................465
The SQL Delete Statement..................................................................................................................465
The Data Provider Model .............................................................................................466 Direct Data Access ......................................................................................................467
Creating a Connection ........................................................................................................................469
The Select Command .........................................................................................................................475
The DataReader ..................................................................................................................................476
CONTENTS
xvi
Putting It All Together .........................................................................................................................476
Updating Data .....................................................................................................................................481
Disconnected Data Access ..........................................................................................491 Selecting Disconnected Data..............................................................................................................492
Selecting Multiple Tables ...................................................................................................................494
Defining Relationships........................................................................................................................495
The Last Word..............................................................................................................498
Chapter 15: Data Binding .................................................................................499 Introducing Data Binding .............................................................................................499
Types of ASP.NET Data Binding..........................................................................................................500
How Data Binding Works ....................................................................................................................500
Single-Value Data Binding ...........................................................................................500 A Simple Data Binding Example .........................................................................................................501
Simple Data Binding with Properties..................................................................................................504
Problems with Single-Value Data Binding..........................................................................................505
Using Code Instead of Simple Data Binding .......................................................................................506
Repeated-Value Data Binding......................................................................................506 Data Binding with Simple List Controls ..............................................................................................507
A Simple List Binding Example...........................................................................................................508
Strongly Typed Collections .................................................................................................................509
Multiple Binding..................................................................................................................................510
Data Binding with a Dictionary Collection ..........................................................................................512
Using the DataValueField Property .....................................................................................................513
Data Binding with ADO.NET ................................................................................................................514
Creating a Record Editor.....................................................................................................................516
Data Source Controls ...................................................................................................521 The Page Life Cycle with Data Binding...............................................................................................523
The SqlDataSource .............................................................................................................................523
Selecting Records...............................................................................................................................525
Parameterized Commands .................................................................................................................527
CONTENTS
xvii
Handling Errors...................................................................................................................................532
Updating Records ...............................................................................................................................533
The Last Word..............................................................................................................537
Chapter 16: The Data Controls .........................................................................539 The GridView................................................................................................................539
Automatically Generating Columns ....................................................................................................540
Defining Columns ...............................................................................................................................542
Formatting the GridView..............................................................................................546 Formatting Fields................................................................................................................................546
Using Styles........................................................................................................................................547
Formatting-Specific Values ................................................................................................................550
Selecting a GridView Row............................................................................................552 Adding a Select Button .......................................................................................................................553
Using Selection to Create Master-Details Pages ................................................................................554
Editing with the GridView ............................................................................................556 Sorting and Paging the GridView .................................................................................559
Sorting ................................................................................................................................................559
Paging.................................................................................................................................................561
Using GridView Templates...........................................................................................563 Using Multiple Templates ...................................................................................................................565
Editing Templates in Visual Studio .....................................................................................................566
Handling Events in a Template ...........................................................................................................567
Editing with a Template......................................................................................................................568
The DetailsView and FormView ...................................................................................573 The DetailsView ..................................................................................................................................573
The FormView.....................................................................................................................................575
The Last Word..............................................................................................................578
Chapter 17: Files and Streams.........................................................................579 Files and Web Applications..........................................................................................579
CONTENTS
xviii
File System Information...............................................................................................580 The Path Class ....................................................................................................................................581
The Directory and File Classes ...........................................................................................................582
The DirectoryInfo and FileInfo Classes ...............................................................................................587
The DriveInfo Class.............................................................................................................................589
A Sample File Browser .......................................................................................................................590
Reading and Writing with Streams ..............................................................................594 Text Files ............................................................................................................................................594
Binary Files.........................................................................................................................................596
Shortcuts for Reading and Writing Files .............................................................................................597
A Simple Guest Book ..........................................................................................................................598
Allowing File Uploads ..................................................................................................604 The FileUpload Control .......................................................................................................................604
The Last Word..............................................................................................................607
Chapter 18: XML...............................................................................................609 XML Explained .............................................................................................................609
Improving the List with XML...............................................................................................................611
XML Basics .........................................................................................................................................612
Attributes ............................................................................................................................................613
Comments ..........................................................................................................................................614
The XML Classes..........................................................................................................615 The XML TextWriter ............................................................................................................................615
The XML Text Reader..........................................................................................................................618
Working with XML Documents in Memory .........................................................................................623
Reading an XML Document ................................................................................................................628
Searching an XML Document .............................................................................................................631
XML Validation .............................................................................................................632 XML Namespaces ...............................................................................................................................632 XML Schema Definition ......................................................................................................................635 Validating an XML Document..............................................................................................................637
CONTENTS
xix
XML Display and Transforms.......................................................................................640 The Xml Web Control ..........................................................................................................................642
The Last Word..............................................................................................................643
Part 5: Website Security .......................................................................................645
Chapter 19: Security Fundamentals.................................................................647 Understanding Security ...............................................................................................647
Testing and Deploying Security Settings............................................................................................648
Authentication and Authorization ................................................................................649 Forms Authentication ..................................................................................................649
Web.config Settings ...........................................................................................................................651
Authorization Rules ............................................................................................................................651
The WAT .............................................................................................................................................655
The Login Page ...................................................................................................................................657
Windows Authentication ..............................................................................................663 Web.config Settings ...........................................................................................................................663
A Windows Authentication Test..........................................................................................................666
The Last Word..............................................................................................................667
Chapter 20: Membership..................................................................................669 The Membership Data Store ........................................................................................669
Membership with SQL Server Express ...............................................................................................671 Using the Full Version of SQL Server ..................................................................................................673 Configuring the Membership Provider................................................................................................676 Creating Users with the WAT..............................................................................................................679 The Membership and MembershipUser Classes ................................................................................682 Authentication with Membership .......................................................................................................686 Disabled Accounts ..............................................................................................................................687
The Security Controls ..................................................................................................687 The Login Control................................................................................................................................688
The CreateUserWizard Control............................................................................................................694
CONTENTS
xx
The PasswordRecovery Control. ..........................................................................................................698
Role-Based Security . ..................................................................................................700 Creating and Assigning Roles. .............................................................................................................701
Restricting Access Based on Roles . ....................................................................................................705
The LoginView Control..........................................................................................................................705
The Last Word. ............................................................................................................707
Chapter 21: Profiles .........................................................................................709 Understanding Profiles . ..............................................................................................709
Profile Performance..............................................................................................................................710
How Profiles Store Data........................................................................................................................710
Using the SqlProfileProvider . ......................................................................................712 Enabling Authentication........................................................................................................................712 Using SQL Server Express ....................................................................................................................713 Using the Full Version of SQL Server . ..................................................................................................713 The Profile Databases...........................................................................................................................714 Defining Profile Properties....................................................................................................................716 Using Profile Properties ........................................................................................................................717 Profile Serialization ..............................................................................................................................719 Profile Groups .......................................................................................................................................721 Profiles and Custom Data Types. .........................................................................................................722 The Profile API . .....................................................................................................................................725 Anonymous Profiles..............................................................................................................................728
The Last Word. ............................................................................................................731
Part 6: Advanced ASP.NET....................................................................................733
Chapter 22: Introducing ASP.NET.....................................................................735 Why Use Components? . ..............................................................................................735 Component Jargon . ....................................................................................................736
Three-Tier Design.................................................................................................................................736
Encapsulation . ......................................................................................................................................738
CONTENTS
xxi
Business Objects ................................................................................................................................738
Data Objects .......................................................................................................................................738
Components and Classes ...................................................................................................................738
Creating a Component .................................................................................................739 Classes and Namespaces...................................................................................................................740
Class Members ...................................................................................................................................742
Adding a Reference to the Component...............................................................................................742
Using the Component .........................................................................................................................745
Properties and State ....................................................................................................747 A Stateful Account Class ....................................................................................................................748
A Stateless AccountUtility Class .........................................................................................................749
Data-Access Components............................................................................................750 A Simple Data-Access Component .....................................................................................................750
Using the Data-Access Component ....................................................................................................754
Enhancing the Component with Error Handling..................................................................................757
Enhancing the Component with Aggregate Information.....................................................................758
The ObjectDataSource .................................................................................................759 Making Classes the ObjectDataSource Can Understand ....................................................................759
Selecting Records...............................................................................................................................760
Using Method Parameters ..................................................................................................................761
Updating Records ...............................................................................................................................762
The Last Word..............................................................................................................764
Chapter 23: Caching.........................................................................................765 Understanding Caching ...............................................................................................765
When to Use Caching..........................................................................................................................766 Caching in ASP.NET ............................................................................................................................767
Output Caching ............................................................................................................767 Caching on the Client Side .................................................................................................................769 Caching and the Query String.............................................................................................................769 Caching with Specific Query String Parameters.................................................................................770
CONTENTS
xxii
A Multiple Caching Example ...............................................................................................................771
Fragment Caching ..............................................................................................................................772
Cache Profiles.....................................................................................................................................773
Data Caching ...............................................................................................................774 Adding Items to the Cache .................................................................................................................774
A Simple Cache Test...........................................................................................................................776
Caching to Provide Multiple Views .....................................................................................................777
Caching with the Data Source Controls ..............................................................................................781
Caching with Dependencies ........................................................................................785 File Dependencies ..............................................................................................................................785
Cache Item Dependencies ..................................................................................................................786
SQL Server Cache Dependencies .......................................................................................................787
The Last Word..............................................................................................................790
Chapter 24: LINQ and the Entity Framework....................................................791 Understanding LINQ.....................................................................................................791 LINQ Basics..................................................................................................................792
LINQ Expressions................................................................................................................................795
The Entity Framework..................................................................................................799 Creating an Entity Data Model ............................................................................................................800
The Data Model Diagram ....................................................................................................................803
Updating a Data Model .......................................................................................................................806
The Data Model Code .........................................................................................................................808
Querying the Data Model ....................................................................................................................809
Handling Errors...................................................................................................................................810
Navigating Relationships ....................................................................................................................812
Getting More Advanced with the Entity Framework ....................................................815 Querying with LINQ to Entities............................................................................................................815 Controlling When Data is Loaded........................................................................................................818 Updates, Inserts, and Deletes.............................................................................................................820 Managing Concurrency.......................................................................................................................822
CONTENTS
xxiii
The EntityDataSource ..................................................................................................823 Displaying Data...................................................................................................................................823
Editing Data ........................................................................................................................................828
The Last Word..............................................................................................................828
Chapter 25: ASP.NET AJAX...............................................................................829 Understanding Ajax......................................................................................................829
Ajax: The Good....................................................................................................................................830
Ajax: The Bad......................................................................................................................................830
The ASP.NET AJAX Toolkit ..................................................................................................................831
The ScriptManager .............................................................................................................................831
Partial Refreshes .........................................................................................................833 A Simple UpdatePanel Test ................................................................................................................834
Handling Errors...................................................................................................................................837
Conditional Updates............................................................................................................................839
Triggers ..............................................................................................................................................840
Progress Notification ...................................................................................................845 Showing a Simulated Progress Bar ....................................................................................................845
Cancellation........................................................................................................................................847
Timed Refreshes..........................................................................................................849 The ASP.NET AJAX Control Toolkit...............................................................................851
Installing the ASP.NET AJAX Control Toolkit.......................................................................................851
The Accordion.....................................................................................................................................853
The AutoCompleteExtender ................................................................................................................856
Getting More Controls.........................................................................................................................859
The Last Word..............................................................................................................864
Chapter 26: Deploying ASP.NET Applications ..................................................865 ASP.NET Applications and the Web Server..................................................................865
How Web Servers Work ......................................................................................................................865
The Virtual Directory ...........................................................................................................................867
CONTENTS
xxiv
Web Application URLs.........................................................................................................................867
Web Farms .........................................................................................................................................869
Internet Information Services (IIS) ...............................................................................869 The Many Faces of IIS ........................................................................................................................869
Installing IIS in Windows 7 or Windows Vista.....................................................................................870
Installing IIS 7 in Windows Server 2008 .............................................................................................871
Managing Websites with IIS Manager .........................................................................873 Creating a Virtual Directory ................................................................................................................874
Understanding Application Pools........................................................................................................876
The ASP.NET Account .........................................................................................................................878
Configuring a Website ........................................................................................................................882
The Default Page ................................................................................................................................885
Custom Error Pages............................................................................................................................886
The Machine Key ..................................................................................................888 Windows Authentication.....................................................................................................................890
Confidentiality with SSL and Certificates ...........................................................................................892
Deploying a Simple Site...............................................................................................895 Web Applications and Components ....................................................................................................895
Other Configuration Steps ..................................................................................................................896
Code Compilation ...............................................................................................................................896
Deploying with Visual Studio .......................................................................................897 Creating a Virtual Directory for a New Project....................................................................................898
Copying a Website ..............................................................................................................................901
Publishing a Website ..........................................................................................................................904
The Last Word..............................................................................................................905
Index.....................................................................................................................907
CONTENTS
xxv
About the Author
Matthew MacDonald is an author, educator, and Microsoft MVP. Hes the author of more than a dozen books about .NET programming, including Pro Silverlight 4 in C# (Apress, 2010) and Pro WPF in C# 2010 (Apress, 2010). Hes also the coauthor of Pro ASP.NET 4 in C# 2010 (Apress, 2010). He lives in Toronto with his wife and daughters.
CONTENTS
xxvi
About the Technical Reviewer
Damien Foggon is a developer, writer, and technical reviewer in cutting-edge technologies and has contributed to more than 50 books on .NET, C#, Visual Basic, and ASP.NET. He is the cofounder of the Newcastle-based user-group NEBytes (http://www.nebytes.net), is a multiple MCPD in .NET 2.0 and .NET 3.5, and can be found online at http://blog.littlepond.co.uk.
http://www.nebytes.nethttp://blog.littlepond.co.uk
CONTENTS
xxvii
Acknowledgments
No author could complete a book without a small army of helpful individuals. Im deeply indebted to the whole Apress team, including Anne Collett, who helped everything move swiftly and smoothly; Kim Wimpsett, who performed the copy edit; Damien Foggon, who performed a thorough technical review; and many other individuals who worked behind the scenes indexing pages, drawing figures, and proofreading the final copy. I also owe a special thanks to Gary Cornell, who always offers invaluable advice about projects and the publishing world.
Id also like to thank those who were involved with previous editions of this book. This includes Emma Acker and Jane Brownlow at Osborne McGraw-Hill, as well as previous tech reviewers Ronald Landers, Gavin Smyth, Tim Verycruysse, Julian Skinner, and Andy Olsen. I also owe a hearty thanks to all the readers who caught errors and took the time to report problems and ask good questions. Keep sending in the feedbackit helps make better books!
Finally, Id never write any book without the support of my wife and these special individuals: Nora, Razia, Paul, and Hamid. Thanks, everyone!
INTRODUCTION
xxviii
Introduction
ASP.NET is Microsofts platform for developing web applications. Using ASP.NET, you can create e-commerce shops, data-driven portal sites, and just about anything else you can find on the Internet. Best of all, you dont need to paste together a jumble of HTML and script code in order to program the Web. Instead, you can create full-scale web applications using nothing but code and a design tool such as Visual Studio 2008.
The cost of all this innovation is the learning curve. To master ASP.NET, you need to learn how to use an advanced design tool (Visual Studio), a toolkit of objects (the .NET Framework), and an object-oriented programming language (such as C# 2010). Taken together, these topics provide more than enough to overwhelm any first-time web developer.
Beginning ASP.NET 4 in C# 2010 assumes you want to master ASP.NET, starting from the basics. Using this book, youll build your knowledge until you understand the concepts, techniques, and best practices for writing sophisticated web applications. The journey is long, but its also satisfying. At the end of the day, youll find that ASP.NET allows you to tackle challenges that are simply out of reach on many other platforms.
About This Book This book explores ASP.NET, which is a core part of Microsofts .NET Framework. The .NET Framework is not a single applicationits actually a collection of technologies bundled into one marketing term. The .NET Framework includes languages such as C# 2010 and VB 2010, an engine for hosting programmable web pages, a model for interacting with databases (ADO.NET), a higher-level framework for performing queries (LINQ and the Entity Framework), and a class library stocked with tools for everything from reading files to validating a password. To master ASP.NET, you need to learn about each of these ingredients.
This book covers all these topics from the ground up. As a result, youll find yourself learning many techniques that will interest any .NET developer, even those who create Windows applications. For example, youll learn about component-based programming; youll discover structured error handling; and youll see how to access files, XML, and relational databases. Youll also learn the key topics you need for web programming, such as state management, web controls, and caching. By the end of this book, youll be ready to create your own rich web applications and make them available over the Internet.
INT