You are on page 1of 97

ASP.

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

Looking Back: Active Server Pages (ASP)


What is ASP? Microsoft Active Server Pages (ASP) is a server-side scripting technology. Any scripting or programming language that is compliant with the Component Object Model (COM) can be used to create Web server applications. Take a pure HTML file and add scripting code to it, so that one file contains both HTML and, for example, Microsoft Visual Basic Scripting Edition (VBScript). That file has the file extension .asp (instead of .html) and is accessed via HTTP requests. In the browser, a user enters the URL for the file. When the server receives the request, it recognizes the extension; Microsoft Internet Information Service (IIS) treats the .asp file differently from an .html file. A COM component (asp.dll) parses the file for the scripting code and processes it from the top of the file to bottom. The scripting code inside the .asp file is interpreted each time the file is requested. Normally, a standard HTML document will be generated and sent to the browser as a response; but other data, such as images or binary data, can be returned. What can I do with ASP? Fortunately you are not limited to dynamically generating and presenting date and time information in the client browser or performing computations. You can also access COM components to extend the functionality of your Web site.

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

Whats Wrong with That?


There are many problems with ASP if you think of todays need for powerful Web applications. Some of these restrictions are listed here: Mixes layout (HTML) and logic (scripting code) Mixing HTML code and scripting code may not cause problems when implementing and editing one file the first time. You will begin to have problems when a programmer and a designer have to update the functionality and the layout, because having both HTML and scripting code in one file complicates the update process. Interpreting ASP code leads to performance loss As mentioned earlier, the scripting code in an ASP file is interpreted each time the file is requested. The .asp file name extension alerts IIS that the file contains scripting code. IIS then parses the file for the code and processes it. On Web servers where hundreds of client requests per minute are expected, this time consuming processing leads to a performance loss. Uses JScript and VBScript Microsoft JScript and VBScript are common scripting languages and currently supported by the ASP scripting engine. Because both JScript and VBScript are not strongly typed, this leads to another performance loss. You can use other scripting languages, but custom scripting engines are hard to find.

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 Core Concepts


ASP.NET is a new way to program dynamic and interactive Web applications. There is more in it than just a few new features; it is much more than ASP 4.0. ASP.NET is a new programming framework for Web applications. It is a compiled .NET-based environment that makes extensive use of the .NET Framework. Because it has evolved from ASP, ASP.NET looks very similar to its predecessorbut only at first sight. Some items look very familiar, and they remind us of ASP. But concepts like Web Forms, Web Services, or Server Controls gives ASP.NET the power to build real Web applications.

ASP.NET

Overview

ASP.NET Core Concepts


Separate layout and business logic To make a clean sweep, with ASP.NET you have the ability to completely separate layout and business logic. This means that you can split all inline code from the page and store both code and content in different files (with different file name extensions). Now your designers can work with nearly pure HTML files, while the programmers can implement the working code. Use services provided by the .NET Framework The .NET Framework provides class libraries that can be used by your application. Some of the key classes help you with input/output, access to operating system services, data access, or even debugging. We will go into more detail on some of them in this module. Code is compiled the first time a page is requested When a page is requested for the first time, its code is compiled to classes instead of being interpreted by a scripting engine. This compilation is done once, and then the objects are kept in memory. Besides other advantages, this allows for strong typing and performance optimizations; of course, this solution improves performance even without using optimization at compile time, because accessing existing objects in memory is faster than interpreting the code. State management To refer to the problems mentioned before, ASP.NET provides solutions for session and application state

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

The .NET Framework Architecture


To really understand what makes ASP.NET more than just ASP 4.0 we need to have a look at the underlying .NET Framework architecture. The .NET Framework architecture is built on top of the operating system services. This framework contains different layers. In this slide there is the .NET Framework common language runtime, which resides on top of the operating system services. The common language runtime loads and executes code that targets the runtime. This code is therefore called managed code. The runtime gives you, for example, the ability for cross-language integration. For that matter it makes use of the common type system, which defines a standard set of types and rules to create new types. As mentioned earlier, the .NET Framework provides a rich set of class libraries. These include base classes, like networking and input/output classes, a data class library for data access, and classes for use by programming tools, such as debugging services. All of them are brought together by the Services Framework, which sits on top of the common language runtime. The top layer of the .NET framework consists of the Windows application model and, in parallel, the Web application model. Use the Windows application modelWindows Forms to develop more traditional Windows applications and take advantage of new Windows 2000 features. You can

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

