Visual Studio 2005 24Visual Studio Web Projects 25Web Server Options 26Tutorial: Creating ASP.NET Web Forms 29Creating a Web Site in Visual Studio 30Adding a New Web Form 31Adding HTML C
Trang 2C ORE I NTERNET
Trang 4Upper Saddle River, NJ • Boston • Indianapolis • San Francisco
New York • Toronto • Montreal • London • Munich • Paris • MadridCapetown • Sydney • Tokyo • Singapore • Mexico City
Trang 5incidental or consequential damages in connection with or arising out of the use of the information or programs contained herein.
The publisher offers excellent discounts on this book when ordered in quantity for bulk purchases or special sales, which may include electronic versions and/or custom covers and content particular to your business, training goals, marketing focus, and branding interests For more information, please contact:
U.S Corporate and Government Sales
Visit us on the Web: www.prenhallprofessional.com
Library of Congress Cataloging-in-Publication Data
Connolly, Randy,
Core Web application development with ASP NET 2.0 / Randy Connolly.
p cm.
Includes bibliographical references and index.
ISBN 0-321-41950-2 (pbk : alk paper) 1 Active server pages 2.
Microsoft NET 3 Web servers 4 Web site development 5 Internet
programming I Title
TK5105.8885.A26C67 2007
005.2'76—dc22
2006037360
Copyright © 2007 Pearson Education, Inc.
All rights reserved Printed in the United States of America This publication is protected by copyright, and permission must be obtained from the publisher prior to any prohibited reproduction, storage in a retrieval system, or transmission in any form or by any means, electronic, mechanical, photocopying, recording, or likewise For information regarding permissions, write to:
Pearson Education, Inc.
Rights and Contracts Department
One Lake Street
Fax: (201) 236-3290
Upper Saddle River, NJ 07458
ISBN 0-321-41950-2
Text printed in the United States on recycled paper at Courier in Stoughton, Massachusetts.
First printing, February 2007
Trang 6To Diana, Alexander, Benjamin, and Norm.
With much love.
Trang 8Static Versus Dynamic Web Content 4
Competing Dynamic Server Technologies 5
Trang 9Visual Studio 2005 24Visual Studio Web Projects 25Web Server Options 26Tutorial: Creating ASP.NET Web Forms 29Creating a Web Site in Visual Studio 30Adding a New Web Form 31
Adding HTML Content to a Web Form 33Adding Programming Logic 39
Encountering Errors 43Using the Visual Studio Debugger 46Summary 50
Exercises 50Key Concepts 50References 51
C h a p t e r 2
HOW ASP.NET WORKS 53
ASP.NET Event Model 53Postback 55View State and Control State 57Page Lifecycle 58
ASP.NET Code Compilation 72Compilation Order 76The Page Class 78
Request 79Response 80Server 80ASP.NET Application Lifecycle 81User Requests ASP.NET Resource from Server 82ASP.NET Core Objects Are Created for the Request 88Assign HttpApplication Object to Request 89
Process Request Using HttpApplication Pipeline 92Summary 94
Exercises 94Key Concepts 94References 95
Trang 10Contents ix
C h a p t e r 3
WORKING WITH THE STANDARD
WEB SERVER CONTROLS 97
Introducing Server Controls 98
HTML Server Controls 98
Web Server Controls 98
Validation Controls 99
User Controls 99
Custom Server Controls 99
Overview of Web Server Controls 99
Common Members 101
Manipulating Properties Programmatically 104
The Essential Standard Web Server Controls 107
THE ADDITIONAL STANDARD
WEB SERVER CONTROLS 179
Overview of the Additional Standard Web Server Controls 180
Panel Control 182
Trang 11MultiView and View Controls 191Navigation Between Views 193Creating Tabbed Panels Using a MultiView 194Wizard Control 200
Using the Wizard Control 205Understanding the Layout of the Wizard Control 208Customizing the Wizard 210
Wizard Event Handling 219FileUpload Control 222
Processing the Uploaded File 225Limiting the Size of the Uploaded File 226PlaceHolder Control 227
Creating a File Browser 228AdRotator Control 237
Advertisement XML File 238Displaying Advertisements from a Database 239Programming the AdRotator 240
Xml Control 241Creating an XSLT File 243Programming the XML Control 247Summary 253
Exercises 254Key Concepts 254References 255
C h a p t e r 5
EXCEPTION HANDLING AND
VALIDATION CONTROLS 257
Error Handling 257.NET Exception Handling 258Exception Handling at the Class Level Using a try…catch Block 259Exception Handling at the Page Level 262Exception Handling at the Application Level 264Using the Validation Server Controls 271
ASP.NET Form Validation Process 273
Trang 12Changing the Appearance of Server Controls 311
Using Common Appearance Properties 312
Using CSS with Controls 314
Appearance Properties, CSS, and ASP.NET 319
Using Themes and Skins 320
Dynamically Setting the Theme 331
Creating a Sample Page with Two Themes 333
Master Pages 343
Defining the Master Page 347
Nested Master Pages 350
How Master Pages Work 353
Programming the Master Page 354
Master Pages and Themes 357
Trang 13User Controls 365Creating and Using User Controls 365Adding Data and Behaviors to the User Control 367Summary 369
Exercises 370Key Concepts 371References 371
C h a p t e r 7
ASP.NET SITE NAVIGATION 373
ASP.NET Site Navigation Overview 374Provider Model 375
XML Site Map 377Consuming the XML Site Map 378Programming the Site Map 383Using Different Site Maps 385Other Features of the Site Map 388SiteMapPath Control 388
Styling the SiteMapPath 390Integrating Query Strings into the SiteMapPath 393Menu Control 397
Using the Menu Control 401Changing the Appearance of the Menu 406Handling Menu Events 414
TreeView Control 421Understanding the TreeView Control 423Using the TreeView Control 426
Changing the Appearance of the TreeView 427Using Other Data with the TreeView Control 431Responding to TreeView Events 435
Summary 442Exercises 442Key Concepts 443References 444
Trang 14Contents xiii
P A R T I I
WORKING WITH DATA 445
C h a p t e r 8
DATA BINDING AND REPRESENTATION 447
Introducing Data Binding 448
How to Use Data Binding 448
What Can Be a Data Source? 449
Using the DataTable 475
Using the DataSet 481
Relating DataTables 486
XML Integration with the DataSet 488
Choosing a Data Container 495
.NET Collections as Data Containers 496
Custom Collections as Data Containers 496
DataSets as Data Containers 497
Typed DataSets as Data Containers 498
Choosing a Data Provider 506
Data Provider Classes 508
Trang 15DbConnection Classes 508Connection Strings 509Programming a DbConnection 511Storing Connection Strings 513Connection Pooling 515DbCommand Classes 515Creating a DbCommand 517SQL Commands for Retrieving, Adding, Updating, or Deleting Data 517Stored Procedures 519
Executing a DbCommand 520Using DbParameters 521Using Transactions 525DbDataReader Classes 529Programming a DbDataReader 530Implicit Connection Closing 532Tutorial: Reading and Updating Data 534DbDataAdapter Classes 544
Filling a DataSet 545Updating Data 547Data Provider-Independent ADO.NET Coding 550Data Source Controls 554
Using Parameters 557Modifying Data 560How Do Data Source Controls Work? 561Using the ObjectDataSource 562
Summary 574Exercises 574Key Concepts 575References 576
Trang 16Contents xv
Using General Templates 591
Linking Pages with the DataList 593
Customizing the DetailsView Fields 618
Modifying DetailsView Data 622
Editing Data within the GridView 651
Other GridView Tasks 655
Designing and Implementing a Business Object 674
Using the Business Object Programmatically 684
Using Business Objects with the ObjectDataSource 685
Four-Layer Model 689
Designing a Four-Layer Architecture 689
Modifying the Data Access Layer 692
Creating a Complex Domain Entity 696
Creating the Application Logic Layer 699
Using the Architecture in the Presentation Layer 702
Trang 17Summary 714Exercises 714Key Concepts 715References 716
C h a p t e r 1 2
MANAGING ASP.NET STATE 717
Client-Stored State 718View State 718Control State 722Hidden Fields 722Querystrings 723Cookies 723Application State 725The Global.asax File 726Session State 727
How Does Session State Work? 728Session State Providers 730
Profile Properties 737ASP.NET Cache 738Application Data Caching 738Cache Dependencies 743Page Output Caching 745Summary 748
Exercises 748Key Concepts 749References 749
Trang 18Contents xvii
The ASP.NET Security Process 758
Code Access Security and ASP.NET Trust Levels 760
ASP.NET Authentication 764
Forms Authentication 765
Using Forms Authentication 765
Creating a Login Form 768
How Forms Authentication Works 775
Using Cookieless Authentication Tickets 779
Provider Model 780
Provider Model Architecture 781
Creating Custom Providers 784
Membership 791
Overview of Membership System 792
Configuring the SqlMembershipProvider 793
Using the Membership API 796
Trang 19How Do Profiles Work? 840Saving and Retrieving Profile Data 842Using Custom Types 843
Working with Anonymous Users 846When to Use Profiles 852
Web Parts Framework 854Web Parts, Web Part Zones, and the Web Part Manager 856Creating and Using Web Parts 860
Making Web Parts from User Controls 867Making Web Parts from Custom Controls 872Changing the Different Display Modes 876Design Mode 878
Catalog Mode 880Edit Mode 883Web Part Connections 889Summary 903
Exercises 903Key Concepts 904References 904
C h a p t e r 1 5
WEB SERVICES 905
Introduction to Web Services 906Benefits of Web Services 907Consuming Web Services 909How to Consume a Web Service Using Visual Studio 909Consuming Web Services in a User Control 914
Consuming the Amazon Web Service 918Consuming Web Services and Performance 927Asynchronous Web Services 930
Creating Web Services 936Creating a Simple Quote Service 938Testing the Quote Service 943Creating a Web Service Front-End for Business
or Application Logic Classes 945Guidelines for Creating Web Services 947Summary 948
Trang 20INTERNATIONALIZATION AND DEPLOYMENT 951
Internationalizing a Web Application 952
Introducing Resource Files 952
Generating Resource Files 954
Localizing Resource Files 959
Precompiling a Web Site 975
Creating an Installation Program Using Web Setup Project 981
Setting Up the Test Page 1001
Enabling Partial Page Updates 1006
Using Atlas Control Extenders 1009
Summary 1015
References 1015
Trang 22Preface
“… the highest simplicity of structure is produced, not by a few elements,but by the highest complexity.”
—Ralph Waldo Emerson, “Goethe; or, the Writer,”
Representative Men, Chapter 8
In November 2005, version 2.0 of Microsoft’s NET Framework and ASP.NET wasreleased along with a new version of its Visual Studio development environment.This new version of ASP.NET significantly increased its power as well as its complex-ity When I first began teaching Web application development back in 1999 with clas-sic ASP, I could teach my students the essentials of ASP in just two weeks Of course,
to create a sample application of even moderate complexity in ASP required the dents to do a great deal of coding Now, with ASP.NET 2.0, it requires almost two-thirds of a semester to teach my students ASP.NET The students, however, now cancreate a sample application of substantial complexity That is, although ASP.NET 2.0can be complex, it can dramatically improve a Web developer’s productivity Thus, toparaphrase Emerson, after the developer has grasped and comprehended the seem-ing initial complexity of ASP.NET, he may very well be struck by its ultimate simplic-ity, even its beauty
stu-This book endeavors to help the reader make the transition from complexity tosimplicity That is, it tries to make the process of learning how to create realistic Webapplications using ASP.NET 2.0 less daunting for readers who are unfamiliar withASP.NET, as well as for readers who are somewhat familiar with ASP.NET but want
to learn how to use it more effectively
Trang 23As part of the process of learning how to create realistic Web applications, thisbook also endeavors to stress the importance of proper programming and designprinciples When first learning ASP.NET, a developer is often tempted to focus all
of her attention on using the many different Web server controls along with theVisual Studio Designer This is quite understandable given the range and power ofthese controls and the simplicity and functionality of Visual Studio However, asyou create more complex “real-world” Web applications, other considerations, such
as maintainability, scalability, and adaptability, become progressively more tant As a consequence, this book’s ultimate aim is to help the reader (you) becomenot only proficient with ASP.NET 2.0, but also to help you become a better Webapplication developer by also focusing on contemporary best practices in Webapplication development
impor-Target Audience
This book is intended first and foremost for professional developers who desire tolearn how to create Web applications using the latest version of Microsoft’sASP.NET Because I teach Web development at a college, this book is also intendedfor potential use in the classroom for upper-level students taking a course in Webapplication development using ASP.NET
Prerequisites
This book assumes that the reader already knows the basics of HTML and CSS Itdoes not assume any knowledge of ASP.NET or C# The book does assume that youare familiar with programming using an object-oriented language As a result, this
book does not provide detailed coverage of C# (for that, see Stephen Perry’s Core C#
and NET from Prentice Hall, 2006); instead, the book illustrates how to use C# in
conjunction with ASP.NET
The book also contains the occasional UML diagrams Although knowledge of theUML (Unified Modeling Language) may increase your understanding, it is by nomeans a necessity for this book This book also assumes that you are familiar in gen-eral with databases and XML
Approach
This book tries to provide you with a clear path to learning how to effectively andrealistically use ASP.NET 2.0 for creating Web applications Due to the sheer size ofASP.NET 2.0, a fair amount of book space is used just to teach the very basics of
Trang 24Preface xxiii
ASP.NET This book’s approach is to verge on the side of conciseness in regard to the
very basics in order to spend more time with the issues you typically face after you
master those basics
As should be no surprise in a book that is about software development, there is a
fair amount of programming code in this book Much of the code consists of very
short code snippets There are, however, the occasional longer code listings These
listings provide a more complex completed example, such as an RSS reader, a file
manager for uploading and downloading files, or a sample business object These
list-ings are all heavily commented so that you can learn not only from the book’s text,
but also from these longer code listings Most chapters also contain a few
walk-through exercises These are a set of step-by-step instructions for accomplishing
some task in ASP.NET
There are several possible pathways through each chapter A reader could focus
principally on the main text and its code snippets, and skip over the longer code
list-ings and the walkthrough exercises Other readers might prefer to first work through
a chapter’s walkthrough exercises, and then read through the text to extract a fuller
understanding of the chapter’s content Other readers might glance through the
chapter text, and then “read” the longer code listings
The book is structured so that a reader with no knowledge of ASP.NET can
progress linearly through the chapters, in that material in one chapter builds on
knowledge of the material presented in earlier chapters However, the material is
presented in such a way that a reader can take a more “random” approach, skipping
forward and backward to the material that is of interest to her
The approach and sequence of topics in this book were chosen principally as a
result of my experience teaching ASP.NET in the classroom to undergraduates, as
well as to professional developers It was also influenced by my own experiences
using ASP.NET professionally for real-world clients
Overview
This book is broken into three principal parts The first part is “Core ASP.NET,”
and consists of the first seven chapters of the book These chapters introduce and
explore the key fundamental features of ASP.NET The second part encompasses
the next five chapters: “Working with Data.” It focuses on perhaps the most
impor-tant aspect of any Web application: representing, extracting, manipulating, and
presenting data to the user The third and final part contains four chapters:
“Imple-menting Web Applications.” Its focus is the more advanced side of application
development with ASP.NET: security, personalization, Web services, and
localiza-tion and deployment
Chapter 1 introduces ASP.NET and the NET Framework It examines the
different components of the NET platform, compares ASP.NET to other Web
Trang 25development environments, describes the ASP.NET compilation model, examinesthe event system in ASP.NET, and illustrates how to create simple ASP.NET pagesusing Visual Studio 2005.
Chapter 2 continues the coverage of the basics of ASP.NET This chapter
exam-ines in depth how ASP.NET works It describes the event system in ASP.NET, thepage lifecycle, and the essential mechanisms of postback and view state It also cov-ers some more advanced topics that could be skipped and returned to after youbecome more comfortable with ASP.NET These topics include the ASP.NET com-pilation model, the Page class, as well as the application lifecycle
Chapter 3 provides an overview of ASP.NET’s Web server control architecture,
covers Web forms syntax, examines how to use the common features of all Webserver controls, and provides and illustrates how to use a core subset of the standardWeb server controls Because ASP.NET 2.0 now has so many Web server controls,some of the less frequently used core Web server controls are covered in Chapter 4
Chapter 4 continues the coverage of the standard Web server controls The
con-trols covered in this chapter are more complicated Some of the concon-trols covered inthis chapter include the Panel, MultiView, Wizard,FileUpload, and Xml con-trols Several of the longest code listings in the entire book are in this chapter
Chapter 5 covers one of the most important facets of Web application
develop-ment, namely, how to deal with exceptions, both at the language level and at theASP.NET level It also illustrates how to use the ASP.NET validation controls
Chapter 6 examines how to create complex user interfaces using styles,
themes, skins, and master pages The chapter also covers the creation of your ownuser controls
Chapter 7 examines how to describe and create a site’s navigation system using
the ASP.NET site navigation controls
Chapter 8 is the first chapter of the second part of the book ASP.NET 2.0
intro-duces a new way of working with data and this chapter’s focus is on the different waysthat data can be represented It covers data binding, arrays, collections, generics, anddata sets
Chapter 9 continues the material from Chapter 8 by examining how to
program-matically and declaratively work with data in databases This chapter begins by ining how to access and modify data within databases in ASP.NET using the classes
exam-of ADO.NET The chapter also covers the codeless approach to accessing data usingthe data source controls introduced in version 2.0 of ASP.NET
Chapter 10 illustrates how to use the various data controls in ASP.NET It
illus-trates the use of the Repeater,DataList,FormView,DetailsView, and View controls Each of these controls uses data binding to display (and for some evenedit) multiple sets of data in different ways
Grid-Chapter 11 shifts the focus away from individual controls and classes and
instead examines some of the issues involved in creating a more complex Webapplication with ASP.NET It begins with the design of Web applications and some
Trang 26Preface xxv
common layering models for Web applications, and then moves on to implement
two sample layered architectures
Chapter 12 covers an aspect of ASP.NET that is vital for any Web application:
managing state This chapter begins with the various types of ASP.NET state whose
data is stored on the client, such as view state and cookies It then moves on to those
state mechanisms whose data is stored in the server: session state, application state,
and finally the ASP.NET cache
Chapter 13 is the first chapter of the final part of the book It covers security, one
of the most important aspects of any Web application It discusses authentication and
authorization in the context of ASP.NET, illustrates how to use the various login
con-trol as well as the new provider system, including the membership and role
manage-ment providers
Chapter 14 examines two mechanisms in ASP.NET 2.0 for integrating user
per-sonalization into a Web application: namely, the profile system and the Web part
framework The profile system allows an application to persist user information
across time and multiple pages The Web part framework provides the developer
with a mechanism for creating pages in which the user can customize the placement,
appearance, and possibly the behavior of the page’s content
Chapter 15 looks at how to synchronously and asynchronously consume Web
ser-vices in ASP.NET The chapter also demonstrates how to construct Web serser-vices
Chapter 16 demonstrates how to plan and adapt an ASP.NET application for an
international audience, as well as the various ways to deploy a completed ASP.NET
Web application
The Appendix provides a preliminary examination of ASP.NET AJAX, which up
until the fall of 2006 was known by the code-name Atlas ASP.NET AJAX is a free
framework from Microsoft that adds Asynchronous JavaScript and XML (AJAX)
support to ASP.NET ASP.NET AJAX encompasses a fairly large set of functionality
that integrates client script (Javascript) libraries with ASP.NET server-based pages
It provides an API for working with Javascript, a declarative alternative to working
with Javascript, rich client-script components, along with special Atlas server-side
controls
Supplementary Materials
The Web site for this book is http://www.randyconnolly.com/core It contains
• The source code for all the examples in the book
• All databases, images, and style sheets used in the chapter examples
• Solutions to the practice exercises that are at the end of each chapter
• A list of known errors in the book and the code
• A form for submitting corrections and suggestions
• Downloadable versions of additional or updated appendices
Trang 27This book is also intended for potential use in the classroom for upper-level dents taking a course in Web application development using ASP.NET For educa-tors who adopt this book for their courses, the following material is available fromthis same site:
stu-• Powerpoint lectures for each chapter
• Recommended syllabi and detailed lesson plans for half-semester courses
• Assignments and course projects
• Multiple-choice, short-answer, and long-answer examination questions
• Laboratory tutorials
Prentice Hall also maintains a book Web page that contains additional tion: www.prenhallprofessional.com/title/0321419502
Trang 28Acknowledgments
This book took almost exactly one year to the day to write During this time, I
incurred numerous obligations to which I am now very grateful to have the
opportu-nity to acknowledge First, I would like to thank my editor Joan Murray for taking a
chance and giving me this chance Thank you as well to some of the other people at
Pearson Education who helped with the editing and production of this book,
includ-ing Jessica D’Amico, Kelli Brooks, Sean Donahue, Vanessa Moore, and Julie Nahil I
am also thankful for the initial encouragement I received from Shannon Bailey,
senior sales representative for Pearson Education
One of the pleasures of writing a book like this is that you receive feedback from
technical reviewers I am thankful to the following reviewers: Robin Pars and Jerry
Maresca Cay Horstmann and J Ambrose Little were particularly diligent and
insightful reviewers, and I am extra grateful to them
As I wrote this book, I realized that I was ignorant of many things On numerous
occasions, this ignorance was somewhat rectified by the many excellent articles and
blogs of the following people: K Scott Allen, Dino Esposito, Martin Fowler, Scott
Guthrie, Jimmy Nilsson, Fritz Onion, Ted Pattison, Scott Mitchell, and Rick Strahl
During this past year, I continued with my full-time teaching responsibilities My
work life was made more manageable by my two department chairs during this time,
Judy Gartaganis and Bill Paterson My stress levels during the year were thankfully
often alleviated by my colleague, Paul Pospisil I am also thankful for the support of
the Mount Royal College 2005/6 Research Reserve Fund, which funded a reduction
in my teaching load
Trang 29I have had many excellent students over the years Many of my students havehelped, perhaps without realizing it, in both the planning and implementation of thisbook, and to them I continue to be both inspired and grateful.
Finally, and most importantly, I must acknowledge the support of my family Mywife Diana and my children Alexander and Benjamin saw very little of me the past sixmonths In the final difficult last three months, I was always motivated by my desire
to spend time with them again, as well as continually encouraged to create somethingworthy of their respect
— Randy Connolly
January 2007
One of the pleasures of writing a book such as this is that you receive back from technical reviewers I am thankful to the following reviewers: Robin Pars, [other reviewers here since I do not know their names] Cay Horstmann and J Ambrose Little were particularly diligent and insightful
feed-reviewers and I am extra grateful to them
As I wrote this book, I realized that I was ignorant of many things On numerous occasions, this ignorance was somewhat rectified by the many excellent articles and blogs of the following people: K Scott Allen, Dino Esposito, Martin Fowler, Scott Guthrie, Jimmy Nilsson, Fritz Onion, Ted
Pattison, Scott Mitchell, and Rick Strahl
During this past year I still had my full-time teaching responsibilities My work life was made more manageable by my two Department Chairs dur- ing this time, Judy Gartaganis and Bill Paterson My stress levels during the year were thankfully often alleviated by my colleague, Paul Pospisil I am also thankful for the support of the Mount Royal College 2005/6 Research Reserve Fund which funded a reduction in my teaching load
I have had many excellent students over the years Many of my students have helped, perhaps without realizing it, in both the planning and imple- mentation of this book, and to them I continue to be both inspired and
Trang 30About the Author
Randy Connolly teaches Computer Science students at Mount Royal College in
Calgary, Canada He has been with the Computer Science and Information Systems
department since 1997 He takes great pride in teaching tomorrow’s talented young
developers He specializes in teaching Web application development, games
devel-opment, and object-oriented design His extensive experience and expertise in
ASP.NET comes from a combination of teaching and work in the professional sector
Connolly spent more than eight years developing Web sites for international clients
and more than sixteen years doing corporate software development He has been the
recipient of the Canadian Social Science and Humanities Research Council Doctoral
fellowship grant and the Petro-Canada Innovation in Research and Teaching Award
(1998 and 2003)
Trang 34ASP.NET 2.0
“The true beginning of our end.”
—William Shakespeare, A Midsummer Night’s Dream
The end goal of this book is to teach and guide the reader through the increasinglylarge topic of Web application development using ASP.NET 2.0 The true beginning ofthis end then is to introduce ASP.NET in a reasonably manageable fashion This chap-ter begins this journey by answering the question, “Why ASP.NET?” That is, it explainswhy ASP.NET was developed and examines the advantages it provides As part of theanswer to this question, the chapter looks at other competing technologies as well asprovides an overview of the NET Framework The chapter briefly introduces thenature and structure of ASP.NET, illustrates how to use Microsoft Visual Studio 2005,and then finishes with a number of tutorial walkthroughs for creating some sampleASP.NET Web Forms using Visual Studio In sum, this first chapter is strictly introduc-tory; in-depth coverage of how ASP.NET works is left to the next chapter
Why ASP.NET?
Released in November 2005, ASP.NET 2.0 is the current version of ASP.NET,Microsoft’s powerful technology for creating dynamic Web content ASP.NET is one
Trang 35of the key components of Microsoft’s NET Framework, which is both a ment framework and software platform ASP.NET 1.0 and 1.1, initially released in
develop-2002, replaced Microsoft’s older but still quite popular ASP (Active Server Pages)technology This section provides an overview of ASP.NET It begins by describingdynamic server technology in general, moves on to a brief examination of competingdynamic technologies, and then highlights the key features of ASP.NET
Static Versus Dynamic Web Content
Over the past 10 years, the Internet has evolved from a hypertextual information tem offering static information to a marketplace for the buying and selling of goodsand services, and now to a widely used infrastructure for the development and host-ing of software applications within organizations Thus, over time, the Internet hasmoved from principally static page content to dynamically generated content via pro-grams running on Web servers That is, most Web pages that you view are not staticHTML pages but are instead the output from programs that run on servers and thatinteract with server resources like databases and XML Web services Figures 1.1 and1.2 illustrate the differences between static and dynamic Web content
sys-Figure 1.1 Static Web content
Web Server
1 Browser requests index.htm from server
2 Server responds by sending content of index.htm to browser
3 Browser renders (displays) requested content
Trang 36Why ASP.NET? 5
Competing Dynamic Server Technologies
There are quite a number of different technologies for dynamically generating Web
content All of these technologies share one thing in common: Using programming
logic, they generate HTML on the server and send it back to the requesting browser
Yet despite this essential similarity, we can categorize dynamic technology into three
broad types:
• Direct output
• Page scripting
• Hybrid
The first technologies for generating dynamic Web content were of the direct
output type CGI and Java servlets are examples of this type With this approach,
programmers had to write the code for directly outputting each and every HTML
line back to the client, as in the following Java servlet code
Figure 1.2 Dynamic Web content
Web Server
1 Browser requests program from server
3 Program runs, gets information about the request from the server, interacts with server resources such as databases, and generates response (HTML and Javascript) that is sent back to browser
4 Browser renders content
program
2 Server recognizes request as program or script
Trang 37public class HelloWorld extends HttpServlet
For this reason, Web developers largely left the direct output approach behindwhen a new approach became available in the later 1990s with Microsoft’s ASP andthe open-source PHP (PHP Hypertext Preprocessor) We might call the approach
used in ASP and PHP a page scripting approach That is, each Web page is a
sepa-rate ASP or PHP script file The key to the page scripting approach is that thesescript files contain both regular HTML markup as well as programming logic con-tained within some special tag (<% … %> for ASP, <?php … ?> for PHP), as shown inthe following sample ASP code
Trang 38cre-Why ASP.NET? 7
site of pages) becomes progressively more complex, the page scripting approach
can become progressively harder to maintain, change, and debug The term
spa-ghetti code doesn’t quite do justice to the tangled labyrinthine convolutions of a
two-thousand-line-long ASP or PHP page A complex, poorly written ASP or PHP
page can be a nightmare to maintain, because it usually mixes user interface markup,
presentation logic, data access logic, and business or application logic all within the
same page (though one can certainly use server-side includes and other mechanisms
in ASP or PHP to create more maintainable pages)
Another related drawback is that the languages used in ASP (usually VBScript)
and PHP (up until the more recent PHP 5) lack modern programming features such
as inheritance and structured exception handling As well, both VBScript and PHP
are interpreted scripting languages This means that the server has to decode each
line of programming code in the page for every single request As a result, complex
ASP or PHP pages with lots of programming logic that are heavily requested could
be quite slow (though there are PHP compilers available that can mitigate this
partic-ular drawback)
Finally, another drawback (though to many it certainly is an advantage) to the
page scripting model is its simplicity The problem with simplicity here is that both
ASP and PHP provide only a bare minimum of built-in functionality and services
This makes these technologies easy to learn; however, almost everything requires
programming due to the minimal services they provide the developer As a result,
almost every common task in a dynamic Web page requires programming The
typi-cal ASP or PHP page often has a great deal of repetitive code for common tasks such
as populating an HTML select list with field values from a database table or for
val-idating form input In other words, what is lacking in the page scripting approach are
simplified abstractions that encapsulate these very common Web development tasks
and which would therefore reduce the amount of coding needed to create the typical
dynamic Web page
These drawbacks are addressed (though in different ways) in the most current
dynamic server technology approach, which we might call the hybrid approach.
Sun’s JSP (JavaServer Pages) and related technologies such as JavaServer Faces
and Struts, Adobe’s (originally Macromedia’s) ColdFusion, open-source Ruby on
Rails, and Microsoft’s ASP.NET combine, in varying degrees, the programming
flexibility and the execution speed of the direct output approach, with the ease of
the page scripting model, and add common Web programming functionality via
proprietary tags ColdFusion uses a rich tag-based language that minimizes the
amount of necessary coding JSP initially used a fairly minimal set of built-in tags,
although it did provide a mechanism (custom tags) for creating new tags; instead,
JSP allows a programmer to use Java to implement contemporary software design
best practices to create Web sites that are more maintainable and extensible
ASP.NET also allows the developer to use contemporary software design best
prac-tices, but adds a rich set of built-in tags (plus the capability to create new ones) that
encapsulate many common Web tasks
Trang 39CORE NOTE
You may wonder whether Adobe Flash is also an example of dynamic
server technology It is not Flash objects are downloaded to the browser,
and if the Flash plugin is installed, it executes on the browser Although a
Flash object can interact with server resources, it does not execute on
• Smoother deployment and configuration
ASP.NET provides better performance over ASP because ASP.NET pages arecompiled (the code compilation model is covered in detail later in Chapter 2) It isalso a significantly more powerful development environment It uses fully object-oriented languages that work with a rich class library along with a very complete set
of server-based controls that encapsulate common Web functionality that cantly reduces the amount of coding for Web developers
signifi-ASP.NET sites can be easier to maintain because developers can use current bestpractices in software design and engineering As well, because ASP.NET handlesmuch of the logic necessary for producing correct output for different devices (forinstance, Internet Explorer, FireFox, or old Netscape browsers), it can reduce theamount of maintenance work required to test and fine-tune your pages for differentoutput devices
Finally, ASP.NET provides a smooth deployment experience Due to the ture of the NET Framework (covered next), deploying ASP.NET applications nowgenerally only involves uploading files The NET applications and components donot need to be registered with the Windows registry, so there is no more “DLL Hell.”
architec-As well, ASP.NET simplifies the configuration experience by providing XML-basedconfiguration files as well as an integrated security system
.NET Framework
Many of the advantages that ASP.NET provides in comparison to other dynamic Web
technologies are a result of its integration into Microsoft’s NET Framework The
Trang 40.NET Framework 9
.NET Framework is a development framework that provides a new programming
interface to Windows services and APIs, and integrates a number of technologies
that emerged from Microsoft during the late 1990s The NET Framework is also a
software platform for the running and deployment of Windows-based software
sys-tems (though other operating syssys-tems can in theory be targeted)
The core features of the NET Framework are as follows:
• Language interoperability—A software system can be created using any
combination of the available NET languages You can thus use the NET
language that you feel most comfortable and productive with (although for
this book we use C# only) The NET Framework makes this possible with a
specification called the CTS (Common Type System), to which all NET
compilers must adhere
• Fully object-oriented languages—To better compete with Java and to better
reflect current software development methodologies, all NET languages
are fully object oriented
• Common runtime engine shared by all languages—For there to be language
interoperability, a common runtime engine is needed to locate and load
.NET data types, as well as handle memory management, provide security
sandboxing, and ensure type-safety
• Base class library usable by all languages—The NET Framework provides a
rich and consistent set of classes for performing typical software tasks
(draw-ing user interface widgets, interact(draw-ing with data, communicat(draw-ing across a
network, etc)
• Simplified deployment—With NET, there is no longer any need to register
components (via the registry), and thus there are fewer deployment
prob-lems in comparison to older Windows-based applications
• Better security—.NET provides code-access security as well as a general
security context via the NET runtime environment
• Better performance—.NET languages are compiled into an intermediary
machine-independent format, which in turn is Just-In-Time (JIT) compiled
into CPU-specific binary code; as such, it provides superior performance
This JIT-compiled code is also optimized for the specific processor(s) on
which it is running
CORE NOTE
In June 2006, Microsoft combined a number of new Windows
development technologies and branded them as the NET Framework
3.0 This NET Framework 3.0 includes Windows CardSpace, Windows
Communication Foundation (formerly Indigo), Windows Presentation
Foundation (formerly Avalon), Windows Workflow Foundation (formerly