BUY THIS BOOK
Add to Cart

Print Book $44.95


Safari Books Online

What is this?

Add to UK Cart

Print Book £31.95

What is this?

Looking to Reprint this content?


ASP.NET in a Nutshell
ASP.NET in a Nutshell, Second Edition By G. Andrew Duthie, Matthew MacDonald
August 2003
Pages: 998

Cover | Table of Contents | Colophon


Table of Contents

Chapter 1: Introduction
ASP.NET is Microsoft's latest technology for building web-based applications and services, a successor to Active Server Pages (ASP) that draws on the power of the .NET Framework development platform and the Visual Studio .NET developer toolset. To better understand ASP.NET, it is important to understand some key concepts of the .NET development platform. It is also helpful to grasp object-oriented development (OOD), which is at the very heart of the .NET Framework that provides the foundation for ASP.NET development. In this chapter, we'll review these concepts, look at what's new in ASP.NET (versus classic ASP), review new features in ASP.NET 1.1, and discuss choosing a language to suit your needs.
A t the core of Microsoft's .NET platform initiative is a new set of technologies known collectively as the .NET Framework, which we'll refer to commonly as the Framework. The Framework provides a platform for simplified rapid development of both web-based and Windows-based applications. The Framework has two primary components, the Common Language Runtime (CLR) and the Framework Class Library (FCL).
As with many new technologies, there are a host of new terms and acronyms to understand, so we'll introduce and explain the most important ones in the Framework over the next several sections.
The CLR is the execution environment for code written for the .NET Framework. The CLR manages the execution of .NET code, including memory allocation and garbage collection (which helps avoid memory leaks), security (including applying differing trust levels to code from different sources), thread management, enforcing type-safety, and many other tasks.
The CLR works with every language available for the .NET Framework, so there is no need to have a separate runtime for each language. Code developed in a .NET language is compiled by the individual language compiler (such as the Visual Basic .NET compiler) into an intermediate format called (appropriately enough) Intermediate Language (IL). At runtime, this IL code generated by the compiler is just-in-time (JIT) compiled by the CLR into native code for the processor type the CLR is running on. This compilation provides the flexibility of being able to develop with multiple languages and target multiple processor types while still retaining the performance of native code at execution time.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
.NET Platform Fundamentals
A t the core of Microsoft's .NET platform initiative is a new set of technologies known collectively as the .NET Framework, which we'll refer to commonly as the Framework. The Framework provides a platform for simplified rapid development of both web-based and Windows-based applications. The Framework has two primary components, the Common Language Runtime (CLR) and the Framework Class Library (FCL).
As with many new technologies, there are a host of new terms and acronyms to understand, so we'll introduce and explain the most important ones in the Framework over the next several sections.
The CLR is the execution environment for code written for the .NET Framework. The CLR manages the execution of .NET code, including memory allocation and garbage collection (which helps avoid memory leaks), security (including applying differing trust levels to code from different sources), thread management, enforcing type-safety, and many other tasks.
The CLR works with every language available for the .NET Framework, so there is no need to have a separate runtime for each language. Code developed in a .NET language is compiled by the individual language compiler (such as the Visual Basic .NET compiler) into an intermediate format called (appropriately enough) Intermediate Language (IL). At runtime, this IL code generated by the compiler is just-in-time (JIT) compiled by the CLR into native code for the processor type the CLR is running on. This compilation provides the flexibility of being able to develop with multiple languages and target multiple processor types while still retaining the performance of native code at execution time.
While there is some up-front cost on first execution to the JIT compilation model, the Framework also offers the ability to pregenerate native code at install time through a utility called
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Object Orientation in the .NET Platform
The .NET Framework was built to be object oriented from the ground up. What does this mean? For those of you who are unfamiliar with object-oriented programming, here's a quick review.
We've already discussed classes. Classes are the blueprints or templates from which objects are created. Objects, the heart of object-oriented programming, are usable instances of a class. Objects expose properties, which contain data related to or about the object, and/or methods, which allow actions to be performed on the object.
In object-oriented programming, objects need to support three important qualities: encapsulation, inheritance, and polymorphism.
Encapsulation refers to the ability of an object to hide its internal data from outside view and allow access to only that data through publicly available methods. This helps prevent clients from accidentally or purposefully leaving object data in a corrupt state and makes it easier for the developer of the class on which the object is based to change the internal implementation of these data members without breaking its clients.
Inheritance refers to the ability to derive one class from another. This allows developers to create a new class based on an existing class. The new class inherits all methods and properties of the existing class. The developer can then add new methods or properties or override existing methods. Inheritance allows you to develop specialized versions of objects that are customized to meet your precise needs. We'll discuss this type of scenario more in Chapter 6.
The .NET Framework offers only single inheritance—that is, a class may only derive from a single base class. This is different from languages such as C++, which allow classes to be derived from multiple base classes.
Polymorphism refers to the ability of multiple classes derived from the same base class to expose methods with the same name—all of which clients can call in exactly the same way, regardless of the underlying implementation. Thus, a
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Choosing a Language
Choosing which language to use when developing ASP.NET applications is both easier and harder than choosing a language for classic ASP development. It is harder because it may be intimidating for some to choose between a substantially revised Visual Basic and a completely new language, C#. It is easier because the choice of language no longer requires giving up substantial amounts of functionality for your preferred language.
As in many other cases, including language choice in classic ASP, a lot of the decision is determined by where you're coming from. If you're:
An experienced ASP developer who has used VBScript
You'll probably prefer Visual Basic.NET.
An experienced ASP developer who's used JScript
You'll want to look at C# or JScript.NET (keeping in mind that finding code examples in C# is easier, since the novelty of the language makes it more interesting for many).
An experienced Visual Basic developer
Visual Basic.NET is the obvious choice, but you may also find it worthwhile to check out C#, which offers a lot of the power of C++ without such a steep learning curve.
An experienced C, C++, or Java developer
You'll probably feel right at home with C#, which, as a C-derived language, shares a lot of syntax with these languages.
New to ASP.NET development, with no prior ASP experience
Visual Basic.NET will probably be easiest to learn, although C# runs a close second.
Because of the level of cross-language interoperability in .NET, your choice needn't be an either/or. You can feel free to create applications and classes in Visual Basic.NET, C#, JScript.NET, or any .NET-enabled language, knowing that they will be able to work together smoothly and easily, thanks to the CLR.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Why and When Would I Use ASP.NET?
You should use ASP.NET for any new projects you are about to start for the following reasons:
  • Reduced development time
  • Increased performance
  • Increased application stability
  • Increased scalability
  • New ASP.NET features (see the discussion later in this chapter)
