ASP.NET improves on the type of application that developers could use in classic ASP, and adds a new application, called a webservice. Read this article to learn more about the new application, which lets clients use the functionality of a particular application without needing to use the application's specific user interface. The article is excerpted from chapter two of ASP.NET in a Nutshell, by G. Andrew Duthie. (O'Reilly, 2003, ISBN: 0596005202).
Contributed by O'Reilly Media Rating: / 47 December 15, 2004
In Chapter 1, we introduced the .NET platform, some of its most important concepts, and new features available in ASP.NET. In this chapter, we’ll look at the types of applications you can create with ASP.NET, discuss when you might want to use one type over another, explore the structure of ASP.NET applications, and look at the various file types that make up an ASP.NET application.
Application Types
In classic ASP, there was really only one type of application—one in which a client accessed a page with the .asp extension and in which that page, either through embedded VBScript or JScript or through script in combination with components built on Microsoft’s COM standard, returned HTML to the browser to form the user interface with which the client would interact. Clients typically interacted with the application only through this user interface and did not have the option of creating their own alternative interface to the functionality exposed by the application.
ASP.NET provides an enhanced version of this type of application, which we’ll discuss in the next section. ASP.NET also introduces a new type of application, called a webservice, which provides clients the ability to use functionality exposed by an application without being tied into that application’s user interface implementation.
ASP.NET Web Applications
The ASP.NET Web Application is the type of application most developers will work with on a regular basis. The terminology comes from the description used in the Visual Studio .NET environment to describe the project type used to create this type of application. You may also hear this type of application described as an ASP.NET Web Forms Application. For reasons we’ll explore in the next chapter, we prefer the former term.
An ASP.NET Web Application, in its simplest form, consists of a directory made available via HTTP using the IIS administration tool or through the Web Sharing tabof a folder’s Properties dialog (or by creating a webapplication project in Visual Studio .NET) and at least one ASP.NET page, designated by the .aspx file extension. This file (or files), whose structure we’ll discuss in detail in the next chapter, typically contains a mix of HTML and server-side code. This HTML and server-side code combine to create the final output of the page, typically consisting of HTML markup that is sent to the client browser. A simple ASP.NET page is shown in Example 2-1.
The page shown in Example 2-1 simply executes the code appearing in the <script runat="server">, which uses an ASP.NET Label control to display some text, along with the standard HTML tags that are contained in the file. Figure 2-1 shows the output of the page as viewed in Notepad by using the View Source option in Internet Explorer. In this case, the Page_Load method (actually an event handler, which we’ll discuss more in later chapters) sets the Text property of an ASP.NET Label control to “Hello, world!”. Because the Label control will render its Text property to the browser automatically, “Hello, world!” will appear in the output that is sent to the browser, as shown in Figure 2-1.
The key to understanding how ASP.NET Web Applications work is understanding that the code in a <script runat="server"> block (or a <% %> render block) is executed on the server—after the client requests the page, but before the output of the page request is sent to the client browser. This allows developers to decide, based on the code they write and the input received from the user, just what output actually is sent to the browser, either directly (such as by calling the Write method of the Response object) or by manipulating controls, as shown in Example 2-1. It also allows additional functionality, such as server-side state management, to be provided to these applications.
Figure 2-1.Output of a simple ASP.NET page (source view)
Web Forms and Web Controls
Example 2-1 uses a control called the Label control to output text to the browser. This control is an example of what are referred to as Web Controls. Web Controls (also referred to as Server Controls), which are discussed in detail in Chapter 5, are compiled classes that run on the server and provide functionality similar to that of Windows controls such as textboxes, dropdown lists, etc. The key is that these controls run at the server, and so can be manipulated programmatically in server-side code.
WebForm is a term used to describe an .aspxfile that makes use of Web Controls.
Besides the containing directory and ASP.NET file(s), an ASP.NET Web Application may also contain configuration files ( web.config ), User Control files ( .ascx ), and an application settings file ( Global.asax ), as well as code-behind, assembly, and class files that provide additional functionality to the application. We’ll discuss each of these file types later in this chapter.
This chapter is from ASP.NET in a Nutshell, by G. Andrew Duthie. (O'Reilly, 2003, ISBN: 0596005202). Check it out at your favorite bookstore today. Buy this book now.
The ASP.NET Mobile Web Application is a subtype of Web Application specific to developing for mobile devices such as cell phones and PDAs. The primary thing that distinguishes a mobile webapplication from a standard web application in ASP.NET is the use of the ASP.NET mobile controls, which are built into the .NET Framework as of Version 1.1. These include the mobile Form control and standard controls such as labels, textboxes, and panels, as well as mobile-specific controls such as the TextView, PhoneCall, and SelectionList controls. Note that both mobile Web Forms pages (those that use the mobile controls) and standard Web Forms pages can coexist within the same application, if desired.
To simplify development of ASP.NET applications for mobile devices, Visual Studio .NET 2003 provides an ASP.NET Mobile Web Application project template. This template includes a default mobile Web Form, as well as a special section added to the Web.config file called <deviceFilters>, which contains settings for device-specific rendering.
ASP.NET Web Services
The other type of application available to ASP.NET developers is the ASP.NET WebService. Like ASP.NET Web Applications, there are a number of terms floating around for this type of application. (Microsoft refers to web services as “XML Web Services,” perhaps in hopes of a positive association between web services and the XML standard.) A web service is an application that exposes programmatic functionality to clients over the Internet or an intranet using the underlying plumbing of a developing W3C standard called SOAP. In simple terms, it can be seen as a simple function call across the Internet.
What Is SOAP?
The proposed SOAP standard, which at the time of this writing was a W3C Candidate Recommendation (see http://www.w3.org/Consortium /Process-20010719/tr.html#RecsCRfor information on where this fits in the standardization process) and versioned at 1.2, describes a protocol that may be used within the framework of HTTP (other transport protocols are possible, but the SOAP specification does not define how to use them) to send and receive requests and responses consisting of either specific data or remote procedure calls and responses, or both. The SOAP specification defines the format for messages sent via SOAP, methods for communicating how a message should be processed, and encoding rules for communicating data types across heterogeneous platforms.
Assuming that the proposed SOAP standard is adopted as a W3C Recommendation ( recommendation is the term used by the W3C to describe stable standards such as HTML 4.01; see http://www.w3.orgfor more information on current recommendations), application developers on a given platform can expose their functionality to others on different platforms in a fashion that makes the differences in platform transparent. As long as both the server and the client follow the SOAP specification, the applications can communicate, regardless of the platform differences.
Since SOAP has not yet been adopted as a recommendation and is still under development, current implementations from Microsoft and other vendors have not yet achieved the level of cross-platform interoperability that is promised once SOAP is adopted as a recommendation. As such, you should take the time to test and evaluate the interoperability of your chosen platform(s) before committing substantial resources to web services, if you are planning to use web services to facilitate cross-platform interoperability.
The simplest form of an ASP.NET Web Service consists of a directory made available via HTTP using the IIS administration tool or through the Web Sharing tab of a folder’s Properties dialog (or by creating a Web Application project in Visual Studio .NET) and at least one web service file, designated by the .asmx file extension. Unlike an ASP.NET page, this file (or files), whose structure we’ll discuss in detail in Chapter 4, typically does not contain HTML, but consists solely of server-side code. The methods to be exposed by the web service carry the WebMethod attribute (note that the syntax of the WebMethod attribute varies depending on the language used). A simple web service is shown in Example 2-2.
Example 2-2. A simple web service
<%@ WebService Language="VB" Class="Hello" %>
Imports System Imports System.Web.Services
Public Class Hello : Inherits WebService <WebMethod()> Public Function SayHello() As String Return("Hello, World!") End Function End Class
If the .asmx file that makes up this webservice is called from a browser, ASP.NET will output a page that documents how the webservice should be called, and also provides the ability to test the invocation of the web service. This page is shown in Figure 2-2.
When invoked, the web service shown in Example 2-2 will return “Hello, World!” as an XML-formatted response, according to the SOAP 1.1 specification, as shown here:
The documentation page provided by ASP.NET also allows you to review the Web Service Description Language (WSDL) description of your web service. WSDL, which we’ll discuss further in Chapter 4, is an XML-based format for describing the functionality exposed by a web service, including the format and data type of input and output parameters, and can be considered a contract for how clients interact with the web service. In this way, WSDL plays a role similar to that of Interface Description Language (IDL) in Microsoft’s COM component specification.
Besides providing a detailed discussion of how to create a webservice, Chapter 4 shows you how to consume a web service.
Figure 2-2.Output of a simple web service
This chapter is from ASP.NET in a Nutshell, by G. Andrew Duthie. (O'Reilly, 2003, ISBN: 0596005202). Check it out at your favorite bookstore today. Buy this book now.
Although it is convenient, for the sake of discussing application types, to divide ASP.NET applications into web applications and web services, the truth is that from a practical standpoint, ASP.NET applications can be comprised of both types; an ASP.NET Web Application may contain .asmx files that implement web services, and a webservice application may contain .aspx files that implement user interfaces for web services or functionality contained in .NET assemblies. Thus, from the standpoint of application structure, ASP.NET Web Applications and ASP.NET Web Services are quite similar.
Application Structure
The structure of an ASP.NET application consists of a site or virtual directory in IIS and at least one ASP.NET page or web service. Optionally, each ASP.NET application may have:
A single global.asax file, located in the root of the application.
One or more web.config files. There can be only one web.config file per directory or subdirectory in the application.
One or more User Control files bearing the .ascx extension.
One or more class files, either for ASP.NET code-behinds or for assemblies used in your application.
A /bin directory containing .NET assemblies you wish to use in your application. Assemblies in the /bin directory are automatically made available to your application.
ASP.NET Web Applications created in Visual Studio .NET contain Solution and Project-related files ( .sln, .suo, .vbproj, and .csproj, for example), and an optional default cascading style sheets file ( .css). These applications may also optionally contain resource files ( .resx), dataset and/or XML schema definitions ( .xsd), and other file types.
Any other type of file ( .htm, .asp, images, etc.) that you’d expect a classic web application to contain. Note, however, that .asp pages within an ASP.NET application will not share an Application and Session state with the ASP.NET application.
Figure 2-3 provides a visual explanation of how an ASP.NET application is structured.
Figure 2-3.Structure of an ASP.NET application
This chapter is from ASP.NET in a Nutshell, by G. Andrew Duthie. (O'Reilly, 2003, ISBN: 0596005202). Check it out at your favorite bookstore today. Buy this book now.
In ASP.NET, as in classic ASP, the boundary of an application is determined primarily by the site or virtual directory defined for that application in IIS. Requests for ASP.NET pages or web services that reside within that site or virtual directory and its subdirectories are treated as part of the application and have access to application-specific items such as the Application and Session intrinsic objects (provided, respectively, by the HttpApplicationState and HttpSessionState classes). They also share resources with other requests to the application.
Request Lifecycle and Handling
When a request comes in from a client for a file within the purview of IIS (i.e., an HTTP request for a file within one of the sites or virtual directories set up in IIS), IIS checks the file extension of the file being requested and then checks its mapping of file types to handler programs to determine which program should be used to process the request. In the case of a classic ASP application, a request for a file with the .asp extension is handled by the asp.dll ISAPI application. The App Mappings tab of the Application Configuration dialog for IIS, shown in Figure 2-4, allows you to view and modify the mappings of file extensions to the executables used to handle those extensions, as well as to determine the HTTP verbs (GET, POST, etc.) that qualify the mapping.
Requests for files with the .aspx and .asmx extensions and for other ASP.NET-related files are handled by the aspnet_wp.dll ISAPI application. This application, in turn, hands the requests off to the aspnet_wp.exe worker process. Once the request is handed off to the ASP.NET worker process, it handles the rest of the processing by:
JIT (just in time)-compiling the code in the page (and in any code-behind page identified with thesrcattribute) if no cached compiled version of the requested resource exists.
Executing the compiled assembly associated with the page or web service, including refreshing any control or page state from a previous request, handling events raised by the request, and rendering the appropriate output to the client.
Releasing used resources and discarding any transient state information (information not stored in either the Application or Session state collections).
With the exception of the Application state collection, which is available to all clients within a given ASP.NET application, and the Session state collection, which is associated with a specific client by a value either stored in an HTTP cookie on the client or munged into the URL for the application, each individual request to the application is independent from any other, even for that client.
The practical effect is that each request must contain sufficient information to successfully process the request—whether that information comes from form fields passed from the client, information stored in the Application or Session collections, or even information from cookies or a database.
This chapter is from ASP.NET in a Nutshell, by G. Andrew Duthie. (O'Reilly, 2003, ISBN: 0596005202). Check it out at your favorite bookstore today. Buy this book now.
A number of different file types are associated with an ASP.NET application, and it’s important to understand the purpose of each type, even if you aren’t using all of them in your current applications. In this section, we’ll look at the major file types associated with ASP.NET Web Applications and web services and what each of them does.
web.config Files
web.config is the file type used for configuration of various settings within an ASP.NET application. Applications may contain more than one web.config file (though there may be only one per directory or subdirectory), and the web.config files are applied in an hierarchical fashion. What this means is that if you have defined a particular setting (such as the user accounts permitted to access that directory) in the web.config file at the root of your application, this setting applies to the application and all of its subdirectories, if it has any. You can override that setting for a particular subdirectory by using a web.config file in a subdirectory of the application. The web.config files use an XML-based syntax, and both the tag names and their attributes are case-sensitive.
web.config provides configuration settings for:
Application-specific settings, such as connection string information (since the web.config file resides within the web application’s file space, it is probably best to avoid storing sensitive information such as passwords in plain text in a configuration file, or at all, if that’s feasible).
Authentication and authorization.
Browser capabilities (mapping specific functionality to the information retrieved from a User Agent string).
Compilation settings, including whether an application should be run in debug or release mode.
Custom error handling information.
Globalization settings.
HttpHandlers and HttpModules associated with the application.
HttpRuntime settings.
Application Identity and encryption/decryption key settings.
ASP.NET Page defaults (for the @ Page directive).
ASP.NET Process settings, including settings for Web Gardens, and proactive restart of applications based on memory used or number of requests received.
Code-access security settings, including mappings of trust levels to security policy files, and trust setting for an application.
Session state settings, including whether to run Session state in process, out of process, or in SQL Server.
Application Trace settings. Tracing is a useful new feature for debugging and troubleshooting that we’ll discuss in Chapter 10.
Web service settings.
Note that web.config is an optional file. Any configuration settings not set in a web.config file within the application will be inherited from the server-level configuration file, machine.config. A sample web.config file is shown in Example 2-3.
<sessionSTATE mode="InProc" stateConnectionString="tcpip=127.0.0.1:42424" sqlConnectionString="data source=127.0.0.1; user id=sa;password=" cookieless="false" timeout="20" />
</system.web>
</configuration>
We’ll discuss how to make changes to web.config, and the syntax of the various configuration sections, in Chapter 8.
This chapter is from ASP.NET in a Nutshell, by G. Andrew Duthie. (O'Reilly, 2003, ISBN: 0596005202). Check it out at your favorite bookstore today. Buy this book now.
global.asax performs a similar function in ASP.NET that global.asa performs in classic ASP. That is, it is an optional file that may contain code to respond to Application-or Session-level events. Like global.asa in classic ASP, there can be only one global.asax file per ASP.NET application. Unlike the global.asa file in classic ASP, which was parsed, the global.asax application file is compiled at runtime into a .NET managed assembly ultimately derived from the HttpApplication class. In addition to handling Application-and Session-level events, such as Session_OnStart, global.asax also allows you to handle events raised by HttpModules associated with your application (in fact, the Session state in ASP.NET is implemented as an HttpModule, so its events are already handled this way).
The global.asax file can be constructed one of two ways. The file can contain the event handlers and other code you want associated with your application directly, or it can reference a code-behind class file that contains the event handlers and code to associate with the application. Note that the code-behind used, if any, must inherit from the HttpApplication class in the System.Web namespace. The latter is the way that the global.asax files in ASP.NET applications created with Visual Studio .NET are constructed. Example 2-4 shows a typical global.asax file that uses code-behind, while Example 2-5 shows the code-behind file it uses.
Public Class Global Inherits System.Web.HttpApplication
Sub Application_BeginRequest(ByVal sender As Object, _ ByVal e As EventArgs) ' Fires at the beginning of each request End Sub
Sub Application_AuthenticateRequest(ByVal sender As Object, _ ByVal e As EventArgs) ' Fires upon attempting to authenticate the user End Sub
Sub Application_Error(ByVal sender As Object, ByVal e As EventArgs) ' Fires when an error occurs End Sub
End Class
We’ll discuss the uses of the global.asax file in more detail in Chapters 13 and 19.
This chapter is from ASP.NET in a Nutshell, by G. Andrew Duthie. (O'Reilly, 2003, ISBN: 0596005202). Check it out at your favorite bookstore today. Buy this book now.
.aspx files, also known as ASP.NET pages or Web Forms, are the meat and potatoes of an ASP.NET Web Application. These files contain the HTML tags, server controls, and code that present a user interface to your users, and process their requests (or call helper functions in business-tier components to do so). Like the global.asax file, .aspx files may either contain code directly or refer to a code-behind class that contains the code for that page. Note that the code-behind used, if any, must inherit from the Page class in the System.Web.UI namespace. We’ll discuss .aspx files in detail in Chapter 3.
.asmx Files
.asmx files are the files used to implement ASP.NET Web Services. These files contain the methods, marked with the WebMethod attribute, that will be exposed by your application as web services. Like global.asax and .aspx files, .asmx files may either contain code directly or refer to a code-behind class that implements the methods to be exposed as web services. Note that the code-behind used, if any, must inherit from the WebService class in the System.Web.Services namespace We’ll discuss .asmx files in detail in Chapter 4.
.ascx Files
.ascx files are used to implement what are known as ASP.NET user controls. User controls are a technique for code reuse that lies somewhere between the function of the #Include directive in classic ASP (which you can still use in ASP.NET, if you choose) and the function of custom ASP.NET Server Controls. User controls are made up of HTML tags, server controls, and code (or any combination of the above), and can be reused through a simple tag-based syntax. They have the advantages of being simpler to develop than custom server controls, as well as offering greater functionality than includes (such as the ability to expose properties and methods). We’ll discuss user controls further in Chapters 3 and 6.
This chapter is from ASP.NET in a Nutshell, by G. Andrew Duthie. (O'Reilly, 2003, ISBN: 0596005202). Check it out at your favorite bookstore today. Buy this book now.
In addition to the file types mentioned here, you’ll also frequently deal with code-behind and/or class files. A code-behind file, also known as a code-behind class file, is a file containing .NET managed code (such as VB.NET or C#) that defines a class from which an ASP.NET page file, web service file, or application file inherits. This inherited relationship is indicated by the codebehind or src attribute, which indicates the file containing the code-behind class, and the inherits attribute, which indicates the namespace name (if any) and the class name of the class to inherit. Example 2-4 shows these attributes in action. At runtime, when the page, the web service, or the application is initialized for the first time, the ASP.NET runtime locates the code-behind file and either executes the compiled assembly associated with it (in the case of the codebehind attribute, which is used when the class will be precompiled) or compiles the class into an assembly dynamically (in the case of thesrcattribute). We’ll discuss the use of code-behind classes and the choice of which attribute to use in greater detail in Chapters 3 and 4.
Class files are simply source code files containing .NET managed code that is organized into namespaces and classes and that has been compiled before deployment, using either the Visual Studio .NET environment or the appropriate command-line compiler, into a .NET managed assembly. Class files are typically kept separate from the webapplication in which their assemblies are used, just as the source code for COM components used in classic ASP applications is typically kept separate from the web tree.
.vb extension
The .vb extension indicates source code files written in Visual Basic .NET. By default, code-behind classes created by the Visual Studio .NET environment use the naming convention filename.parentfileextension.languageextension. Thus, a VB.NET code-behind file for an ASP.NET page might have the name WebForm1.aspx.vb. This naming convention clearly conveys the relationship between the code-behind file and the page that inherits from it, as well as the language used in the code-behind file, so you can adopt this naming convention or use a similar one, even when not developing in the Visual Studio .NET environment.
.cs extension
The .csextension indicates source code files written in Microsoft’s new C# (pronounced “C Sharp”) language. These files, when created by Visual Studio .NET, use the same naming convention as the one just described.
parentfileextension.languageextension. Thus, a VB.NET code-behind file for an ASP.NET page might have the name WebForm1.aspx.vb. This naming convention clearly conveys the relationship between the code-behind file and the page that inherits from it, as well as the language used in the code-behind file, so you can adopt this naming convention or use a similar one, even when not developing in the Visual Studio .NET environment.
.cs extension
The .cs extension indicates source code files written in Microsoft’s new C# (pronounced “C Sharp”) language. These files, when created by Visual Studio .NET, use the same naming convention as the one just described.
This chapter is from ASP.NET in a Nutshell, by G. Andrew Duthie. (O'Reilly, 2003, ISBN: 0596005202). Check it out at your favorite bookstore today. Buy this book now.