Web Application Model


But now we will show you in more detail how ASP.NET requests are handled. As with earlier versions of ASP, a client can access your Web application using URLs. So, a Web application is a set of URLs related to one or more virtual directories on the Web server. Each request is processed by the HTTP runtime, which is the core of the ASP.NET Web application model. Processing consists of resolving the URL of the request to the corresponding application, and dispatching the request to the application for further processing. Requests are led through a pipeline of HTTP modules. With each module a developer can catch and modify requests. One of those modules could be, for example, a security module. At the end of the module pipeline, there are request handlers. They enable the processing of individual URLs within an application. From the developers point of view there is easy access to a clean and well-structured object model. Beside those aspects mentioned above, there is an object encapsulating all information about an individual HTTP request within ASP.NET. This object is called HttpContext. HTTP modules and request handlers access ASP.NET intrinsic via HttpContext.

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

HTTP Module Pipeline


Both the HTTP modules and request handlers are managed classes. HTTP module pipeline The HTTP module pipeline can consist of one or more modules. Each module implements a specific interface or functionality. This architecture makes it easy to extend the functionality of your Web application: just add another module! If you need state management, just add the state management module by adding the module to the <httpmodules> section in your Web.Config file. It is also possible to add third-party modules for additional needs, which are not covered by .NET. While all requests to one application are routed through the same pipeline, an application can be associated with multiple request handlers. Request handler Request handlers are higher-level implementations like Web Services, and reside at the end of the module pipeline, waiting to process the request. So, you can have multiple request handlers, but only one per URL.

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

Class Hierarchy (1/2)


The .NET Framework includes classes, interfaces, and value types. This is a rich set, so you dont have to design all your .NET types from the ground up. All .NET Framework types can be used from any programming language that targets the common language runtime. The properties of the types are always the same, whatever programming language you are using: so, a double is a double is a double. Namespaces The .NET types are structured hierarchically using dotseparated names, so that related classes are grouped logically. The expression up to the last dot is called the namespace, whereas the last part is a class name. Therefore the complete name of the Button class is System.Web.UI.WebControls.Button; it is contained in the System.Web.UI.WebControls namespace. The root is the System namespace. There are more than 20 second-level namespaces covering your most common needsand more. For example, you have a namespace for working with data, called System.Data. Then you have classes to manipulate the .NET Framework security system, grouped in System.Security. Now, to put two and two together, the .NET Framework provides abstract base classes and class implementations from those base classes. In addition, you are free to derive your own classes and implement your own functionality as needed. To make use of a namespace, use the using keyword:

ASP.NET using [alias =] class_or_namespace

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

Class Hierarchy (2/2)


One of the most interesting namespaces for ASP.NET developers is the System.Web namespace and its subsidiary namespaces. The slide shows the Web Controls class hierarchy. Yellow boxes are abstract classes and the blue ones are concrete classes. A basic rule in .NET development is that classes must comply with the Common Language Specification (CLS). To ensure this, all classes must inherit from a CLScompliant class! All objects in .NET derive from the root object System.Object, which is CLS-compliant, so that every object of any type is guaranteed to have a minimum set of capabilities. For example, all objects have a (public) GetType() method. To follow the rule, all Web server controls derive directly or indirectly from the base class System.Web.UI. Controls.WebControl. Of course, this sample is just a view on a lower part of all Web server controls. Some Web server controls map to HTML elements; they are shown on the right. The ones on the left provide data binding support. Data binding means that you can bind control properties to data in a data store. If you want to design your own Web server control, you can extend existing ones, combine them, or create a new control that must inherit from the WebControl base class. Now lets take a closer look at the Button class. It has public and protected properties, methods, and events (and fields, but they are not important for now). A public property, for example, is the Text property; a protected

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

Business Logic and Layout