Some of these benefits, such as reduction in development time, assume familiarity with the .NET development platform. If you are starting your first ASP.NET development project, you should allow some time for getting up to speed on the new platform. Subsequent projects should see reduced development time over classic ASP, as developers become more familiar with the platform.
In addition to these factors, ASP.NET, like ASP, is available for free. The only costs associated with ASP.NET development are the costs of the operating system on which you wish to run your application (Windows 2000, Windows XP, or Windows Server 2003) and the cost of the development environment you choose to use. Of course, as with classic ASP, you can use free or inexpensive text editors to create your applications. Given that the .NET Framework is a free add-on to Windows (and is integrated with the Windows Server 2003 line), it is possible to create ASP.NET applications without spending a penny beyond the cost of the operating system and hardware on which it will run. Integrated development environments, such as Microsoft Visual Studio .NET 2003, are also available at an additional cost and greatly simplify ASP .NET development.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Why and When Would I Port an Existing Application to ASP.NET?
A trickier question is, "When will it be worthwhile to make the effort to migrate an existing application from ASP to ASP.NET?" The reality is that while classic ASP and ASP.NET have many common features, for most applications, it will not be a trivial task to migrate an application from one to the other. Changes in languages, as well as some changes in the way that ASP.NET operates compared to classic ASP, mean that depending on how your classic ASP application is structured, migration could require a significant amount of effort.
How do you decide whether a migration is worthwhile? If your application is in production, meets your needs functionally and in terms of performance and scalability, and you do not anticipate further development on the application, it's probably best to simply run it as a classic ASP application. One big plus of the ASP.NET architecture is that it runs side by side with classic ASP, so you don't have to migrate applications. Keep in mind, however, that while classic ASP and ASP.NET applications can run side by side, even in the same directory, they do not share Session and Application context. Thus, you will need to devise your own means of transferring any information you store in the Session or Application collections to and from ASP and ASP.NET, if you want to share that information between classic ASP and ASP.NET pages.
If your application is due for a new development cycle or revision, it's worth examining the types of functionality that your application uses and examining whether ASP.NET would be helpful in meeting the needs of the application. For example, if you have an application that struggles to meet your needs in terms of performance and scalability, the improved performance of the compiled-code model of ASP.NET and its new out-of-process Session State support may enable you to meet these goals easily.
What's important to consider is balancing the cost of migration against the benefits offered by migration. In this book, we will discuss the improvements and benefits offered by ASP.NET. It is left as an exercise for the reader to weigh these improvements against one another and determine whether to migrate a particular application.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
New Features in ASP.NET
We'll close our introductory look at the .NET platform with a list of new features that are unique to ASP.NET and the chapter in which each will be discussed.
Web Forms
A new feature that, in combination with an editor such as Visual Studio .NET, provides the ASP.NET developer the same drag and drop development convenience enjoyed by Visual Basic developers for years. Web Forms improve the speed of development by encapsulating frequently used features into server controls, which are declared using a tag-based syntax similar to HTML and XML. We'll discuss Web Forms in Chapter 3 and Chapter 12.
Web services
Web services allow developers to expose the functionality of their applications via HTTP and XML so that any client who understands these protocols can call them. Web services can make the task of application integration easier, particularly in situations in which application-to-application integration is made difficult by firewalls and/or differing platforms. We'll discuss web services in Chapter 4.
Server controls
Server controls are declared using an HTML-like syntax, making them easier to work with for page UI designers. They are executed on the server, returning HTML to the browser. Server controls may be manipulated on the server programmatically and provide power and flexibility for applications that must support a variety of browsers. We'll discuss using server controls in Chapter 5 and custom server control development in Chapter 6.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Chapter 2: ASP.NET Applications
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.
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 web service, which provides clients the ability to use functionality exposed by an application without being tied into that application's user interface implementation.
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 tab of a folder's Properties dialog (or by creating a web application project in Visual Studio .NET) and at least one ASP.NET page, designated by the
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
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 web service, which provides clients the ability to use functionality exposed by an application without being tied into that application's user interface implementation.
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 tab of a folder's Properties dialog (or by creating a web application 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.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Application Structure and Boundaries
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 web service 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.
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.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Application File Types
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 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.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Chapter 3: Web Forms
Web Forms are an ASP.NET technology used to create programmable web pages. They are the primary building block of ASP.NET Web Applications. The main goal of Web Forms is to bring the same productivity to web applications that Visual Basic brought to Windows applications. Web Forms consist of the user interface (UI) and the UI logic written on the server side. The UI and UI logic can reside either in the same file or in separate files.
Web Forms in ASP.NET offer a number of advantages over ASP and other technologies for generating web applications. ASP.NET Web Forms:
  • Provide support for any HTML 3.2-compliant browser. Even ASP.NET Server Controls that provide advanced client-side functionality will gracefully degrade for browsers that do not support DHTML or script. These controls will, however, take advantage of such support in browsers such as Internet Explorer 5.0 or later.
  • Are built on the Common Language Runtime and provide all the benefits of the runtime, such as managed execution, type safety, and inheritance.
  • Can be built with any Common Language Runtime language, including C#, Visual Basic .NET, and JScript .NET.
  • Can be created using rapid application development tools such as Visual Studio .NET. You can build a Web Forms page simply by dragging and dropping controls from the VS.NET toolbox onto the page.
  • Provide a rich set of server controls that provide almost all the functionality required for a web application. ASP.NET ships with a broad array of built-in server controls.
  • Offer a flexible programming model, in which code may be included in the same file as the Web Form, as in the classic ASP model or in separate module files, referred to as code-behind files. Code-behind promotes the separation of code and content, which can improve your code's readability, maintainability, and reusability.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Structuring an ASP.NET Page
