In short, this is the book to read if you’re a professional developer moving to Matthew MacDonald and Mario Szpuszta Pro ASP.NET 2.0 Mario Szpuszta, author of Advanced .NET Remoting, Sec
Trang 1Pro ASP.NET 2.0 in C# 2005
Dear Reader,
As you know, ASP.NET is Microsoft’s premier technology for creating server-sideweb applications In fact, ASP.NET 1.0 was a revolution in the web programmingworld It was so wildly popular that it was licensed on thousands of commercialweb servers while it was still a beta product
ASP.NET 2.0 is the next major milestone in web development ASP.NET 2.0keeps the same technical underpinning as ASP.NET 1.x but adds layers and layers
of higher-level features These features include a streamlined data bindingmodel, an out-of-the-box security framework, tools for building dynamic webportals, and a slew of powerful new web controls
In this book, you’ll learn how ASP.NET 2.0 really works You won’t be boredwith a rehash of the C# language—instead, you’ll get the hard-won practicaladvice that you need to build sophisticated, scalable websites You’ll also diginto advanced topics that other ASP.NET books avoid, such as creating customcontrols, handling images, and enabling encryption New features are clearlyidentified, so if you’ve programmed with a previous version of ASP.NET you’llsail through the basics and get right to the most important changes andenhancements
In short, this is the book to read if you’re a professional developer moving to
Matthew MacDonald and Mario Szpuszta
Pro ASP.NET 2.0
Mario Szpuszta, author of
Advanced NET Remoting,
Second Edition (coauthor)
THE APRESS ROADMAP
Pro ASP.NET 2.0
in C# 2005
Pro C# 2005 andthe NET 2.0 Platform
Beginning ASP.NET 2.0
in C# 2005
Expert ASP.NET 2.0Advanced Application Design
Pro ASP.NET 2.0Website Programming
www.apress.com
SOURCE CODE ONLINE
www.asptoday.com
For a limited time, get the
free, fully searchable eBook—
a $30 value! See inside for details.
For a limited time, get the
free, fully searchable eBook—
a $30 value! See inside for details.
Trang 2Matthew MacDonald and Mario Szpuszta,
Christopher Miller Matt Milner Jan Narkiewicz
Matt Odhner Ryan O'Keefe Andrew Reid Matthew Reynolds Enrico Sabbadin Bill Sempf Doug Seven Srinivasa Sivakumar Thiru Thangarathinam Doug Thews
Trang 3Pro ASP.NET 2.0 in C# 2005
Copyright © 2005 by Matthew MacDonald and Mario Szpuszta
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 retrievalsystem, without the prior written permission of the copyright owner and the publisher
ISBN-13 (pbk): 978-1-59059-496-4
ISBN-10 (pbk): 1-59059-496-7
Printed and bound in the United States of America 9 8 7 6 5 4 3 2
Trademarked names may appear in this book Rather than use a trademark symbol with every occurrence
of a trademarked name, we use the names only in an editorial fashion and to the benefit of the trademarkowner, with no intention of infringement of the trademark
Lead Editor: Ewan Buckingham
Technical Reviewers: Robert Lair, Jason Lefebvre
Editorial Board: Steve Anglin, Dan Appleman, Ewan Buckingham, Gary Cornell, Tony Davis,
Jason Gilmore, Jonathan Hassell, Chris Mills, Dominic Shakeshaft, Jim SumserAssociate Publisher: Grace Wong
Project Manager: Kylie Johnston
Copy Edit Manager: Nicole LeClerc
Copy Editor: Kim Wimpsett
Assistant Production Director: Kari Brooks-Copony
Production Editor: Laura Cheu
Compositor: Dina Quan
Proofreaders: Liz Welch and Lori Bring
Indexer: Broccoli Information Management
Artist: Kinetic Publishing Services, LLC
Interior Designer: Diana Van Winkle
Cover Designer: Kurt Krames
Manufacturing Manager: Tom Debolski
Distributed to the book trade worldwide by Springer-Verlag New York, Inc., 233 Spring Street, 6th Floor,New York, NY 10013 Phone 1-800-SPRINGER, fax 201-348-4505, e-mail orders-ny@springer-sbm.com, orvisit http://www.springeronline.com
For information on translations, please contact Apress directly at 2560 Ninth Street, Suite 219, Berkeley,
CA 94710 Phone 510-549-5930, fax 510-549-5939, e-mail info@apress.com, or visit http://www.apress.com.The information in this book is distributed on an “as is” basis, without warranty Although every precautionhas been taken in the preparation of this work, neither the author(s) nor Apress shall have any liability toany person or entity with respect to any loss or damage caused or alleged to be caused directly or indi-rectly by the information contained in this work
The source code for this book is available to readers at http://www.apress.com in the Source Code section
Trang 5Contents at a Glance
About the Revising Authors xxv
About the Technical Reviewers xxvii
Introduction xxix
PART 1 ■ ■ ■ Core Concepts ■ CHAPTER 1 Introducing ASP.NET 3
■ CHAPTER 2 Visual Studio 2005 23
■ CHAPTER 3 Web Forms 63
■ CHAPTER 4 Server Controls 103
■ CHAPTER 5 ASP.NET Applications 151
■ CHAPTER 6 State Management 195
PART 2 ■ ■ ■ Data Access ■ CHAPTER 7 ADO.NET Fundamentals 229
■ CHAPTER 8 Data Components and the DataSet 265
■ CHAPTER 9 Data Binding 295
■ CHAPTER 10 Rich Data Controls 335
■ CHAPTER 11 Caching 391
■ CHAPTER 12 XML 425
■ CHAPTER 13 Files and Streams 471
PART 3 ■ ■ ■ Building ASP.NET Websites ■ CHAPTER 14 User Controls 505
■ CHAPTER 15 Themes and Master Pages 525
■ CHAPTER 16 Website Navigation 555
■ CHAPTER 17 Resources and Localization 599
■ CHAPTER 18 Website Deployment 619
Trang 6PART 4 ■ ■ ■ Security
■ CHAPTER 19 The ASP.NET Security Model 667
■ CHAPTER 20 Forms Authentication 689
■ CHAPTER 21 Membership 709
■ CHAPTER 22 Windows Authentication 751
■ CHAPTER 23 Authorization and Roles 777
■ CHAPTER 24 Profiles 803
■ CHAPTER 25 Cryptography 839
■ CHAPTER 26 Custom Membership Providers 867
PART 5 ■ ■ ■ Advanced User Interface ■ CHAPTER 27 Custom Server Controls 899
■ CHAPTER 28 Design-Time Support 941
■ CHAPTER 29 JavaScript 975
■ CHAPTER 30 Dynamic Graphics and GDI+ 1011
■ CHAPTER 31 Portals with Web Part Pages 1043
PART 6 ■ ■ ■ Web Services ■ CHAPTER 32 Creating Web Services 1087
■ CHAPTER 33 Web Service Standards and Extensions 1129
■ CHAPTER 34 Advanced Web Services 1175
■ INDEX 1211
v
Trang 8About the Revising Authors xxv
About the Technical Reviewers xxvii
Introduction xxix
PART 1 ■ ■ ■ Core Concepts ■ CHAPTER 1 Introducing ASP.NET 3
The Evolution of Web Development 3
The Development World Before ASP.NET 3
What’s Wrong with Classic ASP? 4
ASP.NET 1.0 6
Seven Important Facts About ASP.NET 7
Fact 1: ASP.NET Is Integrated with the NET Framework 7
Fact 2: ASP.NET Is Compiled, Not Interpreted 7
Fact 3: ASP.NET Is Multilanguage 9
Fact 4: ASP.NET Runs Inside the Common Language Runtime 11
Fact 5: ASP.NET Is Object-Oriented 12
Fact 6: ASP.NET Is Multidevice and Multibrowser 14
Fact 7: ASP.NET Is Easy to Deploy and Configure 14
ASP.NET 2.0: The Story Continues 15
C# 2005 16
Visual Studio 2005 16
ASP.NET 2.0 16
Summary 22
■ CHAPTER 2 Visual Studio 2005 23
The NET Development Model 24
The Compiler 24
The Visual Studio IDE 25
Websites in Visual Studio 26
Projectless Development 28
Migrating a Visual Studio NET Project 29
Designing a Web Page 30
The Visual Studio IDE 34
Solution Explorer 36
Document Window 37
Toolbox 37
vii
Trang 9Error List and Task List 38
Server Explorer 39
The Code Editor 40
Adding Assembly References 41
IntelliSense and Outlining 43
The Coding Model 47
How Code-Behind Files Are Connected to Pages 49
How Control Tags Are Connected to Page Variables 50
How Events Are Connected to Event Handlers 50
Visual Studio Debugging 52
Single-Step Debugging 52
Advanced Breakpoints 55
Variable Watches 56
Visual Studio Macros 57
ASP.NET Development Helper 59
Summary 61
■ CHAPTER 3 Web Forms 63
Page Processing 64
HTML Forms 64
Dynamic Interfaces 66
The ASP.NET Event Model 66
Automatic Postbacks 67
View State 69
XHTML Compliance 73
Web Forms Processing Stages 76
Page Framework Initialization 77
User Code Initialization 77
Validation 78
Event Handling 78
Automatic Data Binding 79
Cleanup 79
A Page Flow Example 80
The Page As a Control Container 82
Showing the Control Tree 82
The Page Header 86
Dynamic Control Creation 87
The Page Class 89
Session, Application, and Cache 89
Request 89
Response 91
Server 92
User 94
Trace 95
Accessing the HTTP Context in Another Class 100
Trang 10■ CHAPTER 4 Server Controls 103
Types of Server Controls 104
The Server Control Hierarchy 105
HTML Server Controls 106
The HtmlControl Class 107
The HtmlContainerControl Class 108
The HtmlInputControl Class 108
The HTML Server Control Classes 108
Setting Style Attributes and Other Properties 110
Programmatically Creating Server Controls 111
Handling Server-Side Events 113
Web Controls 116
The WebControl Base Class 117
Basic Web Control Classes 117
Units 119
Enumerated Values 120
Colors 120
Fonts 121
Focus 122
The Default Button 123
Scrollable Panels 123
Handling Web Control Events 124
The List Controls 127
The Selectable List Controls 128
The BulletedList Control 130
Input Validation Controls 132
The Validation Controls 133
The Validation Process 134
The BaseValidator Class 135
The RequiredFieldValidator Control 137
The RangeValidator Control 137
The CompareValidator Control 137
The RegularExpressionValidator Control 138
The CustomValidator Control 141
The ValidationSummary Control 142
Using the Validators Programmatically 143
Validation Groups 144
The ASP.NET Rich Controls 145
The AdRotator Control 146
The Calendar Control 148
Summary 150
■ CHAPTER 5 ASP.NET Applications 151
Anatomy of an ASP.NET Application 152
The Application Domain 152
Application Lifetime 153
Trang 11Application Updates 154
Application Directory Structure 154
The Global.asax Application File 155
Application Events 156
Demonstrating Application Events 158
ASP.NET Configuration 159
The Machine.config File 160
The Web.config File 162
Configuration Settings 164
Reading and Writing Configuration Sections Programmatically 168
The Website Administration Tool (WAT) 171
Extending the Configuration File Structure 173
Encrypting Configuration Sections 175
.NET Components 177
Creating a Component 178
Using a Component Through the App_Code Directory 179
Using a Component Through the Bin Directory 180
Extending the HTTP Pipeline 182
HTTP Handlers and HTTP Modules 183
Creating a Custom HTTP Handler 184
Configuring a Custom HTTP Handler 185
Registering HTTP Handlers Without Configuring IIS 186
Creating an Advanced HTTP Handler 187
Creating a Custom HTTP Module 190
Summary 193
■ CHAPTER 6 State Management 195
ASP.NET State Management 196
View State 198
A View State Example 199
Storing Objects in View State 200
Retaining Member Variables 202
Assessing View State 203
Trimming View State in a List Control 205
View State Security 206
Transferring Information 207
The Query String 207
Cross-Page Posting 209
Cross-Page Posting and Validation 211
Custom Cookies 213
Session State 214
Session Architecture 214
Using Session State 216
Configuring Session State 217
Securing Session State 222
Trang 12Application State 223
Static Application Variables 224
Summary 226
PART 2 ■ ■ ■ Data Access ■ CHAPTER 7 ADO.NET Fundamentals 229
The ADO.NET Architecture 230
ADO.NET Data Providers 230
Standardization in ADO.NET 232
SQL Server 2005 233
Fundamental ADO.NET Classes 233
The Connection Class 234
Connection Strings 235
Testing a Connection 236
Connection Pooling 237
Connection Statistics 239
The Command and DataReader Classes 240
Command Basics 240
The DataReader Class 241
The ExecuteReader() Method and the DataReader 242
The ExecuteScalar() Method 247
The ExecuteNonQuery() Method 247
SQL Injection Attacks 248
Using Parameterized Commands 250
Calling Stored Procedures 251
Transactions 253
Transactions and ASP.NET Applications 254
Isolation Levels 258
Savepoints 259
Nested Transactions 260
Provider-Agnostic Code 260
Creating the Factory 260
Create Objects with Factory 261
A Query with Provider-Agnostic Code 262
Summary 263
■ CHAPTER 8 Data Components and the DataSet 265
Building a Data Access Component 265
The Data Package 267
The Stored Procedures 267
The Data Utility Class 268
Testing the Component 274
Trang 13Disconnected Data 276
Web Applications and the DataSet 277
XML Integration 277
The DataSet Classes 278
The DataTable Class 279
The DataRow Class 280
The DataAdapter Class 280
Filling a DataSet 280
Working with Multiple Tables and Relationships 282
Searching for Specific Rows 286
Using the DataSet in a Custom Data Class 286
Data Binding 287
The DataView Class 288
Sorting with a DataView 288
Filtering with a DataView 290
Advanced Filtering with Relationships 292
Calculated Columns 292
Summary 294
■ CHAPTER 9 Data Binding 295
Basic Data Binding 296
Single-Value Binding 296
Other Types of Expressions 298
Repeated-Value Binding 302
Data Source Controls 309
The Page Life Cycle with Data Binding 310
The SqlDataSource 311
Selecting Records 312
Parameterized Commands 314
Handling Errors 318
Updating Records 318
Disadvantages of the SqlDataSource 322
The ObjectDataSource 323
Selecting Records 324
Updating Records 328
Updating with a Data Object 329
The Limits of the Data Source Controls 331
The Problem 331
Adding the Extra Items 332
Handling the Extra Options with the SqlDataSource 333
Handling the Extra Options with the ObjectDataSource 334
Summary 334
Trang 14■ CHAPTER 10 Rich Data Controls 335
The GridView 336
Defining Columns 336
Formatting the GridView 339
Formatting Fields 340
Styles 341
Formatting-Specific Values 344
GridView Row Selection 346
Using Selection to Create a Master-Details Form 346
The SelectedIndexChanged Event 348
Using a Data Field As a Select Button 349
Sorting the GridView 350
Sorting with the SqlDataSource 350
Sorting with the ObjectDataSource 351
Sorting and Selection 353
Advanced Sorting 354
Paging the GridView 355
Automatic Paging 355
Custom Pagination with the ObjectDataSource 357
Customizing the Pager Bar 360
GridView Templates 361
Using Multiple Templates 362
Editing Templates in Visual Studio 363
Binding to a Method 364
Handling Events in a Template 366
Editing with a Template 367
The DetailsView and FormView 372
The DetailsView 372
The FormView 374
Advanced Grids 375
Summaries in the GridView 375
A Parent/Child View in a Single Table 377
Serving Images from a Database 379
Detecting Concurrency Conflicts 385
Summary 389
■ CHAPTER 11 Caching 391
Understanding ASP.NET Caching 392
Output Caching 393
Declarative Output Caching 393
Caching and the Query String 394
Caching with Specific Query String Parameters 395
Custom Caching Control 396
Caching with the HttpCachePolicy Class 397
Post-Cache Substitution and Fragment Caching 398
Trang 15Cache Profiles 400
Caching to Disk 401
Data Caching 401
Adding Items to the Cache 402
A Simple Cache Test 404
Cache Priorities 405
Caching with the Data Source Controls 406
Cache Dependencies 409
File and Cache Item Dependencies 410
Aggregate Dependencies 410
The Item Removed Callback 411
Understanding SQL Cache Notifications 413
Cache Notifications in SQL Server 2000 or SQL Server 7 415
Cache Notifications in SQL Server 2005 419
Custom Cache Dependencies 420
A Basic Custom Cache Dependency 421
A Custom Cache Dependency Using Message Queues 422
Summary 424
■ CHAPTER 12 XML 425
When Does Using XML Make Sense? 426
An Introduction to XML 426
The Advantages of XML 427
Well-Formed XML 428
XML Namespaces 429
XML Schemas 430
Writing and Reading XML Programmatically 431
Writing XML Files 432
Reading XML Files 435
Validating XML Files 447
Displaying XML Content with XSL 450
A Basic Stylesheet 450
Using XslTransform 451
Using the Xml Control 452
XML Data Binding 453
Nonhierarchical Binding 453
Using XPath 455
Nested Grids 458
Hierarchical Binding with the TreeView 459
Using XSLT 461
Binding to XML Content from Other Sources 463
Updating XML Through the XmlDataSource 464
XML and ADO.NET 464
Converting the DataSet to XML 465
Accessing a DataSet As XML 466
Trang 16■ CHAPTER 13 Files and Streams 471
Working with the File System 472
The Directory and File Classes 472
The DirectoryInfo and FileInfo Classes 474
The DriveInfo Class 477
Working with Attributes 478
Filter Files with Wildcards 480
Retrieving File Version Information 480
The Path Class 481
A File Browser 483
Reading and Writing Files with Streams 488
Text Files 489
Binary Files 491
Uploading Files 492
Making Files Safe for Multiple Users 494
Compression 498
Serialization 499
Summary 502
PART 3 ■ ■ ■ Building ASP.NET Websites ■ CHAPTER 14 User Controls 505
User Control Basics 506
Creating a Simple User Control 506
Converting a Page to a User Control 508
Adding Code to a User Control 508
Handling Events 508
Adding Properties 510
Using Custom Objects 512
Adding Events 514
Exposing the Inner Web Control 517
Dynamically Loading User Controls 518
Portal Frameworks 519
Partial Page Caching 522
VaryByControl 522
Sharing Cached Controls 524
Summary 524
■ CHAPTER 15 Themes and Master Pages 525
Standardizing Website Formatting 525
Cascading Style Sheets 525
Themes 528
Theme Folders and Skins 529
Applying a Simple Theme 530
Trang 17Handling Theme Conflicts 531
Creating Multiple Skins for the Same Control 532
Skins with Templates and Images 533
Using CSS in a Theme 535
Applying Themes Through a Configuration File 536
Applying Themes Dynamically 536
Standardizing Website Layout 538
Master Page Basics 538
A Simple Master Page 539
A Simple Content Page 541
Design-Time Quirks with Master Pages 543
Default Content 546
A More Practical Master Page 546
Master Pages and Relative Paths 548
Master Pages and Formatting 549
Applying Master Pages Through a Configuration File 549
Advanced Master Pages 549
Specifying a Title and Metatags for a Content Page 550
Interacting with the Master Page Class 550
Dynamically Setting a Master Page 552
Nesting Master Pages 552
Summary 554
■ CHAPTER 16 Website Navigation 555
Pages with Multiple Views 555
The MultiView Control 556
The Wizard Control 559
Site Maps 567
Defining a Site Map 568
Binding to a Site Map 569
Breadcrumbs 570
Binding Portions of a SiteMap 572
Programmatic Navigation 575
Binding Other Controls 576
Adding Custom Site Map Information 577
Creating a Custom SiteMapProvider 578
URL Mapping 583
The TreeView Control 584
The TreeNode 585
Populating Nodes on Demand 587
TreeView Styles 589
Menu Control 592
Menu Styles 595
Menu Templates 596
Summary 598
Trang 18■ CHAPTER 17 Resources and Localization 599
Resources in NET Applications 599
Localization of Web Applications 607
Localization and the Common Language Runtime 607
Local Resources for a Single Page 611
Sharing Resources Between Pages 615
Localizing Static Text 617
Text Directions 618
Summary 618
■ CHAPTER 18 Website Deployment 619
Internet Information Services (IIS) 619
IIS and URL Processing 620
Request Processing with IIS and ASP.NET 622
IIS 5.x Process Model 623
IIS 6.0 Process Model 626
Installing IIS 631
Managing Websites 634
Creating a Virtual Directory 634
Virtual Directories and Web Applications 636
Folder Settings 637
Managing Application Pools in IIS 6.0 641
Creating Application Pools 641
Application Pools and Web Applications 644
Custom Application Pool Identities 644
Deploying Your ASP.NET Applications 647
Verifying the ASP.NET Installation 648
ASP.NET Side-By-Side Execution 650
Configure HTTP Runtime Settings 651
Compilation Models 652
Deploying with Visual Studio 653
The VirtualPathProvider in ASP.NET 2.0 655
Health Monitoring in ASP.NET 2.0 660
Understanding the Basic Structure 660
Events and Providers 660
Summary 664
PART 4 ■ ■ ■ Security ■ CHAPTER 19 The ASP.NET Security Model 667
What It Means to Create Secure Software 667
Understanding Potential Threats 668
Secure Coding Guidelines 668
Understanding Gatekeepers 669
Trang 19Understanding the Levels of Security 670
Authentication 670
Authorization 672
Confidentiality and Integrity 673
Pulling It All Together 673
Internet Information Services Security 675
IIS Authentication 675
IIS Authorization 676
IIS and Secure Sockets Layer 677
ASP.NET Security Architecture 682
Authentication 684
Authorization 685
The Security Context 686
Membership and Roles APIs 687
Summary 688
■ CHAPTER 20 Forms Authentication 689
Introducing Forms Authentication 689
Why Use Forms Authentication? 690
Why Would You Not Use Forms Authentication? 692
Why Not Implement Cookie Authentication Yourself? 693
The Forms Authentication Classes 694
Implementing Forms Authentication 695
Configuring Forms Authentication 695
Denying Access to Anonymous Users 698
Creating a Custom Login Page 698
Custom Credentials Store 704
Persistent Cookies in Forms Authentication 705
Summary 707
■ CHAPTER 21 Membership 709
Introducing the ASP.NET Membership API 709
Using the Membership API 711
Configuring Forms Authentication 713
Creating the Data Store 714
Configuring Connection String and Membership Provider 718
Creating and Authenticating Users 721
Using the Security Controls 723
The Login Control 724
The LoginStatus Control 733
The LoginView Control 733
The PasswordRecovery Control 735
The ChangePassword Control 739
The CreateUserWizard Control 740
Trang 20Updating Users in the Store 747
Creating and Deleting Users 748
Validating Users 749
Summary 749
■ CHAPTER 22 Windows Authentication 751
Introducing Windows Authentication 751
Why Use Windows Authentication? 751
Why Would You Not Use Windows Authentication? 752
Mechanisms for Windows Authentication 753
Implementing Windows Authentication 759
Configuring IIS 759
Configuring ASP.NET 760
Denying Access to Anonymous Users 761
Accessing Windows User Information 761
Impersonation 764
Impersonation in Windows 2000 765
Impersonation on Windows XP 766
Impersonation and Delegation on Windows Server 2003 767
Configured Impersonation 769
Programmatic Impersonation 772
Summary 775
■ CHAPTER 23 Authorization and Roles 777
URL Authorization 777
Authorization Rules 778
File Authorization 783
Authorization Checks in Code 784
Using the IsInRole() Method 784
Using the PrincipalPermission Class 785
Using the Roles Service for Role-Based Authorization 787
Using the LoginView Control with Roles 793
Accessing Roles Programmatically 794
Using the Roles Service with Windows Authentication 796
Protecting Non-Web-Page Resources 798
Adding a File Type Mapping 798
Writing a Custom HTTP Handler 800
Summary 801
■ CHAPTER 24 Profiles 803
Understanding Profiles 803
Profile Performance 803
How Profiles Store Data 804
Profiles and Authentication 805
Profiles vs Custom Data Components 806
Trang 21Using the SqlProfileProvider 806
Creating the Profile Tables 807
Configuring the Provider 809
Defining Profile Properties 810
Using Profile Properties 811
Profile Serialization 812
Profile Groups 814
Profiles and Custom Data Types 814
The Profiles API 818
Anonymous Profiles 820
Building a Shopping Cart 822
The Shopping Cart Classes 823
The Test Page 826
Multiple Selection 828
Custom Profiles Providers 829
The Custom Profiles Provider Classes 829
Designing the FactoredProfileProvider 831
Coding the FactoredProfileProvider 832
Testing the FactoredProfileProvider 836
Summary 838
■ CHAPTER 25 Cryptography 839
Encrypting Data: Confidentiality Matters 839
The NET Cryptography Namespace 840
Understanding the NET Cryptography Classes 843
Symmetric Encryption Algorithms 844
Asymmetric Encryption 845
The Abstract Encryption Classes 846
The ICryptoTransform Interface 847
The CryptoStream Class 847
Encrypting Sensitive Data 848
Managing Secrets 849
Using Symmetric Algorithms 850
Using Asymmetric Algorithms 855
Encrypting Sensitive Data in a Database 858
Encrypting the Query String 861
Wrapping the Query String 862
Creating a Test Page 864
Summary 866
■ CHAPTER 26 Custom Membership Providers 867
Architecture of Custom Providers 867
Basic Steps for Creating Custom Providers 869
Overall Design of the Custom Provider 869
Trang 22Implementing the Provider Classes 876Using the Custom Provider Classes 894Summary 896
■ CHAPTER 27 Custom Server Controls 899
Custom Server Control Basics 900Creating a Bare-Bones Custom Control 900Using a Custom Control 902Custom Controls in the Toolbox 903Creating a WebControl That Supports Style Properties 904The Rendering Process 908Dealing with Different Browsers 909The HtmlTextWriter 909Browser Detection 910Browser Properties 912Adaptive Rendering 914Control State and Events 915View State 915Control State 917Postback Data and Change Events 918Triggering a Postback 921Extending Existing Web Controls 923Composite Controls 923Derived Controls 925Templated Controls 930Creating a Templated Control 930Using Customized Templates 933Styles 936Summary 940
■ CHAPTER 28 Design-Time Support 941
Design-Time Attributes 942The Properties Window 942Attributes and Inheritance 945The Toolbox Icon 946Web Resources 947Code Serialization 949Type Converters 949Serialization Attributes 957Type Editors 962Control Designers 965
A Basic Control Designer 966
Trang 23Smart Tags 968The Action List 969The DesignerActionItem Collection 970The Control Designer 972Summary 973
■ CHAPTER 29 JavaScript 975
JavaScript Essentials 975JavaScript Events 976Script Blocks 978Rendering Script Blocks 986Script Injection Attacks 987Request Validation 988Disabling Request Validation 988Client Callbacks 991Creating a Client Callback 991Client Callbacks “Under the Hood” 995Custom Controls with JavaScript 996Pop-Up Windows 997Rollover Buttons 1000Dynamic Panels 1003Frames 1006Frame Navigation 1007Inline Frames 1008Summary 1010
■ CHAPTER 30 Dynamic Graphics and GDI+ 1011
The ImageMap Control 1011Creating Hotspots 1012Handling Hotspot Clicks 1013
A Custom Hotspot 1014Drawing with GDI+ 1016Simple Drawing 1017Image Format and Quality 1019The Graphics Class 1020Using a GraphicsPath 1023Pens 1024Brushes 1026Embedding Dynamic Graphics in a Web Page 1028Using the PNG Format 1029Passing Information to Dynamic Images 1030Custom Controls That Use GDI+ 1033Charting with GDI+ 1037Summary 1042
Trang 24■ CHAPTER 31 Portals with Web Part Pages 1043
Typical Portal Pages 1043Basic Web Part Pages 1045Creating the Page Design 1045WebPartManager and WebPartZones 1047Adding Web Parts to the Page 1048Customizing the Page 1051Creating Web Parts 1054Simple Web Part Tasks 1054Developing Advanced Web Parts 1062Web Part Editors 1070Connecting Web Parts 1076Authorizing Web Parts 1083Final Tasks for Personalization 1084Summary 1084
PART 6 ■ ■ ■ Web Services
■ CHAPTER 32 Creating Web Services 1087
Web Services Overview 1088The History of Web Services 1088Distributed Computing and Web Services 1089The Problems with Distributed Component Technologies 1091The Benefits of Web Services 1091Making Money with Web Services 1093The Web Service Stack 1093Building a Basic Web Service 1096The Web Service Class 1096Web Service Requirements 1097Exposing a Web Service 1100Testing a Web Service 1103Consuming a Web Service 1106The Proxy Class 1112Creating an ASP.NET Client 1113Creating a Windows Forms Client 1115Creating an ASP Client with MSXML 1117Creating an ASP Client with the SOAP Toolkit 1119Refining a Web Service 1120CacheDuration 1120EnableSession 1123BufferResponse 1126TransactionOption 1126Summary 1128
Trang 25■ CHAPTER 33 Web Service Standards and Extensions 1129
WS-Interoperability 1129SOAP 1131SOAP Encoding 1132SOAP Versions 1133Tracing SOAP Messages 1134The SOAP Envelope 1136The SOAP Header 1140WSDL 1144Viewing the WSDL for a Web Service 1144The Basic Structure 1146Implementing an Existing Contract 1151Customizing SOAP Messages 1152Serializing Complex Data Types 1152Customizing XML Serialization with Attributes 1156Type Sharing 1159Customizing XML Serialization with IXmlSerializable 1161Custom Serialization for Large Data Types 1165Schema Importer Extensions 1170Summary 1173
■ CHAPTER 34 Advanced Web Services 1175
Asynchronous Calls 1175Asynchronous Delegates 1176
A Simple Asynchronous Call 1178Concurrent Asynchronous Calls 1180Responsive Windows Clients 1181Asynchronous Services 1185Securing Web Services 1186Windows Authentication 1186Custom Ticket-Based Authentication 1189Tracking the User Identity 1190Authenticating the User 1191Authorizing the User 1192Testing the SOAP Authentication System 1192SOAP Extensions 1194Creating a SOAP Extension 1196The Web Services Enhancements 1203Installing the WSE 1204Performing Authentication with the WSE 1206Summary 1210
■ INDEX 1211
Trang 26About the Revising Authors
■MATTHEW MACDONALDis an author, educator, and MCSD developer He’s aregular contributor to programming journals and the author of more than a
dozen books about NET programming, including ASP.NET: The Complete
Reference (Osborne McGraw-Hill, 2002), Programming NET Web Services
(O’Reilly, 2002), Beginning ASP.NET in C (Apress, 2004), and Microsoft NET
Distributed Applications (Microsoft Press, 2003) In a dimly remembered past
life, he studied English literature and theoretical physics
■MARIO SZPUSZTAworks in the Developer and Platform Group of MicrosoftAustria Before he started working for Microsoft, Mario was involved in severalprojects based on COM+ and DCOM with Visual Basic and Visual C++ as well
as projects based on Java and J2SE With beta 2 of the first version of the NETFramework, he started developing web applications with ASP.NET Currently,
as a developer evangelist for Microsoft Austria, he conducts workshops, ings, and proof-of-concept projects with independent software vendors inAustria based on NET web services and Office 2003 technologies
train-xxv
Trang 28About the Technical Reviewers
■ROBERT LAIRis the president and CEO of Intensity Software (http://www.intensitysoftware.com),
which specializes in Microsoft NET consulting services In addition to consulting services, Intensity
offers Kicks for NET, a CICS-to-ASP.NET migration utility that automates the migration process
while maintaining the existing business logic’s source code Robert was one of the developers who
created the original IBuySpy Store and Portal demo applications as well as the NetCOBOL for NET
version of IBuySpy and the QuickStart samples Robert has been a participating author for a number
of books and has written numerous articles about Microsoft NET–related topics Robert’s personal
website is at http://www.robertlair.com, and his blog is at http://www.robertlair.com/blogs/lair
Robert would like to thank his beautiful wife, Debi, and four-year-old son, Max, for the familytime that was sacrificed while reviewing this book
■JASON LEFEBVREis the vice president and one of the founding partners of Intensity Software He
uses Visual Studio and the Microsoft NET Framework daily while architecting solutions for clients
of Intensity’s consulting services He is also one of the developers who created the original IBuySpy
Store demo application and its NetCOBOL for NET translation Jason has been a participating
author for a number of books and has written numerous articles about Microsoft NET–related
topics
He would like to thank his friends’ new puppy, Oliver, for being so cute
xxvii
Trang 30It’s not hard to get developers interested in ASP.NET Without exaggeration, ASP.NET is the most
complete platform for web development that’s ever been put together It far outclasses its
predeces-sor, ASP, which was designed as a quick-and-dirty set of tools for inserting dynamic content into
ordinary web pages By contrast, ASP.NET is a full-blown platform for developing comprehensive,
blisteringly fast web applications.
In this book, you’ll learn everything you need to master ASP.NET 2.0 If you’ve programmedwith a previous version of ASP.NET, you’ll sail through the basics and quickly begin learning about
the exciting new features in version 2.0 If you’ve never programmed with ASP.NET, you’ll find that
this book provides a well-paced tour that leads through all the fundamentals, along with a
back-stage pass that lets you see how the ASP.NET internals really work The only requirement for this
book is that you have a solid understanding of the C# language and the basics of NET If you’re a
seasoned Java or C++ developer but you’re new to C#, you may find it easier to start with a book
about NET fundamentals before you read this one Try C# and the NET 2.0 Platform, Third Edition
(Apress, 2005) for a comprehensive introduction or, for a quicker start, read A Programmer’s
Intro-duction to C# 2.0, Third Edition (Apress, 2005).
ASP.NET from 1.0 to 2.0
As you no doubt already know, ASP.NET is Microsoft’s next-generation technology for creating
server-side web applications It’s built on the Microsoft NET Framework, which is a cluster of
closely related new technologies that revolutionizes everything from database access to distributed
applications ASP.NET is one of the most important components of the NET Framework—it’s the
part that enables you to develop high-performance web applications and web services
ASP.NET 1.0 was a revolution in the web programming world It was so wildly popular that itwas licensed on thousands of commercial web servers through Microsoft’s Go-Live license program
while it was still a beta product ASP.NET 1.0 was finally released in early 2002
ASP.NET 1.1 wasn’t as ambitious Instead, it was just a chance for Microsoft architects to pauseand catch their collective breath The focus in ASP.NET 1.1 wasn’t on new features—there weren’t
any—but on performance tune-ups, security tweaks, and minor bug fixes New features were quietly
shelved and saved for the next major milestone, ASP.NET 2.0 ASP.NET 1.1 was released late in 2003,
solidifying ASP.NET as the web development platform of choice for professional developers
Two long years later, ASP.NET 2.0 finally appeared on the horizon Unlike the ASP.NET 1.0release, ASP.NET 2.0 doesn’t represent the start of a new direction in web development In fact,
almost all the underlying architecture that underpins ASP.NET 1.0 remains the same in ASP.NET 2.0
The difference is that ASP.NET 2.0 adds layers of higher-level features to the existing technology
Essentially, after the success of ASP.NET 1.0, Microsoft poured developers, time, and resources
into planning and preparing ASP.NET 2.0 Seeing as they no longer needed to rewrite the ASP.NET
engine, the ASP.NET team members were free to be innovative with new controls, create better data
management solutions, build a role-based security framework, and even make a whole toolkit for
creating portal websites In short, ASP.NET 2.0 gives developers a chance to relax and enjoy a wealth
of new frills designed for their favorite platform In this book, you’ll learn how to use, customize,
and extend all these features
xxix
Trang 31What Does This Book Cover?
Here is a quick breakdown of what you’ll find in this book:
Part 1: Core Concepts: You’ll begin in Chapter 1 with a look at the overall ASP.NET platform,
the NET Framework, and the changes in store for ASP.NET 2.0 In Chapter 2 you’ll branch out
to learn the tools of the trade—namely, Visual Studio 2005 In Chapters 3, 4, 5, and 6 you’ll learnthe key parts of the ASP.NET infrastructure, such as the web-page model, application configu-ration, state management, and caching As you learn these core concepts, you’ll also take alow-level look at how ASP.NET processes requests and manages the lifetime of your web appli-cations You’ll even learn how to extend the ASP.NET architecture
Part 2: Data Access: This part tackles one of the core problem domains for all software
development—accessing and manipulating data In Chapters 7 and 8 you’ll consider the damentals of ADO.NET as they apply to web applications and learn how to design data accesscomponents In Chapter 9 and Chapter 10 you’ll learn about ASP.NET’s set of innovative data-bound controls that let you format and present data without writing pages of code Chapter 11branches out into advanced caching strategies that ensure blistering performance Finally,Chapters 12 and 13 move beyond the world of databases to show you how to work with XMLcontent and handle ordinary file access
fun-Part 3: Building ASP.NET Websites: In this part you’ll learn about essential techniques and
fea-tures for managing groups of web pages You’ll start simply with user controls in Chapter 14,which allow you to reuse segments of the user interface In Chapter 15 you’ll consider twonew ASP.NET innovations—themes (for styling controls automatically) and master pages (forreusing a layout template across multiple pages) Chapter 16 shows how you can use the newnavigation model in ASP.NET 2.0 to let visitors surf from one page to another Finally, Chapter 17explores localization, and Chapter 18 describes deployment and the IIS web server software
Part 4: Security: In this part you’ll look at ASP.NET’s rich complement of security features.
You’ll start with a high-level overview of security concepts in Chapter 19 and then learn the insand outs of forms authentication (Chapter 20) and the new Membership API that works with
it (Chapter 21) In Chapter 22 you’ll tackle Windows authentication, and in Chapter 23 you’lllearn how to restrict authenticated users with sophisticated authorization rules and use role-based security In Chapter 24 you’ll explore the Profiles API, a new, prebuilt solution for storinguser-specific information, and in Chapter 25 you’ll go one step further and learn how to protectthe data you store in a database as well as the information you send in a URL with encryption.Finally, Chapter 26 shows how you can plug into the ASP.NET security model by designing acustom Membership provider
Part 5: Advanced User Interface: This part shows how you can extend web pages with
advanced techniques In Chapter 27 and 28 you’ll tackle custom controls In Chapter 29 andChapter 30 you’ll branch out to use JavaScript for dynamic pages and GDI+ for handcraftedgraphics Finally, Chapter 31 explores the ASP.NET 2.0 Web Parts Framework for creating webportals
Part 6: Web Services: Web services promise to revolutionize the way functionality is shared
across different applications, network environments, and computing platforms In Chapter 32you’ll start at the beginning; you’ll see how to create basic web services and how to use them inASP.NET web applications, NET Windows applications, and even legacy ASP applications InChapter 33 you’ll take a low-level look at the standards that make it all possible and see howthey work In Chapter 34 you’ll learn how to use advanced techniques to call web services asyn-chronously, implement secure services, and start working with newer web service standards
Trang 32Who Is This Book For?
This book is intended as a primer for professional developers who have a reasonable knowledge of
server-side web development This book doesn’t provide an exhaustive look at every ingredient in
the NET Framework—in fact, such a book would require twice as many pages Instead, this book
aims to provide a lean, intelligent introduction to ASP.NET for professional programmers who don’t
want to rehash the basics Along the way, you’ll focus on other corners of the NET Framework that
you’ll need in order to build professional web applications, including data access and XML Using
these features, you’ll be able to create next-generation websites with the best tools on hand today
This book is also relentlessly practical You won’t just learn about features but you’ll also learn about the real-world techniques that can take your website to the next level Later chapters are dedi-
cated to cutting-edge topics such as custom controls, dynamic graphics, advanced security, and
high-performance data access, all with the goal of giving you everything you need to build
profes-sional web applications
To get the most from this book, you should be familiar with the syntax of the C# languageand with object-oriented concepts You don’t need to have experience with a previous version of
ASP.NET, as all the fundamentals are covered in this book If you’re an experienced Java or C++
developer with no NET experience, you should consider supplementing this book with an
intro-duction to NET, such as A Programmer’s Introintro-duction to C# 2.0, Third Edition (Apress, 2005).
What Do You Need to Use This Book?
The main prerequisite for this book is a computer with Visual Studio 2005 Although you could
theoretically write code by hand, the sheer tedium and the likelihood of error mean this approach
is never used in a professional environment
■ Note You can use the scaled-down Visual Studio Web Developer 2005 Express Edition, but you’ll run into
sig-nificant limitations on some of the examples Most important, you can’t use Visual Studio Web Developer 2005
Express Edition to create class libraries, which are an essential part of modern component-oriented design
Additionally, to run ASP.NET pages, you need Windows 2000 Professional, Windows XPProfessional, Windows 2000 Server, or Windows Server 2003 You also need to install IIS (Internet
Information Services), the web hosting software that’s part of the Windows operating system, if you
want to create web services or test deployment strategies
Finally, this book includes several examples that use sample databases that are included withSQL Server to demonstrate data access code, security techniques, and web services If you use other
relational database engines, the same concepts will apply, but you will need to modify the example
code
This book was created with the latest beta 2 and post–beta 2 builds of ASP.NET BecauseASP.NET is just ending its beta cycle, it’s possible that the final release of the product will have
some changes These changes may include new features or minor syntactic differences (such as a
renamed property or method) To help manage the confusion, refer to the Source Code section of
http://www.apress.com to download the final release–ready code examples
Trang 33Customer Support
We always value hearing from our readers, and we want to know what you think about this book—what you liked, what you didn’t like, and what you think we can do better next time You can sendyour comments by e-mail to feedback@apress.com Please be sure to mention the book title in yourmessage
Sample Code
To download the sample code, visit the Source Code section of the Apress site at http://www.apress.com, and select this book’s title You can then download the sample code, which is com-pressed into a single ZIP file Before you use the code, you’ll need to uncompress it using a utilitysuch as WinZip Code is arranged into separate directories by chapter Before using the code, refer tothe accompanying readme.txt file for information about other prerequisites and considerations
Errata
We’ve made every effort to make sure the text and the code contain no errors However, no one isperfect, and mistakes do occur If you find an error in the book, such as a spelling mistake or a faultypiece of code, we would be grateful to hear about it By sending in errata, you may save anotherreader hours of frustration, and you’ll be helping us to provide higher-quality information Simplye-mail the problem to support@apress.com, where your information will be checked and posted onthe errata page or used in subsequent editions of the book You can view errata from the book’sdetail page
Trang 34Core Concepts
P A R T 1
■ ■ ■
Trang 36Introducing ASP.NET
When Microsoft created NET, it wasn’t just dreaming about the future—it was also worrying
about the headaches and limitations of the current generation of web development technologies
Before you get started with ASP.NET 2.0, it helps to take a step back and consider these problems
You’ll then understand the solution that NET offers
In this chapter you’ll consider the history of web development leading up to ASP.NET, take awhirlwind tour of the most significant features of NET, and preview the core changes in ASP.NET 2.0
If you’re new to ASP.NET, this chapter will quickly get you up to speed On the other hand, if you’re
a seasoned NET developer, you have two choices Your first option is to read this chapter for a brisk
review of where we are today Alternatively, you can skip to the section “ASP.NET 2.0: The Story
Con-tinues” to preview what ASP.NET 2.0 has in store
The Evolution of Web Development
More than ten years ago, Tim Berners-Lee performed the first transmission across HTTP (Hypertext
Transfer Protocol) Since then, HTTP has become exponentially more popular, expanding beyond a
small group of computer-science visionaries to the personal and business sectors Today, it’s almost
a household word
When HTTP was first established, developers faced the challenge of designing applicationsthat could discover and interact with each other To help meet these challenges, standards such as
HTML (Hypertext Markup Language) and XML (Extensible Markup Language) were created HTML
established a simple language that could describe how to display rich documents on virtually any
computer platform XML created a set of rules for building platform-neutral data formats that
dif-ferent applications could use to exchange information These standards guaranteed that the Web
could be used by anyone, located anywhere, using any type of computing system
At the same time, software vendors faced their own challenges They needed to develop notonly language and programming tools that could integrate with the Web but also entire frameworks
that would allow developers to architect, develop, and deploy these applications easily Major
soft-ware vendors including IBM, Sun Microsystems, and Microsoft rushed to meet this need with a host
of products
ASP.NET 1.0 opened a new chapter in this ongoing arms race With NET, Microsoft created anintegrated suite of components that combines the building blocks of the Web—markup languages
and HTTP—with proven object-oriented methodology
The Development World Before ASP.NET
Older technologies for server-based web applications rely on scripting languages or proprietary
tag-ging conventions Most of these web development models just provide clumsy hooks that allow you
to trigger applications or run components on the server They don’t provide a modern, integrated
framework for web programming 3
■ ■ ■
Trang 37Overall, most of the web development frameworks that were created before ASP.NET fall intoone of two categories:
• Scripts that are interpreted by a server-side resource
• Separate, tiny applications that are executed by server-side callsClassic ASP (Active Server Pages, the version of ASP that predates ASP.NET) and ColdFusionfall into the first category You, the developer, are responsible for creating a script file that containsembedded code The script file is examined by another component, which alternates betweenrendering ordinary HTML and executing your embedded code If you’ve created ASP applicationsbefore, you probably know that scripted applications usually execute at a much slower rate thancompiled applications Additionally, scripted platforms introduce other problems, such as the lack
of ability to control security settings and inefficient resource usage
The second approach, used widely by Perl over CGI (Common Gateway Interface), yields anentirely different set of problems In these frameworks, the web server launches a separate applica-tion to handle the client’s request That application executes its code and dynamically creates theHTML that should be sent back to the client Though these applications execute faster than theirscripted counterparts, they tend to require more memory Although it's possible to create a scalableweb application using technologies like CGI, it requires careful design and coding This type ofapplication can also be quite difficult to write, debug, and integrate with other components ASP.NET is far more than a simple evolution of either type of application Instead, it breaks thetrend with a whole new development model The difference is that ASP.NET is deeply integrated
with its underlying framework ASP.NET is not an extension or modification to the NET Framework
with loosely coupled hooks into the functionality it provides Instead, ASP.NET is a portion of the.NET Framework that’s managed by the NET runtime In essence, ASP.NET blurs the line between
application development and web development by extending the tools and technologies previously
monopolized by desktop developers into the web development world
What’s Wrong with Classic ASP?
If you’ve programmed only with classic ASP before, you might wonder why Microsoft changedeverything with ASP.NET Learning a whole new framework isn’t trivial, and NET introduces a slew
of concepts and can pose some serious stumbling blocks
Overall, classic ASP is a solid tool for developing web applications using Microsoft gies However, as with most development models, ASP solves some problems but also raises a few
technolo-of its own The following sections outline these problems
Spaghetti Code
If you’ve created applications with ASP, you’ve probably seen lengthy pages that contain server-sidescript code intermingled with HTML Consider the following example, which fills an HTML drop-down list with the results of a database query:
Trang 38rs.Open "SELECT * FROM Authors", dbConn, 3, 3
Do While Not rs.EOF
%>
</select>
This example needs an unimpressive 16 lines of code to generate one simple HTML control
But what’s worse is the way this style of coding diminishes application performance because it
mingles HTML and script When this page is processed by the ASP ISAPI (Internet Server
Applica-tion Programming Interface) extension that runs on the web server, the scripting engine needs to
switch on and off multiple times just to handle this single request This increases the amount of
time needed to process the whole page and send it to the client
Furthermore, web pages written in this style can easily grow to unmanageable lengths If youadd your own custom COM components to the puzzle (which are needed to supply functionality
ASP can’t provide), the management nightmare grows The bottom line is that no matter what
approach you take, ASP code tends to become beastly, long, and incredibly difficult to debug—if
you can even get ASP debugging working in your environment at all
In ASP.NET, these problems don’t exist Web pages are written with traditional object-orientedconcepts in mind Your web pages contain controls that can be programmed against in a way simi-
lar to desktop applications This means you don’t need to combine a jumble of HTML markup and
inline code If you opt to use the code-behind approach when creating ASP.NET pages, the code
and presentation are actually placed in two different files, which simplifies code maintenance and
allows you to separate the task of web-page design from the heavy-duty work of web coding
Script Languages
At the time of its creation, ASP seemed like a perfect solution for desktop developers who were
mov-ing to the world of the Web Rather than requirmov-ing programmers to learn a completely new language
or methodology, ASP allowed developers to use familiar languages such as VBScript on a
server-based programming platform By leveraging the already-popular COM (Component Object Model)
programming model as a backbone, these scripting languages also acted as a convenient vehicle
for accessing server components and resources But even though ASP was easy to understand for
developers who were already skilled with scripting languages such as VBScript, this familiarity came
with a price Because ASP was based on old technologies that were originally designed for client
use, it couldn’t perform as well in the new environment of web development
Performance wasn’t the only problem Every object or variable used in a classic ASP script is
created as a variant data type As most Visual Basic programmers know, variant data types are
weakly typed They require larger amounts of memory, are late-bound, and result in slower
per-formance Additionally, the compiler and development tools can’t identify them at design time This
made it all but impossible to create a truly integrated IDE (integrated development environment)
that could provide ASP programmers with anything like the powerful debugging, IntelliSense, and
error checking found in Visual Basic and Visual C++ And without debugging tools, ASP
program-mers were hard-pressed to troubleshoot the problems in their scripts
ASP.NET circumvents all these problems For starters, ASP.NET pages and web services are cuted within the CLR (common language runtime), so they can be authored in any language that
exe-has a CLR-compliant compiler No longer are you limited to using VBScript or JavaScript—instead,
you can use modern object-oriented languages such as Visual Basic and C#
Trang 39It’s also important to note that ASP.NET pages are not interpreted but are instead compiled
into assemblies (the NET term for any unit of compiled code) This is one of the most significant
enhancements to Microsoft’s web development model What actually happens behind the scenes isrevolutionary Even if you create your code in Notepad and copy it directly to a virtual directory on aweb server, the application is dynamically compiled as soon as a client accesses it, and it is cachedfor future requests If any of the files are modified after this compilation process, the application isrecompiled automatically the next time a client requests it
The Death of COM
Though Microsoft claims undying support for COM, the technology that underlies the Windowsoperating system, and almost every application that runs on it, it’s obvious that NET is the start of
a new path for modern development Future versions of the Windows operating system (includingthe elusive Longhorn) will integrate the NET Framework more deeply into the operating systemkernel, making it the first-class language of all application development And as COM applicationswane in popularity and applications are converted to NET, classic ASP will become a thing of thepast Even though NET includes robust support for COM interoperability, the fact remains thatclassic ASP applications have no real place in a NET world
ASP.NET 1.0
Microsoft developers have described ASP.NET as their chance to “hit the reset button” and startfrom scratch with an entirely new, more modern development model The traditional conceptsinvolved in creating web applications still hold true in the NET world Each web application con-sists of web pages You can render rich HTML and even use JavaScript, create components thatencapsulate programming logic, and tweak and tune your applications using configuration settings.However, behind the scenes ASP.NET works quite differently than traditional scripting technologiessuch as classic ASP or PHP (PHP: Hypertext Preprocessor) It’s also much more ambitious than JSP(JavaServer Pages)
Some of the differences between ASP.NET and earlier web development platforms include thefollowing:
• ASP.NET features a completely object-oriented programming model, which includes anevent-driven, control-based architecture that encourages code encapsulation and codereuse
• ASP.NET gives you the ability to code in any supported NET language (including VisualBasic, C#, J#, and many other languages that have third-party compilers)
• ASP.NET is also a platform for building web services, which are reusable units of code that
other applications can call across platform and computer boundaries You can use a webservice to do everything from web-enabling a desktop application to sharing data with aJava client running on Unix
• ASP.NET is dedicated to high performance ASP.NET pages and components are compiled ondemand instead of being interpreted every time they’re used ASP.NET also includes a fine-tuned data access model and flexible data caching to further boost performance
These are only a few of the features, which include enhanced state management, practical databinding, dynamic graphics, and a robust security model You’ll look at these improvements in detail
in this book and see what ASP.NET 2.0 adds to the picture
Trang 40Seven Important Facts About ASP.NET
If you’re new to ASP.NET (or you just want to review a few fundamentals), you’ll be interested in the
following sections They introduce seven touchstones of NET development
Fact 1: ASP.NET Is Integrated with the NET Framework
The NET Framework is divided into an almost painstaking collection of functional parts, with a
staggering total of more than 7,000 types (the NET term for classes, structures, interfaces, and other
core programming ingredients) Before you can program any type of NET application, you need a
basic understanding of those parts—and an understanding of why things are organized the way
they are
The massive collection of functionality that the NET Framework provides is organized in a waythat traditional Windows programmers will see as a happy improvement Each one of the thousands
of classes in the NET Framework is grouped into a logical, hierarchical container called a
name-space Different namespaces provide different features Taken together, the NET namespaces offer
functionality for nearly every aspect of distributed development from message queuing to security
This massive toolkit is called the class library.
Interestingly, the way you use the NET Framework classes in ASP.NET is the same as the wayyou use them in any other type of NET application (including a stand-alone Windows application,
a Windows service, a command-line utility, and so on) In other words, NET gives the same tools to
web developers that it gives to rich client developers
If you’ve programmed extensively with ASP.NET 1.x, you’ll find that the same set of classes
is available in ASP.NET 2.0 The difference is that ASP.NET 2.0 adds even more classes to the mix,
many in entirely new namespaces for features such as configuration, health monitoring, and
personalization
■ Tip One of the best resources for learning about new corners of the NET Framework is the NET Framework
class library reference, which is part of the MSDN Help library reference If you have Visual Studio 2005 installed,
you can view the MSDN Help library by selecting Start ➤Programs ➤Microsoft Visual Studio 2005 ➤Microsoft
Visual Studio 2005 Documentation (the exact shortcut depends on your version of Visual Studio) Once you’ve
loaded the help, you can find class reference information grouped by namespace under the NET Development ➤
.NET Framework SDK ➤Class Library Reference node
Fact 2: ASP.NET Is Compiled, Not Interpreted
One of the major reasons for performance degradation in ASP scripts is that all ASP web-page code
uses interpreted scripting languages This means that when your application is executed, a scripting
host on the server machine needs to interpret your code and translate it to lower-level machine
code, line by line This process is notoriously slow
■ Note In fact, in this case the reputation is a little worse than the reality Interpreted code is certainly slower
than compiled code, but the performance hit isn’t so significant that you can’t build a professional website using
ASP