The first feature we want to introduce targets one of the most time and resource consuming problems in the past. Imagine you have a complex ASP Web application for, lets say, a Web portal in the financial area. You have implemented some functionality like registration as a portal user, entering and modifying security sensitive data, storing the data on a database server, and doing some computations on the data. You probably have created many .asp pages, all of them containing HTML and scripting code. Furthermore, imagine that your application hits the market and you wish to extend the functionality and change the layout in parallel, and all this within two weeks. Now you need either a programming-experienced artist or an artistic programmer, because it will be difficult to edit the scripting code and HTML in .asp files synchronously. No more blending of HTML and scripting code An easier way to solve the problem is to separate the code from content. Then it is possible for a programmer to edit the scripting code, while a graphic artist works on the layout. Completely separate layout and processing logic ASP.NET gives you the ability to store the (HTML) user interface and the scripting code in different files. Thus you could have one or more .aspx files specifying the design, and one or more .aspx.cs files (C# resource files) containing the business logic.

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

Page Syntax (1/3)


Directives You can use directives to specify optional settings used by the page compiler when processing ASP.NET files. For each directive you can set different attributes. One example is the language directive at the beginning of a page defining the default programming language. Code Declaration Blocks Code declaration blocks are lines of code enclosed in <script> tags. They contain the runat=server attribute, which tells ASP.NET that these controls can be accessed on the server and on the client. Optionally you can specify the language for the block. The code block itself consists of the definition of member variables and methods. Code Render Blocks Render blocks contain inline code or inline expressions enclosed by the character sequences shown here. The language used inside those blocks could be specified through a directive like the one shown before. HTML Control Syntax You can declare several standard HTML elements as HTML server controls. Use the element as you are familiar with in HTML and add the attribute runat=server. This causes the HTML element to be treated as a server control. It is now programmatically accessible by using a unique ID. HTML server controls must reside within a <form> section that also has the attribute runat=server.

36

ASP.NET

Features

Page Syntax (2/3)


Custom Control Syntax There are two different kinds of custom controls. On the one hand there are the controls that ship with .NET, and on the other hand you can create your own custom controls. Using custom server controls is the best way to encapsulate common programmatic functionality. Just specify elements as you did with HTML elements, but add a tag prefix, which is an alias for the fully qualified namespace of the control. Again you must include the runat=server attribute. If you want to get programmatic access to the control, just add an Id attribute. You can include properties for each server control to characterize its behavior. For example, you can set the maximum length of a TextBox. Those properties might have subproperties; you know this principle from HTML. Now you have the ability to specify, for example, the size and type of the font you use (font-size and font-type). The last attribute is dedicated to event binding. This can be used to bind the control to a specific event. If you implement your own method MyClick(), this method will be executed when the corresponding button is clicked if you use the server control event binding shown in the slide.

ASP.NET

37

Features

Page Syntax (3/3)


Data Binding Expression You can create bindings between server controls and data sources. The data binding expression is enclosed by the character sequences <%# and %>. The data-binding model provided by ASP.NET is hierarchical. That means you can create bindings between server control properties and superior data sources. Server-side Object Tags If you need to create an instance of an object on the server, use server-side object tags. When the page is compiled, an instance of the specified object is created. To specify the object use the identifier attribute. You can declare (and instantiate) .NET objects using class as the identifier, and COM objects using either progid or classid. Server-side Include Directives With server-side include directives you can include raw contents of a file anywhere in your ASP.NET file. Specify the type of the path to filename with the pathtype attribute. Use either File, when specifying a relative path, or Virtual, when using a full virtual path. Server-side Comments To prevent server code from executing, use these character sequences to comment it out. You can comment out full blocksnot just single lines.

38

ASP.NET

Features

ASP.NET Sample (1/2)


Now you know enough about ASP.NET to show you a first example of a very simple ASP.NET page. On a first view this looks very similar to ASP. We have a script block and a body block inside of an HTML sequence. The script block contains a method declaration. In the body block we have a form containing an input field (asp:textbox) and a submit button (asp:button). The file itself is named thisfile.aspx. The <form> tag specifies that the file will be requested again when the submit button is clicked. Lets have a closer look at the asp: tag IDs. The textbox ID is "Name". We find it in the <script> block inside the SubmitBtn_Click method. Here we see an assignment, which accesses the value of the Name object via Name.Text and assigns it to the value of the Message object. Now, "Message" is the ID given to the ASP.NET label, which is responsible for displaying the value of the object on the page.

ASP.NET

39

Features

ASP.NET Sample (2/2)


This slide shows you the output of the sample code. The first time this .aspx file is requested you will see just the input field and the LookUp button in your browser window. Now you can enter a nameor a character sequencein the text box. When you click on the button the same file (Thisfile.aspx) is requested and as a response you will see this.

40

ASP.NET

Features

.aspx Execution Cycle


Now let's see whats happening on the server side. You will shortly understand how server controls fit in. A request for an .aspx file causes the ASP.NET runtime to parse the file for code that can be compiled. It then generates a page class that instantiates and populates a tree of server control instances. This page class represents the ASP.NET page. Now an execution sequence is started in which, for example, the ASP.NET page walks its entire list of controls, asking each one to render itself. The controls paint themselves to the page. This means they make themselves visible by generating HTML output to the browser client.

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

State Management (1/2)


State subsumes any piece of information that is related to or affects a Web application. Handling the state, accessing it, manipulating it, or just reading and consuming it is referred to as state management. Now, in ASP.NET we have state management for application state and session state. Application State First we have to clarify: What is an ASP.NET application? An application in ASP.NET consists of files, pages, modules, and executable code that reside in one virtual directory and its subdirectories. Application state is stored in global variables for a given ASP.NET application. For that reason developers have to follow some implementation rules: Variables for storing application state occupy system resources. A global variable has to be locked and unlocked to prevent problems with concurrent access. Be careful when using those locks in multithreaded server environments. Application state will be lost if the application host is torn down. Application state cannot be shared across Web farms.

46

ASP.NET

Features

State Management (2/2)


ASP.NET provides simple and easy-to-use session state management. A session is restricted to a logical application and defines the context in which a user communicates with a server. Session State ASP.NET session state functionality enfolds: Requesting identification and classification and with it authentication and authorization. Storing data across multiple requests that are related and consecutive. Session events, which are session lifetime management events (OnSessionStart and OnSessionEnd). Automatic release of session data after a timeout occurs; for example, if the client does not revisit the page (or more exactly: the session!).

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

Event Model (1/2)


To handle higher-level application events you can place event-handling code into your Web application. Application-level Event Handling The events that we are talking about here are tightly related to Web Forms. Delegate Model In ASP.NET the event model is based on the delegate model. While an event sender has no knowledge about the event receiver, there has to be an intermediary between them. This is the delegate. A delegate is a class that can hold references to methods. Because a delegate has a signature, it can hold references to only those methods that match this signature. The .NET Framework supports single cast and multicast delegates. Single cast delegates bind a function pointer to only one method. Event Delegates Are Multicast Event delegates are multicast, in that they can hold references to more than one event-handling method at a time. This makes it possible to raise an event that targets more than one event handler. Event Wiring Events are like messages emitted from a sender to tell a receiver that something important has happened. The

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

Event Model (2/2)


Events are raised on the client, but handled on the server. This is a big difference between this event model and former ones, where all events were handled on the client. To understand how events are handled, lets have a closer look at the lifetime of Web Forms. Client sends request to server: First of all, a client must request the Web Forms page. This page, for example, contains a button that fires an event, when it is clicked, to inform other objects that it was clicked. Event raised on client and send to server: If an event occurs on the client, the event information is cumulated and posted as a message to the server. Event handler handles event: On the server side the Web Forms framework has to ascertain which event occurred and determine the method that handles the event. ASP.NET sends response back to client: The response generated by the runtime is sent back to the client. Now the cleanup operation is performed, which includes closing of files, closing database connections, and discarding objects. The Global.asax file: You can use the Global.asax file to store event-handling methods.

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

Section 4: Advanced ASP.NET


Section 4 presents concepts and technologies that go beyond simple ASP.NET development, which are: What are Web Forms and Web Services? What are server controls? See how to work with data. Build real Web applications. How to migrate from ASP to ASP.NET.

ASP.NET

57

Advanced ASP.NET

Web Forms Overview (1/2)


ASP.NET Web Forms is the technology that enables you to separate application code from layout. You can link UI controls and server-side code working closely with events. To look back to the simple ASP.NET sample, you can store the UI code in an .aspx file and store the "working code" to another file. Both are merged on the server side and produce the same page that you have seen before.

58

ASP.NET

Advanced ASP.NET

Web Forms Overview (2/2)


This is a short summary of the features of Web Forms. Create programmable Web Pages Web Forms lets you create programmable Web Pages. You can use any programming language that targets the .NET Framework. A rich set of server-side controls is provided, which cover the most common needs to build challenging Web applications. Run on any browser You can use Web Forms without regard to the clients browser, because the controls can determine which browser is used and can generate the HTML output in the appropriate version even if your browser only supports HTML 3.2. Visual and logic parts of your Web application Your application and the code can be clearly structured. Thats because you can separate the visual from the logic parts. This, together with the Web Forms Event Model and many other features, gives you the ability to create your application in an object-oriented way. WebControls namespace To do this, make use of the rich set of methods and attributes provided by the System.Web.UI.WebControls namespace.

ASP.NET

59

Advanced ASP.NET

Sample Web Forms


Youve already seen short samples in the event part of this module and at the beginning on the first ASP.NET sample. But we will give you a more detailed sample now, focusing on Web Forms. As you can see, the ASP.NET code resides in the thisfile.aspx file, while the code driving the page is stored in another file called FileName.aspx.cs.

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

Web Services Overview (1/2)


For the most part, similar to COM programming Developing Web Services is mostly similar to COM programming. The fundamental goal of Web Services is to provide applications and services that run on different platforms, butin contrast to COMwithout regard to a particular object model. Based on simple, open standards The programming model rests upon simple, open, and widely supported standards like HTTP and XML. Communication = Messaging To eliminate the problems with communication when various platforms meet, Web Services communication is founded on XML-based messaging. Client and Web Service are loosely coupled The Web Service and the consumer of a Web Service only need to understand and know how to treat the messages they interchange. In that case the communication partners are loosely coupled. URLsthe key to Web Services Web Services can be accessed via XML messages, HTTP, and URLs. For example, if you know the name of the Web Service and the file it is declared in, you can access it with your browser with the following line:
http://<serverName>/<VirtualDir>/ <fileName>/<methodName>?var=value

62

ASP.NET

Advanced ASP.NET

Web Services Overview (2/2)


Web Services Wire Formats You can create your Web Services so that they work with open protocol groups like HTTP-POST, HTTP-GET, and the Simple Object Access Protocol (SOAP). SOAP is an XML-based protocol for exchanging structured and type information and is an industryaccepted messaging standard. Web Services Description Language (WSDL) A client of Web Services needs to have information about those Web Services, because it has to be clear, for example, which methods are provided and which parameters must be given. The Web Services Description Language (WSDL) describes the format of messages the Web Service understands. With WSDL you can write XML documents in XML grammarto describe the behavior of services and how clients have to interact with them. Transactions Developers have the ability to make use of ASP.NET transaction features. So, all required interactions can be ACID conforming (atomic, consistent, isolated, durable). If an ASP.NET page is marked as, for example, TransactionRequired, it will be hosted by the COM+ Transaction Service.

ASP.NET

63

Advanced ASP.NET

Sample Web Service


This sample shows the declaration of a Web Service class within an ASP.NET file. The WebMethod attribute declares the method as publicly available. Therefore only the first method (Compute1) is exposed to the world outside as a Web service.

64

ASP.NET

Advanced ASP.NET

Server Controls Overview


When creating Web Forms you can use server controls, which are responsible for generating the user interface. With server controls you can encapsulate behavior into tags. Web Forms Server Controls The term server controls always means Web Forms server controls, because they are specifically designed to work with Web Forms. Server Control Families Web Forms provide different server control families, which are presented in more detail on the following slides: HTML server controls ASP.NET server controls Validation controls User controls Mobile controls

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

Server Control Families (1/2)


Now we will have a detailed look at the different types of controls. HTML Server Controls You can convert simple HTML elements to HTML server controls, let the ASP.NET engine create an instance on the server, and now they are programmable on the server. The conversion is done by simply adding attributes to the HTML tag. The attribute runat=server informs the framework to create a server-side instance of the control. If you additionally assign an ID, you can reference the control in your code. For example, you can use the HTMLAnchor control to program against the HTML <a> tag to dynamically generate the HRef value, or use HtmlTable (HTML <table>) to dynamically create tables and their content. ASP.NET Server Controls ASP.NET server controls are abstract controls. There is no one-to-one mapping to HTML server controls. But ASP.NET comes with a rich set of controls. Another feature is the typed object model. This gives you the potential for type-safe programming. Server controls can automatically detect what browser you are using and generate the proper version of HTML output.

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

Server Control Families (2/2)


Validation Controls Another group of server controls are validation controls. These can be used to check the users entries. Validation can be processed on the client and on the server. Validation on the client side can be performed using a client script. In that case, the user will be confronted with immediate feedbackwithout a roundtrip to the server. Server-side validation in addition provides, for example, security against users bypassing client-side validation. ASP.NET provides the following types of validation: Required entrythe field must be filled in by the user. Comparison to a valuethe entered value is checked against another value of another field, a database, or a constant value by using comparison operators. Range checkingthe users entry is checked to see whether it resides between given boundaries. Pattern matchinga regular expression is defined that the entered value must match. User definedimplement your own validation logic.

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

Server Controls: Syntax


Here we focus on the ASP.NET syntax for server controls. Focusing ASP.NET Syntax
<asp:controlName attributes />

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

Server Controls Sample


Now we will see how to make use of ASP.NET server controls. The first code snippet shows the use of a validator control. This control forces the user to enter a value in the TextBox, and it is configured to check the users entries. The second code snippet, taken from Checkout.aspx.cs, shows how all validators are invited to validate their input in relation to the parameters provided by the control.

ASP.NET

71

Advanced ASP.NET

Working with Data (1/3)


With ASP.NET you can select, insert, update, or delete data from databases or files. SQL and XML Working with data in ASP.NET is, for performance reasons, focused on SQL Server databases and XML sources. Managed data access APIs provided by the runtime As weve seen before, .NET code is managed code. Managed code can access managed data, which is allocated and released automatically by the runtime. The common language runtime provides a rich set of APIs to program against different kinds of data sources. For more information see the ADO.NET module. Essential Objects The essential classes for working with a SQL database or accessing XML sources in ASP.NET are: OleDbConnectionfor setting up a connection to a database. OleDbCommandfor executing queries against a database. DataSetrepresents a relational view of the data in memory.

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

Working with Data (2/3)


Many different clients like Web Forms or Windows Forms want to gain access to persisted data. In addition to the ASP.NET solutions were discussing, the .NET Services Framework includes the Microsoft ActiveX Data Objects (ADO.NET) class libraries to provide data access. ADO.NET Overview With ADO.NET you can incorporate connected and disconnected data access into your application. Managed data providers implement classes for connecting to, issuing commands against, and retrieving results from data stores. DataReaders give you access through high-performance streams, minimizing in-memory objects, and DataSets are used to build a complete relational view of the data in memory. DataSets are always disconnected from their data source. For interoperation of very different kinds of communication partners or platforms, ADO.NET provides XML transformation and validation services for any data. XMLReader objects expose stream access to XML data. XML schemas are used to validate those readers.

74

ASP.NET

Advanced ASP.NET

Working with Data (3/3)


Here well give you a small sample of how to work with data. It uses the ASP.NET built-in mechanisms. The sample is based on an online shopping system. Imagine that a user has already dropped a few products into the shopping cart. The first block shows the code that calculates the order summary. You have to include the System.Data namespace to make use of the DataRow class. In the next line a method is called to work out the order summary. Then a new DataRow object is created and filled with the data calculated before. At last the subtotal value is assigned to lblSubTotal.Text. This is an asp:Label ID that can be used in an ASP.NET file to display the subtotal value as part of a table.

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 to ASP.NET Migration


Now for those who may want to ask if they should throw away all the ASP solutions they built over the years, here's an answer: ASP is not replaced by ASP.NET! There are ways to reuse your ASP files: migrate ASP to ASP.NET or let them cooperate on the same server. ASP and ASP.NET can coexist on the same server Both ASP and ASP.NET can coexist on one IIS server; .asp files are processed using the ASP engine, and .aspx files are processed by the ASP.NET runtime. Make use of ASP.NET features But if you want to make use of .NET features, you have to modify your ASP files. ASP.NET introduces improvements in areas like state management, security, Web farm support, and many more. To migrate, ASP files must be modified Simple ASP applications are easy to migrate. Just change the file extension to .aspx, and if you are lucky, you dont have to modify your code. While ASP.NET is not 100% compatible with ASP, a step-by-step migration is possible. One way to do this with Visual Studio.NET is that you can add existing ASP files to the opened project and rename the files giving them the filename extension .aspx. A migration wizard will be started immediately to generate a codebehind file automatically.

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

Appendix: Exploring DuwamishOnline C#

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

Appendix: Exploring DuwamishOnline C#

Installing the Sample (1/2)


Install the Enterprise Samples with Visual Studio.NET When you install Visual Studio.NET, make sure to include the Enterprise Samples into your installation. By default, they will be installed. If you did not install them, run setup again and simply add them. Location of the C# Version The C# version of the Duwamish sample is located below your Visual Studio.NET installation folder in the .\EnterpriseSamples\DuwamishOnline CS subdirectory. Location of the Visual Basic Version The Visual Basic version does, of course, reside in the .\EnterpriseSamples\DuwamishOnline VB directory. Installation Tasks Before you install the sample, you should check the following prerequisites: You should install the sample on Windows 2000 Server with SQL Server 2000 preinstalled. Duwamish Online uses the English Query feature of SQL Server, so you should make sure that this feature is installed for SQL Server 2000. For more detailed instructions you should read the Readme.htm file before proceeding. Once you are sure that your system has all of the required components, run the Duwamish.msi installer package by double-clicking it from the Microsoft Windows Explorer.

84

ASP.NET

Appendix: Exploring DuwamishOnline C#

Installing the Sample (2/2)


The installation wizard will guide you The installation package will start the installation wizard that will take you through all necessary steps. Defaults should be OK for almost everybody Unless you want to install both the C# and Visual Basic versions side-by-side, the default values should be OK. You may want to pay special attention to the database account (which must have administrative rights) and its password. If you want to install both demos, you should install the first with the default values and choose different settings and directory names for the second one, so that they will not produce conflicts. The exact procedure and options will be obvious once you have installed the first version. Setup will install database, Web site, and code Once you have confirmed all settings, the installer will proceed to install the database, the Web site, and all related projects and code. After installation is complete After the installation is complete, you will find a Duwamish.sln file, which you can open with Visual Studio.NET using Open Solution on the File menu. To run an initial build of the sample code, click Build Solution on the Build menu.

ASP.NET

85

Appendix: Exploring DuwamishOnline C#

Duwamish Architecture Overview


The architecture of Duwamish is mostly equivalent to what the enterprise templates of Visual Studio.NET will generate for you as a skeleton. All access to the database is essentially encapsulated in the DataAccess module, which is being used by the BusinessRules and BusinessFacade to retrieve and store data. Data is communicated throughout the layers using objects that are being provided by the Common module, while the SystemFramework supplies auxiliary functionality for diagnostics and other technical tasks. The Web module implements the user interface for the application, accessing all functionality through the BusinessFacade.

86

ASP.NET

Appendix: Exploring DuwamishOnline C#

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

Appendix: Exploring DuwamishOnline C#

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

Appendix: Exploring DuwamishOnline C#

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

Appendix: Exploring DuwamishOnline C#

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

Appendix: Exploring DuwamishOnline C#

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

Appendix: Exploring DuwamishOnline C#

Shop at DuwamishOnline.NET !
Demo: Duwamish in Action

92

ASP.NET

Appendix: Exploring DuwamishOnline C#

Exploring ASP.NET Features in Duwamish Online


To familiarize ourselves with the Duwamish sample code and to see ASP.NET in action, were going to take a brief tour through the Checkout code block. At this point it is assumed that you could successfully install the Duwamish sample for C# and that you are able to open the solution file Duwamish.sln using File/Open Solution in Visual Studio.NET. To make navigation a bit easier and to allow us to more easily find what we want to show you, were first going to identify the two key tools in Visual Studio.NET that are used in this walkthrough. On the upper right side of your Visual Studio.NET window you should see a number of tabbed, overlapped tool windowstry locating the Solution Explorer and the Class View windows. If you cant find them there, bring both up by clicking Solution Explorer and Class View on the View menu. Duwamish.Web First, go to the Solution Explorer. The Duwamish sample consists of six separate projectsone for each subsystem that weve seen in the architectural overview. The scope that we are going to look at is Web. But before we even dig into the code, you will notice the References folderexpand it. This folder contains references to all external .NET assemblies that are being used in this project. This is equivalent to libraries in C++, but much easier from the start.

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.

You might also like