Contents
Preface xxi Acknowledgments About the Author
xxvii xxix
PART I
CORE ASP.NET 1
Chapter 1
INTRODUCING ASP.NET 2.0 3
Why ASP.NET? 3 Static Versus Dynamic Web Content 4 Competing Dynamic Server Technologies ASP.NET Advantages 8 .NET Framework 8 Components of .NET Framework 10 .NET Execution 14 ASP.NET Web Forms 15 C# Language 21 Web Application Structure 21
5
vii
viii
Contents
Visual Studio 2005 24 Visual Studio Web Projects 25 Web Server Options 26 Tutorial: Creating ASP.NET Web Forms 29 Creating a Web Site in Visual Studio 30 Adding a New Web Form 31 Adding HTML Content to a Web Form 33 Adding Programming Logic 39 Encountering Errors 43 Using the Visual Studio Debugger 46 Summary 50 Exercises 50 Key Concepts 50 References 51
Chapter 2
HOW ASP.NET WORKS 53
ASP.NET Event Model 53 Postback 55 View State and Control State 57 Page Lifecycle 58 ASP.NET Code Compilation 72 Compilation Order 76 The Page Class 78 Request 79 Response 80 Server 80 ASP.NET Application Lifecycle 81 User Requests ASP.NET Resource from Server 82 ASP.NET Core Objects Are Created for the Request Assign HttpApplication Object to Request 89 Process Request Using HttpApplication Pipeline 92 Summary 94 Exercises 94 Key Concepts 94 References 95
88
Contents
ix
Chapter 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 The Essential Standard Web Server Controls Label Control 108 Literal Control 110 TextBox Control 112 Button-Style Controls 115 CheckBox Control 123 RadioButton Control 126 List-Style Controls 127 Image Control 138 ImageMap Control 141 HyperLink Control 145 HiddenField Control 147 Table Control 149 Calendar Control 158 Summary 177 Exercises 177 Key Concepts 177 References 178
104 107
Chapter 4
THE ADDITIONAL STANDARD WEB SERVER CONTROLS 179
Overview of the Additional Standard Web Server Controls Panel Control 182 180
x
Contents
MultiView and View Controls 191 Navigation Between Views 193 Creating Tabbed Panels Using a MultiView 194 Wizard Control 200 Using the Wizard Control 205 Understanding the Layout of the Wizard Control 208 Customizing the Wizard 210 Wizard Event Handling 219 FileUpload Control 222 Processing the Uploaded File 225 Limiting the Size of the Uploaded File 226 PlaceHolder Control 227 Creating a File Browser 228 AdRotator Control 237 Advertisement XML File 238 Displaying Advertisements from a Database 239 Programming the AdRotator 240 Xml Control 241 Creating an XSLT File 243 Programming the XML Control 247 Summary 253 Exercises 254 Key Concepts 254 References 255
Chapter 5
EXCEPTION HANDLING AND VALIDATION CONTROLS 257
Error Handling 257 .NET Exception Handling 258 Exception Handling at the Class Level Using a try…catch Block 259 Exception Handling at the Page Level 262 Exception Handling at the Application Level Using the Validation Server Controls 271 ASP.NET Form Validation Process 273
264
Contents
xi
RequiredFieldValidator Control 280 ValidationSummary Control 282 CompareValidator Control 284 RangeValidator Control 287 RegularExpressionValidator Control 288 CustomValidator Control 296 Validation Groups 302 Summary 309 Exercises 309 Key Concepts 309 References 310
Chapter 6
CUSTOMIZING AND MANAGING YOUR SITE’S APPEARANCE 311
Changing 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 Defining Skins 321 Creating Themes in Visual Studio 322 Applying a Theme 324 How Themes Work 324 Overriding Themes 325 Named Skins 326 Themes and Images 327 Themes and CSS 328 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
xii
Contents
User Controls 365 Creating and Using User Controls 365 Adding Data and Behaviors to the User Control Summary 369 Exercises 370 Key Concepts 371 References 371
367
Chapter 7
ASP.NET SITE NAVIGATION 373
ASP.NET Site Navigation Overview 374 Provider Model 375 XML Site Map 377 Consuming the XML Site Map 378 Programming the Site Map 383 Using Different Site Maps 385 Other Features of the Site Map 388 SiteMapPath Control 388 Styling the SiteMapPath 390 Integrating Query Strings into the SiteMapPath 393 Menu Control 397 Using the Menu Control 401 Changing the Appearance of the Menu 406 Handling Menu Events 414 TreeView Control 421 Understanding the TreeView Control 423 Using the TreeView Control 426 Changing the Appearance of the TreeView 427 Using Other Data with the TreeView Control 431 Responding to TreeView Events 435 Summary 442 Exercises 442 Key Concepts 443 References 444
Contents
xiii
PART II
WORKING WITH DATA 445
Chapter 8
DATA BINDING AND REPRESENTATION 447
Introducing Data Binding 448 How to Use Data Binding 448 What Can Be a Data Source? 449 Using Collections 450 Collection Interfaces 451 Using the Common Collections 453 ArrayList 456 Generics 461 Dictionary Collections 465 Creating Your Own Generic Collection 468 DataSet 472 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 Summary 499 Exercises 499 Key Concepts 500 References 500
Chapter 9
USING ADO.NET 503
Introducing ADO.NET 503 Choosing a Data Provider 506 Data Provider Classes 508
xiv
Contents
DbConnection Classes 508 Connection Strings 509 Programming a DbConnection 511 Storing Connection Strings 513 Connection Pooling 515 DbCommand Classes 515 Creating a DbCommand 517 SQL Commands for Retrieving, Adding, Updating, or Deleting Data 517 Stored Procedures 519 Executing a DbCommand 520 Using DbParameters 521 Using Transactions 525 DbDataReader Classes 529 Programming a DbDataReader 530 Implicit Connection Closing 532 Tutorial: Reading and Updating Data 534 DbDataAdapter Classes 544 Filling a DataSet 545 Updating Data 547 Data Provider-Independent ADO.NET Coding 550 Data Source Controls 554 Using Parameters 557 Modifying Data 560 How Do Data Source Controls Work? 561 Using the ObjectDataSource 562 Summary 574 Exercises 574 Key Concepts 575 References 576
Chapter 10
DATA CONTROLS 577
577 Introducing the Multivalue Data Controls Understanding Templates 582 Data-Binding Expressions 584 DataList Control 587
Contents
xv
Using General Templates 591 Linking Pages with the DataList 593 Repeater Control 595 FormView Control 599 Moving from Record to Record 602 Modifying Data 604 DetailsView Control 614 Customizing the DetailsView Fields 618 Modifying DetailsView Data 622 GridView Control 626 Customizing the GridView Columns 629 Selecting Rows 639 GridView Pagination 645 GridView Sorting 648 Editing Data within the GridView 651 Other GridView Tasks 655 Summary 663 Exercises 663 Key Concepts 664 References 664
Chapter 11
DESIGNING AND IMPLEMENTING WEB APPLICATIONS
Designing an Application 666 Using Layers 667 Consequences of Layering 669 Two-Layer Model 670 Three-Layer Model 673 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
665
xvi
Contents
Summary 714 Exercises 714 Key Concepts 715 References 716
Chapter 12
MANAGING ASP.NET STATE 717
Client-Stored State 718 View State 718 Control State 722 Hidden Fields 722 Querystrings 723 Cookies 723 Application State 725 The Global.asax File 726 Session State 727 How Does Session State Work? Session State Providers 730 Profile Properties 737 ASP.NET Cache 738 Application Data Caching 738 Cache Dependencies 743 Page Output Caching 745 Summary 748 Exercises 748 Key Concepts 749 References 749
728
PART III
IMPLEMENTING WEB APPLICATIONS 751
Chapter 13
SECURITY, MEMBERSHIP, AND ROLE MANAGEMENT
Introduction to ASP.NET Security 754 Overview of IIS Security 755
753
Contents
xvii
The ASP.NET Security Process 758 Code Access Security and ASP.NET Trust Levels 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 Role Management 803 Role Provider 803 Managing Roles 803 Using the Role Management API 806 Login Controls 814 Login Control 814 LoginName Control 820 LoginStatus Control 821 LoginView Control 822 ChangePassword Control 824 PasswordRecovery Control 826 CreateUserWizard Control 828 Summary 829 Exercises 830 Key Concepts 830 References 831
760
Chapter 14
PERSONALIZATION WITH PROFILES AND WEB PARTS
ASP.NET Profiles 834 Defining Profiles 834 Using Profile Data 836
833
xviii
Contents
How Do Profiles Work? 840 Saving and Retrieving Profile Data 842 Using Custom Types 843 Working with Anonymous Users 846 When to Use Profiles 852 Web Parts Framework 854 Web Parts, Web Part Zones, and the Web Part Manager Creating and Using Web Parts 860 Making Web Parts from User Controls 867 Making Web Parts from Custom Controls 872 Changing the Different Display Modes 876 Design Mode 878 Catalog Mode 880 Edit Mode 883 Web Part Connections 889 Summary 903 Exercises 903 Key Concepts 904 References 904
856
Chapter 15
WEB SERVICES 905
Introduction to Web Services 906 Benefits of Web Services 907 Consuming Web Services 909 How to Consume a Web Service Using Visual Studio Consuming Web Services in a User Control 914 Consuming the Amazon Web Service 918 Consuming Web Services and Performance 927 Asynchronous Web Services 930 Creating Web Services 936 Creating a Simple Quote Service 938 Testing the Quote Service 943 Creating a Web Service Front-End for Business or Application Logic Classes 945 Guidelines for Creating Web Services 947 Summary 948
909
Contents
xix
Exercises 949 Key Concepts 950 References 950
Chapter 16
INTERNATIONALIZATION AND DEPLOYMENT 951
Internationalizing a Web Application 952 Introducing Resource Files 952 Generating Resource Files 954 Localizing Resource Files 959 Global Resources 964 Page-Level Culture Settings 966 Deployment 972 Manually Copy Files from Development to Deployment Machine 972 Precompiling a Web Site 975 Creating an Installation Program Using Web Setup Project Summary 987 Exercises 988 Key Concepts 988 References 988
981
Appendix
ASP.NET AJAX SNEAK PEEK 991
Introducing Atlas 992 Installing Atlas 994 Atlas Architecture 996 Atlas Server Features 1000 Using Atlas 1001 Setting Up the Test Page 1001 Enabling Partial Page Updates 1006 Using Atlas Control Extenders 1009 Summary 1015 References 1015
Index
1017
This page intentionally left blank
Part
I
Core ASP.NET
■ ■ ■ ■ ■ ■ ■
Chapter 1 Introducing ASP.NET 2.0 3 Chapter 2 How ASP.NET Works 53 Chapter 3 Working with the Standard Web Server Controls 97
Chapter 4 The Additional Standard Web Server Controls 179 Chapter 5 Exception Handling and Validation Controls 257
Chapter 6 Customizing and Managing Your Site’s Appearance 311 Chapter 7 ASP.NET Site Navigation 373
1
This page intentionally left blank
Chapter
INTRODUCING ASP.NET 2.0
1
“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 increasingly large topic of Web application development using ASP.NET 2.0. The true beginning of this end then is to introduce ASP.NET in a reasonably manageable fashion. This chapter begins this journey by answering the question, “Why ASP.NET?” That is, it explains why ASP.NET was developed and examines the advantages it provides. As part of the answer to this question, the chapter looks at other competing technologies as well as provides an overview of the .NET Framework. The chapter briefly introduces the nature 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 sample ASP.NET Web Forms using Visual Studio. In sum, this first chapter is strictly introductory; 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
3
4
Chapter 1
Introducing ASP.NET 2.0
of the key components of Microsoft’s .NET Framework, which is both a development framework and software platform. ASP.NET 1.0 and 1.1, initially released in 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 describing dynamic server technology in general, moves on to a brief examination of competing dynamic 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 system offering static information to a marketplace for the buying and selling of goods and services, and now to a widely used infrastructure for the development and hosting of software applications within organizations. Thus, over time, the Internet has moved from principally static page content to dynamically generated content via programs running on Web servers. That is, most Web pages that you view are not static HTML pages but are instead the output from programs that run on servers and that interact with server resources like databases and XML Web services. Figures 1.1 and 1.2 illustrate the differences between static and dynamic Web content.
1. Browser requests index.htm from server
Web Server
2. Server responds by sending content of index.htm to browser
3. Browser renders (displays) requested content
Figure 1.1
Static Web content
Why ASP.NET?
5
1. Browser requests program from server
Web Server
program
2. Server recognizes request as program or script
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
Figure 1.2
Dynamic Web content
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.
6
Chapter 1
Introducing ASP.NET 2.0
public class HelloWorld extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) { response.setContentType("text/html"); PrintWriter out = response.getWriter(); out.println(""); out.println("
Sample"); out.println(""); out.println("
Date Tester
"); out.println("The date is "); java.util.Date aDate = new java.util.Date(); out.println(aDate.ToString()); out.println(""); out.println(""); } }
The key advantage of this approach is fast execution time, because these programs could usually be compiled to binary (or byte code for the Java servlets). However, its main drawback is that any change in the design of a Web page, no matter how minor, requires the intervention of a programmer, who must make the change, recompile the code, and perhaps turn off the server to deploy. For this reason, Web developers largely left the direct output approach behind when a new approach became available in the later 1990s with Microsoft’s ASP and the 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 separate ASP or PHP script file. The key to the page scripting approach is that these script files contain both regular HTML markup as well as programming logic contained within some special tag (<% … %> for ASP, for PHP), as shown in the following sample ASP code.
Sample The time is now
<% = Time %> <% if hour(now) < 8 then %> It is
too early in the morning <% else %> Good day <% end if %>
Both ASP and PHP have a fairly quick learning curve and can be used to create quite complex sites. However, the page scripting approach does have a number of drawbacks. The principal of these drawbacks is that as a page (or a whole
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 spaghetti 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 particular 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 typical 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 validating 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 practices, but adds a rich set of built-in tags (plus the capability to create new ones) that encapsulate many common Web tasks.
8
Chapter 1
Introducing ASP.NET 2.0
CORE 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 the server.
ASP.NET Advantages
ASP.NET provides a number of advantages compared to Microsoft’s earlier, “classic” ASP technology. These advantages are • • • • Better performance More powerful development environment Easier maintenance Smoother deployment and configuration
ASP.NET provides better performance over ASP because ASP.NET pages are compiled (the code compilation model is covered in detail later in Chapter 2). It is also a significantly more powerful development environment. It uses fully objectoriented languages that work with a rich class library along with a very complete set of server-based controls that encapsulate common Web functionality that significantly reduces the amount of coding for Web developers. ASP.NET sites can be easier to maintain because developers can use current best practices in software design and engineering. As well, because ASP.NET handles much of the logic necessary for producing correct output for different devices (for instance, Internet Explorer, FireFox, or old Netscape browsers), it can reduce the amount of maintenance work required to test and fine-tune your pages for different output devices. Finally, ASP.NET provides a smooth deployment experience. Due to the architecture of the .NET Framework (covered next), deploying ASP.NET applications now generally only involves uploading files. The .NET applications and components do not need to be registered with the Windows registry, so there is no more “DLL Hell.” As well, ASP.NET simplifies the configuration experience by providing XML-based configuration 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
.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 systems (though other operating systems 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 (drawing user interface widgets, interacting with data, communicating 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 problems 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
10
Chapter 1
Introducing ASP.NET 2.0
WinFx), as well the .NET Framework 2.0. Thus, .NET Framework 3.0 rather confusedly contains the current version of the .NET Framework, which at present is still version 2.0.
Components of .NET Framework
The .NET Framework sits on top of the Windows operating system, and consists of the three fundamental components shown in Figure 1.3.
Compilers Component1
Base Class Library Package1 Common Language Runtime
Figure 1.3
Components of the .NET Framework
Language Compilers
Initially, perhaps the most trumpeted aspect of the .NET Framework is that the various .NET languages can interoperate. Language interoperability means that you can use multiple .NET languages within a single .NET application. Microsoft provides Visual Basic.NET (VB.NET), C#, JScript.NET, C++, and J++. The two most popular choices are VB.NET and C#. Other .NET languages are available from third parties. Although it is certainly possible to create a .NET application using multiple languages, this does not happen all that frequently. From this author’s experience, most .NET applications are written using a single language, because this generally makes an application easier to maintain and support in the long run. Language interoperability is, however, often utilized whenever a .NET application makes use of someone else’s compiled class libraries. For instance, the base class library classes that are part of .NET are written in C#, but can be used just as easily by a Visual Basic .NET application as a C# application. How is this language interoperability possible? It is possible because all .NET language must follow the rules in the Common Language Specification (CLS). These
.NET Framework
11
rules define a subset of common data types and programming constructs that all .NET languages must support (although a language can contain additional types and constructs that are not specified by the CLS). You can use any CLS-compliant language in a .NET application. The different .NET languages can work together because they are compiled into a common format. No matter what programming language is used, all code is compiled into Microsoft Intermediate Language (MSIL), also called Common Intermediate Language (CIL or simply IL), rather than binary. MSIL is a CPU-independent virtual machine language analogous to Java’s bytecode. It consists of CPU-independent instructions for loading/storing information and calling methods. MSIL is not itself interpreted or executed. Instead, the Common Language Runtime (CLR, covered shortly) converts the MSIL into managed native binary code at runtime using the Just-In-Time compiler as methods are called; alternately, the entire assembly can be precompiled to native code by the runtime at install time. Figure 1.4 illustrates this process.
Source
.NET Language Compiler
MSIL
JIT Compiler
Machine Code
Figure 1.4 General compilation process
MSIL is physically stored within special containers called assemblies. Although these assemblies have familiar extensions (e.g., DLL or EXE), they are quite different from traditional Windows DLL or EXE files. A .NET assembly contains not only MSIL instructions; it also contains a collection of metadata that includes type definitions, version information, external assembly references, and other standardized information. This metadata allows different components, tools, and runtimes to work together. The CLR uses this metadata for verification, security enforcement, cross-context marshaling, memory layout, and execution. For this reason, .NET
12
Chapter 1
Introducing ASP.NET 2.0
assemblies are said to contain managed code, in that the CLR manages the memory utilization and execution of the code. It should be noted that .NET assemblies (which contain MSIL code) can be decompiled (using, for instance, the ILDasm.exe program that is installed with the Framework) and even reverse engineered. This can potentially be a problem if one has proprietary algorithms or important licensing keys that need to be hidden. If you need to protect the intellectual property contained within your source code, you may want to use an obfuscator (there are several that are commercially available as well as the free Dotfuscator Community Edition available within Visual Studio 2005). An obfuscator makes the process of reverse-engineering MSIL much more difficult (but not impossible because it does not do any encryption or hiding).
CORE NOTE
Even if you feel that you do not need to use an obfuscator for your applications, do remember that any assembly that is publicly available can be decompiled. Thus, avoid placing security information such as passwords, access codes, or encryption keys into your source code.
Common Language Runtime
The Common Language Runtime (CLR) provides a common runtime environment for the execution of code written in any of the .NET languages. It is a software-only, virtual platform that abstracts functionality from the operating system platform. Conceptually, the CLR and Java’s JVM (Java Virtual Machine) are similar in that they are both runtime infrastructures that abstract the underlying platform hardware and operating system. However, although the JVM officially supports only the Java language, the CLR supports multiple languages because all .NET languages are compiled into the same MSIL format (although because the JVM executes bytecode, it could, in principle, support languages other than Java). Unlike Java’s bytecode, however, MSIL is never interpreted. Another conceptual difference is that Java code runs on any platform with a JVM, whereas .NET code runs only on platforms that support the CLR, which officially at present is only Windows. There are some non-Microsoft efforts at porting the .NET Framework to other environments, such as the Mono project and DotGNU Portable .NET. The key components of the CLR are as follows. • • A type system that locates, loads, and manages the .NET types and operations found in its programming languages A metadata system for persisting and organizing compiled code into a common format called assemblies
.NET Framework
13
•
An execution system that loads assemblies, performs Just-In-Time compilation, runs programs, performs security checks, and manages garbage collection
.NET Framework Base Class Library
The .NET Framework Base Class Library (BCL) provides a rich but standard set of CLS-compliant classes that developers can use in their applications. This library includes classes for working with the base types and exceptions, representing common data structures and collections, performing data access, and constructing Windows and Web interfaces. These classes are hierarchically organized into logical containers called namespaces (see Figure 1.5). These namespaces are somewhat analogous to Java packages, except that .NET namespaces, unlike Java packages, are not also physical containers. Compiled .NET code (i.e., MSIL) is physically stored in assemblies; an assembly can contain classes in multiple namespaces, or classes within a namespace can be physically partitioned across multiple assemblies.
System System.Web System.Web.UI System.Web.Serv ices etc
System.Data System.Data.SqlClient System.Data.OleDb etc
System.Xml System.Xml.Schema etc
System.IO
System.Window s.Forms
etc
Figure 1.5
Partial .NET Framework class library hierarchy
14
Chapter 1
Introducing ASP.NET 2.0
.NET Execution
As mentioned in the previous section, .NET programs written in a CLS-compliant language are compiled by the appropriate language compiler into MSIL and then persisted into one or more assemblies. These programs may make use of other classes, written by other developers, or provided as part of the .NET Framework itself in the BCL. The CLR is involved in the execution of the MSIL-based programs, as shown in Figure 1.6.
Source Source Code Code
Language Compiler
MSIL CIL Assembly Assembly (EXE or DLL)
Class Class Libraries Libraries (MSIL) (CIL)
CLR Class Loader
JIT Compiler
Native Native Code Code
Execution and Management
Figure 1.6 .NET execution
As can be seen from Figure 1.6, the CLR is involved in the loading of MSIL, its translation into native code, and the execution of this code. Due to this involvement of the CLR in the execution and management of memory, this code is referred to as managed code.
ASP.NET Web Forms
15
CORE NOTE
It should be remembered that the .NET Framework runs on a host OS (for now, Windows only). Thus, there must be some interface with the Windows mechanism for program loading and execution. The Windows DLL (not a .NET assembly DLL) mscorwks.dll loads the DLLs that actually constitute the CLR: mscoree.dll (the execution engine) and mscorjit.dll (JIT compiler).
There is certainly much more to learn about the .NET and ASP.NET execution process. This material is covered in Chapter 2. Instead, let us move on and introduce ASP.NET itself.
ASP.NET Web Forms
An ASP.NET Web application consists of a number of Web pages, controls, programming classes, and services running within a single Web server application directory (and any subdirectories within it). The heart (and bones and muscles) of a Web application are its Web pages. These are text files with an .aspx extension and are referred to as Web Forms. A Web Form consists of two parts. • • The declaratively defined (that is, by markup/tags) visual elements. This consists of both HTML and ASP.NET controls. The form’s programming logic.
ASP.NET allows the programming logic to exist within either • The same file as the visual elements. This code is contained within a code declaration block (i.e., within tags) embedded within the Web Form. • A separate, fully defined class file. This file is usually called a code-behind file, although some refer to it as a code-separation file, a code-beside file, or simply a code file. Listing 1.1 contains the obligatory Hello World example using an embedded code declaration block. The content that is specific to ASP.NET has been emphasized by using a bold monospaced font in the listing. Figure 1.7 illustrates how the result will look in the browser.
16
Chapter 1
Introducing ASP.NET 2.0
Listing 1.1 HelloWorldEmbedded.aspx
<%@ Page Language="C#" %>
Hello World Embedded
Figure 1.7
HelloWorldEmbedded.aspx in the browser
CORE NOTE
All code examples in the book can be downloaded from my Web site, http://www.randyconnolly.com/core.
ASP.NET Web Forms
17
The example in Listing 1.1 begins with the Page directive, which is used to define page-specific instructions used by the ASP.NET environment. Directives are processing instructions for the parser and compilers (these will be covered in more detail in Chapter 2) when they process an ASP.NET page. Although directives can be located anywhere in an .aspx file, the standard practice is to place them at the beginning of the file. Directive statements are not case sensitive and quotation marks are not required around the attribute values. In this example, the only attribute in the page directive is to specify which programming language will be used in any of the page’s scripting blocks. The default value is VB, although this can be changed via the compilation element in the Web.config file (covered later in the chapter). Some other possible values are C#, C++, VJ#, and JScript. Notice that the
174
Chapter 3
Working with the Standard Web Server Controls
Popup.aspx contains most of the magic. This page contains only the Calendar control, as well as a Javascript function that places the selected date in the appropriate TextBox in the calling page (PopupCalendarTest.aspx). The markup for Popup.aspx is shown in Listing 3.32. The most complex part of this page is the Javascript function. It retrieves the control name of the text box to place the date by retrieving the first querystring parameter (via window.location.search.substr(1)) and then retrieving the value of that parameter (via substring(8)). We use the number 8 with the substring() because the parameter name (i.e., control) plus the equal sign (=) is 8 characters long. Listing 3.32 Popup.aspx
Select Date
Looking at the Popup.aspx, you may wonder where the Javascript SetDate function is actually called. The answer to this lies in the event handler for the Calendar control’s DayRender event (shown in Listing 3.33). The DayRender event handler replaces the built-in postback links for each day in the Calendar with a HyperLink control that links to the Javascript SetDate function (and passes in the date for that day). The text for the HyperLink control (the day number) is retrieved from the existing text of the cell.
Listing 3.33 Popup.aspx.cs
protected void calPopup_DayRender(object sender, DayRenderEventArgs e) { HyperLink link = new HyperLink();
176
Chapter 3
Working with the Standard Web Server Controls
LiteralControl lc = (LiteralControl)e.Cell.Controls[0]; link.Text = lc.Text; link.NavigateUrl = "javascript:SetDate('" + e.Day.Date.ToShortDateString() + "');"; e.Cell.Controls.Clear(); e.Cell.Controls.Add(link); }
Figure 3.28 illustrates how these pages appear in the browser. Notice the URL for the day link in the status bar of Popup.aspx.
Step 1
Click button makes Popup.aspx appear
Step 2
Choosing date makes date appear in TextBox
Figure 3.28
The pop-up calendar
CORE NOTE
There are certainly other ways of achieving a pop-up calendar. For instance, we could use the Atlas PopupControl (Atlas is Microsoft’s AJAX Framework for ASP.NET and is covered in the Appendix), which can turn any ASP.NET control into a lightweight pop-up window. There are also various third-party controls that can achieve similar functionality.
Key Summary Concepts
177
Summary
This chapter examined in some detail the most essential of the standard Web server controls. These controls are the building blocks of most Web Forms; almost any ASP.NET Web Form generally uses one or more of these controls. All of these controls benefit from the advantages of having common class ancestors, namely, the WebControl and the Control classes. As such, there is a common set of properties, methods, and events that are shared by all controls. There are still some additional standard Web server controls that were not covered in this chapter. The next chapter covers the remaining, more specialized, standard controls.
Exercises
The solutions to the following exercises can be found at my Web site, http://www.randyconnolly.com/core. Additional exercises only available for teachers and instructors are also available from this site. 1. Create a Web Form that contains a DropDownList, TextBox, CheckBoxList, Calendar, and a Button control. The two list controls should have multiple items defined. The Button’s click event handler should display in a Label control the item selected in the DropDownList, the text entered in the TextBox, the checked items in the CheckBoxList, and the selected date in the Calendar. 2. Create a Web Form that contains two sets of links. The first set of links should consist of working HyperLink controls that navigate to some other page. The second set of links should consist of working LinkButton controls. That is, these link buttons should display in a Label control information about the button that was clicked. 3. Use the Table control to create a data table containing four rows and columns of data, one header row, and one footer row. This data table should be properly accessible.
Key Concepts
• • • • • HTML attributes HTML server controls Style elements Subproperties Web server controls
178
Chapter 3
Working with the Standard Web Server Controls
References
Allen, Scott. “The Calendar Control and the DayRender Event in ASP.NET.” http://odetocode.com/Articles/223.aspx. Bellinaso, Marco. “Creating a Popup Calendar Control.”
http://www.devx.com/vb2themax/Tip/18850.
Homer, Alex. “Accessibility Improvements in ASP.NET 2.0—Part 2.” http://www.15seconds.com. Mitchell, Scott. “List Control Items and Attributes.”
http://aspnet.4guysfromrolla.com/articles/091405.aspx.
Thomason, Larisa. “Designing Accessible Tables.”
http://www.netmechanic.com/news/vol4/accessibility_no16.htm.
Chapter
4
THE ADDITIONAL STANDARD WEB SERVER CONTROLS
The previous chapter introduced the most essential of the standard Web server controls. This chapter examines the remaining standard Web server controls. Although you may use these controls less frequently than those covered in the previous chapter, they are still quite useful to know. The controls covered in this chapter can be grouped into two categories: those that are container controls and those that are not. The Panel, MultiView and View, Wizard, and PlaceHolder controls’ basic function is to act as a container or parent for other controls. These container controls have many powerful features that make them an important part of any ASP.NET developer’s repertoire. The other controls covered in this chapter (AdRotator, FileUpload, and Xml controls) are not container controls; they perform fairly specialized jobs and as such may not be used nearly as frequently as some other controls. Nonetheless, they do have many unique and useful features that this chapter attempts to demonstrate. The controls covered in this chapter have a rich set of features that require much longer explanations than the controls covered in the last chapter. To enticingly present these features, this chapter contains several longer demonstration projects: a pizza ordering form, a tabbed panel, a checkout wizard, a file browser, and a RSS reader.
179
180
Chapter 4
The Additional Standard Web Server Controls
Overview of the Additional Standard Web Server Controls
This chapter covers the additional standard Web server controls in detail. For each of these controls, there are descriptions, property and event summaries, and sample listings that illustrate typical uses of that control. In comparison to the standard Web server controls covered in the previous chapter, the standard Web server controls covered in this chapter are significantly more rich and generalized; they can be used for a very wide range of tasks. As such, many of the controls covered in this chapter are also provided with a more complex, real-world example.
CORE NOTE
You can download either a starting or finished version of the files used in the chapter from my Web site, http://www.randyconnolly.com/core.
Table 4.1 lists the additional standard Web server controls covered in this chapter.
Table 4.1 Additional Standard Web Server Controls Server Control
AdRotator
Description Displays an advertisement banner (i.e., a randomly selected image that, when clicked, navigates to a new Web page). Allows a user to upload a file to the server. Consists of a text box and Browse button. The MultiView control is a container for groups of View controls. Provides a container for other controls. A container control used for dynamically loading other controls. Provides a series of interconnected forms used for collecting information incrementally from the user. Displays an XML file or the results of an XSLT (Extensible Stylesheet Language Transformation) transformation.
FileUpload
MultiView and View
Panel PlaceHolder
Wizard
Xml
Overview of the Additional Standard Web Server Controls
181
All but two of the controls examined in the previous chapter ultimately inherit from the WebControl base class; the other two inherit from Control, the base class of WebControl. As can be seen in Figure 4.1, half of the controls covered in this chapter also inherit from Control, whereas the others inherit (eventually) from the WebControl class.
Control
MultiView
WebControl
Xml
View
PlaceHolder
Panel
BaseDataBoundControl
FileUpload
CompositeControl
DataBoundControl
Wizard
AdRotator
Figure 4.1
Object model for additional server controls
If you compare the members available to the WebControl class with those available to the Control class (see Tables 2.2 and 2.3 on page 77), you will see that the Control class does not have any user interface functionalities other than visibility; rather, it supplies the basic members that all controls need: ID, child control collections, and common control events. The WebControl class, on the other hand, provides the appearance properties and behaviors required by most Web server controls (ForeColor, Height, CssClass, etc.). The reason that MultiView, View, PlaceHolder, and Xml controls do not inherit from the WebControl base class is that these classes either do not supply a user interface (PlaceHolder) or they provide a user interface that is not related to the base one provided by WebControl (MultiView, View, and Xml).
182
Chapter 4
The Additional Standard Web Server Controls
Panel Control
The Panel control is a container control that can be used as a parent container for plain text, HTML elements, and other Web server controls. The Panel control is typically used for creating group behavior, for creating a unique look for an area on a page, or to programmatically display and hide groups of controls. For instance, you could set the BackColor property of a group of controls at once by setting the BackColor property of the Panel, as shown in the following.
First Second
If you want to programmatically hide a group of controls inside a Panel, you could easily do so by simply setting the Visible property of the Panel.
panTest.Visible = false;
Table 4.2 lists the unique properties of the Panel control.
Table 4.2 Unique Properties of the Panel Control Property
BackImageUrl
Description The URL of the image to display in the background of the panel (i.e., behind its content). Indicates the default button control. This indicates which button is clicked when the Panel control has focus and the user presses the Enter key. Specifies the direction to display controls that contain text within the panel. Possible values are defined by the ContentDirection enumeration (NotSet, LeftToRight, RightToLeft). Used for localization purposes to handle languages that display right to left. Localization is covered in Chapter 16. Sets the caption for the panel as a whole. Rendered via the HTML