An ASP.NET page is a declarative text file with the extension . aspx. A page consists of structural elements that can perform various operations—ultimately resulting in output of HTML or other MIME-type output that can be handled by the browser. An ASP.NET page can contain any or all of the following elements:
Page directives
Start with the @ symbol, followed by attribute/value pairs, and are used to specify page-level settings, such as the language used in the page or namespaces to be imported. For example, the following code specifies the C# programming language:
<%@ Page Language="C#" %>
Code declaration blocks
Consist of variable and member declarations within <script>...</script> tags, as follows:
<script language="C#" runat="server"> 
// code goes here
</script>
Note that there are limitations on what code you can place in <script> blocks in ASP.NET. In classic ASP, you can write executable code in a <script> block without wrapping that code in a subroutine. In ASP.NET, only variable declarations can be placed outside of a subroutine. Any other executable code not contained in a subroutine will result in an error.
Render code blocks
Used to write inline code and inline expressions within HTML elements. For example:
<% int i; %>
<H1><%=Heading%> </H1>
There are limitations on what code you can place in render blocks in ASP.NET. In classic ASP, you can define subroutines in render blocks. In ASP.NET, this is not permitted and results in an error.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Stages of Page Processing
During Web Forms processing, the page goes through distinct stages, which are illustrated in Figure 3-1. The Web Forms processor calls a corresponding page processing event at each stage.
Figure 3-1: The stages of Web Forms page processing
In ASP pages other than global.asa, you have to write your program logic sequentially because your code is executed in the order in which it appears (termed procedural programming). ASP.NET, on the other hand, features event-driven programming, in which the order of execution of a particular code block is not predetermined. You write a block of code called an event handler that is executed whenever that event occurs.
If you've developed client-side code or have programmed using Visual Basic, you're already familiar with event-driven programming. ASP.NET takes event-driven programming to the server side, encouraging you to structure your programming logic into event handlers. In ASP.NET, the Page object is the representation of your ASP.NET page, and you can write handlers at the page level. ASP, on the other hand, supports only events at the application and session levels.
The Page class inherits all of its important events from the System.Web. UI.Control class, which is the ultimate parent of all server controls. This means that all events described below also apply to both built-in and custom server controls because all of these controls ultimately derive from System.Web.UI.Control.
We'll examine these events in detail. First, however, we'll examine how an event is associated with a particular event handler in Visual Basic .NET and C#.
There are three main techniques for handling events in ASP.NET, one of which takes advantage of ASP.NET's ability to wire up standard event handlers automatically and two of which rely on wiring up event handlers manually.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
State Management
In a typical web page, it is very common for data entry forms to retain their values after the form has been posted and the same page is returned to the client (that is, to retain the values from a posted form in the postback). To implement this feature in classic ASP, you need to determine whether or not the page is requested by a client for the first time. You also need to write code that will display the submitted value in the controls. In contrast, ASP.NET performs state management automatically in postbacks.
ASP.NET uses a simple hidden HTML form field to retain the values automatically during postbacks. There are no ActiveX controls or applets or client-side scripts used to maintain state. Thus, you need not write code to retain values explicitly.
ASP.NET maintains only the state of server controls—i.e., the controls declared with the runat="server" attribute/value pair. State management can be enabled or disabled for individual controls or an entire page by setting the MaintainState property to True (its default value) or False.
Now let's revisit the concept of ViewState, which was introduced earlier in this chapter. ViewState is a collection of information about the properties of an ASP.NET page and its controls (maintained in a hidden form field named _VIEWSTATE). Since control state on the server does not exist once the page has been rendered to the client, ViewState exists to store the value of properties of controls on the page. As the name itself implies, ViewState preserves the state associated with a particular view of a page. It is used by the noninput controls (such as Label and DataGrid) to store their ambient state across requests. Thus, when a page is posted back to the server, and the result of the postback is rendered to the browser, controls such as textboxes and listboxes will automatically retain their state, unless the control's EnableViewState property has been set to False or the state of the control was modified programmatically on the server.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Caching Page Output
Another new feature of ASP.NET that should not be overlooked is its support for caching—in particular, output caching. Output caching provides the ability to have the rendered output of a page cached for a specified duration simply and easily. By caching the rendered output in memory, subsequent requests for the page can be delivered substantially faster and with considerably less processor utilization than if the page needs to be re-rendered for each request, which can lead to substantial performance increases. The ASP.NET team has reported page delivery two to three times faster when using output caching. Output caching is available for both ASP.NET pages and ASP.NET user controls.
Not every page can be cached in its entirety. Some pages contain too much dynamic information to be cached as a whole, but even these pages may have portions that seldom change. By moving these static portions into user controls (which also provides the possibility of reuse) and then output caching the user controls, at least some performance benefit can be realized—even for very dynamic pages.
The best part about output caching is its simplicity. In its most basic state, caching the output of a page requires a directive like the following (which you should add directly below the @ Page or @ Control directive):
<%@ OutputCache Duration="20" VaryByParam="None" %>
This directive tells ASP.NET to cache the output of the page for 20 seconds and to return the same cached version of the page for all requests. Example 3-7 demonstrates how to cache the output of a page for 60 seconds and to cache a different version of the page for each different value of the name parameter, when sent as part of the query string of a GET request (for example, http://localhost/aspnetian/OutCache.aspx?name=John). The cache can be varied by form fields in a POST request as well, if desired, by setting the value of the VaryByParam attribute to the name of the form field to vary by.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Additional Resources
The following sites provide more information on topics discussed in this chapter:
http://www.gotdotnet.com/QuickStart/aspplus/
The ASP.NET QuickStart samples, which can also be installed locally, provide a wide range of examples and sample code and explanations that can be very useful when starting out. The GotDotNet.com site also has sample code available from other users.
http://www.asp.net/forums/
The ASP.NET forums includes forums specific to a wide variety of ASP.NET programming topics, including Web Forms, Caching, State Management, and many more. Questions are answered by experts within the ASP.NET developer community, and even sometimes by members of the ASP.NET development team themselves.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Chapter 4: Web Services
The primary purpose of ASP.NET web services is to provide access to application functionality through standard web protocols (including HTTP and XML), regardless of the application's location or the platform on which it is built. When your application exposes functionality as a web service, that functionality can be consumed by clients on any platform, presuming the clients understand XML and SOAP and can communicate via the HTTP protocol. More plainly, a web service is a function that is called over the Internet.
An ASP.NET web service can be very simple or it can provide complex functionality. It can return a variety of data types—from simple strings and integer values to complex data types such as classes and datasets. Web services are traditionally thought of as providing only business services (e.g., you call a method, perhaps passing in some parameters, and you receive a return value), but there's no reason why you can't create a web service that returns a chunk of HTML. Doing so would allow you to provide cross-platform access to functionality similar to that provided by ASP.NET Server Controls, albeit with some performance overhead.
The ability of web services to fulfill their mission of providing cross-platform interoperability and application integration depends on a number of existing and emerging standards and specifications. The following list describes the most important standards, including their current standardization status. Note that the W3C term for a stable standard is Recommendation.
HTTP (Current version 1.1, Recommendation; http://www.w3.org/Protocols)
HTTP is the standard protocol of the World Wide Web. HTTP is essential to web services because most organizations allow communication over TCP port 80 (the default HTTP port) to traverse their firewalls. This contrasts with protocols such as DCOM, which use ports that are routinely blocked—making them virtually useless for the Internet.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Standards and Specifications
The ability of web services to fulfill their mission of providing cross-platform interoperability and application integration depends on a number of existing and emerging standards and specifications. The following list describes the most important standards, including their current standardization status. Note that the W3C term for a stable standard is Recommendation.
HTTP (Current version 1.1, Recommendation; http://www.w3.org/Protocols)
HTTP is the standard protocol of the World Wide Web. HTTP is essential to web services because most organizations allow communication over TCP port 80 (the default HTTP port) to traverse their firewalls. This contrasts with protocols such as DCOM, which use ports that are routinely blocked—making them virtually useless for the Internet.
XML (Current version 1.0, Recommendation; http://www.w3.org/XML)
eXtensible Markup Language (XML) provides a standardized way of structuring and communicating data via a tag-based text syntax. Combined with the XML Schema standard, XML allows simple and complex data types to be serialized and deserialized to text for transmission over an HTTP connection.
SOAP (Current version 1.1, Submission; http://www.w3.org/2000/xp)
Simple Object Access Protocol (SOAP) is an emerging standard that specifies how to format RPC-style requests and responses using XML and communicating over HTTP. SOAP is essential to web services. See What Is SOAP? for more information on the SOAP protocol status and its impact on developing web services. Note that SOAP Version 1.2 is a Candidate Recommendation at the time of this writing, so it will soon replace Version 1.1.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Web Services Architecture
In ASP.NET, a web service is essentially a listener that monitors a particular URL exposed via HTTP, looking for requests packaged as SOAP messages. When a request arrives, the ASP.NET runtime unpackages the request and calls the method for which the request is intended, passing in any parameters included with the request. If the request has a return value (which is not required), the ASP.NET runtime packages up the return value (based on the XML schema datatype specifications) and sends it to the client as a SOAP message. What this means to developers is that your application doesn't need to know anything about the client that will consume it, other than the fact that it can understand XML and SOAP. Thus, developers can essentially write methods that will be called as web services just as though they were writing methods that would be called locally.
This functionality is provided by the runtime largely for free. Developers expose their functionality as web services by marking their methods with a specific metadata attribute, the WebService attribute. The Common Language Runtime (CLR) takes care of the rest—from packaging and unpackaging SOAP requests to automatically providing HTML documentation of the web service—if it is called from a web browser (rather than by a SOAP request).
Figure 4-1 illustrates how an ASP.NET web service works.
Figure 4-1: Inside an ASP.NET web service
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Creating a Web Service
There are two different coding techniques with which one can construct a web service: inline code and code-behind.
Creating a single-file web service is quite simple. All that's required is to create a new file, add an @ WebService directive and a class containing the implementation for the methods you want to expose, and decorate the methods to be exposed with the WebMethod attribute. The @ WebService directive supports the following attributes:
Class
Specifies the name of the class containing the implementation of the web service. This attribute is necessary to allow the ASP.NET runtime to locate the compiled class at runtime.
CodeBehind
Specifies the name of a code-behind file that contains the class that implements the web service. This attribute is used by Visual Studio .NET when building the project containing the code-behind class.
Debug
Specifies whether the web service should be compiled with debug symbols.
Language
Specifies the language used for code written inline in the .asmx file.
To demonstrate the creation of a web service, look at Example 4-1, which implements a simple "Quote of the Day" web service.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Consuming a Web Service
In ASP.NET, consuming a web service is nearly as easy as creating one. ASP.NET provides a utility called wsdl.exe that can create a proxy class, which is a class that knows all of the necessary details of communicating with the web service via SOAP, as shown in Figure 4-1, and which can be called from a client application the same way as any other managed class. In this way, the proxy class abstracts away the complexities of communication with the web service.
Consuming a web service in ASP.NET requires four steps:
  1. Locate the WSDL contract for the desired web service.
  2. Create a proxy class by using the wsdl.exe command-line utility.
  3. Compile the proxy class.
  4. Create a new instance of the proxy class in the client application (WinForms, Console, or ASP.NET) and call the desired methods.
In the case of our Qotd_cb web service, you would execute the following command (again, conveniently saved as a DOS batch file) to generate a proxy class based on the web service:
wsdl /l:vb /out:Qotd_cb_proxy.vb http://localhost/ASPdotNET_iaN/Chapter_ 4/Qotd_cb.asmx?WSDL
  
pause
The /l parameter specifies that the proxy class should be generated in Visual Basic .NET (the default is C#). The /out parameter specifies the name and, optionally, the path of the output file. This is important if you are compiling your proxy class in the same directory as the code-behind class that implements the web service. In this case, if you do not specify the output filename, the file Qotd_cb.vb will be overwritten. Once the proxy class has been generated, it should be compiled, and the resulting assembly should be placed in the bin directory. This can be accomplished using a command such as the one in the following snippet:
vbc /t:library /r:System.Web.dll,System.dll,System.Web.Services.dll, System.
Xml.dll,System.Data.dll /out:bin\qotd_cb_proxy.dll 
qotd_cb_proxy.vb
  
pause
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Additional Resources
The following sites provide additional information on the topics discussed in this chapter:
http://www.gotdotnet.com/QuickStart/aspplus/
The ASP.NET QuickStart samples, which can also be installed locally, provide a wide range of examples and sample code and explanations that can be very useful when starting out. The GotDotNet.com site has sample code available from other users and many other features.
http://www.asp.net/forums/
Created by the Microsoft ASP.NET team, and moderated by community leaders, the ASP.NET forums includes a forum dedicates specifically to XML Web Services, as well as to other related topics.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Chapter 5: ASP.NET Server Controls
Controls provide the familiar elements of a graphical user interface (GUI): buttons, drop-down boxes, checkboxes, etc. Server controls are controls that enable server-side processing. They provide a range of functionality, from simple data entry to complex data validation.
ASP.NET ships with a suite of ready-to-run server controls you can use to develop powerful Web Forms pages. A key component of the ASP.NET development model, these server controls abstract significant amounts of programming logic into simple-to-use tags. Server controls make it easy to separate programmatic logic from UI elements using code-behind, because you typically instantiate the controls using a tag-based syntax while keeping your UI-related logic in a separate code-behind file. In practical terms, this means that programmers can hand over a .aspx page to UI designers without having to worry about their programming logic getting completely ruined in the process.
In ASP.NET, it's easy for developers to create their own controls from scratch or to build on the functionality of existing controls by creating user controls that combine HTML, server controls, and other page elements, or by creating their own custom server controls. We'll discuss both techniques in Chapter 6.
ASP.NET Server Controls are classified as either HTML controls or web controls. This chapter summarizes the standard controls and the various methods for creating and modifying them.
The HTML controls have a one-to-one mapping with HTML tags. You can create HTML controls and change their appearance by modifying their properties. HTML controls have an object model that closely resembles the HTML syntax of the elements, as well as the Dynamic HTML (DHTML) object model.
The attributes of an HTML tag correspond to the properties of the HTML control. The HTML controls are declared by using the standard HTML tags with the attribute runat="server". For example:
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
HTML Controls
The HTML controls have a one-to-one mapping with HTML tags. You can create HTML controls and change their appearance by modifying their properties. HTML controls have an object model that closely resembles the HTML syntax of the elements, as well as the Dynamic HTML (DHTML) object model.
The attributes of an HTML tag correspond to the properties of the HTML control. The HTML controls are declared by using the standard HTML tags with the attribute runat="server". For example:
<input type="text" id="txtName" runat="server">
The id attribute is very important for all server controls if you plan to access your control programmatically, since it defines the name by which the object will be referenced in code.
In ASP.NET, the following HTML tags are supported as HTML controls:
<a>
<img>
<form>
<table>