Ebook - Beginning ASP.NET 4 in C# 2010
Trang 1in C# 2010
■ ■ ■
Matthew MacDonald
Trang 2All rights reserved No part of this work may be reproduced or transmitted in any form or by any means, electronic or mechanical, including photocopying, recording, or by any information storage or retrieval system, without the prior written permission of the copyright the publisher ISBN-13 (pbk): 978-1-4302-2608-6
ISBN-13 (electronic): 978-1-4302-2609-3
Printed and bound in the United States of America 9 8 7 6 5 4 3 2 1
Trademarked names, logos, and images may appear in this book Rather than use a trademark symbol with every occurrence of a trademarked name, logo, or image we use the names, logos, and images only in an editorial fashion and to the benefit of the trademark owner, with no intention of infringement of the trademark
The use in this publication of trade names, trademarks, service marks, and similar terms, even if they are not identified as such, is not to be taken as an expression of opinion as to whether or not they are subject to proprietary rights
President and Publisher: Paul Manning
Lead Editor: Ewan Buckingham
Technical Reviewer: Damien Foggon
Editorial Board: Clay Andres, Steve Anglin, Mark Beckner, Ewan Buckingham, Gary Cornell, Jonathan Gennick, Jonathan Hassell, Michelle Lowman, Matthew Moodie, Duncan Parkes, Jeffrey Pepper, Frank Pohlmann, Douglas Pundick, Ben Renow-Clarke, Dominic
Shakeshaft, Matt Wade, Tom Welsh
Coordinating Editor: Anne Collett
Copy Editor: Kim Wimpsett
Compositor: Mary Sudul
Indexer: BIM Indexing & Proofreading Services
Artist: April Milne
Cover Designer: Anna Ishchenko
Distributed to the book trade worldwide by Springer Science+Business Media, LLC., 233 Spring Street, 6th Floor, New York, NY 10013 Phone 1-800-SPRINGER, fax (201) 348-4505, e-mail orders-ny@springer-sbm.com, or visit www.springeronline.com
For information on translations, please e-mail rights@apress.com, or visit www.apress.com
Apress and friends of ED books may be purchased in bulk for academic, corporate, or promotional use eBook versions and licenses are also available for most titles For more information, reference our Special Bulk Sales–eBook Licensing web page at www.apress.com/info/bulksales
The information in this book is distributed on an “as is” basis, without warranty Although every precaution has been taken in the preparation of this work, neither the author(s) nor Apress shall have any liability to any person or entity with respect to any loss or damage caused or alleged to be caused directly or indirectly by the information contained in this work
Trang 3About the Author xxv
About the Technical Reviewer xxvi
Acknowledgments xxvii
Introduction xxviii
Part 1: Introducing NET 1
■ Chapter 1: The NET Framework 3
The Evolution of Web Development 3
HTML and HTML Forms 3
Server-Side Programming 6
Client-Side Programming 7
The NET Framework 9
C#, VB, and the NET Languages 11
The Common Language Runtime 13
The NET Class Library 14
Visual Studio 15
The Last Word 16
■ Chapter 2: The C# Language 17
The NET Languages 17
C# Language Basics 18
Case Sensitivity 18
Commenting 18
Statement Termination 19
Trang 4Blocks 20
Variables and Data Types 20
Assignment and Initializers 22
Strings and Escaped Characters 24
Arrays 24
Enumerations 26
Variable Operations 27
Advanced Math 29
Type Conversions 29
Object-Based Manipulation 31
The String Type 32
The DateTime and TimeSpan Types 34
The Array Type 36
Conditional Logic 37
The if Statement 38
The switch Statement 39
Loops 40
The for Loop 40
The foreach Loop 41
The while loop 42
Methods 43
Parameters 44
Method Overloading 45
Optional and Named Parameters 46
Delegates 47
The Last Word 48
■ Chapter 3: Types, Objects, and Namespaces 49
The Basics About Classes 49
Static Members 50
Trang 5Building a Basic Class 51
Creating an Object 53
Adding Properties 54
Automatic Properties 56
Adding a Method 56
Adding a Constructor 57
Adding an Event 59
Testing the Product Class 60
Value Types and Reference Types 63
Assignment Operations 63
Equality Testing 64
Passing Parameters by Reference and by Value 64
Reviewing NET Types 65
Understanding Namespaces and Assemblies 67
Using Namespaces 68
Importing Namespaces 69
Assemblies 70
Advanced Class Programming 71
Inheritance 71
Static Members 73
Casting Objects 74
Partial Classes 76
Generics 77
The Last Word 79
Part 2: Developing ASP.NET Applications 81
■ Chapter 4: Visual Studio 83
The Promise of Visual Studio 83
Creating Websites 84
Creating an Empty Web Application 85
Trang 6Websites and Web Projects 89
The Hidden Solution Files 90
The Solution Explorer 91
Adding Web Forms 92
Migrating a Website from a Previous Version of Visual Studio 93
Designing a Web Page 95
Adding Web Controls 96
The Properties Window 98
The Anatomy of a Web Form 100
The Web Form Markup 100
The Page Directive 101
The Doctype 102
The Essentials of XHTML 104
Writing Code 110
The Code-Behind Class 110
Adding Event Handlers 110
Outlining 112
IntelliSense 113
Code Formatting and Coloring 117
Visual Studio Debugging 118
The Visual Studio Web Server 118
Single-Step Debugging 119
Variable Watches 124
The Last Word 125
■ Chapter 5: Web Form Fundamentals 127
The Anatomy of an ASP.NET Application 127
ASP.NET File Types 128
ASP.NET Application Directories 129
Introducing Server Controls 130
Trang 7Converting an HTML Page to an ASP.NET Page 131
View State 134
The HTML Control Classes 135
Adding the Currency Converter Code 138
Event Handling 140
Behind the Scenes with the Currency Converter 142
Error Handling 144
Improving the Currency Converter 144
Adding Multiple Currencies 145
Storing Information in the List 146
Adding Linked Images 147
Setting Styles 150
A Deeper Look at HTML Control Classes 151
HTML Control Events 151
Advanced Events with the HtmlInputImage Control 152
The HtmlControl Base Class 154
The HtmlContainerControl Class 155
The HtmlInputControl Class 155
The Page Class 156
Sending the User to a New Page 157
HTML Encoding 158
Application Events 160
The global.asax File 161
Additional Application Events 162
ASP.NET Configuration 163
The web.config File 163
Nested Configuration 164
Storing Custom Settings in the web.config File 166
The Website Administration Tool (WAT) 168
The Last Word 170
Trang 8■ Chapter 6: Web Controls 173
Stepping Up to Web Controls .173
Basic Web Control Classes 174
The Web Control Tags 175
Web Control Classes .176
The WebControl Base Class 177
Units 179
Enumerations 179
Colors 180
Fonts .181
Focus 183
The Default Button 183
List Controls .184
Multiple-Select List Controls 185
The BulletedList Control 187
Table Controls .188
Web Control Events and AutoPostBack 193
How Postback Events Work .197
The Page Life Cycle 198
A Simple Web Page .201
Improving the Greeting Card Generator .206
Generating the Cards Automatically 208
The Last Word .211
■ Chapter 7: Error Handling, Logging, and Tracing 213
Common Errors .213
Exception Handling .215
The Exception Class 215
The Exception Chain 217
Trang 9Handling Exceptions 218
Catching Specific Exceptions 219
Nested Exception Handlers 221
Exception Handling in Action 222
Mastering Exceptions 224
Throwing Your Own Exceptions 224
Logging Exceptions 229
Viewing the Windows Event Logs 229
Writing to the Event Log 232
Custom Logs 234
A Custom Logging Class 236
Retrieving Log Information 237
Page Tracing 239
Enabling Tracing 240
Tracing Information 240
Writing Trace Information 246
Application-Level Tracing 250
The Last Word 252
■ Chapter 8: State Management 253
The Problem of State 253
View State 253
The ViewState Collection 254
A View State Example 254
Making View State Secure 255
Retaining Member Variables 257
Storing Custom Objects 259
Transferring Information Between Pages 260
Cross-Page Posting 260
The Query String 265
Trang 10Cookies 269
A Cookie Example 271
Session State 272
Session Tracking 272
Using Session State 273
A Session State Example 274
Session State Configuration 277
Cookieless 278
Timeout 281
Mode 281
Application State 286
An Overview of State Management Choices 288
The Last Word 290
Part 3: Building Better Web Forms 291
■ Chapter 9: Validation 293
Understanding Validation 293
The Validation Controls 294
Server-Side Validation 295
Client-Side Validation 295
The Validation Controls 295
A Simple Validation Example 297
Other Display Options 299
Manual Validation 302
Validating with Regular Expressions 304
A Validated Customer Form 308
Validation Groups 313
The Last Word 314
Trang 11■ Chapter 10: Rich Controls 315
The Calendar 315
Formatting the Calendar 317
Restricting Dates 319
The AdRotator 323
The Advertisement File 323
The AdRotator Class 325
Pages with Multiple Views 326
The MultiView Control 328
The Wizard Control 333
The Last Word 341
■ Chapter 11: User Controls and Graphics 343
User Controls 343
Creating a Simple User Control 344
Independent User Controls 347
Integrated User Controls 349
User Control Events 352
Passing Information with Events 354
Dynamic Graphics 357
Basic Drawing 357
Drawing a Custom Image 360
Placing Custom Images Inside Web Pages 361
Image Format and Quality 363
The Last Word 366
■ Chapter 12: Styles, Themes, and Master Pages 367
Styles 367
Style Types 368
Creating a Basic Inline Style 368
Creating a Style Sheet 377
Trang 12Applying Style Sheet Rules 380
Themes 383
How Themes Work 383
Applying a Simple Theme 385
Handling Theme Conflicts 386
Creating Multiple Skins for the Same Control 388
More Advanced Skins 389
Master Page Basics 391
A Simple Master Page and Content Page 392
How Master Pages and Content Pages Are Connected 396
A Master Page with Multiple Content Regions 398
Default Content 401
Master Pages and Relative Paths 402
Advanced Master Pages 403
Style-Based Layouts 403
Code in a Master Page 408
Interacting with a Master Page Programmatically 409
The Last Word 410
■ Chapter 13: Website Navigation 411
Site Maps 411
Defining a Site Map 412
Seeing a Simple Site Map in Action 416
Binding an Ordinary Page to a Site Map 416
Binding a Master Page to a Site Map 418
Binding Portions of a Site Map 420
The SiteMap Class 425
URL Mapping and Routing 427
URL Mapping 428
URL Routing 428
Trang 13The SiteMapPath Control 430
Customizing the SiteMapPath 431
Using SiteMapPath Styles and Templates 432
Adding Custom Site Map Information 434
The TreeView Control 435
TreeView Properties 436
TreeView Styles 438
The Menu Control 442
Menu Styles 444
Menu Templates 445
The Last Word 448
Part 4: Working with Data 449
■ Chapter 14: ADO.NET Fundamentals 451
Understanding Databases 451
Configuring Your Database 453
SQL Server Express 453
Browsing and Modifying Databases in Visual Studio 454
The sqlcmd Command-Line Tool 457
SQL Basics 458
Running Queries in Visual Studio 459
The Select Statement 461
The SQL Update Statement 463
The SQL Insert Statement 465
The SQL Delete Statement 465
The Data Provider Model 466
Direct Data Access 467
Creating a Connection 469
The Select Command 475
The DataReader 476
Trang 14Putting It All Together 476
Updating Data 481
Disconnected Data Access 491
Selecting Disconnected Data 492
Selecting Multiple Tables 494
Defining Relationships 495
The Last Word 498
■ Chapter 15: Data Binding 499
Introducing Data Binding 499
Types of ASP.NET Data Binding 500
How Data Binding Works 500
Single-Value Data Binding 500
A Simple Data Binding Example 501
Simple Data Binding with Properties 504
Problems with Single-Value Data Binding 505
Using Code Instead of Simple Data Binding 506
Repeated-Value Data Binding 506
Data Binding with Simple List Controls 507
A Simple List Binding Example 508
Strongly Typed Collections 509
Multiple Binding 510
Data Binding with a Dictionary Collection 512
Using the DataValueField Property 513
Data Binding with ADO.NET 514
Creating a Record Editor 516
Data Source Controls 521
The Page Life Cycle with Data Binding 523
The SqlDataSource 523
Selecting Records 525
Trang 15Handling Errors 532
Updating Records 533
The Last Word 537
■ Chapter 16: The Data Controls 539
The GridView 539
Automatically Generating Columns 540
Defining Columns 542
Formatting the GridView 546
Formatting Fields 546
Using Styles 547
Formatting-Specific Values 550
Selecting a GridView Row 552
Adding a Select Button 553
Using Selection to Create Master-Details Pages 554
Editing with the GridView 556
Sorting and Paging the GridView 559
Sorting 559
Paging 561
Using GridView Templates 563
Using Multiple Templates 565
Editing Templates in Visual Studio 566
Handling Events in a Template 567
Editing with a Template 568
The DetailsView and FormView 573
The DetailsView 573
The FormView 575
The Last Word 578
■ Chapter 17: Files and Streams 579
Files and Web Applications 579
Trang 16File System Information 580
The Path Class 581
The Directory and File Classes 582
The DirectoryInfo and FileInfo Classes 587
The DriveInfo Class 589
A Sample File Browser 590
Reading and Writing with Streams 594
Text Files 594
Binary Files 596
Shortcuts for Reading and Writing Files 597
A Simple Guest Book 598
Allowing File Uploads 604
The FileUpload Control 604
The Last Word 607
■ Chapter 18: XML 609
XML Explained 609
Improving the List with XML 611
XML Basics 612
Attributes 613
Comments 614
The XML Classes 615
The XML TextWriter 615
The XML Text Reader 618
Working with XML Documents in Memory 623
Reading an XML Document 628
Searching an XML Document 631
XML Validation 632
XML Namespaces 632
XML Schema Definition 635
Trang 17XML Display and Transforms 640
The Xml Web Control 642
The Last Word 643
Part 5: Website Security 645
■ Chapter 19: Security Fundamentals 647
Understanding Security 647
Testing and Deploying Security Settings 648
Authentication and Authorization 649
Forms Authentication 649
Web.config Settings 651
Authorization Rules 651
The WAT 655
The Login Page 657
Windows Authentication 663
Web.config Settings 663
A Windows Authentication Test 666
The Last Word 667
■ Chapter 20: Membership 669
The Membership Data Store 669
Membership with SQL Server Express 671
Using the Full Version of SQL Server 673
Configuring the Membership Provider 676
Creating Users with the WAT 679
The Membership and MembershipUser Classes 682
Authentication with Membership 686
Disabled Accounts 687
The Security Controls 687
The Login Control 688
The CreateUserWizard Control 694
Trang 18The PasswordRecovery Control .698
Role-Based Security 700
Creating and Assigning Roles .701
Restricting Access Based on Roles 705
The LoginView Control 705
The Last Word .707
■ Chapter 21: Profiles 709
Understanding Profiles 709
Profile Performance 710
How Profiles Store Data 710
Using the SqlProfileProvider 712
Enabling Authentication 712
Using SQL Server Express 713
Using the Full Version of SQL Server 713
The Profile Databases 714
Defining Profile Properties 716
Using Profile Properties 717
Profile Serialization 719
Profile Groups 721
Profiles and Custom Data Types .722
The Profile API 725
Anonymous Profiles 728
The Last Word .731
Part 6: Advanced ASP.NET 733
■ Chapter 22: Introducing ASP.NET 735
Why Use Components? .735
Component Jargon 736
Three-Tier Design 736
Trang 19Business Objects 738
Data Objects 738
Components and Classes 738
Creating a Component 739
Classes and Namespaces 740
Class Members 742
Adding a Reference to the Component 742
Using the Component 745
Properties and State 747
A Stateful Account Class 748
A Stateless AccountUtility Class 749
Data-Access Components 750
A Simple Data-Access Component 750
Using the Data-Access Component 754
Enhancing the Component with Error Handling 757
Enhancing the Component with Aggregate Information 758
The ObjectDataSource 759
Making Classes the ObjectDataSource Can Understand 759
Selecting Records 760
Using Method Parameters 761
Updating Records 762
The Last Word 764
■ Chapter 23: Caching 765
Understanding Caching 765
When to Use Caching 766
Caching in ASP.NET 767
Output Caching 767
Caching on the Client Side 769
Caching and the Query String 769
Caching with Specific Query String Parameters 770
Trang 20A Multiple Caching Example 771
Fragment Caching 772
Cache Profiles 773
Data Caching 774
Adding Items to the Cache 774
A Simple Cache Test 776
Caching to Provide Multiple Views 777
Caching with the Data Source Controls 781
Caching with Dependencies 785
File Dependencies 785
Cache Item Dependencies 786
SQL Server Cache Dependencies 787
The Last Word 790
■ Chapter 24: LINQ and the Entity Framework 791
Understanding LINQ 791
LINQ Basics 792
LINQ Expressions 795
The Entity Framework 799
Creating an Entity Data Model 800
The Data Model Diagram 803
Updating a Data Model 806
The Data Model Code 808
Querying the Data Model 809
Handling Errors 810
Navigating Relationships 812
Getting More Advanced with the Entity Framework 815
Querying with LINQ to Entities 815
Controlling When Data is Loaded 818
Updates, Inserts, and Deletes 820
Trang 21The EntityDataSource 823
Displaying Data 823
Editing Data 828
The Last Word 828
■ Chapter 25: ASP.NET AJAX 829
Understanding Ajax 829
Ajax: The Good 830
Ajax: The Bad 830
The ASP.NET AJAX Toolkit 831
The ScriptManager 831
Partial Refreshes 833
A Simple UpdatePanel Test 834
Handling Errors 837
Conditional Updates 839
Triggers 840
Progress Notification 845
Showing a Simulated Progress Bar 845
Cancellation 847
Timed Refreshes 849
The ASP.NET AJAX Control Toolkit 851
Installing the ASP.NET AJAX Control Toolkit 851
The Accordion 853
The AutoCompleteExtender 856
Getting More Controls 859
The Last Word 864
■ Chapter 26: Deploying ASP.NET Applications 865
ASP.NET Applications and the Web Server 865
How Web Servers Work 865
The Virtual Directory 867
Trang 22Web Application URLs 867 Web Farms 869 Internet Information Services (IIS) 869 The Many Faces of IIS 869 Installing IIS in Windows 7 or Windows Vista 870 Installing IIS 7 in Windows Server 2008 871 Managing Websites with IIS Manager 873 Creating a Virtual Directory 874 Understanding Application Pools 876 The ASP.NET Account 878 Configuring a Website 882 The Default Page 885 Custom Error Pages 886
The Machine Key 888
Windows Authentication 890 Confidentiality with SSL and Certificates 892 Deploying a Simple Site 895 Web Applications and Components 895 Other Configuration Steps 896 Code Compilation 896 Deploying with Visual Studio 897 Creating a Virtual Directory for a New Project 898 Copying a Website 901 Publishing a Website 904 The Last Word 905 Index 907
Trang 23About the Author
■ Matthew MacDonald is an author, educator, and Microsoft MVP He’s the
author of more than a dozen books about NET programming, including Pro
Silverlight 4 in C# (Apress, 2010) and Pro WPF in C# 2010 (Apress, 2010) He’s also
the coauthor of Pro ASP.NET 4 in C# 2010 (Apress, 2010) He lives in Toronto with
his wife and daughters
Trang 24About the Technical Reviewer
■ Damien Foggon is a developer, writer, and technical reviewer in cutting-edge technologies and has
contributed to more than 50 books on NET, C#, Visual Basic, and ASP.NET He is the cofounder of the Newcastle-based user-group NEBytes (http://www.nebytes.net), is a multiple MCPD in NET 2.0 and NET 3.5, and can be found online at http://blog.littlepond.co.uk
Trang 25Acknowledgments
No author could complete a book without a small army of helpful individuals I’m deeply indebted to
the whole Apress team, including Anne Collett, who helped everything move swiftly and smoothly;
Kim Wimpsett, who performed the copy edit; Damien Foggon, who performed a thorough technical
review; and many other individuals who worked behind the scenes indexing pages, drawing figures, and proofreading the final copy I also owe a special thanks to Gary Cornell, who always offers
invaluable advice about projects and the publishing world
I’d also like to thank those who were involved with previous editions of this book This includes
Emma Acker and Jane Brownlow at Osborne McGraw-Hill, as well as previous tech reviewers Ronald Landers, Gavin Smyth, Tim Verycruysse, Julian Skinner, and Andy Olsen I also owe a hearty thanks to all the readers who caught errors and took the time to report problems and ask good questions Keep
sending in the feedback—it helps make better books!
Finally, I’d never write any book without the support of my wife and these special individuals:
Nora, Razia, Paul, and Hamid Thanks, everyone!
Trang 26Introduction
ASP.NET is Microsoft’s platform for developing web applications Using ASP.NET, you can create commerce shops, data-driven portal sites, and just about anything else you can find on the Internet Best of all, you don’t need to paste together a jumble of HTML and script code in order to program the Web Instead, you can create full-scale web applications using nothing but code and a design tool such
e-as Visual Studio 2008
The cost of all this innovation is the learning curve To master ASP.NET, you need to learn how to use an advanced design tool (Visual Studio), a toolkit of objects (the NET Framework), and an object-oriented programming language (such as C# 2010) Taken together, these topics provide more than enough to overwhelm any first-time web developer
Beginning ASP.NET 4 in C# 2010 assumes you want to master ASP.NET, starting from the basics
Using this book, you’ll build your knowledge until you understand the concepts, techniques, and best practices for writing sophisticated web applications The journey is long, but it’s also satisfying At the end of the day, you’ll find that ASP.NET allows you to tackle challenges that are simply out of reach on many other platforms
About This Book
This book explores ASP.NET, which is a core part of Microsoft’s NET Framework The NET Framework
is not a single application—it’s actually a collection of technologies bundled into one marketing term The NET Framework includes languages such as C# 2010 and VB 2010, an engine for hosting
programmable web pages, a model for interacting with databases (ADO.NET), a higher-level
framework for performing queries (LINQ and the Entity Framework), and a class library stocked with tools for everything from reading files to validating a password To master ASP.NET, you need to learn about each of these ingredients
This book covers all these topics from the ground up As a result, you’ll find yourself learning many techniques that will interest any NET developer, even those who create Windows applications For example, you’ll learn about component-based programming; you’ll discover structured error handling; and you’ll see how to access files, XML, and relational databases You’ll also learn the key topics you need for web programming, such as state management, web controls, and caching By the end of this book, you’ll be ready to create your own rich web applications and make them available over the Internet
Trang 27■ Note This book has a single goal: to be as relentlessly practical as possible I take special care not to leave you hanging in the places where other ASP.NET books abandon their readers For example, when encountering a new technology, you’ll not only learn how it works but also why (and when) you should use it I also highlight common questions and best practices with tip boxes and sidebars at every step of the way Finally, if a topic is covered in
this book, it’s covered right This means you won’t learn how to perform a task without learning about potential
drawbacks and the problems you might run into—and how you can safeguard yourself with real-world code
Who Should Read This Book
This book is aimed at anyone who wants to create dynamic websites with ASP.NET Ideally, you’ll have experience with a previous version of a programming language such as C or Java If not, you should be familiar with basic programming concepts (loops, conditional structures, arrays, and so on), whether
you’ve learned them in Visual Basic, Pascal, Turing, or a completely different programming language This is the only requirement for reading this book
Understanding HTML and XHTML (the markup languages used to write web pages) will help you, but it’s not required ASP.NET works at a higher level, allowing you to deal with full-featured web
controls instead of raw web page markup However, you’ll get a quick overview of XHTML
fundamentals in Chapter 4, and you’ll learn about CSS, the Cascading Style Sheets standard, in
Chapter 12
This book will also appeal to programmers who have some experience with C# and NET but
haven’t worked with ASP.NET in the past However, if you’ve used a previous version of ASP.NET,
you’ll probably be more interested in a faster-paced book such as Pro ASP.NET 4 in C# 2010 instead
■ Note This book begins with the fundamentals: C# syntax, the basics of object-oriented programming, and the philosophy of the NET Framework If you haven’t worked with C# before, you can spend a little more time with the syntax review in Chapter 2 to pick up everything you need to know If you aren’t familiar with the ideas of object-oriented programming, Chapter 3 fills in the blanks with a quick, but comprehensive, review of the subject The
rest of the book builds on this foundation, from ASP.NET basics to advanced examples that show the techniques you’ll use in real-world web applications
Trang 28ASP.NET MVC
This book focuses on web forms, which is ASP.NET’s core model However, Microsoft has recently added a
whole new toolkit, called ASP.NET Model-View-Controller (ASP.NET MVC), which offers a dramatically different way to build web pages
The core idea of ASP.NET MVC is that your application is separated into three logical parts The model includes the application-specific business code that powers your application The view creates a suitable representation of the model, by converting it to the HTML that browsers understand The controller
coordinates the whole show, handling user interactions, updating the model, and passing the information
to the view Although this sounds simple enough, the MVC pattern sidelines several traditional ASP.NET concepts that are discussed in this book, including web forms, web controls, view state, postbacks, and session state To some, the MVC pattern is cleaner and more suited to the Web To others, it’s a whole lot
of extra effort with no clear payoff Microsoft suggests you consider ASP.NET MVC if you need to
implement test-driven development (which uses automated tests to validate web pages) or if you need
complete control over the URLs and the HTML markup that’s used in your web pages
ASP.NET MVC isn’t discussed in this book (and it’s a bit of a slog for developers who aren’t already familiar with ASP.NET) However, you can get more information from the official ASP.NET MVC website at
http://www.asp.net/mvc or the excellent book Pro ASP.NET MVC 2 Framework by Steven Sanderson
What You Need to Use This Book
To develop ASP.NET web pages, you need a computer with Visual Studio 2010 You can use the free
Visual Studio Web Developer 2010 Express edition (available at http://www.microsoft.com/express),which has all the tools and functionality you’ll use in this book
To use an ASP.NET web page (in other words, to surf to it over the Internet), you simply need a web
browser ASP.NET fully supports Internet Explorer, Firefox, Opera, Safari, Google Chrome, and anyother browser that respects the HTML standard on virtually any operating system A few featureswon’t work with extremely old browsers (such as the ASP.NET AJAX techniques you’ll learn about inChapter 25), but 99 percent of web surfers can use any ASP.NET page to its fullest
If you plan to host websites on your computer, you’ll also need to use Internet Information
Services (IIS), the web hosting software that’s part of the Windows operating system You might also useIIS if you want to test deployment strategies You’ll learn how to use and configure IIS in Chapter 26 Finally, this book includes several examples that use SQL Server You can use any version of SQLServer to try these examples, including SQL Server Express edition, which is included with some versions of Visual Studio (and freely downloadable at http://www.microsoft.com/express) If you use other relational database engines, the same concepts will apply; you will just need to modify theexample code
Code Samples
To master ASP.NET, you need to experiment with it One of the best ways to learn ASP.NET is to try thecode samples for this book, examine them, and dive in with your own modifications To obtain thesample code, surf to http://www.prosetech.com or the publisher’s website at http://www.apress.com
Trang 29Chapter Overview
This book is divided into six parts Unless you’ve already had experience with the NET Framework, the most productive way to read this book is in order from start to finish Chapters later in the book
sometimes incorporate features that were introduced earlier in order to create more well-rounded
and realistic examples On the other hand, if you’re already familiar with the NET platform, C#, and
object-oriented programming, you’ll make short work of the first part of this book
Part 1: Introducing NET
You could start coding an ASP.NET application right away by following the examples in the second part
of this book But to really master ASP.NET, you need to understand a few fundamental concepts about the NET Framework
Chapter 1 sorts through the Microsoft jargon and explains what the NET Framework really does
and why you need it Chapter 2 introduces you to C# with a comprehensive language tour Finally,
Chapter 3 explains the basics of modern object-oriented programming
Part 2: Developing ASP.NET Applications
The second part of this book delves into the heart of ASP.NET programming and introduces its new
event-based model In Chapter 4, you’ll take a look around the Visual Studio design environment and learn a few fundamentals about web forms, events, and XHTML In Chapters 5 and 6, you learn how to
program a web page’s user interface through a layer of objects called server controls
Next, you’ll explore two more essentials of ASP NET programming Chapter 7 presents different
techniques for handling errors Chapter 8 describes different strategies for state management Taken together, the chapters in this part contain all the core concepts you need to design web pages and
create a basic ASP.NET website
Part 3: Building Better Web Forms
The third part of this book explores several topics that can help you transform ordinary web pages into polished web applications In Chapter 9 you’ll learn to use the validation controls to catch invalid data before the user submits it In Chapter 10 you’ll move on to consider some of ASP.NET’s more exotic
controls, such as the Calendar and Wizard In Chapter 11, you’ll learn how to build your own reusable blocks of web page user interface and draw custom graphics on the fly Finally, Chapter 12 shows how you can standardize the appearance of an entire website with themes and master pages, and Chapter
13 shows you how to add navigation to a website
Part 4: Working with Data
Almost all software needs to work with data, and web applications are no exception In Chapter 14, you begin exploring the world of data by considering ADO.NET—Microsoft’s NET-powered technology for interacting with relational databases Chapters 15 and 16 explain how to use data binding and the
advanced ASP.NET data controls to create web pages that integrate attractive, customizable data
displays with automatic support for paging, sorting, and editing
Trang 30Chapter 17 moves out of the database world and considers how to interact with files Chapter 18 broadens the picture even further and describes how ASP.NET applications can use the XML support that’s built into the NET Framework
Part 5: Website Security
Every public website needs to deal with security—making sure that sensitive data cannot be accessed
by the wrong users In Chapter 19, you’ll start out learning how ASP.NET provides different
authentication systems for dealing with users You can write your own custom logic to verify user names and passwords, or you can use existing Windows account information In Chapter 20, you’ll learn about the membership model, which extends the authentication system with prebuilt security controls and handy objects that automate common tasks If you want, you can even get ASP.NET to create and manage a database with user information automatically Finally, Chapter 21 deals with another add-on—the profiles model that lets you store information for each user automatically, without writing any database code
Part 6: Advanced ASP.NET
This part includes the advanced topics you can use to take your web applications that extra step Chapter 22 covers how you can create reusable components for ASP.NET applications Chapter 23 demonstrates how careful use of caching can boost the performance of almost any web application Chapter 24 explores LINQ and the Entity Framework, two features which let you interact with a
database without writing reams of custom code Chapter 25 introduces ASP.NET AJAX, which allows you
to build responsive web pages that add rich features such as text autocompletion and drag-and-drop Finally, Chapter 26 walks you through the steps for deploying your application to a web server
Feedback
This book has the ambitious goal of being the best tutorial and reference for ASP.NET Toward that end, your comments and suggestions are extremely helpful You can send complaints, adulation, and everything in between directly to apress@prosetech.com I can’t solve your ASP.NET problems or critique your code, but I do benefit from information about what this book did right and wrong (and what it
may have done in an utterly confusing way) You can also send comments about the website support for this book
Trang 31Introducing NET
Trang 32■ ■ ■
The NET Framework
Microsoft has a time-honored reputation for creating innovative technologies and wrapping them in
buzzwords that confuse everyone The NET Framework is the latest example—it’s been described as a feeble Java clone, a meaningless marketing term, and an attempt to take over the Internet with
proprietary technology But none of these descriptions is truly accurate
.NET is actually a cluster of technologies—some revolutionary, some not—that are designed to help developers build a variety of different types of applications Developers can use the NET Framework to build rich Windows applications, services that run quietly in the background, and even command-line tools Of course, if you’re reading this book you’re most interested in using NET to craft web
applications To do so, you’ll use a specific subset of the NET Framework called ASP.NET, and you’ll
work with one of NET’s core languages: C#
In this chapter, you’ll examine the technologies that underlie NET First, you’ll take a quick look at the history of web development and learn why the NET Framework was created Next, you’ll get a high-level overview of the different parts of NET and see how ASP.NET 4 fits into the picture
The Evolution of Web Development
The Internet began in the late 1960s as an experiment Its goal was to create a truly resilient information network—one that could withstand the loss of several computers without preventing the others from
communicating Driven by potential disaster scenarios (such as nuclear attack), the U.S Department of Defense provided the initial funding
The early Internet was mostly limited to educational institutions and defense contractors It
flourished as a tool for academic collaboration, allowing researchers across the globe to share
information In the early 1990s, modems were created that could work over existing phone lines, and the Internet began to open up to commercial users In 1993, the first HTML browser was created, and the
Internet revolution began
HTML and HTML Forms
It would be difficult to describe early websites as web applications Instead, the first generation of
websites often looked more like brochures, consisting mostly of fixed HTML pages that needed to be
updated by hand
A basic HTML page is a little like a word-processing document—it contains formatted content that
can be displayed on your computer, but it doesn’t actually do anything The following example shows
HTML at its simplest, with a document that contains a heading and a single line of text:
Trang 33<h1>Sample Web Page Heading</h1>
<p>This is a sample web page.</p>
</body>
</html>
An HTML document has two types of content: the text and the elements (or tags) that tell the browser how to format it The elements are easily recognizable, because they are designated with angled brackets (< >) HTML defines elements for different levels of headings, paragraphs, hyperlinks, italic and bold formatting, horizontal lines, and so on For example, <h1>Some Text</h1> uses the <h1> element
This element tells the browser to display Some Text in the Heading 1 style, which uses a large, bold font
Similarly, <p>This is a sample web page.</p> creates a paragraph with one line of text The <head> element groups the header information together and includes the <title> element with the text that appears in the browser window, while the <body> element groups together the actual document content that’s displayed in the browser window
Figure 1-1 shows this simple HTML page in a browser Right now, this is just a fixed file (named SampleWebPage.htm) that contains HTML content It has no interactivity, doesn’t require a web server, and certainly can’t be considered a web application
Figure 1-1 Ordinary HTML
Trang 34■ Tip You don’t need to master HTML to program ASP.NET web pages, although it’s often useful For a quick
introduction to HTML, refer to one of the excellent HTML tutorials on the Internet, such as
http://www.w3schools.com/html You’ll also get a mini-introduction to HTML elements in Chapter 4
HTML 2.0 introduced the first seed of web programming with a technology called HTML forms
HTML forms expand HTML so that it includes not only formatting tags but also tags for graphical
widgets, or controls These controls include common ingredients such as drop-down lists, text boxes,
and buttons Here’s a sample web page created with HTML form controls:
In an HTML form, all controls are placed between the <form> and </form> tags The preceding
example includes two check boxes (represented by the <input type="checkbox"/> element) and a button (represented by the <input type="submit"/> element) The <br /> element adds a line break in between lines In a browser, this page looks like Figure 1-2
Trang 35Figure 1-2 An HTML form
HTML forms allow web developers to design standard input pages When the user clicks the Submit button on the page shown in Figure 1-2, all the data in the input controls (in this case, the two check boxes) is patched together into one long string of text and sent to the web server On the server side, a custom application receives and processes the data
Amazingly enough, the controls that were created for HTML forms more than ten years ago are still the basic foundation that you’ll use to build dynamic ASP.NET pages! The difference is the type of application that runs on the server side In the past, when the user clicked a button on a form page, the information might have been e-mailed to a set account or sent to an application on the server that used the challenging Common Gateway Interface (CGI) standard Today, you’ll work with the much more capable and elegant ASP.NET platform
Server-Side Programming
Early web development platforms had two key problems First, they didn’t always scale well As a result, popular websites would struggle to keep up with the demand of too many simultaneous users,
eventually crashing or slowing to a crawl Second, they provided little more than a bare-bones
programming environment If you wanted higher-level features, such as the ability to authenticate users, store personalized information, or display records you’ve retrieved from a database, you needed to write pages of code from scratch Building a web application this way is tedious and
error-prone
To counter these problems, Microsoft created higher-level development platforms—first ASP and then ASP.NET Both of these technologies allow developers to program dynamic web pages without worrying about the low-level implementation details For that reason, both platforms have been
incredibly successful
The original ASP platform garnered a huge audience of nearly 1 million developers, becoming far more popular than even Microsoft anticipated It wasn’t long before it was being wedged into all sorts of unusual places, including mission-critical business applications and highly trafficked
Trang 36e-commerce sites Because ASP wasn’t designed with these uses in mind, performance, security, and
configuration problems soon appeared
That’s where ASP.NET comes into the picture ASP.NET was developed as an industrial-strength
web application framework that could address the limitations of ASP Compared to classic ASP, ASP.NET offers better performance, better design tools, and a rich set of ready-made features ASP.NET was wildly popular from the moment it was released—in fact, it was put to work in dozens of large-scale
commercial websites while still in beta
■ Note Despite having similar underpinnings, ASP and ASP.NET are radically different ASP is a script-based
programming language that requires a thorough understanding of HTML and a good deal of painful coding
ASP.NET, on the other hand, is an object-oriented programming model that lets you put together a web page as
easily as you would build a Windows application
Client-Side Programming
At the same time that server-side web development was moving through an alphabet soup of
technologies, a new type of programming was gaining popularity Developers began to experiment with the different ways they could enhance web pages by embedding miniature applets built with JavaScript, ActiveX, Java, and Flash into web pages These client-side technologies don’t involve any server
processing Instead, the complete application is downloaded to the client browser, which executes it
locally
The greatest problem with client-side technologies is that they aren’t supported equally by all
browsers and operating systems One of the reasons that web development is so popular in the first
place is because web applications don’t require setup CDs, downloads, client-side configuration, and
other tedious (and error-prone) deployment steps Instead, a web application can be used on any
computer that has Internet access But when developers use client-side technologies, they encounter a few familiar headaches Suddenly, cross-browser compatibility becomes a problem Developers are
forced to test their websites with different operating systems and browsers and to deal with a wide range
of browser quirks, bugs, and legacy behaviors In other words, the client-side model sacrifices some of
the most important benefits of web development
For that reason, ASP.NET is designed first and foremost as a server-side technology All ASP.NET
code executes on the server When the code is finished executing, the user receives an ordinary HTML
page, which can be viewed in any browser Figure 1-3 shows the difference between the server-side and client-side models
Trang 37Figure 1-3 Server-side and client-side web applications
These are some other reasons for avoiding client-side programming:
Isolation: Client-side code can’t access server-side resources For example, a client-side application
has no easy way to read a file or interact with a database on the server (at least not without runninginto problems with security and browser compatibility)
Security: End users can view client-side code And once malicious users understand how an
application works, they can often tamper with it
Trang 38Thin clients: In today’s world, web-enabled devices such as mobile phones, handheld computers,
and personal digital assistants (PDAs) are pervasive These devices usually have some sort of built-in web browsing ability, but they don’t support all the features of traditional desktop-based browsers For example, thin clients might not support client-side features such as JavaScript and Flash
However, client-side programming isn’t truly dead In many cases, ASP.NET allows you to combine the best of client-side programming with server-side programming For example, the best ASP.NET
controls can intelligently detect the features of the client browser If the browser supports JavaScript,
these controls will return a web page that incorporates JavaScript for a richer, more responsive user
interface And in Chapter 25, you’ll learn how you can super-charge ordinary ASP.NET pages with Ajax features, which use even more client-side JavaScript The twist is that ASP.NET takes care of the complex cross-platform coding, ensuring that your web pages work on all modern browsers
However, it’s important to understand one fundamental fact No matter what the capabilities of the
browser, your C# code is always executed on the server The client-side frills are just the icing on the
cake
The NET Framework
As you’ve already learned, the NET Framework is really a cluster of several technologies:
The NET languages: These include Visual Basic, C#, F#, and C++
The Common Language Runtime (CLR): This is the engine that executes all NET programs and
provides automatic services for these applications, such as security checking, memory
management, and optimization
The NET Framework class library: The class library collects thousands of pieces of prebuilt
functionality that you can “snap in” to your applications These features are sometimes organized into technology sets, such as ADO.NET (the technology for creating database applications) and
Windows Presentation Foundation (WPF, the technology for creating desktop user interfaces)
ASP.NET: This is the engine that hosts the web applications you create with NET, and supports
almost any feature from the NET Framework class library ASP.NET also includes a set of
web-specific services, such as secure authentication and data storage
Visual Studio: This optional development tool contains a rich set of productivity and debugging
features Visual Studio includes the complete NET Framework, so you won’t need to download
it separately
Sometimes the division between these components isn’t clear For example, the term ASP.NET is
sometimes used in a narrow sense to refer to the portion of the NET class library used to design web
pages On the other hand, ASP.NET also refers to the whole topic of NET web applications, which
includes NET languages and many fundamental pieces of the class library that aren’t web-specific
(That’s generally the way we use the term in this book Our exhaustive examination of ASP.NET includes NET basics, the C# language, and topics that any NET developer could use, such as component-based programming and database access.)
Figure 1-4 shows the NET class library and CLR—the two fundamental parts of NET
Trang 39Figure 1-4 The NET Framework
Trang 40In the remainder of this chapter, you’ll take a quick look at the different ingredients that make up
the NET Framework
C#, VB, and the NET Languages
This book uses C#, Microsoft’s NET language of preference C# resembles Java and C++ in syntax, but no direct migration path exists from Java or C++
Interestingly, VB and C# are actually quite similar Though the syntax is different, both VB and C#
use the NET class library and are supported by the CLR In fact, almost any block of C# code can be
translated, line by line, into an equivalent block of VB code (and vice versa) An occasional language
difference pops up, but for the most part, a developer who has learned one NET language can move
quickly and efficiently to another
In short, both VB and C# are elegant, modern languages that are ideal for creating the next
generation of web applications
■ Note NET 1.0 introduced completely new languages However, the changes in subsequent versions of NET
have been more subtle Although the version of C# in NET 4 adds a few new features, most parts of the language remain unchanged In Chapter 2 and Chapter 3, you’ll sort through the syntax of C# and learn the basics of object-oriented programming
Intermediate Language
All the NET languages are compiled into another lower-level language before the code is executed This lower-level language is the Common Intermediate Language (CIL, or just IL) The CLR, the engine of
.NET, uses only IL code Because all NET languages are designed based on IL, they all have profound
similarities This is the reason that the VB and C# languages provide essentially the same features and
performance In fact, the languages are so compatible that a web page written with C# can use a VB
component in the same way it uses a C# component, and vice versa
The NET Framework formalizes this compatibility with something called the Common Language
Specification (CLS) Essentially, the CLS is a contract that, if respected, guarantees that a component
written in one NET language can be used in all the others One part of the CLS is the common type
system (CTS), which defines the rules for data types such as strings, numbers, and arrays that are shared
in all NET languages The CLS also defines object-oriented ingredients such as classes, methods, events, and quite a bit more For the most part, NET developers don’t need to think about how the CLS works, even though they rely on it every day
Figure 1-5 shows how the NET languages are compiled to IL Every EXE or DLL file that you build
with a NET language contains IL code This is the file you deploy to other computers In the case of a
web application, you deploy your compiled code to a live web server