Professional Documents
Culture Documents
NET
ASP.NET
Overview
Objectives
This module will introduce you to ASP.NET. ASP.NET is a new way to program dynamic and interactive Web applications. ASP.NET is a compiled environment that makes extensive use of the Microsoft .NET Framework, and the entire .NET platform is available to any ASP.NET application. What you will learn Build real, powerful Web applications Overview of ASP.NET and its features Related Topics Covered in This Lesson How to make use of the .NET Framework services and features What makes ASP.NET more than just ASP 4.0.
ASP.NET
Overview
Section 1: Overview
We start with an overview of Active Server Pages (ASP) and its issues. Then the core concepts of ASP.NET are introduced.
ASP.NET
Overview
ASP.NET
With ASP you can use client-side scripts as well as server-side scripts. Maybe you want to validate user input or access a database. ASP provides solutions for transaction processing and managing session state. While ASP should not be used for implementing business logic, you can easily and quickly create simple Web applications.
ASP.NET
Overview
ASP.NET
Browser compatibility Another restriction is that you have to be sure that the users browser can make use of the scripting language your ASP code is written in. No real state management Session state is only maintained if the client browser supports cookies. Session state information can only be held by using the ASP Session object. And you have to implement additional code if you, for example, want to identify a user. A big problem with ASP and state management is that the information cannot be shared across Web farms. This causes you trouble if you want to enhance the performance of your application by hosting it on more than one server. If IIS fails, all the data corresponding to a session state is lost, because the session information is stored in memory on the server. Update files only when server is down If your Web application makes use of components, copying new files to your application should only be done when the Web server is stopped. Otherwise it is like pulling the rug from under your applications feet, because the components may be in use (and locked) and must be registered.
ASP.NET
Overview
ASP.NET
Overview
10
ASP.NET
management. State information can, for example, be kept in memory or stored in a database. It can be shared across Web farms, and state information can be recovered, even if the server fails or the connection breaks down. Make use of programming languages The ASP.NET code is not scripting code anymore. Your programmers can choose whatever programming language they prefer. Visual Basic, C++, and Microsofts new componentoriented language C# are just 3 out of 17 supported languages to meet the demands; even the good old ones like COBOL can be chosen. And if there are programmers preferring different languages or if you have to use more than one language to meet your needs, do so. Take, for example, Visual Basic and C# to implement the business logic, because now languages can be integrated with one another. A class written in one language can derive from a class implemented in another language. Cross-language interoperation is possible because of the underlying .NET Framework. Update files while the server is running! Components of your application can be updated while the server is online and clients are connected. The Framework will use the new files as soon as they are copied to the application. Removed or old files that are still in use are kept in memory until the clients have finished.
ASP.NET
11
Architecture
Section 2: Architecture
In this section you will get an overview of the .NET Framework architecture, the Web application model, and the configuration system.
12
ASP.NET
Architecture
ASP.NET
13
include existing COM components, but also make use of Web Services (which are explained later). The Web application modelin the slide presented as ASP.NETincludes Web Forms and Web Services. ASP.NET comes with built-in Web Forms controls, which are responsible for generating the user interface. They mirror typical HTML widgets like text boxes or buttons. If these controls do not fit your needs, you are free to create your own user controls. Web Services brings you a model to bind different applications over the Internet. This model is based on existing infrastructure and applications and is therefore standard-based, simple, and adaptable. A Web Service can be understood as a contract between server and client. Those contracts are described by the XML-based Web Services Description Language (WSDL). Doing so, Web Services are defined as endpoints that communicate via XML-based messages.
14
ASP.NET
Architecture
ASP.NET
15
Architecture
HTTP Runtime
Now in more detail: Managed code While the HTTP runtime is managed codebecause it targets the common language runtimeit runs within an unmanaged host process that could be, for example, Microsoft IIS. So, for ASP.NET the .NET Framework uses IIS as a more or less dump gateway for its own HTTP infrastructure. Aims for 100% availability The HTTP runtime processes all requests asynchronously. Because of this and because its multithreaded, the HTTP runtime is fail-safe to a high level. For example, badly written code cannot block the HTTP runtime. Replaces ISAPI The HTTP runtime replaces the Internet Application Programming Interface (ISAPI). Server
16
ASP.NET
Architecture
ASP.NET
17
Architecture
Hierarchical Configuration
ASP.NET ships with a rich and flexible configuration system for both developers and administrators. Concepts and architecture All configuration settings are stored in XML-based files named Web.Config. Those files are human readable and writeable. They are easy to edit by developers and administrators using text editors or, for example, Perl scripts. Configuration files are kept within the directory tree of your Web application. You can store different Web.Config files on the server. Each configuration file affects the directory that it is placed in and all subdirectories. This is called hierarchical configuration architecture. For example, assume that you stored a Web.Config file for your Web application in SubDir1 and none in the root directory. Then all configuration settings for the root directory are taken from the default Web.Config file (more about this on the next slide). The application subdirectories SubDir1 and SubDir2 are configured by the settings in the Web.Config file that is stored in SubDir1. SubDir2 will inherit all configuration settings of its parent directory. Of course, you dont have to write one configuration file for each directory of your application. It is possible to apply settings to specific directories using the <location> tag. This hierarchical configuration architecture is a simple way to customize your configuration. Additionally, all changes are automatically detected by the system. There
18
ASP.NET
is no need to register new configuration files or to restart the application or the server.
ASP.NET
19
Architecture
Web.Config sample
Web.Config sample All configuration settings must reside between the starting <configuration> and ending </configuration> tags. The two main parts of the file are the leading configuration section handler declarations and the actual configuration sections: <configSections> This section contains the configuration section handler declarations. With each declaration you specify the name for the configuration section and the type of the section handler. In this sample we declare httpmodules and sessionstate. <sectionName> For each declaration you have to write a configuration section. So, here we have two sections, one for httpmodules and one for sessionstate. In the httpmodules section you can register HTTP modules for your HTTP module pipeline. In the section named sessionstate you can set a session timeout or specify a server for remote session state store.
20
ASP.NET
Architecture
Custom Configuration
Default and custom configuration settings ASP.NET has a default configuration file named machine.config, which is located in the directory %windir %\Microsoft.NET\Framework\v#.#.####\CONFIG. This file makes use of the standard set of configuration section handlers. Those section handlers are also used to specify your settings within the Web.Config files. You use particular tags to specify the settings and to customize the configuration of your application. Using the tags you can easily build your own configuration file. But if all the standard section handlers do not meet your needs, you are free to extend the set of handlers by implementing your own. To do that you must create a class that implements the System.Configuration. IConfigurationSectionHandler interface. But you have to be aware of two problems when working with the configuration files: Be careful when using virtual directories, because there are some side effects of configuration inheritance, which can cause unexpected behavior or failures. For example, if you access a file using a path that contains a virtual directory, configuration files in parent directories are ignored. If your virtual directory named AppDir1 points directly to the physical location C:\RootDir\SubDir1\SubDir2 and you use the URL http://localhost/AppDir1/MyFile.aspx
ASP.NET
21
the configuration information stored in SubDir1 is not loaded. Another important thing to mention is that all configuration settings apply only to ASP.NET page files (.aspx), and not to .html or .asp files. Keep this in mind, if you are thinking about security settings.
22
ASP.NET
Architecture
23
For this sample, to use the Button class the appropriate line is:
using MyAlias = System.Web.UI.WebControls
By doing so, you dont need to specify the namespace when using types or classes from that namespace. Or you can use the alias (MyAlias in this case) to represent the namespace name.
24
ASP.NET
Architecture
ASP.NET
25
method is the OnClick method, which raises the (public) Click event. This should be enough to point out the main principle of namespaces.
26
ASP.NET
Features
Section 3: Features
Section 3 gives you a first look and a brief introduction to the vast amount of ASP.NET features and benefits. First well see how to write ASP.NET pages and how they are processed. Then we will look at solutions ASP.NET provides for state management, security, and event handling.
ASP.NET
27
Features
28
ASP.NET
Of course, you still can mix HTML and code in one fileif you want to.
ASP.NET
29
Features
Supported Languages
As mentioned at the beginning, your programmers are not restricted to using only C# for implementing the functionality of a Web application. From the beginning .NET supports: Microsoft Visual Basic Microsoft JScript C# C++
All languages that target the common language runtime can make use of cross-language inheritance and interoperability. Visual Basic Visual Basic.NET is a powerful object-oriented programming language. It is integrated with the .NET Framework and therefore targets the common language runtime. And with Visual Basic.NET there is no further need for VBScript. JScript With JScript.NET we have compiled code, typed and typeless variables, cross-language support, and access to the .NET Framework. JScript.NET brings together the existing JScript and some features of class-based languages. C# C# is Microsofts new component-oriented programming language. You will get a short overview in a few minutes.
30
ASP.NET
C++ You can still develop your applications with C++. Visual Studio.NET provides new language extensions for native C++ called Managed Extensions for C++. Managed code runs under control of the .NET Framework. With Managed Extensions you can target the .NET platform to write .NET applications or migrate your unmanaged C++ code to it. Also, you can access .NET classes from native code and vice versa. Others As programming languages are very different from one another, you have to use features of your programming language that are guaranteed to be available in all other languages. The Common Language Specification (CLS) defines a minimum set of features that compilers must support to target the common language runtime. Several other third-party compilers, for example, COBOL, Smalltalk, and Eiffel, support .NET.
ASP.NET
31
Features
C# Overview
This section contains a short overview of C#. A detailed overview is contained in the module C#. New component-oriented language from Microsoft With C# Microsoft introduces the first real componentoriented programming language. This new language is an addition to the C/C++ family. C# was specifically designed for the .NET run time environment and Framework. Because it is evolved from C/C++, developers who are familiar with C and C++ will feel right at home. The syntax looks very similar, but there are many improvements. C# combines the power of C with the ease of Visual Basic! C# brings enhancements to areas like: Type safety Versioning Events Garbage collection Access to APIs like .NET, COM, or Automation
Hello World sample This is a minimal C# application designed to write Hello World! to the system console. To access the functionality of the Console class that allows us to write to the system console, were pulling in all declarations of the System namespace (this doesnt
32
ASP.NET
recursively include Systems subordinate namespaces, though). All code in C# must be contained in classes, and therefore it is not surprising that the application itself is a (publicly accessible) class. The applications entry point is a static method with a fixed signature and the default name Main. To keep things simple, were then just calling the (also static) method WriteLine on the Console class to write Hello World! to the console and exit.
ASP.NET
33
Features
QuickStart
After this short excursion with some background information on the .NET Framework, we will now focus on ASP.NET. File name extensions Web applications written with ASP.NET will consist of many files with different file name extensions. The most common are listed here. You will learn later what Web Forms or Web Services are; for now; just pay attention to the related file name extensions. Native ASP.NET files by default have the extension .aspx (which is, of course, an extension to .asp) or .ascx. Web Services normally have the extension .asmx. Your file names containing the business logic will depend on the language you use. So, for example, a C# file would have the extension .aspx.cs. You already Web.Config. learned about the configuration file
Another one worth mentioning is the ASP.NET application file Global.asaxin the ASP world formerly known as Global.asa. But now there is also a codebehind file Global.asax.vb, for example, if the file contains Visual Basic.NET code. Global.asax is an optional file that resides in the root directory of your application, and it contains global logic for your application. All of them are text files All of these files are text files, and therefore human readable and writeable.
34
ASP.NET
The easiest way to start The easiest way to start with ASP.NET is to take a simple ASP page and change the file name extension to .aspx.
ASP.NET
35
Features
36
ASP.NET
Features
ASP.NET
37
Features
38
ASP.NET
Features
ASP.NET
39
Features
40
ASP.NET
Features
ASP.NET
41
Features
Execution Process
We need to have a look at whats happening to your code in ASP.NET. Compilation, when page is requested the first time The first time a page is requested, the code is compiled. Compiling code in .NET means that a compiler in a first step emits Microsoft intermediate language (MSIL) and produces metadataif you compile your source code to managed code. In a following step MSIL has to be converted to native code. Microsoft intermediate language (MSIL) Microsoft intermediate language is code in an assembly languagelike style. It is CPU independent and therefore can be efficiently converted to native code. The conversion in turn can be CPU-specific and optimized. The intermediate language provides a hardware abstraction layer. MSIL is executed by the common language runtime. Common language runtime The common language runtime contains just-in-time (JIT) compilers to convert the MSIL into native code. This is done on the same computer architecture that the code should run on. The runtime manages the code when it is compiled into MSILthe code is therefore called managed code.
42
ASP.NET
Features
Assemblies
Information that is related to executable code is stored together as metadata. The metadata is generated from the source codeat the moment the compiler produces MSILby the compiler. Executable files and metadata together are characterized as self-describing components. Further on, a group of resources (for example, a collection of physical files) and types along with the corresponding metadata (which is then called manifest) are referred to as an assembly. Assemblies are essential to the common language runtime. A resource may be a DLL, and now you can use your servicethe DLLwithout entering DLL Hell by just copying the assembly to whatever location you want to use it; no installation, no registration. Assemblies build the substantial entity for reuse, deployment, version control, and security. Assemblies are usually made up of one or more Portable Execution (PE) and resource files. And a .NET application consists of one or more related assemblies. Note .NET DLLs have nothing to do with todays DLLs; the only thing in common is the file name extension. Result of compiling is still a .dll or .exe file While the outcome of compilation is still a DLL or EXE file, assemblies are the principle of how to avoid DLL conflicts. To install the application just xcopy the assemblyand all related assembliesto your application directory. You can store and use many copies of one DLL file on a server. Two applications that are physically located in
ASP.NET
43
different directories may use the same DLL. In the past they have to share one single file. Now each application can have a copy of the DLL within its application directory. This solves the versioning problem, where different applications need different versions of a DLL, as well as the locking problem, where one application uses and locks a DLL while another application wants to gain access to the DLL. Imagine a multi-file Assembly1 referencing a single-file Assembly2. To do this, Assembly2 has to expose a socalled shared name that can be referred to by Assembly1 using a token. This mechanism works with a public key and a signature generated over the target assembly. By the way: this is also a security solution guaranteeing that Assembly2 is really Assembly2.
44
ASP.NET
Features
Metadata
The metadata is referred to as an assemblys manifest. A manifest can be stored as part of a DLL or as a standalone file. It contains a list of all files of the corresponding assembly, version information including version and build numbers, shared name information guaranteeing name uniqueness, type reference information, and more. Optionally, a developer can store a description, configuration information, or product information. All this information is, among other things, used to: Locate and load class types. Lay out objects instances in memory. Resolve method invocations and field references. Translate MSIL to native code. Enforce security.
ASP.NET
45
Features
46
ASP.NET
Features
All session state information in .NET is stored by default in a state server process. This process runs as a Windows service. The state can be serialized and stored as binary data in memory. Additionally you have the possibility to store the data in a Microsoft SQL Server database. The state service and the state information could reside on the same server as the application, but it can also be stored on an external state provider. This state provider is a dedicated machine managing the state information. With this arrangement, session state is still available after a crash of the application server.
ASP.NET
47
Features
Security (1/3)
There are several reasons why you should think of security when you want to present a Web application. Reasons for Security One reason is that you might want to prevent access to some areas of your Web server. Different groups of users might have different access rights to different areas or virtual directories of your application. You also need security when you have to record and store secure relevant user data. This data has to be protected against public and unwanted access. Security Configuration The Web.Config file has already been introduced. So it may be enough to mention that all security-related configuration information in ASP.NET is contained in this file. You have the ability to configure three fundamental functions for ASP.NET security: authentication, authorization, and impersonation. Therefore your Web.Config will have three additional sequences enclosed in the parent <security> tag. Authentication, Authorization, Impersonation AuthenticationAll your Web clients communicate with your Web application through IIS. So you can use IIS authentication (Basic, Digest, and NTLM/Kerberos) in addition to the ASP.NET built-in authentication solutions (Passport and Cookie). AuthorizationOnce a client request is authenticated, authorization determines whether this identity is allowed to have access to the requested resource.
48
ASP.NET
ImpersonationThrough impersonation ASP.NET applications can get the identity of a client and behave like the client on whose behalf they are now operating.
Code Access Security In ASP.NET you can make use of .NET Framework features. So you have access to the security solutions that the runtime provides. These are, for example, code access or role-based security. Code access security is a way to protect your server from malicious mobile code and allows benevolent mobile code to run safely. Code access security gives you an answer to the question: Are you the code you told me you were?
ASP.NET
49
Features
Security (2/3)
The presented security solutions only work for ASP.NET resources. Other files types such as .gif, .txt, or .asp are still accessible, but you can map such files explicitly to the ASP.NET security system by configuring IIS. Authentication ASP.NET supports three authentication providers. These providers validate the credentials a client sends along with a request against some authority. If the credentials are valid, an authenticated identity is given to the client. The three providers are: Windows authentication, which works hand in hand with IIS security. Passport authentication, which is a centralized authentication service provided by Microsoft. Cookie authentication, which issues a cookie to the request/response that contains the credentials for reacquiring the identity.
Authorization Once a client request is authenticated, the system determines whether access to the requested resource can be granted or not. ASP.NET distinguishes two types of authorization: File authorization File authorization is active when using Windows authentication. To determine whether access should be granted or not, a check against an access control list (ACL) is done.
50
ASP.NET
URL authorization Identities are mapped to pieces of the Uniform Resource Identifier (URI) namespace using URL authorization to selectively allow access to parts of the namespace.
ASP.NET
51
Features
Security (3/3)
Impersonation When using impersonation, IIS and Windows file access security come into play. IIS authenticates the user using Basic, Digest, or Windows NTLM/Kerberos authentication. IIS then passes a token to ASP.NET; the token is either authenticated or unauthenticated. ASP.NET now impersonates the given token, so that the ASP.NET application can operate with the identity of the requesting client. The access to the requested resource is permitted according to NTFS settings (obviously, the Web server file system must be formatted as NTFS). Code Access Security Besides the ASP.NET built-in security features, a developer can make use of several security solutions of the .NET Framework. Here we focus on one of them: code access security. With code access security you can admit code originating from one computer system to be executed safely on another system. Therefore the codes identity and origin has to be verified. To determine whether the code should be authorized or not, the runtimes security system walks the call stack, checking for each caller whether access to a resource or performing an operation should be allowed. In the .NET Framework you must specify the operations the code is allowed to perform.
52
ASP.NET
Features
ASP.NET
53
receiver handles the message and therefore it is an event handler. To bring an event handler in the position to receive events, it has to be registered with an event sender. This is referred to as event wiring.
54
ASP.NET
Features
ASP.NET
55
Features
Event Samples
Here are two event samples: the Click and the Load event. The Click event is raised by the Button.OnClick method. It can be useful if you want to have additional processing when, for example, a button is clicked. The Control.Load event fires every time the corresponding control was loaded to the Page object. This notifies the control to perform additional steps each time the page is requested. Events in C# The sample code snippets show in more detail how to use the Click event: You have to add this line in your ASP.NET file. The property we are interested in is the onclick="". The value for this property is the name of the methodthe event handlerthat should be called when the user clicks the Next button. This method could be implemented inline or in a code-behind file.
56
ASP.NET
Advanced ASP.NET
ASP.NET
57
Advanced ASP.NET
58
ASP.NET
Advanced ASP.NET
ASP.NET
59
Advanced ASP.NET
60
ASP.NET
Advanced ASP.NET
Web Services
Today there is a strong need on easy-to-use and easy-tocreate Web applications, while those applications are required to be language and platform independent. The .NET Framework provides Web Services, which are based on open Internet standards like HTTP and XML. Like components, Web Services are black boxes that can be reused without knowledge of how the service is implemented. Broadly speaking, Web Services are URLaddressable resources that return requested information to a client or cause an update in a data model. Provide a specific functionality Web Services provide specific functionality, like interest computation, performing security-related tasks, or just sending data through XML messages. Exposed over the Internet Web Services are called Web Services because you can expose and use them over the Internet, which is a typical usage scenario. But it is also possible to use them only internally or locally in a single application. To be consumed by applications Web Services can be consumed by independent of: Operating system Programming language Component model applications
ASP.NET
61
Advanced ASP.NET
62
ASP.NET
Advanced ASP.NET
ASP.NET
63
Advanced ASP.NET
64
ASP.NET
Advanced ASP.NET
Data Binding You can bind Web Forms control properties to any data in a data store. This so-called data binding gives you nearly complete control over how data moves to the page and back again to the data store. Page Class When a page is loaded, the ASP.NET runtime generates and instantiates a Page class. This object forms a collection of your separate components (like visual elements and business logic). So all (visual and code) elements are accessible through this object.
ASP.NET
65
Advanced ASP.NET
66
ASP.NET
Two samples: Button This is a way to enable the user to finish editing a form. A Button enforces the submitting of the page, and you can additionally raise events like the Click event. TextBox A TextBox is an input box where the user can enter information like numbers, text, or dates formatted as single line, multiline, or password. This control raises a TextChanged event when the focus leaves the control.
ASP.NET
67
Advanced ASP.NET
When the validation fails, an error message is generated and sent back to the client browser. This can be done in several ways. For example, all error messages related to a specific transaction could be collected and presented to the user in summary.
68
ASP.NET
User Controls (Pagelets) If you want to design your own server control, you can extend existing ones, combine them, or create a new control. Like all others, your own controls must inherit from the WebControl base class. User controls are sometimes referred to as Pagelets. Mobile Controls With mobile controls a developer can encapsulate Wireless Markup Language (WML) to target multiple devices such as WAP devices.
ASP.NET
69
Advanced ASP.NET
controlName The control name specifies the control you want to use. For example, the Button control, the CheckBox control, or the Table control. Attributes You can manipulate the behavior of the controls using attributes. For instance, you can specify how they are processed and how they can be accessed.
70
ASP.NET
Advanced ASP.NET
ASP.NET
71
Advanced ASP.NET
72
ASP.NET
Namespaces These classes reside in the namespaces System.Data and System.Data.OleDb. Both provide many more classes, for example, to throw events when entries have changed, or collecting information relevant to errors.
ASP.NET
73
Advanced ASP.NET
74
ASP.NET
Advanced ASP.NET
ASP.NET
75
Advanced ASP.NET
Caching
Caching is another important performance-related topic. As you might know, your browser caches data (mostly images) while you are surfing the Web. Some data is stored on your local machine as "Temporary Internet Files". This is done to speed up loading a page you request more than once. Enhance performance of your Web application Objects that need a lot of time to be constructed should be built once and used many times. These objects should be stored in memory. ASP.NET provides caching mechanisms to do this, and enhance the performance of your .NET application. Output Caching Page caching allows you to cache complete pages. That is, dynamic pages are output-cached, so they can be served directly from the cache when a page is requested the second time. Another feature is called fragment caching. ASP.NET output caching can handle cached fragments and substitution blocks. So you can cache only portions of an ASP.NET page. Expiration settings You can define how long pages should be available through the cache. Expiration policies let you define relative and absolute expirations.
76
ASP.NET
Cache APIs In situations when you are not satisfied with the ASP.NET built-in caching features, you can extend or customize it through the cache API. A good example for the benefits of caching is if you want to offer your products via the Web. If the content is dynamic, but does not change every minute, you should cache certain product pages to enhance performance.
ASP.NET
77
Advanced ASP.NET
Web Applications
The whole architecture and ASP.NET features provide an infrastructure to build structured Web applications. ASP.NET defines a Web application as the ASP.NET defines a Web application as the sum of all files, handlers, modules, and executable code that can be invoked or run in the scope of a given virtual directory on a Web application server. Distributed Applications You can create distributed applications where Web Forms build the presentation layer; the middle tier consists of the Internet and Web Services, and the third layer is built from databases like Microsoft SQL Server. We've seen that the preferable format for data exchange and communication between these layers is XML, because all mentioned parts are based on or provide this format. Furthermore, from what weve seen in the Web Services part, ASP.NET is an ideal platform to create SOAP-based Web Services.
78
ASP.NET
Advanced ASP.NET
ASP.NET
79
Performance In most cases modification cannot be avoided if you want to target the .NET Framework and enhance the performance of your application.
80
ASP.NET
Advanced ASP.NET
Migration Issues
To migrate from ASP to ASP.NET you have to address some migration issues to make your code .NET ready: Structure ASP.NET introduces changes in layout and coding style, like new directives and, of course, syntax. Security .NET ships with a comprehensive security model. Languages You can use C#, which is the default language, or Visual Basic.NET. Note: VBScript is not managed. Data Access Among other new data access features, ADO.NET is the new technology that ships with the .NET Framework. But ADO will function under ASP.NET, so you dont have to migrate immediately to ADO.NET.
ASP.NET
81
Summary
Summary
Here we can give you only an overview of ASP.NET features. If you are interested in all particulars of specific aspects, please refer to the corresponding module. You are now introduced to the core concepts of ASP.NET, which are: Configuration concepts Web Forms and Web Services Security principles, including authentication and authorization schemes Application and session state management Accessing data (SQL, XML, and ADO.NET) Web applications Migration to .NET
82
ASP.NET
Duwamish Online
The Duwamish Online store is one of the Enterprise Samples delivered with the Visual Studio.NET product. Duwamish implements a fictitious e-commerce bookstore complete with catalogue, personal profile management and order handling. The Duwamish Sample is shipping in both a C# and a Visual Basic.NET version. Before we are going to start the walkthrough for the technologies that have been presented in this module, you will first learn how to install the Duwamish sample and how the sample is organized.
ASP.NET
83
84
ASP.NET
ASP.NET
85
86
ASP.NET
Common Components
Duwamish7.Common The Common namespace (and subproject) contains all configuration options that are common to all parts of the system. Also common to the entire system are the definitions for the catalogue (Books, Categories) and the order system (Customer, OrderData) and consequently they are also located in this shared project that is being used by all layers. While the data is held in ADO.NET DataSets, this should not be confused with being the actual database layer. The Common namespace provides its own, internal relational view of the Duwamish data thats being mapped to a physical data store by the DataAccess layer (next slide). Duwamish7.SystemFramework The SystemFramework contains all utility classes that are implemented to serve a specific technical purpose but are not immediately related to the business code. All of the code in this project is generally useful and applies to projects beyond the scope of Duwamish. It contains diagnostic utility classes, pre and post condition checking, and dynamic configuration tools.
ASP.NET
87
Duwamish7.DataAccess
Contains all database-related code The DataAccess namespace contains all databaserelated code in Duwamish, providing a central point for maintenance if the underlying data model needs to be optimized or extended. The DataAccess module maps the common definitions for the internal data representation that are defined in the Common.Data namespace to the physical layout of the underlying database. Uses ADO.NET architecture The project builds on the ADO.NET infrastructure and uses the SQL Server managed provider to access the data store. To retrieve and manipulate data, DataAccess uses DataSetCommands bound to the DataSets provided by the Common.Data subsystem. Optimized for performance using stored procs To optimize performance, the sample uses only a minimal set of ad hoc SQL commands and relies heavily on stored procedures, which are substantially faster.
88
ASP.NET
Duwamish7.BusinessRules
Implements all business rules The BusinessRules layer serves to implement all logic that is mandated by the system requirements. It validates data, implements calculations, and performs the manipulation of data. All data access performed through DataAccess All modifications that are being made to the underlying data store are performed through the DataAccess layer.
ASP.NET
89
Duwamish7.BusinessFacade
Implements logical business subsystems The BusinessFacade sits on top of the BusinessRules and provides a logical subsystem view. The BusinessFacade provides consistent, separate interfaces to the customer system, the order system, and the product system. While data is read through the DataAccess layer, all manipulation is validated and performed through the BusinessRules.
90
ASP.NET
Duwamish7.Web
Implements the user interface for Web access The Web namespace implements the full user interface for the application. Uses ASP.NET architecture The UI is built on top of ASP.NET using Web Forms, custom Web controls, validation, code behind forms, and many more ASP.NET innovations. All functionality accessed through BusinessFacade Of course, all of the data displayed to the user and all interactions run through the BusinessFacade. This layered model enables reusing the entire back end for a shop with a radically different look and behavior or to expose parts of the application as a Web Service or a Windows Forms application.
ASP.NET
91
Shop at DuwamishOnline.NET !
Demo: Duwamish in Action
92
ASP.NET
ASP.NET
93
We will explore some of the new ASP.NET features, which are: Code behind Server controls Validation Event handling Data access and data binding
As we just mentioned, the Web part is the UI of Duwamish. We will have a closer look at the files of the Checkout section and start exploring the code by opening the file Secure/Checkout.aspx. The Page Class If an ASP.NET file is requested, a Page object is created on the server. Therefore, we need to specify which other files are necessary to instantiate the Page class. This is done with directives. The first lines of Checkout.aspx are such Page directives. The @Import directive imports the Duwamish7.Web namespace. The Duwamish team used cascaded namespaces to organize their code into logical groups. The base namespace for the entire Duwamish sample is Duwamish7, and the subnamespace for this project is Duwamish7.Web. The @Page directive sets the language to C# and includes the code-behind file Checkout.cs. The other directives include additional ASP.NET files, as was done with #include under ASP. Note To view the code of the included files just right-click on the file name in the code editor and then click View Code. Another way is to open the files by double-clicking them in the solution explorer or by choosing File / Open / File from the menu bar. Code Behind Code-behind files contain the business logic of your application, and could be, for example, .cs (C#) or .vb (Visual Basic.NET) files. Because we are using the Duwamish C# sample, all code-behind files are .cs files. We will refer to those files several times during this walkthrough. Server Controls The first thing we will look at is how to make use of custom server controls. In the code editor, search for a tag containing the Module prefix (<Module:). This prefix is a so-called TagPrefix defined in one of the aforementioned directives. The <Module: tags mark the places where the code of the
94
ASP.NET
include files (defined in the directivesremember?) will be expanded. Open the files: Secure\Checkout.cs Modules\CheckoutModule.ascx Modules\CheckoutModule.cs
(In the following we will use only the names of the files without the path of the subdirectory.) Go to Checkout.aspx; the Module:Checkout tag contains the attributes id=modCheckout and runat="server". The id enables you to reference programmatically an instance of this object that will be created on the server. This object (specified by the id) is an instance of the class CheckoutModule, which is implemented in CheckoutModule.cs. CheckoutModule.cs is the code behind CheckoutModule.ascx. Depending on what step of the checkout process you are currently in, the content of the HTML page that will be generated and send back to the users browser will dynamically change its look. Here, in this case, the flow chart in the upper left corner of the page will change, so that an arrow appears in front of the appropriate checkout step and the corresponding phrase is highlighted. To see how this is done for the arrow images, go to CheckoutModule.ascx. There you can find the image server control <asp:Image. This control has a visibility property that can be programmatically affected by using the control id. Now, open the code behind file CheckoutModule.cs, where you can find the method ToggleDisplay(). With the code line idName.Visible = true; you can change the visibility of the image. This should be enough for custom server controls. Lets see how ASP.NET server controls can be used. Go to the file Checkout.aspx and search for the <asp:Panel tag. There are three sections in the file enclosed by such tags. The section we want to look at has id=ShippingPanel. This id is used by the SetPanelDisplay() method in the file Checkout.cs. There you find a switch statement where, depending on the checkout-step, the Panel is shown or not (therefore the method ShowPanel() is called). So, if you are in the first of three checkout steps, m_Stage is 0 (see in method SetPanelDisplay()), and in this case the visibility of ShippingPanel is set true. The response file that will be generated on the server will now contain the ShippingPanel section of the file
ASP.NET
95
Checkout.aspxthe other two panel sections are not visible. Validation Now well find out how the user input validation works. Go to Checkout.aspx and search for the <asp:TextBox id=txtPhoneNumber tag. There you will find two validator controls, RequiredFieldValidator and RegularExpressionValidator. Both are included here and configured in a way that they check the users entry in the Phone Number field. The errormessage attribute defines a special note that will be displayed when the entry is not correct (RegularExpressionValidator) or even missing (RequiredFieldValidator). The controls, of course, contain the runat="server" attribute and specify the control that is to be validated (ControlToValidate) as txtPhoneNumber. That is the id of the TextBox control. The RequiredFieldValidator makes use of the display attribute, which here is set to dynamic. Doing so allows multiple validators to occupy the same physical space on the content page when they become visible. The regular expression that has to be fulfilled by the Phone Number entry is given in the ValidationExpression attribute of RegularExpressionValidator. Now, whats going on, when the field(s) are edited and the user clicks the Next button? When the page is first accessed nothing happens. But when the user clicks the Next button, the btnNext_Click() method is called, which is implemented in Checkout.cs. The following code snippet, taken from Checkout.cs, shows how all validators are invited to validate their input in relation to the parameters provided by the control:
foreach (IValidator val in Page.Validators) { val.Validate(); }
It iterates over all validators on the Page and calls the method Validate() of the IValidator interface. Event Handling In the last section we mentioned that a method is called when the user clicks the Next button. This is done by using Web Forms events. Open Checkout.aspx and search for the asp:ImageButton tag with id="btnNext" at the end of the
96
ASP.NET
file. (By the way: the ImageButton control lets you catch user clicks within an image.)
<asp:ImageButton id=btnNext runat="server" imageurl="../images/next.gif" onclick="btnNext_Click"> //this is the event </asp:ImageButton>
The name of the event is added as an attribute to the tag line. Its value is the name of the method that is called when the button is clicked. This method is implemented in the code-behind file Checkout.cs. (This ImageButton tag also contains the runat="server" attribute) When the user clicks the Next button, the OnClick event is raised and communicated to the server. There the corresponding event handler method btnNext_Click() handles the event, which means: validating the entries and setting some variables that are used to generate the content of the next page.
ASP.NET
97
Legal Notices
Unpublished work. 2001 Microsoft Corporation. All rights reserved. Microsoft, ActiveX, JScript, Visual Basic, Visual Studio, and Windows are either registered trademarks or trademarks of Microsoft Corporation in the United States and/or other countries. The names of actual companies and products mentioned herein may be the trademarks of their respective owners.