Chris Payne
Teach Yourself
ASP.NET in
21 Days SECOND EDITION
800 East 96th St., Indianapolis, Indiana, 46240 USA
Sams Teach Yourself ASP.NET in 21 Days, Second Edition Copyright © 2003 by Sams Publishing All rights reserved. No part of this book shall be reproduced, stored in a retrieval system, or transmitted by any means, electronic, mechanical, photocopying, recording, or otherwise, without written permission from the publisher. No patent liability is assumed with respect to the use of the information contained herein. Although every precaution has been taken in the preparation of this book, the publisher and author assume no responsibility for errors or omissions. Nor is any liability assumed for damages resulting from the use of the information contained herein. International Standard Book Number: 0-672-32445-8 Library of Congress Catalog Card Number: 2002105533 Printed in the United States of America First Printing: August 2002 05
04
03
ACQUISITIONS EDITOR Neil Rowe
DEVELOPMENT EDITOR Kevin Howard
MANAGING EDITOR Charlotte Clapp
INDEXER Erika Millen
PROOFREADER Michael Henry
TECHNICAL EDITORS Mike Diehl Mike Nishazaki
TEAM COORDINATOR Lynne Williams
MULTIMEDIA DEVELOPER 6
5
4
Trademarks All terms mentioned in this book that are known to be trademarks or service marks have been appropriately capitalized. Sams Publishing cannot attest to the accuracy of this information. Use of a term in this book should not be regarded as affecting the validity of any trademark or service mark.
Warning and Disclaimer Every effort has been made to make this book as complete and as accurate as possible, but no warranty or fitness is implied. The information provided is on an “as is” basis. The author and the publisher shall have neither liability nor responsibility to any person or entity with respect to any loss or damages arising from the information contained in this book.
Bulk Sales Sams Publishing offers excellent discounts on this book when ordered in quantity for bulk purchases or special sales. For more information, please contact U.S. Corporate and Government Sales 1-800-382-3419
[email protected] For sales outside of the U.S., please contact International Sales 1-317-428-3341
[email protected]
Dan Scherf
INTERIOR DESIGNER Gary Adair
COVER DESIGNER Aren Howell
PAGE LAYOUT D&G Limited, LLC
Contents at a Glance Foreword Introduction WEEK 1 At a Glance Day 1
Getting Started with ASP.NET
xx 1 5 7
2
Building ASP.NET Pages
31
3
Using Visual Basic.NET
59
4
Using ASP.NET Objects with C# and VB.NET
105
5
Beginning Web Forms
139
6
Learning More About Web Forms
171
7
Validating ASP.NET Pages
209
WEEK 1 In Review
245
WEEK 2 At a Glance
257
Day 8
Beginning to Build Databases
259
9
Using Databases with ASP.NET
285
10
Communicating with ADO.NET
335
11
Using XML in ASP.NET
381
12
Employing Advanced Data Techniques
417
13
Reading and Writing Files on the Web Server
453
14
Using ASP.NET's Improved Caching Capabilities
489
WEEK 2 In Review
519
WEEK 3 At a Glance
535
Day 15
Using Business Objects
537
16
Creating Web Services
569
17
Consuming and Securing XML Web Services
595
18
Configuring and Deploying ASP.NET Applications
625
19
Separating Code from Content
659
20
Debugging ASP.NET Pages
697
21
Securing Your ASP.NET Applications
731
WEEK 3 In Review
761
Bonus Days 22
Building a Complete Application
777
23
Creating Mobile Web Pages
835
Appendices Appendix A
Answers to Quiz Questions
867
B
Common ASP.NET Mistakes
929
C
ASP.NET Controls: Properties and Methods
937
D
ADO.NET Controls: Properties and Methods
971
Index
993
Table of Contents Introduction
1
Who Is This Book’s Intended Audience? ..............................................................1 What Do You Need to Know Prior to Reading This Book? ..................................2 What Software Do You Need to Complete the Examples Provided with This Book? ..........................................................................................................2 How This Book Is Organized ................................................................................3 Conventions Used in This Book ............................................................................4 Finally… ................................................................................................................4
WEEK 1 At a Glance DAY 1 Getting Started with ASP.NET
5 7
The Way the Web Works ........................................................................................8 Dynamic Processing ..........................................................................................8 The ASP.NET Difference ................................................................................10 Client-Side Processing ....................................................................................10 How ASP.NET Ties It Together ......................................................................11 The .NET Framework ..........................................................................................12 Common Language Runtime ..........................................................................12 .NET Framework Classes ................................................................................14 Setting Up and Installing ASP.NET ....................................................................15 Installing Internet Information Server ............................................................15 Installing the .NET Framework SDK ..............................................................19 Creating ASP.NET Pages ......................................................................................20 Development Environments ............................................................................22 Elements of an ASP.NET Page ............................................................................23 Comparison of ASP and ASP.NET ......................................................................26 Fundamental Changes from ASP ....................................................................26 Programmatic Enhancements Over ASP ........................................................27 Differences in Programming Methodologies ..................................................28 Summary ..............................................................................................................28 Q&A ......................................................................................................................29 Workshop ..............................................................................................................29 Quiz ................................................................................................................29 Exercises ..........................................................................................................30
vi
Sams Teach Yourself ASP.NET in 21 Days
DAY 2 Building ASP.NET Pages
31
A Simple ASP.NET Application ..........................................................................32 Web Forms ......................................................................................................33 Code Declaration Blocks ................................................................................36 Code Render Blocks ........................................................................................37 Page Directives ................................................................................................39 The Flow ..........................................................................................................40 Viewstate ........................................................................................................42 Writing ASP.NET and HTML Code ....................................................................42 Commenting Your Code ..................................................................................44 Code That Spans Multiple Lines ....................................................................45 The Impact of the Application ..............................................................................47 More on ASP.NET Compilation ......................................................................47 Importing Namespaces ....................................................................................48 Common Language Runtime and ASP.NET ........................................................49 Intermediate Language ....................................................................................50 Execution ........................................................................................................50 Processing ........................................................................................................50 Assemblies ......................................................................................................51 Side-by-Side Execution ..................................................................................51 What Does the CLR Mean for ASP.NET? ......................................................52 ASP.NET Programming Languages ....................................................................52 Another Look at the Code ....................................................................................52 That’s Not ASP! ....................................................................................................54 Summary ..............................................................................................................55 Q&A ......................................................................................................................56 Workshop ..............................................................................................................56 Quiz ................................................................................................................56 Exercises ..........................................................................................................57 DAY 3 Using Visual Basic.NET and C#
59
Introduction to Visual Basic.NET and C# ............................................................60 Variables ................................................................................................................60 Data Types ......................................................................................................61 Declaring Variables ..........................................................................................63 Naming Variables ............................................................................................65 Data Type Conversions ....................................................................................66 Arrays ....................................................................................................................69 Operators ..............................................................................................................73 Conditional Logic ................................................................................................74 If Statements ..................................................................................................74 Case and Switch Statements ............................................................................77
Contents
vii
Looping Logic ......................................................................................................79 While Loops ....................................................................................................79 For Loops ........................................................................................................82 Infinite Loops ..................................................................................................83 Branching Logic ..................................................................................................84 Subroutines ......................................................................................................85 Functions ........................................................................................................87 Optional Parameters ........................................................................................89 Event Handlers ................................................................................................90 Classes ..................................................................................................................93 Inheritance ......................................................................................................97 Useful VB.NET Functions ....................................................................................98 For Future VB.NET and C# Gurus: Where to Go ..............................................101 That’s Not ASP! ..................................................................................................101 Summary ............................................................................................................102 Q&A ....................................................................................................................103 Workshop ............................................................................................................103 Quiz ..............................................................................................................103 Exercises ........................................................................................................103 DAY 4 Using ASP.NET Objects with C# and VB.NET
105
A Recap of Objects ............................................................................................106 Properties ......................................................................................................106 Methods ........................................................................................................106 Object Instances ............................................................................................107 Static Members ..............................................................................................108 ASP.NET Objects ..............................................................................................109 The Response Object ....................................................................................109 The Request Object ......................................................................................114 The HttpCookie Object ................................................................................116 The Page Object ............................................................................................120 The Session Object ......................................................................................124 The HttpApplication Object ........................................................................132 The HttpServerUtility Object ....................................................................133 That’s Not ASP! ..................................................................................................135 Summary ............................................................................................................135 Q&A ....................................................................................................................136 Workshop ............................................................................................................136 Quiz ..............................................................................................................137 Exercises ........................................................................................................137
viii
Sams Teach Yourself ASP.NET in 21 Days
DAY 5 Beginning Web Forms
139
Introduction to Forms ........................................................................................140 Introduction to Web Forms ................................................................................141 Web Forms Programming Model ......................................................................142 Server Controls ..............................................................................................143 Server Control Events ..................................................................................144 Posting Web Forms ........................................................................................149 Saving State ..................................................................................................151 Web Forms Processing Order ........................................................................153 HTML Server Controls ......................................................................................154 Web Server Controls ..........................................................................................159 Using Web Controls ......................................................................................160 Posting Data Immediately ............................................................................164 Web Server Controls Versus HTML Server Controls ..................................167 That’s Not ASP! ..................................................................................................168 Summary ............................................................................................................168 Q&A ....................................................................................................................169 Workshop ............................................................................................................170 Quiz ..............................................................................................................170 Exercises ........................................................................................................170 DAY 6 Learning More About Web Forms
171
The Extensibility of Web Forms ........................................................................172 User Controls ......................................................................................................172 Creating User Controls ..................................................................................173 Using User Controls ......................................................................................178 Enhancing the User Control ..........................................................................180 Custom Controls ................................................................................................184 Creating Custom Controls ............................................................................185 Using Custom Controls ................................................................................187 Using Properties and State ............................................................................188 Wiring Up Events ..........................................................................................193 Creating Controls at Runtime ............................................................................200 That’s Not ASP! ..................................................................................................204 Summary ............................................................................................................205 Q&A ....................................................................................................................206 Workshop ............................................................................................................206 Quiz ..............................................................................................................206 Exercises ........................................................................................................207
Contents
DAY 7 Validating ASP.NET Pages
ix
209
Validation Scenarios ..........................................................................................210 ASP.NET Validation ..........................................................................................215 How Validation Controls Work ....................................................................216 Using Validation Controls ..................................................................................221 Validating on the Server ................................................................................229 Disabling Validation ......................................................................................230 Regular Expressions ......................................................................................231 Customizing Validation ......................................................................................233 Error Messages ..............................................................................................233 Displaying Validation Summaries ................................................................235 Custom Validation Controls ..........................................................................238 That’s Not ASP! ..................................................................................................241 Summary ............................................................................................................242 Q&A ....................................................................................................................243 Workshop ............................................................................................................243 Quiz ..............................................................................................................244 Exercises ........................................................................................................244
WEEK 1 In Review
245
Bonus Project 1 ..................................................................................................245 A Banking Application ......................................................................................245 User Controls ................................................................................................246 The Login Page ............................................................................................247 The Account Page ..........................................................................................250 Paying Bills ..................................................................................................253 Summary ............................................................................................................255
WEEK 2 At a Glance DAY 8 Beginning to Build Databases
257 259
What Are Databases? ..........................................................................................260 Keys and Constraints ....................................................................................262 Database Communication Standards ............................................................263 When Should I Use a Database? ..................................................................264 Creating Databases ............................................................................................264 The Structured Query Language ........................................................................270 The SELECT Statement ..................................................................................270 The INSERT Statement ..................................................................................275 The UPDATE Statement ..................................................................................275 The DELETE Statement ..................................................................................276
x
Sams Teach Yourself ASP.NET in 21 Days
Accessing Data with ASP.NET ..........................................................................276 Let’s Access Data! ........................................................................................277 That’s Not ASP! ............................................................................................279 Summary ............................................................................................................281 Q&A ....................................................................................................................282 Workshop ............................................................................................................282 Quiz ..............................................................................................................283 Exercises ........................................................................................................283 DAY 9 Using Databases with ASP.NET
285
Introduction to Accessing Data from ASP.NET ................................................286 The DataSet ........................................................................................................287 Using the DataSet ........................................................................................289 Relationships ................................................................................................291 Filling DataSets ............................................................................................292 Data Binding ......................................................................................................294 Using Data Binding ......................................................................................296 Data Binding Controls ........................................................................................301 Repeater Server Control ..............................................................................301 DataList Server Control ..............................................................................306 DataGrid Server Control ..............................................................................311 Summary of Data Binding Controls ..............................................................320 That’s Not ASP! ..................................................................................................331 Summary ............................................................................................................332 Q&A ....................................................................................................................332 Workshop ............................................................................................................333 Quiz ..............................................................................................................333 Exercises ........................................................................................................333 DAY 10 Communicating with ADO.NET
335
An Introduction to ADO.NET ............................................................................336 ADO.NET Versus ADO ................................................................................336 ADO.NET and XML ....................................................................................338 The ADO.NET Object Model ......................................................................339 The DataSet Revisited ........................................................................................340 Modifying Data in a DataRow ........................................................................342 Viewing Data in a DataTable ........................................................................344 Concurrency ..................................................................................................347 Database Interaction with ADO.NET ................................................................348 Connection Information ................................................................................348 The OleDbConnection Object ........................................................................349 The OleDbCommand Object ..............................................................................350 The OleDbDataReader Object ........................................................................351
Contents
xi
Update, Insert, and Delete ..........................................................................354 The OleDbDataAdapter Object ......................................................................354 Using ADO.NET with ASP.NET ........................................................................362 That’s Not ASP! ..................................................................................................377 Summary ............................................................................................................378 Q&A ....................................................................................................................378 Workshop ............................................................................................................379 Quiz ..............................................................................................................379 Exercises ........................................................................................................380
DAY 11 Using XML in ASP.NET
381
An Introduction to XML ....................................................................................382 The XML Data Model ..................................................................................383 XML Schemas ..............................................................................................385 Accessing XML with ASP.NET ........................................................................388 Reading XML ................................................................................................388 Writing XML ................................................................................................393 Validating XML ............................................................................................395 The XML Document Object Model ..................................................................399 Loading XML Data ......................................................................................401 Modifying XML Data ..................................................................................405 XML and the DataSet ........................................................................................408 That’s Not ASP! ..................................................................................................414 Summary ............................................................................................................415 Q&A ....................................................................................................................415 Workshop ............................................................................................................416 Quiz ..............................................................................................................416 Exercises ........................................................................................................416 DAY 12 Employing Advanced Data Techniques
417
Advanced Database Techniques ........................................................................418 Parameterized Queries ..................................................................................418 Stored Procedures ..........................................................................................423 Transactions ..................................................................................................433 Advanced XML Techniques ..............................................................................435 XPathNavigator ............................................................................................436 XPath ..............................................................................................................439 XslTransforms ..............................................................................................443 That’s Not ASP! ..................................................................................................449 Summary ............................................................................................................449 Q&A ....................................................................................................................451 Workshop ............................................................................................................451
xii
Sams Teach Yourself ASP.NET in 21 Days
Quiz ..............................................................................................................451 Exercises ........................................................................................................452 DAY 13 Reading and Writing Files on the Web Server
453
Using Files with ASP.NET ................................................................................454 Including External Files ......................................................................................454 Server-Side Includes ......................................................................................454 Other Includes ..............................................................................................457 Accessing Files ..................................................................................................457 Files, Streams, Readers, and Writers ............................................................457 Examining Files and Directories ..................................................................460 Opening Files ................................................................................................468 Reading Files ................................................................................................471 Writing Files ..................................................................................................475 Other File and Directory Operations ............................................................476 Summary of File Objects ..............................................................................477 Isolated Storage ..................................................................................................478 Creating Isolated Storage Locations ............................................................479 Accessing Isolated Storage ............................................................................480 That’s Not ASP! ..................................................................................................484 Summary ............................................................................................................485 Q&A ....................................................................................................................486 Workshop ............................................................................................................487 Quiz ..............................................................................................................487 Exercises ........................................................................................................487 DAY 14 Using ASP.NET’s Improved Caching Capabilities
489
What Is Caching? ................................................................................................490 How ASP.NET Uses Caching ............................................................................491 Page Caching ................................................................................................492 Configuration Caching ..................................................................................492 Output and Data Caching ..............................................................................492 How to Use Caching ..........................................................................................493 Caching Page Output ....................................................................................493 Caching Objects ............................................................................................500 Cache Dependencies ......................................................................................508 Using the HttpCachePolicy Class ................................................................511 Using Caching Effectively ..................................................................................516 That’s Not ASP! ..................................................................................................517 Summary ............................................................................................................517 Q&A ....................................................................................................................518 Workshop ............................................................................................................518
Contents
xiii
Quiz ..............................................................................................................518 Exercises ........................................................................................................518
WEEK 2 In Review
519
Bonus Project 2 ..................................................................................................519 Hold Banking Application ..................................................................................519 Adding Data Capability ......................................................................................520 The Database ................................................................................................520 The ASP.NET Pages ......................................................................................523 Summary ............................................................................................................533
WEEK 3 At a Glance DAY 15 Using Business Objects
535 537
Introduction to Components ..............................................................................538 What Are Business Objects? ........................................................................538 Why Use Components? ................................................................................539 How ASP.NET Uses Components ................................................................541 Creating Business Objects ..................................................................................541 Developing Business Objects ............................................................................545 A Working Example ..........................................................................................550 A Few Considerations ..................................................................................558 Working with Non-.NET Components ..............................................................559 That’s Not ASP! ..................................................................................................563 Summary ............................................................................................................564 Q&A ....................................................................................................................564 Workshop ............................................................................................................566 Quiz ..............................................................................................................566 Exercises ........................................................................................................567 DAY 16 Creating XML Web Services
569
The Way the Web Works—Revisited ................................................................570 Introduction to XML Web Services ....................................................................571 Web Service Scenarios ..................................................................................573 The Web Service Programming Model ........................................................573 Protocols for Accessing Web Services ..........................................................575 Why Web Services? ......................................................................................577 Building a Web Service ......................................................................................578 Building the Functionality ............................................................................578 Enabling Discovery ......................................................................................582 The WebMethod Attribute ................................................................................583 Deploying Web Services ..............................................................................586
xiv
Sams Teach Yourself ASP.NET in 21 Days
Creating a Web Service from an Existing Business Object ..............................586 Returning Data from Services ............................................................................590 That’s Not ASP! ..................................................................................................591 Summary ............................................................................................................591 Q&A ....................................................................................................................592 Workshop ............................................................................................................593 Quiz ..............................................................................................................593 Exercises ........................................................................................................593 DAY 17 Consuming and Securing XML Web Services
595
Consuming XML Web Services ........................................................................595 Consuming a Web Service Through an ASP.NET Page ....................................599 Discovery ......................................................................................................599 Building the Proxy Class ..............................................................................601 Implementing the Proxy Class ......................................................................605 Another Web Service Consumption Example ..............................................608 Web Service Consumption Recommendations ..................................................611 Securing Web Services ......................................................................................613 That’s Not ASP! ..................................................................................................621 Summary ............................................................................................................621 Q&A ....................................................................................................................622 Workshop ............................................................................................................622 Quiz ..............................................................................................................622 Exercises ........................................................................................................623 DAY 18 Configuring and Deploying ASP.NET Applications
625
Introduction to ASP.NET Applications ..............................................................626 The /bin Directory ........................................................................................627 global.asax ........................................................................................................628 The HttpApplication Class ..........................................................................629 Programming global.asax ..........................................................................631 Configuring ASP.NET ........................................................................................636 web.config ....................................................................................................637 Configuration Sections ..................................................................................641 Custom Configuration ..................................................................................647 Deploying Your Application ..............................................................................653 Assembly Caches ..........................................................................................653 Shadowed Assemblies ..................................................................................655 That’s Not ASP! ..................................................................................................655 Summary ............................................................................................................656 Q&A ....................................................................................................................657 Workshop ............................................................................................................657
Contents
xv
Quiz ..............................................................................................................657 Exercises ........................................................................................................658 DAY 19 Separating Code from Content
659
The Drive for Separation ....................................................................................660 Code-Behind Forms ............................................................................................661 Using Code-Behind in ASP.NET Pages ........................................................663 Using Code-Behind in User Controls ..........................................................673 Code-Behind Recommendations ..................................................................676 Resource Files and Localization ........................................................................677 Localizing Your Application ..........................................................................678 Packing Resources into Files ........................................................................686 That’s Not ASP! ..................................................................................................692 Summary ............................................................................................................693 Q&A ....................................................................................................................694 Workshop ............................................................................................................695 Quiz ..............................................................................................................695 Exercises ........................................................................................................695 DAY 20 Debugging ASP.NET Pages
697
Introduction to Debugging ..................................................................................698 and catch ....................................................................................................701 Throwing Exceptions ....................................................................................709 When to Use a try Statement ......................................................................710 Tracing ................................................................................................................711 Page-Level Tracing ........................................................................................713 Application-Level Tracing ............................................................................719 The CLR Debugger ............................................................................................721 Using the CLR Debugger ..............................................................................723 Debugging Recommendations ............................................................................726 That’s Not ASP! ..................................................................................................727 Summary ............................................................................................................727 Q&A ....................................................................................................................728 Workshop ............................................................................................................728 Quiz ..............................................................................................................729 Exercises ........................................................................................................729
try
DAY 21 Securing Your ASP.NET Applications
731
Security Basics ....................................................................................................732 Security in Windows ....................................................................................734 Authentication ....................................................................................................735
xvi
Sams Teach Yourself ASP.NET in 21 Days
Windows Authentication ..............................................................................736 Forms Authentication ....................................................................................740 Passport Authentication ................................................................................748 Authorization ......................................................................................................749 Impersonation ....................................................................................................753 Dealing with Secured Users ..............................................................................756 That’s Not ASP! ..................................................................................................757 Summary ............................................................................................................758 Q&A ....................................................................................................................759 Workshop ............................................................................................................759 Quiz ..............................................................................................................759 Exercise ........................................................................................................760
WEEK 3 In Review
761
Bonus Project 3 ..................................................................................................762 Adding the Business Objects ..............................................................................762 The Web Service ................................................................................................772 Summary ............................................................................................................775 Bonus DAY 22 Building a Complete Application
777
The Scenario: BananaMobiles ............................................................................778 Designing the Application ..................................................................................779 Banana Data ..................................................................................................779 The Banana Front End ..................................................................................781 Banana Business Objects ..............................................................................782 Building the BananaMobile Site ........................................................................782 Creating the Database ....................................................................................783 The Business Objects ....................................................................................793 The ASP.NET Pages ......................................................................................804 The Web Service ............................................................................................825 Where to Go from Here ......................................................................................829 That’s Not ASP! ..................................................................................................830 Summary ............................................................................................................831 Q&A ....................................................................................................................832 Workshop ............................................................................................................833 Quiz ..............................................................................................................833 Bonus DAY 23 Creating Mobile Web Forms
835
What Are Mobile Web Forms? ..........................................................................836 How Are Mobile Web Forms Different from ASP.NET Web Forms? ..........837 What Do I Need to Use Mobile Web Forms? ..............................................837 Installing the Mobile Internet Toolkit ................................................................838 Getting Started with Mobile Web Forms ............................................................839
Contents
xvii
The Way Mobile Forms Work ......................................................................843 Building a More Apropos Interface ..............................................................844 Developing Mobile Pages ..................................................................................846 Adding Paging Capabilities ..........................................................................850 Device-Specific Output and Template Sets ..................................................853 Using Mobile Device Capabilities ................................................................855 That’s Not ASP! ..................................................................................................863 Summary ............................................................................................................864 Q&A ....................................................................................................................864 Workshop ............................................................................................................865 Quiz ..............................................................................................................865 Exercises ........................................................................................................866 APPENDIX A Answers to Quiz Questions
867
Answers for Day 1 ..............................................................................................867 Quiz ..............................................................................................................867 Exercises ........................................................................................................868 Answers for Day 2 ..............................................................................................869 Quiz ..............................................................................................................869 Exercises ........................................................................................................869 Answers for Day 3 ..............................................................................................871 Quiz ..............................................................................................................871 Exercise ........................................................................................................872 Answers for Day 4 ..............................................................................................873 Quiz ..............................................................................................................873 Exercises ........................................................................................................873 Answers for Day 5 ..............................................................................................875 Quiz ..............................................................................................................875 Exercises ........................................................................................................876 Answers for Day 6 ..............................................................................................879 Quiz ..............................................................................................................879 Exercises ........................................................................................................879 Answers for Day 7 ..............................................................................................887 Quiz ..............................................................................................................887 Exercise ........................................................................................................888 Answers for Day 8 ..............................................................................................889 Quiz ..............................................................................................................889 Exercise ........................................................................................................889 Answers for Day 9 ..............................................................................................890 Quiz ..............................................................................................................890 Exercise ........................................................................................................890
xviii
Sams Teach Yourself ASP.NET in 21 Days
Answers for Day 10 ............................................................................................891 Quiz ..............................................................................................................891 Exercise ........................................................................................................892 Answers for Day 11 ............................................................................................895 Quiz ..............................................................................................................895 Exercises ........................................................................................................896 Answers for Day 12 ............................................................................................899 Quiz ..............................................................................................................899 Exercise ........................................................................................................900 Answers for Day 13 ............................................................................................903 Quiz ..............................................................................................................903 Exercises ........................................................................................................903 Answers for Day 14 ............................................................................................906 Quiz ..............................................................................................................906 Exercise ........................................................................................................906 Answers for Day 15 ............................................................................................908 Quiz ..............................................................................................................908 Exercise ........................................................................................................909 Answers for Day 16 ............................................................................................911 Quiz ..............................................................................................................911 Exercises ........................................................................................................912 Answers for Day 17 ............................................................................................914 Quiz ..............................................................................................................914 Exercise ........................................................................................................915 Answers for Day 18 ............................................................................................916 Quiz ..............................................................................................................916 Exercise ........................................................................................................918 Answers for Day 19 ............................................................................................918 Quiz ..............................................................................................................918 Exercise ........................................................................................................919 Answers for Day 20 ............................................................................................922 Quiz ..............................................................................................................922 Exercises ........................................................................................................923 Answers for Day 21 ............................................................................................924 Quiz ..............................................................................................................924 Exercise ........................................................................................................925 Answers for Day 22 ............................................................................................926 Quiz ..............................................................................................................926 Answers for Day 23 ............................................................................................927 Quiz ..............................................................................................................927 Exercise ........................................................................................................928
Contents
APPENDIX B Common ASP.NET Mistakes
xix
929
ASP.NET Conundrums ......................................................................................930 Problems with Web Forms ............................................................................930 Other Problems ..............................................................................................932 Changes from Classic ASP ................................................................................933 Problems with VBScript ................................................................................933 Problems with Classic ASP ..........................................................................935 APPENDIX C ASP.NET Controls: Properties and Methods
937
HTML Server Controls ......................................................................................939 Common HTML Server Control Properties ..................................................939 The HTML Server Controls ..........................................................................940 Web Server Controls ..........................................................................................947 Common Web Server Control Properties ......................................................948 The ASP.NET Web Server Controls ..............................................................950 Validation Server Controls ..................................................................................966 Common Validation Server Control Properties ............................................967 The Validation Server Controls ....................................................................967 APPENDIX D ADO.NET Controls: Properties and Methods
971
The DataSet and Related Classes ......................................................................971 Constraint and ConstraintCollection ......................................................971 DataColumn and DataColumnCollection ......................................................973 DataRelation and DataRelationCollection ..............................................974 DataRow and DataRowCollection ..................................................................976 DataSet ..........................................................................................................978 DataTable and DataTableCollection ..........................................................979 DataView ........................................................................................................982 The Managed Providers ......................................................................................984 OleDbCommand ................................................................................................984 OleDbCommandBuilder ..................................................................................985 OleDbConnection ..........................................................................................986 OleDbDataAdapter ........................................................................................987 OleDbDataReader ..........................................................................................989 OleDbError and OleDbErrorCollection ......................................................990 OleDbParameter and OleDbParameterCollection ........................................991 OleDbTransaction ........................................................................................992 Index
993
Foreword Active Server Pages.NET, or ASP.NET, is Microsoft’s latest version of its popular dynamic Web programming technology, Active Server Pages (ASP). ASP.NET, however, is much more than a simple upgrade from classic ASP: A new programming model and a plethora of brand-new tools are just two of the many new features of ASP.NET. The numerous differences between classic ASP and ASP.NET create a bit of a steep learning curve for developers moving from classic ASP to ASP.NET—a learning curve that this book will surely help to flatten. Although having experience with classic ASP or another dynamic Web programming technology will aid in learning ASP.NET, such prior experience is not required. Each lesson’s concepts are explained assuming that the reader has no prior ASP experience. However, if you have created Web pages using classic ASP, you’ll appreciate the “That’s Not ASP!” section at the end of each chapter. These sections highlight the differences between classic ASP and ASP.NET and are ideal for developers coming from a classic ASP background. The new features in ASP.NET make designing dynamic Web pages quicker and easier than ever before. For example, ASP.NET offers developers a number of powerful Web controls, which are HTML-like tags that provide useful functionality, such as displaying a calendar, showing a random banner advertisement, and displaying an HTML table whose rows and columns contain data from a database. These Web controls allow developers to provide rich, W3C-compliant HTML with a minimal amount of coding. To get started with Web controls, refer to Day 5, “Beginning Web Forms.” Sams Teach Yourself ASP.NET in 21 Days breaks down the many complexities of ASP.NET into 21 essential lessons (with a couple bonus lessons thrown in for good measure). Each lesson contains useful information that you will be able to start applying to your Web applications immediately. With the abundance of new features in ASP.NET, this incremental teaching style is beneficial for those new to ASP.NET to get a quick jump start on this exciting new technology. ASP.NET is an exciting new Web development technology that is going to take the world by storm. This next generation of Web development technology makes designing impressive Web sites an easy and fun process. If you’re ready to get started with ASP.NET, you’ll find Sams Teach Yourself ASP.NET in 21 Days an invaluable resource. Happy Programming! Scott Mitchell
[email protected] http://www.4GuysFromRolla.com
About the Author Chris Payne has had a passion for computers and writing since a young age. He holds a bachelor of science degree in biomedical engineering from Boston University. Chris supported himself through college by working as an independent consultant and by writing technical articles focused on Web development. Currently making his home in Orlando, Florida with his wife, Chris is working as a Web developer and continuing his career as an author of both technical and fictional material.
Dedication To Eva Saravia, my wife, for her beauty, love, and support, and my brother, Daniel, for being excited about this book. —Chris Payne
Acknowledgments First, I would like to thank Shelley Kronzek for her faith in me. Without her support, this book would never have been started with me at the helm, and certainly would never have been completed properly. Her motivational skills are unsurpassed, and she truly is a great person. I’d also like to thank Scott Mitchell, for his help in getting this thing together, and for providing me with no-holds-barred criticism. This book was made immensely stronger by his help. I couldn’t forget to thank my other friends at Sams: Jim Terral, Elizabeth Finney, and all my other editors. You all were unbelievably patient with me, and the experience of working with you has enriched me. A big thanks goes to my friends and family, for being patient while I was holed up trying to hit deadlines. Chris Assenza, without whom my writing career wouldn’t be existent; the Saravia family (Carlos, Anita, Carlos Jr., and even Walter!) for putting me up (and eating my leftovers); Angie, Daniel, Austin, and Kaylee Canary for being the best of friends; Liz and Doug Miller just because; and many, many others.
We Want to Hear from You! As the reader of this book, you are our most important critic and commentator. We value your opinion and want to know what we’re doing right, what we could do better, what areas you’d like to see us publish in, and any other words of wisdom you’re willing to pass our way. As an executive editor for Sams Publishing, I welcome your comments. You can e-mail or write me directly to let me know what you did or didn’t like about this book—as well as what we can do to make our books better. Please note that I cannot help you with technical problems related to the topic of this book. We do have a User Services group, however, where I will forward specific technical questions related to the book. When you write, please be sure to include this book’s title and author as well as your name, e-mail address, and phone number. I will carefully review your comments and share them with the author and editors who worked on the book. Email:
[email protected]
Mail:
Michael Stephens Executive Editor Sams Publishing 800 East 96th Street Indianapolis, IN 46240 USA
For more information about this book or another Sams Publishing title, visit our Web site at www.samspublishing.com. Type the ISBN (0672324458) or the title of a book in the Search field to find the page you’re looking for.
Introduction Welcome to Sams Teach Yourself ASP.NET in 21 Days, Second Edition! You most likely picked up this book because you’re curious about building robust Internet applications. You’ve come to the right place! Throughout the next 21 days (and two bonus days), you’ll examine every major aspect of Active Server Pages.NET, the Web-based programming framework from Microsoft: from how these pages look to how they are tied into the operating system. ASP.NET is a technology that allows you to build and control dynamic Web pages easily. It is the next generation of Microsoft’s Active Server Pages (which I’ll refer to as classic ASP), and provides many enhancements to take advantage of new technology. With it, you can interact with databases, personalize Web pages for visitors, display pages on mobile devices (such as cell phones), and even build an entire e-commerce shopping site from scratch. As you move through the tutorial-style lessons in this book, you’ll discover just how easily these tasks can be accomplished. Not only will you see examples and learn how to build these and other applications, but you’ll also gain the understanding to be confident in any endeavor you choose to pursue in ASP.NET. This second edition is updated with the latest changes to the .NET Framework, and is completely compatible with the RTM version of .NET (build 3705 and higher). The examples and exercises have been updated as well. In addition, this edition more fully embraces C# with examples, discussion, and code.
Who Is This Book’s Intended Audience? This book is intended to bring beginners of ASP.NET to advanced levels. That description covers a large group of people. To fully absorb the lessons in this book, you need to be familiar with computer technology and terms (for example, how to navigate your hard drive or browse pages on the Internet). Previous programming experience is not required, but will help immensely. Knowledge of basic HTML is also a must. Classic ASP developers will also benefit greatly from this book. Not only do I show you how to do advanced tasks in ASP.NET, but each day also has a special section—“That’s Not ASP!”—that caters specifically to those who have such prior experience. These sections discuss the changes in ASP.NET from classic ASP, and provide examples that will help your migration to ASP.NET move more smoothly.
2
Sams Teach Yourself ASP.NET in 21 Days
Most importantly, this book is for people who have a desire to build a strong Web presence (or even a simple home page) using the power of ASP.NET. If you’ve never built anything other than an HTML page, ASP.NET is the perfect place to start. It gives you tremendous power, and is easy to get started in. You’ll be amazed at what you can do with ASP.NET.
What Do You Need to Know Prior to Reading This Book? The only must-have prerequisites are a basic knowledge of HTML and some familiarity with your operating system. Each lesson will present, define, and explain new topics, so that you can grasp them and quickly move on. That said, a knowledge of programming concepts will help you move through the book. If you have experience developing traditional applications, or even Web applications, you will be familiar with many of the concepts in this book, allowing you to proceed easier. Also, no experience with classic Active Server Pages is necessary. Concepts that stem from this older framework are explained as if they were completely new, so anyone can learn them or possibly gain a deeper understanding of them.
What Software Do You Need to Complete the Examples Provided with This Book? You will need to use either Windows 2000, XP, or Windows NT with Service Pack 6 to take advantage of most of the examples for this book. Some components of ASP.NET will function on Windows Me, 98, or earlier versions of Windows, but support is problematic, and trying ASP.NET with these operating systems is not recommended. A Web server is required. This can range from IIS 5 to Personal Web Server. I’ll show you in the first lesson how to go about setting up the server properly. Also, you’ll need to get the .NET Framework SDK from Microsoft to work the examples. Again, setup is examined in Day 1. Finally, to take advantage of the database examples, you’ll need some form of OLE DB–compliant database system, such as Microsoft Access or SQL Server. Without it, you won’t be able to play around with the related examples.
Introduction
How This Book Is Organized This book is divided into five parts (encompassing 23 days of lessons). The first week will be spent learning the fundamentals of ASP.NET: how to get started in it, how to build ASP.NET pages, and how to use Visual Basic.NET and C# to enhance your pages. We’ll also take an in-depth look at the Web forms framework—an integral part of ASP.NET that makes developers’ lives much easier. This week presents the foundation you’ll need to continue. The entire second week is spent on data manipulation techniques (after all, most people get into Web programming because they are interested mainly in database interactions). You’ll learn how to set up your databases, how to retrieve information and display it in your ASP.NET pages, and how to modify that data. You’ll learn about traditional databases, interacting with regular files, XML, and caching. The third week rounds out your journey through ASP.NET by focusing on larger, application-level topics, such as debugging, componentizing, and configuration. These topics are necessary to build complete Web based applications. Next, you’ll spend a couple days examining topics that aren’t central to learning ASP.NET, but might help you after you’re through with the book. These include a complete analysis of a Web-based application, and how to use ASP.NET for mobile devices such as cell phones or PDAs. Finally, the appendices provide a complete reference section for the topics covered in the book, as well as tips on how to avoid problem areas. The book is organized in a tutorial style. Each day’s lesson will build on the lesson previous to it, so it might be helpful to proceed in a linear fashion, although it is certainly not required. In general, topics are discussed first, followed by some examples (which are accompanied by analyses). Each day’s lesson concludes with answers to commonly asked questions, a short quiz to test your new knowledge (no cheating!), and a few exercises for you to play with on your own. All these are carefully chosen to further your knowledge and extend your experience with the technology, but are in no way required to be completed.
3
4
Sams Teach Yourself ASP.NET in 21 Days
Conventions Used in This Book The following typographic conventions are used in this book: • Code lines, commands, statements, variables, and any text you type or see onscreen appears in a mono typeface. Bold mono typeface is often used to represent the user’s input. • Placeholders in syntax descriptions appear in an italic mono typeface. Replace the placeholder with the actual filename, parameter, or whatever element it represents. • Italics highlight technical terms when they’re being defined. • The ➥ icon is used before a line of code that is really a continuation of the preceding line. Sometimes a line of code is too long to fit as a single line on the page. If you see ➥ before a line of code, remember that it’s part of the line immediately above it. • The book also contains Notes, Tips, and Cautions to help you spot important or useful information more quickly. Some of these are helpful shortcuts to help you work more efficiently.
Finally… I hope you have a wonderful time learning this exciting technology. With it, you can do many amazing things over the Internet, many of which are in high demand in the technology market. Without further ado, let’s get on with the lessons!
WEEK 1
1
At a Glance
2
ASP.NET is a very complex topic, and therefore requires a very solid foundation. The first week of this book covers the basics of ASP.NET: what it is and what you need to get started, as well as the fundamental concepts of building ASP.NET pages. These topics will provide you with the concepts necessary for every ASP.NET application; consequently, you will use them very often.
3
Day 1, “Getting Started with ASP.NET,” will be an overview of ASP.NET, including its companion technologies in the .NET Framework. You’ll examine installation issues and how you’ll be setting up your projects for the rest of this book.
4
You then dive straight into your first ASP.NET program in Day 2, “Building ASP.NET Pages,” to whet your appetite for things to come. You spend a lot of time in Day 2 looking behind the scenes of your ASP.NET pages, which is vitally important for building more complex applications.
5
Day 3, “Using Visual Basic.NET and C#,” discusses everything you need to know about VB.NET and C# to build your ASP.NET pages. You’ll learn about control structures, variables, looping logic, and more. With these tools, you’ll be able to make your pages do nearly anything!
6
Day 4, “Using ASP.NET Objects with C# and VB.NET,” will be spent introducing and dealing with examples on some of the most common ASP.NET objects. These objects will add tremendous power to your pages.
7
6
Week 1
Day 5, “Beginning Web Forms,” introduces you to the Web forms framework, which allows you to easily build and control user interfaces in ASP.NET. This framework consists of server controls, which are the building blocks of your UIs. This framework is also extensible, as you’ll see in Day 6, “Learning More About Web Forms,” where you’ll learn how to build your own server controls. Finally, in Day 7, “Validating ASP.NET Pages,” you’ll examine another class of server controls, the validation controls, which allow you to validate the input that users enter into your ASP.NET pages easily. By the end of the week, you will have a solid grip on ASP.NET fundamentals, and be ready to dive into more advanced topics in the following weeks. You’re in for a fun ride, so let’s get started!
WEEK 1
DAY
1
Getting Started with ASP.NET Welcome to the first day of your journey through Active Server Pages.NET! Also known as ASP.NET, this is Microsoft’s way to build powerful Web sites that go beyond regular HTML pages. If you want to create Internet applications, you’ve come to the right place. ASP.NET is a robust, easy-to-use solution for developing complex Web sites. Rather than building simple pages that are only for display, you’ll create Web pages that visitors can interact with in wonderful ways. ASP.NET pages allow you to add a new dimension to the Web experience. Today, you’ll learn about the following: • How the Web works with the client/server model • What Active Server Pages.NET is • How ASP.NET ties the client and server together • What the .NET Framework is and how it ties in with ASP.NET
8
Day 1
• What you need to get started building ASP.NET pages, and how to install the required software • How to create ASP.NET pages • How ASP.NET is different from traditional Active Server Pages
The Way the Web Works The Internet is a wonderful thing. It allows people from all over the world to communicate with each other via their computers. This technology has brought about many new possibilities, including e-mail, instant messaging, and the World Wide Web. Originally, Web sites were very simple. There were HTML pages on any topic you could imagine. People could share whatever they liked, and there was always an audience for it. Those early pages were static—visitors couldn’t interact with them in any way. The Web quickly evolved and new levels of functionality were added, including images, tables, and forms. This finally allowed visitors to interact with Web sites, giving rise to guestbooks and user polls. Web site developers began to build other neat little tricks into their sites, such as image rollovers and dropdown menus. This allowed interactivity, but true dynamic content was still lacking. Then server processing was introduced. You could now interact with databases, process content, and determine new types of visitor demographics over the Web. ASP.NET is a server technology that brings together the different pieces of the Web to give Web site developers more power than ever. But before we get too far into ASP.NET, let’s take a look at how dynamic processing works.
Dynamic Processing The Internet works on the client/server model. Two computers work together, sending information back and forth, to perform a task. The most common scenario is communication between a server (a computer that holds information) and a client (a computer that wants the information).
NEW TERM
The client computer sends a request for information to the server computer. The server then responds to the client with the information that was requested of it. This paradigm is the request/response model, and it’s an integral part of the client/server model.
NEW TERM
A Web server is a computer that holds information about a Web site—its HTML pages, images, and so on. The client is the visitor to the Web site (specifically, the visitor’s Web browser). Figure 1.1 illustrates this concept.
Getting Started with ASP.NET
FIGURE 1.1 The request/response model.
9
BROWSER SERVER REQUEST PROCESS REQUEST
RESPONSE
Although this is a marvelous way to communicate and distribute information, it’s rather simple and static. It can’t provide any dynamic information or processing. The server simply waits around for someone to request information, and then it returns the data that’s already stored on its hard drive without really looking at what it’s sending. Generally, a static Web request follows these four steps: 1. The client (the Web browser) locates a Web server through its URL (such as www. microsoft.com). 2. The client requests a page (such as index.html). 3. The server sends the requested document. 4. The client receives the document and displays it. Once the client has received the information, the process is finished. The server has no idea what’s happening on the client. How could it, since the server and client are two separate computers? They only communicate with one another during the request response process. Once the page has been delivered, the server doesn’t care what happens. Enter server processing. This comes in many forms, including the common gateway interface (CGI) and Microsoft’s Active Server Pages, which is now referred to as classic ASP. In this scenario, the server takes a look at what it sends before it sends it, and it can take orders from the client. The server can return dynamic data, such as that from a database, calculations it performs, and anything else the client may ask for. The modified work flow is as follows: 1. The client (the Web browser) locates a Web server through its URL (such as www. microsoft.com). 2. The client requests a page (such as index.html). 3. The server examines the requested file and processes any code it contains. 4. The server translates the results of the processing to HTML (if necessary) and sends the requested document to the client. 5. The client receives the document and displays it.
1
10
Day 1
Even in this scenario, the process is over once the client receives the page. The server has no idea what the client is doing unless it makes another request.
The ASP.NET Difference There’s another model for communicating between servers and clients, known as the event-driven model. The server waits around for something to happen on the client. Once it does, the server takes action and performs some piece of functionality.
NEW TERM
Imagine going to the library. If you followed the request/response model, you’d ask the librarian for information, and he would either give you the answer or point you in the right direction. In the event-driven model, the librarian already knows what you’re doing. If you’re writing a report and need information on Benjamin Franklin, the librarian brings you the correct items automatically. If you’re thirsty, the librarian brings you a glass of water. If you trip and fall, the librarian brings you a bandage. Of course, a Web server can’t know what you’re thinking, but it can respond to your actions. If you type some text on the Web page, the server responds to it. If you click an image, the server responds. This model is much easier for building applications than using a request/ response scenario. ASP.NET works in this way—it detects actions and responds to them. But wait a second! How can ASP.NET know what’s going on in your computer? How can the server react to things happening on the client? ASP.NET relies on clever clientside processing to simulate an event-driven model.
Client-Side Processing Client-side processing occurs when you place some programming code in an HTML page that the client can understand. This code is simply HTML that the browser executes. For example, take a look at Listing 1.1. LISTING 1.1 Client-Side Code Is Executed with JavaScript 1: 2: 3: 4: 5: 6: 7: 8: 9: 10: 11: 12:
Welcome to my page!
Getting Started with ASP.NET
If you’re familiar with client-side scripting or JavaScript, this may look familiar. When the browser receives this page, it treats the entire thing as HTML. The tags denote a portion of the page that contains commands, known as script, for the client. If your browser supports client-side scripting, it will understand that line 5 is telling it to display a message box to the user saying “Hello World!”, as shown in Figure 1.2. FIGURE 1.2 Client-side scripting allows you to interact with the client.
So now you have two places to execute code: on the server, where everything is returned to the client as HTML, and on the client. These two locations of code are distinct and cannot interact with each other. Table 1.1 outlines the differences between client-side and server-side code. TABLE 1.1 The Differences Between Client-Side and Server-Side Code Location
Description
Client side
This code isn’t processed at all by the server. That’s solely the client’s responsibility. Code is written in scripts—plain-text commands that instruct the client to do something. Generally used for performing dynamic client effects, such as image rollovers or displaying message boxes.
Server side
This code is executed only on the server. Any content or information that this code produces must be converted to plain HTML before being sent to the client. Code can be written in scripts as well, but ASP.NET uses compiled languages (more on that later). Used for processing content and returning data.
How ASP.NET Ties It Together So how does ASP.NET know what’s going on with a client? Client-side script cannot interact with server-side code. However, ASP.NET cleverly skirts around this problem. The only way for a client to communicate with the server is during a request.
11
1
12
Day 1
Using client-side script, ASP.NET supplies information about what the client is doing during requests. Going back to the library scenario, this is why the librarian seems to have magical powers that can detect whatever you need. He has a network of spies that observe you, even though you don’t know it. When you do something, a spy quickly runs to the librarian to tell him what has happened. The librarian can then determine the correct course of action, such as bringing you a glass of water or a bandage. ASP.NET’s spies are client-side scripts. Whenever something happens on the client, a client-side script executes and sends information to the server, just as submitting a form sends information to a server. The browser is simply an unknowing accomplice. It thinks it’s just doing its job displaying HTML. So, client-side scripts can’t exactly interact with the server-side, but they can relay messages via posts to the server. Thus, ASP.NET ties together the server and the client, which allows developers to do things in Web pages that weren’t possible before. You don’t have to focus on handling requests and responses, but are free to concentrate on building the logic. You can react to user events immediately instead of waiting until forms are submitted. And you can know the structure of the user interface (UI) and how to handle it ahead of time. ASP.NET truly makes developers’ lives easier.
The .NET Framework Where does the .NET in ASP.NET come from? It stands for the .NET Framework, a set of objects and blueprints from Microsoft for building applications. The .NET Framework provides the underlying functionality of ASP.NET. All applications developed under the .NET Framework, including ASP.NET applications, have certain key features that ensure compatibility, security, and stability. Let’s examine these features individually.
Common Language Runtime The Common Language Runtime (CLR) is an environment that manages the execution of code. In other words, it runs and maintains any code that you write. Traditionally, when you create an application, you write some code in a programming language (such as Visual Basic), compile it into a format that the computer can understand (1’s and 0’s), and then execute it. Note that different types of computers speak different languages (for instance, PCs and Macintoshes). This means that every time you want to use an application on a different type of computer, you have to recompile it to the new computer’s language. In the .NET Framework, things work a little differently.
Getting Started with ASP.NET
13
With the .NET Framework and CLR, you still write code and compile it. However, instead of compiling it into something the computer understands, you compile it into a language called the Microsoft Intermediate Language (MSIL). This language is a shorthand way of representing all the code you’ve written. ASP.NET pages are compiled into MSIL as well. When you compile to MSIL, your application produces something called metadata. This is descriptive information about your application. It tells what the application can do, where it belongs, and so on.
NEW TERM
Note
Along with MSIL and metadata, a new class of programming language compilers has been created—for C#, COBOL, Perl, and so on. These compilers are similar to existing ones, but now can output MSIL as well as compiled code.
Then, when you want to run your program, the Common Language Runtime takes over and compiles the code once more into the computer’s native language. This way MSIL can go on any type of computer. The CLR can speak many different computer languages and does all the compiling for you. Once you compile your application, you can bring it to any other computer! Figure 1.3 illustrates the difference between the traditional process and the .NET Framework. FIGURE 1.3
Traditional Method
The traditional application framework versus the .NET Framework.
Compile into machine code
Code
Application
In the .NET Framework Compile into machine code
Compile
Application
Code MSIL w/ Metadata
CLR
1
14
Day 1
Note
If you’re familiar with the Java platform, you may see the similarities here. Java code is also translated and executed by a run-time environment called the Java Virtual Machine (JVM). This allows a developer to write code, compile once, and have the JVM handle any cross-platform issues.
The CLR uses the metadata to find out how to run the application, which makes it very easy to install programs. The traditional method required information about the application to be stored in a registry or a central depository for application information. Unfortunately, the registry would be invalidated whenever an aspect of your application changed (its directory was moved, a new component was installed, and so on), and the application wouldn’t run properly. With metadata, there’s no need for the registry. All necessary information is stored with the application files, so any changes you make are put into effect automatically. Imagine installing a new application just by copying some files! Code that works with the CLR is called managed code. This is because the CLR manages its execution and provides benefits (such as resource management) without the developer having to build it manually. Code that’s run outside of the CLR is known as unmanaged code.
NEW TERM
That’s not all the CLR does, however. It provides services such as error handling, security features, versioning and deployment support, as well as cross-language integration. That means you can choose any language you want to write your .NET applications, including ASP.NET applications!
.NET Framework Classes The .NET Framework comes with blueprints that describe programming objects. Everything in the .NET Framework is treated as an object—ASP.NET pages, message boxes, and so on. These objects are placed into logical groups called namespaces. For example, all objects that deal with databases are in the System.Data namespace, all XML objects are in the System.Xml namespace, and so on. Grouping objects this way is a very useful way to build libraries of objects. You’ll be using namespaces as you build your ASP.NET applications.
NEW TERM
Note
Again, you can see similarities to Java. The .NET namespaces are similar to Java packages.
Getting Started with ASP.NET
Setting Up and Installing ASP.NET To run ASP.NET pages, you need to have two things on your computer: Internet Information Server (IIS) and the .NET Framework Software Development Kit (SDK). These items are available for Windows 2000 and Windows NT 4 with Service Pack 6a. Without these items, your computer won’t know what to do with ASP.NET files. It will treat them as unknown items and ask you which application should be used to open them, as shown in Figure 1.4. FIGURE 1.4 Without IIS and the .NET Framework SDK, your computer won’t know how to handle ASP.NET files.
Recall that ASP.NET is a server-side technology, which implies that you need a Web server on your computer. Once you have one properly set up and running, visitors can request pages from your computer over the Internet. ASP.NET pages require a bit more work to handle, however, because Web servers don’t understand them. In addition, you need the .NET Framework SDK, which provides the functionality to run ASP.NET pages, as well as supplying the .NET objects and classes. First, let’s examine how to set up your Web server, and then we’ll look at the .NET SDK.
Installing Internet Information Server Internet Information Server is Microsoft’s professional Web server that comes bundled with Windows 2000 and XP, or as a separate download for Windows NT Server. If you’re running NT Server, download the NT Option Pack for free at http://www.microsoft. com/msdownload/ntoptionpack/askwiz.asp, and get started using IIS 4.0. If you have Windows 2000, you’ll already have a copy of IIS 5.0, and for Windows XP, IIS 5.1.
15
1
16
Day 1
To set IIS 5.0 or 5.1 up, go to Start, Settings, Control Panel, Add/Remove Programs, and then select Add/Remove Windows Components. You’ll see a window that allows you to add optional Windows components (see Figure 1.5). FIGURE 1.5 Installing and removing Windows 2000 components.
Select Internet Information Services (IIS) and click Next. Or you can click the Details button to install individual pieces of IIS, such as an FTP or SMTP service. You’d be fine just using the default options, but it doesn’t hurt to install them all. Once you click Next, Windows 2000 (or XP) will gather some information and begin the installation process. Congratulations, you now have a Web server installed on your computer! Open your browser and type http://localhost, and your Web site will open. The page that comes up is a default page created by IIS. You can also access your server by typing http:// computername, where computername is the name of your computer. If you don’t know the name of your computer, using localhost will work fine.
Note
Getting a domain name for your site, like www.MySite.com, is a completely separate process that is well beyond the scope of this book. Check out Network Solutions (www.networksolutions.com) for more information.
Let’s access the Internet Services Manager (ISM), which allows you to configure IIS’s settings. Go to Start, Settings, Control Panel, Administrative Tools, and then select Internet Services Manager. Figure 1.6 shows this application.
Getting Started with ASP.NET
17
FIGURE 1.6
1
Configuring IIS with the ISM.
Tip
There is a shortcut to reach the ISM. Go to Start, Programs, Administrative Tools, and you should see it there as well. If you don’t see Administrative Tools in this list, right-click somewhere on the taskbar and select Properties, Advanced. In the menu at the bottom of the window that pops up, you can choose to display the Administrative Tools.
This application shows the directory structure of your Web site, and the FTP and SMTP sites if you chose to install them. Expand the Default Web Site menu and you should see a few directories and files already there. Right-click on Default Web Site and select Properties. There are a lot of options to play with, and you could spend a lot of time here. For now, you’re only concerned with the Home Directory tab. Notice the Local Path box near the middle of this page, as shown in Figure 1.7. This defaults to c:\inetpub\wwwroot, also known as the root folder. When a visitor comes to your Web site, he’s viewing the contents of this folder. Thus, if a visitor goes to www.yoursite.com, he’s actually looking at whatever is in the c:\inetpub\wwwroot folder. In fact, open My Computer from the desktop and go to your C: drive. You should see this directory now, if it wasn’t there before. This is where you’ll be placing all of your ASP.NET files.
18
Day 1
FIGURE 1.7 Viewing the Home Directory properties for the default Web site.
Click Cancel to go back to the ISM. All of the directories you see here are called virtual directories. (If you don’t see any directories, don’t worry because you’ll create one in a moment.) A virtual directory is a folder on your computer that can be accessed through your Web site as though it were inside c:\inetpub\wwwroot.
NEW TERM
To create a virtual directory, right-click on Default Web Site, go to the New menu, and select Virtual Directory. You’ll see a wizard like the one in Figure 1.8. Click Next and type in an alias. This is the name of the folder that Web site visitors will type to access part of your Web site. Click Next once you’ve entered an alias. On the next page, choose the directory on your computer. This can be any directory, anywhere on your computer. The next page lets you choose some options, but for now, just click Next and then Finish. FIGURE 1.8 The Virtual Directory Wizard lets you create virtual directories easily.
Getting Started with ASP.NET
You should now see an item in the ISM with the alias that you created. If your directory name was images, you could now type http://localhost/images into your Web browser and view that directory’s contents. In most cases, virtual directories will be placed in the root folder—that is, at c:\inetThe interesting part is that the actual directory can be located anywhere on your computer, but visitors to your site can access it just as if it were at the root folder. Virtual directories are important for ASP.NET, as you’ll see in the coming days.
pub\wwwroot.
Installing the .NET Framework SDK The .NET Framework SDK contains the tools and applications that will allow ASP.NET pages to run. This includes the Common Language Runtime you learned about in “The .NET Framework” earlier today. This SDK is free at www.microsoft.com/NET, but be aware that it’s over 100MB and can take more than 6 hours to download on a 56KB modem. You can also order the SDK on CD-ROM for a nominal shipping charge. Once you have a copy of the SDK, run the setup program. This process may take some time because Windows extracts files and gathers information (see Figure 1.9). Once Windows is done examining your computer, you should see a window similar to the one in Figure 1.10. FIGURE 1.9 Setting up the .NET Framework SDK.
FIGURE 1.10 The .NET Framework SDK setup screen.
19
1
20
Day 1
Click Next and accept the agreement, click Next again to select the components you want to install, click Next again to choose the directory to install to, and click Next one last time to install the .NET Framework. After it’s done, a shortcut to the .NET Framework SDK Overview will appear on your desktop (if one doesn’t appear, you can access the .NET Framework by selecting Start Menu, Programs). Click on this and go through it to find out more about the SDK. This shortcut also contains a link to the .NET Framework SDK Documentation, so be sure to check that out as well. Create a text document called MyPage.aspx in your c:\inetpub\wwwroot folder. (.aspx means that this is an ASP.NET file. More on this in the next section.) Now try doubleclicking on this file. You receive the window shown in Figure 1.4 again. What happened? Recall that ASP.NET is a server technology, which means it requires a Web server in order to run. Therefore, ASP.NET files must go through a server to function (such as IIS). Now open your browser and type http://localhost/MyPage.aspx. You’ll see the empty ASP.NET page.
Caution
Simply opening the ASP.NET page in your browser by clicking on the File menu, selecting Open, and navigating to the file won’t work either. This merely tries to open the file in the browser without going through the Web server. You must go through the server by using http://localhost. This is a common mistake among beginners.
Now you’re ready to begin running ASP.NET pages!
Creating ASP.NET Pages ASP.NET pages are simply pure text, like HTML files. Once you have a Web server and the .NET Framework SDK up and running, you can easily create ASP.NET pages in any text editor you choose. ASP.NET pages have the .aspx extension, so any files you want the server to interpret as ASP.NET pages must end in .aspx, such as default.aspx. Let’s create a simple file to get started. Open Notepad (or your editor of choice) and type in the code in Listing 1.2. (Don’t worry about understanding it yet. We’ll get there soon enough.)
Getting Started with ASP.NET
21
LISTING 1.2 Your First ASP.NET Page in VB.NET 1: 2: 3: 4: 5: 6: 7: 8: 9: 10: 11:
sub Page_Load(obj as object, e as eventargs) lblMessage.Text = “Welcome to ASP.NET!” end sub
Listing 1.2 was written using VB.NET, but recall that you can use multiple programming languages to write ASP.NET pages. Listing 1.3 shows the exact same page using C#— we’ll examine the differences in Day 4, “Using ASP.NET Objects with C# and VB.NET.” LISTING 1.3 Your First ASP.NET Page in C# 1: 2: 3: 4: 5: 6: 7: 8: 9: 10: 11:
void Page_Load(Object obj, EventArgs e) { lblMessage.Text = “Welcome to ASP.NET!”; }
Create a new directory named day1 in your c:\inetpub\wwwroot folder and save this file as listing0102.aspx (or listing0103.aspx for the C# version). This page simply displays a welcome message to visitors. Open your Web browser and access this page with the URL http://localhost/day1/listing0102.aspx. You should see the window shown in Figure 1.11.
Tip
Throughout this book, you’ll be creating a new directory for each lesson. Each directory will be placed in its own c:\inetpub\wwwroot\tyaspnet21days folder. For example, Day 2’s ASP.NET pages will go into the c:\inetpub\wwwroot\tyaspnet21days\day2 folder. This directory will then be accessible through the browser via http://localhost/tyaspnet21days/day2. This will make things easy to find.
1
22
Day 1
FIGURE 1.11 Your first ASP.NET welcome page!
Remember that browsers can only understand HTML. Right-click on this output and select View source. You should see the code in Listing 1.4. LISTING 1.4 The HTML from Your ASP.NET Page 1: 2: 3:
Welcome to ASP.NET!
What happened to the rest of the code in listing0102.aspx (see Listing 1.2)? ASP.NET compiled it into MSIL, which was then compiled into machine language by the CLR and executed. The output from the execution is what you see in Listing 1.4. ASP.NET translated all of its output to HTML because it’s the only language that browsers can read.
Development Environments As much as you may like Notepad, it’s not the ideal application for creating ASP.NET pages. It’s easy and fast to use, but doesn’t offer many features that would make ASP.NET development easier. Microsoft Visual Studio.NET (VS.NET) is another commonly used editor. This powerful product allows you to manage entire Web sites, and it provides features such as creating
Getting Started with ASP.NET
and deleting virtual directories, working with databases, and dragging and dropping HTML components. It even color-codes your ASP.NET code to make it easier to read.
Note
Older versions of Visual Studio (6.0 and below) will work as well. However, they don’t support the .NET Framework, so some features won’t work correctly. For example, older versions won’t color-code your ASP.NET code.
Another common environment is Microsoft FrontPage. This is a visual tool that allows you to create Web pages without having to write any HTML code. Unfortunately, it won’t write ASP.NET code for you, so you’ll have to do that yourself. For more information, check out Sams Teach Yourself FrontPage in 21 Days. None of the pages you’ll create in this book require more than Notepad, so the development environment is entirely up to you. The additional features provided by Visual Studio.NET and FrontPage may be of use, but these programs lack the sheer simplicity of Notepad. There are also quite a few non-Microsoft editors out there, such as HoTMetaL. Many of them don’t yet support the .NET Framework, however, so they may not be as functional as the Microsoft editors. Essentially, use what you are most comfortable with. This book will stick to Notepad because it is easy to use and is universally available. Visual Studio.NET and FrontPage are both commercial products that may be out of many people’s budgets.
Elements of an ASP.NET Page Let’s examine a typical ASP.NET page, shown in Listing 1.5. This page displays a message to the user and a form that lets her enter her name. When she clicks the Submit button, she sees a customized welcome message. LISTING 1.5 Interacting with the User 1: 2: 3: 4: 5: 6: 7: 8: 9: 10:
Sub tbMessage_Change(Sender As Object, E As EventArgs) lblMessage.Text = “Hello “ + tbMessage.Text End Sub Sam’s Teach Yourself ASP.NET in 21 Days:
23
1
24
Day 1
LISTING 1.5 continued 11: 12: 13: 14: 15: 16: 17: 18: 19: 20: 21: 22: 23: 24:
Day 2
Please enter your name:
Save this page as listing0105.aspx in the c:\inetpub\wwwroot\tyaspnet21days\day1 directory. View it from a Web browser with the URL http://localhost/tyaspnet21days/ day1/listing0105.aspx. Enter your name in the box and click Submit. You’ll see a nice hello message, as shown in Figure 1.12. FIGURE 1.12 A simple ASP.NET page that displays a personalized welcome message.
Getting Started with ASP.NET
ANALYSIS This page highlights the most common elements found in ASP.NET pages. On
line 1 is the directive, which supplies the ASP.NET page with specific information that’s used during the compiling process. In this case, you’re telling ASP.NET that you’re using the Visual Basic.NET programming language to write your code (you can use “C#” or “CS” to signify that you want to use C# for the programming language).
Lines 3–7 contain a block of code called a code declaration block. This looks similar to the client-side code that you learned about earlier today in “Client-Side Processing,” but it includes a new tag, runat=”server”. This is the code that ASP.NET uses to process its pages, and it’s where you’ll control all the functionality. This code is also compiled into MSIL.
NEW TERM
Tip
If you’re familiar with client-side programming, you know that typically a block is placed in the ... tags in HTML. These blocks, however, can be placed anywhere in the page, and placing them at the very top is a good way to keep your ASP.NET code separate from the HTML code.
Starting on line 9, you begin the HTML page. This is the content that will be sent to the browser (along with whatever your ASP.NET code spits out). Line 12 begins with