What s ASP.NET, Anyway

 

What's ASP.NET, Anyway?

Prior to the advent of ASP.NET, three main technologies and platforms were available to develop Web applications: ASP, Java Server Pages (JSP), and the open source Web platform commonly referred to as LAMP (Linux plus Apache plus MySQL plus either Perl, Python, or PHP as the programming language).

Note 

For completeness, we should also mention a couple of platform-specific, lower-level technologies that ASP and JSP rely on. ASP is actually an ISAPI extension, whereas JSP is implemented as a special servlet application. ISAPI extensions on IIS-based platforms and servlets on Java-based systems, let you create server-side, Web-deployed applications using a more classic approach. You write a module that builds and renders the page rather than declaratively design the page using a mix of markup text and embedded code.

Although each has language-specific and architecture-specific features, all these Web development platforms are designed to create interactive pages as part of a Web-based application. To some extent, all enable developers to separate programming logic from the page layout through the use of components that the page itself is responsible to call and render. Aside from this common ultimate goal, significant differences exist among those platforms, most of which relate to the programming model and languages they promote and support. For example, JSP exploits the Java framework of classes and, with JavaBeans, provides an effective extensibility model for reusing components. In addition, JSP supports tag customization and lets developers associate code with a custom tag definition. Finally, because it's a key element of the Java 2 Enterprise Edition (J2EE) platform, JSP relies on the Java language, a first-class, compiled language as opposed to the scripting languages used by both ASP and LAMP platforms. So how does ASP.NET fit in exactly?

Like ASP and other Web development environments, ASP.NET also works on top of the HTTP protocol and takes advantage of HTTP commands and policies to set up two-way, browser-to-server communication and cooperation. What really differentiates ASP.NET from the plethora of other Web development technologies is the abstract programming model it propounds, the Web Forms model. In addition, the whole ASP.NET platform comes as a native part of the Microsoft .NET Framework. To be sure you grasp the importance of this last point, let me explain. ASP.NET applications are compiled pieces of code, are made of reusable and extensible components, can be authored with first-class languages (including C#, Microsoft Visual Basic .NET, Microsoft JScript .NET, and J#), and can access the entire hierarchy of classes in the .NET Framework.

In short, ASP.NET combines the best of all worlds. It is semantically compatible (and, to some extent, also language compatible) with ASP. It provides the same object-oriented features as JSP applications (tag customization, compiled languages, components, extensibility, and reusability). And as icing on the cake, ASP.NET delivers a wealth of goodies, tools, and powerful system features that can be effectively grouped within the blanket expression tools for abstracting the HTTP programming model. Lots of programmer-friendly classes let you develop pages using typical desktop methods. The Web Forms model promotes an overall event-driven approach, but it is deployed over the Web.

Note 

ASP.NET is supported on a variety of platforms, including Microsoft Windows 2000 with at least Service Pack 2, Windows XP Professional, and Windows Server 2003. To develop ASP.NET server applications, Internet Information Services (IIS) version 5.0 or later, is also required. Other software you need for example, Microsoft Data Access Components (MDAC) 2.7 is automatically installed when you set up the .NET Framework. In terms of performance, robustness, and security, the ideal combination of system software for hosting ASP.NET applications appears to be Windows Server 2003 (preferably with Service Pack 1 applied) and IIS 6.0.

Programming in the Age of Web Forms

The rationale behind the ASP.NET Web Forms model is directly related to the search for a better strategy to deal with the growing demand for cheap but powerful Web interaction. As a matter of fact, the HTTP protocol represents the major strength and weakness of Web applications. The stateless nature of the HTTP protocol introduces vastly different programming concepts that are foreign to many desktop developers first and foremost among these concepts is session state management. On the other hand, the inherent simplicity and scalability of HTTP is the key to its worldwide adoption and effectiveness in short, we probably couldn't have the Internet as we know it without a protocol like HTTP. Yet, as demand for rich and powerful applications increases, programmers have to devise better ways of setting up easy and effective communication from the client to the server and vice versa.

Various techniques have been experimented with over time to smooth the communication across different pages and across multiple invocations of the same page. Most programmers are used to thinking in terms of a client-generated action that results in a server-side reaction. Such a basic and fundamental pattern cannot be accomplished, at least not literally, over the Web. A certain degree of abstraction and some system-provided services are needed to make smooth communication happen.

ASP, much more so than JSP, thinks declaratively and has quite a slim and scanty object model. Overall, programmers who become Web programmers are forced to adopt a different mindset and toss the familiar action/reaction paradigm out the door.

Event-Driven Programming Over HTTP

ASP.NET Web Forms bring the event-driven model of interaction to the Web. Implementing an event model over the Web requires any data related to the client-side user's activity to be forwarded to the server for corresponding and stateful processing. The server processes the output of client actions and triggers reactions. The state of the application contains two types of information: the state of the client and the state of the session. The state of the client mostly the contents of form input fields collectively referred to as the page state is easily accessible through the server-side collections that store posted values. But what about the overall state of the session? The client expects that sending information to the server through one page is naturally related to any other page he or she might view later, such as when adding items to a shopping cart. Who remembers what a particular user has in the shopping cart? By itself, HTTP is incapable of keeping track of this information; that's where session state and a proper server-side infrastructure surrounding and integrating HTTP fit in.

I can't emphasize enough the importance of understanding the concepts involved with stateless programming when developing Web applications. As mentioned, HTTP is a stateless protocol, which means two successive requests across the same session have no knowledge of each other. They are resolved by newly instantiated environments in which no session-specific information is maintained, except all the information the application itself might have stored in global objects. In ASP, reentrant forms are a common way to work around such a system limitation. A reentrant form is an HTML <form> element that posts to the same page that contains it. Reentrant forms alone do not fully solve the issue. However, by combining them with code blocks and hidden fields storing state information that is critical for the page, many developers elegantly overcame the obstacle.

What was once an ASP best-practice has been standardized and integrated in the ASP.NET runtime to become the key feature that endows ASP.NET applications with automatic state maintenance. The ASP.NET runtime carries the page state back and forth across page requests. When generating HTML code for a given page, ASP.NET encodes and stuffs the state of server-side objects into a few hidden, and transparently created, fields. When the page is requested, the same ASP.NET runtime engine checks for embedded state information the hidden fields and uses any decoded information to set up newly created instances of server-side objects. The net effect of such a mechanism is not unlike the Windows Forms model on the desktop and is summarized in Figure 1-1.

image from book
Figure 1-1: Comparing the Windows Forms and Web Forms models in the .NET Framework.

The Windows Forms model stems from the typical event-driven desktop programming style. No matter what connectivity exists between the client and server components, the server always works in reaction to the client's input. The server is aware of the overall application state and operates in a two-tier, connected manner. The Web Forms model needs some machinery to support the same event-driven programming model. In Figure 1-1, the needed machinery is represented by the state deserialization that occurs when the page is requested, and the state serialization performed when the HTML response is being generated.

In charge of this filtering work is the ASP.NET HTTP runtime a piece of code that extends and specializes the overall capabilities of the hosting Web server. Reentrant forms and hidden fields are the low-level tools used to perform the trick. Such a model wouldn't be as effective without a back-end, rich object model spanning the whole content of the server page. Crucial to the building and effective working of the ASP.NET development platform is the component model.

The ASP.NET component model identifies and describes the building blocks of ASP.NET pages. It is implemented through an object model that provides a server-side counterpart to virtually any HTML page elements, such as HTML tags like <form> and <input>. In addition, the ASP.NET object model includes numerous components (called server controls or Web controls) that represent more complex elements of the user interface (UI). Some of these controls have no direct mapping with individual HTML elements but are implemented by combining multiple HTML tags. Typical examples of complex UI elements are the Calendar control and the DataGrid control.

In the end, an ASP.NET page is made of any number of server controls mixed with verbatim text, markup, and images. Sensitive data excerpted from the page and controls state is unobtrusively stored in hidden fields, and it forms the context of that page request. The association between an instance of the page and its state is unambiguous, not programmatically modifiable, and controlled by the ASP.NET HTTP runtime.

The ASP.NET component model is the first stop on the way to the full understanding of the ASP.NET platform. The component model escorts you through the whole development cycle, including the phase of page authoring and run-time system configuration, as shown in Figure 1-2.

image from book
Figure 1-2: A bird's-eye view of the ASP.NET development stack. The arrow indicates the typical top-down application perspective, going down from the user interface to the system services.

Before we dive into the various elements shown in Figure 1-2, let's briefly review the basics of the HTTP protocol, which remains the foundation of Web interaction. After that, we'll move on to describe the structure of an ASP.NET page and how to write and deploy ASP.NET applications.

The HTTP Protocol

This section provides a quick overview of the way Web applications operate. If you already have a working knowledge of the Web underpinnings, feel free to jump ahead to the section "Structure of an ASP.NET Page."

The acronym HTTP has become so familiar to us developers that we sometimes don't remember exactly what it stands for. Actually, HTTP stands for Hypertext Transfer Protocol. HTTP is a text-based protocol that defines how Web browsers and Web servers communicate. The format of HTTP packets is fully described in RFC 2068 and is available for download from http://www.w3.org/Protocols/rfc2068/rfc2068.txt. HTTP packets travel over a Transmission Control Protocol (TCP) connection directed toward default port 80 at the target Internet Protocol (IP) address.

The HTTP Request

When you point the browser to a URL, it uses the available Domain Name System (DNS) to translate the server name you provided with the URL into an IP address. Next, the browser opens a socket and connects to port 80 at that address. The packet with the download request for http://www.contoso.com/default.aspx can take the following simple form:

GET /default.aspx HTTP/1.1 Host: http://www.contoso.com/ 

The first line of text in a request is the start line of the request. It must contain the name of the HTTP command to execute (GET in this case), the URL of the resource, plus the version of the HTTP protocol you want to use.

An HTTP request can contain, and usually does contain, a number of headers. An HTTP header is a line of text that provides additional information about the request. In the HTTP request just shown, the line beginning with "Host:" is an HTTP header. Headers that can be found in an HTTP request include the following:

GET and POST are the most commonly used HTTP commands or verbs. The GET verb means retrieve whatever information is identified by the request URL. The POST verb is used to request that the origin server accept the content enclosed in the request and process it. Typically, the POST verb is used to provide a block of data (that is, the result of submitting a form) to a data-handling process.

The HTTP Response

The server's response includes a status line made from the message's protocol version and an exit code (indicating success or that an error has occurred). The status line is followed by a bunch of headers typically the page content type and length and the body content. A blank line separates the body content from the rest of the message, as shown in the following response:

HTTP/1.1 200 OK Server: Microsoft-IIS/5.0 Content-Type: text/html Content-Length: 51 <html><body><h1>ASP.NET is cool!</h1></body></html> 

The preceding code illustrates the simple HTML output returned by the Web server. Requests and responses are strings formatted according to the HTTP schema, and they travel over a TCP connection. The code 200 means that all went OK with the request. The specified Web server processes the request and returns content of a certain length expressed in the given Multipurpose Internet Mail Extensions (MIME) type (text/html). HTTP codes that could be returned are listed in the HTTP specification, available at the aforementioned URL. In addition, it should be noted that the blank line between the last header and the content of the HTTP response is not just formatting the pair carriage-return and line-feed are required and are a precise part of the standard.

What happens next mostly depends on the MIME type and the local browser's capabilities. As long as the MIME type is text/html, the browser displays the content as HTML. If the MIME type is, say, text/xml , some browsers will render the content as plain text, while others (for example, Microsoft Internet Explorer 6.0) will apply a built-in style sheet.

Building a Server-Side Abstraction Layer

Every conversation between browsers and Web servers consists of an exchange of packets similar to the ones we have just examined. If the requested URL is an HTML page, the Web server typically reads the contents of the .html file and flushes it into the body of the response packet. If the URL is an ASP.NET page, a special IIS module gets involved. The module is an IIS ISAPI plug-in.

An ISAPI extension is a dynamic-link library (DLL) registered on a per-file extension basis. An ISAPI extension registered to handle .aspx files gets involved whenever a request comes in for this type of resource. The ISAPI extension analyzes the request and configures the server-side environment that will actually process the source of the page. When the state for the request has been successfully retrieved and restored completely, the page is allowed to run and produce the HTML output.

Submitting Forms

The HTML <form> tag is the only element authorized to transmit client-side data to the server. When the user clicks on a button of type "submit," by design the browser stuffs the current content of all the controls that belong to the form into a string. The string is then passed to the server as part of the GET or POST command.

The following HTML snippet illustrates a simple form containing a text box and submit button. As you can see, the form is associated with the POST command and the default.aspx URL:

<form method="post" action="default.aspx">     <input type="text" name="EmpCode" />     <input type="submit" value="Send" /> </form> 

The following request shows the POST command that hits the Web server when the user clicks the submit button:

POST /default.aspx HTTP/1.1 Host: http://www.contoso.com/ Content-Type: application/x-www-form-urlencoded Content-Length: 12 EmpCode=1001 

While processing the page request, the ISAPI extension parses the body of the request and exposes any information found through a more programmer-friendly object model. For example, instead of remaining a simple name/value string, the EmpCode variable is moved within an application-wide collection the Request.Form collection. This represents a first level of abstraction built over the raw HTTP programming model. Objects such as Request, Response, and Server form the HTTP context for the call and, as such, represent the minimum set of objects you find in most Web development platforms, including JSP and ASP. In ASP.NET, though, you find much more.

Structure of an ASP.NET Page

An ASP.NET page is a server-side text file saved with the .aspx extension. The internal structure of the page is extremely modular and comprises three distinct sections page directives, code, and page layout:

For the page to work, you don't need to specify all sections. Although real-world pages include all the sections mentioned, perfectly valid and functional pages can include only the code section or page layout. In some special cases, you can even have an ASP.NET page made of a single directive.

In Chapter 2, and even more in Chapter 3, we'll delve deep into the features of a page and its building blocks.

A Sample ASP.NET Page

It is about time we see what an ASP.NET page looks like. To start, a simple text editor will suffice; so let's open Notepad and let the sleeping giant (Microsoft Visual Studio .NET) lie. The following code implements a simple ASP.NET page that lets you enter a string and then changes it to uppercase letters after you click a button. For the sake of simplicity, we use inline code. (As you'll learn later in the book, this is not what you'll be doing in real-world applications and in any page with some complexity.)

<!-- Directives --> <% @Page Language="C#" %>  <!-- Code Section --> <script runat="server"> private void MakeUpper(object sender, EventArgs e) {     string buf = TheString.Value;     TheResult.InnerText = buf.ToUpper(); } </script>  <!-- Layout --> <html> <head><title>Pro ASP.NET (Ch 01)</title></head> <body> <h1>Make It Upper</h1> <form runat="server">     <input runat="server"  type="text" />     <input runat="server"  type="submit" value="Proceed..."         OnServerClick="MakeUpper" />     <hr>     <h3>Results:</h3>     <span runat="server"  /> </form> </body> </html> 

Blank lines and comments in the preceding listing separate the three sections directives, code, and page layout. Notice the unsparing use of the runat attribute it's one of the most important pieces of the whole ASP.NET jigsaw puzzle. In the next section, we'll discuss runat in more detail. For now, it suffices to say that the runat attribute promotes an otherwise lifeless server-side tag to the rank of a component instance.

The page layout is made of literals and HTML tags, some of which contain the aforementioned runat attribute. Everything flagged this way, despite the appearances, is not really an HTML element. More precisely, it is the markup placeholder of a server-side component an ASP.NET control that is actually responsible for the final markup served to the browser. In an ASP.NET source, every tag marked with the runat attribute is not output as is, but undergoes a transformation process on the server at the end of which the real markup is generated. The ASP.NET runtime is in charge of mapping tags to control instances. Let's quickly review the code.

Quick Review of the Code

Thanks to the runat attribute the input text field becomes an instance of the HtmlInputControl class when the page is processed on the server. The Value property of the class determines the default text to assign to the input field. When the user clicks the submit button, the page automatically posts back to itself. The magic is performed by the runat attribute set for the <form> tag. Once on the server, the posted value of the input field is read and automatically assigned to the Value property of a newly created instance of the HtmlInputControl. Next, the code associated with the OnServerClick event runs. This code takes the current content of the text box the posted string and converts it to uppercase letters. Finally, the uppercase string is assigned it to the InnerText property of the server-side control bound to the HTML <span> tag. When the MakeUpper event handler completes, the page is ready for rendering. At this point, updated HTML code is sent to the browser.

To test the page, copy the .aspx file to your Web server's root directory. Normally, this is c:\inetpub\wwwroot. If you want, create an ad hoc virtual directory. Let's assume the page is named hello.aspx. Next, point the browser to the page. Figure 1-3 shows what you get.

image from book
Figure 1-3: Our first (and rather simple) ASP.NET page in action.

It would be useful to take a look at the HTML source of the page when it is first displayed to the user that is, before the user clicks to make the text uppercase.

<!-- Directives --> <!-- Code Section --> <!-- Layout --> <html> <head><title>Pro ASP.NET (Ch 01)</title></head> <body> <h1>Make It Upper</h1> <form method="post" action="hello.aspx" > <div>    <input type="hidden" name="__EVENTTARGET" value="" />    <input type="hidden" name="__EVENTARGUMENT" value="" />    <input type="hidden" name="__VIEWSTATE" value="/wEPDwUJNzM4N ==" /> </div> <script type="text/javascript"> <!-- var theForm = document.forms['Form1']; if (!theForm) {     theForm = document.Form1; } function __doPostBack(eventTarget, eventArgument) {     if (!theForm.onsubmit || (theForm.onsubmit() != false)) {         theForm.__EVENTTARGET.value = eventTarget;         theForm.__EVENTARGUMENT.value = eventArgument;         theForm.submit();     } } // --> </script> <input name="TheString" type="text"  value="Hello, world" /> <input name="Button1" type="submit"  value="Proceed ..." /> <hr> <h3>Results:&nbsp;</h3><span ></span> </form> </body> </html> 

Within the <form> tag, a hard-coded action attribute has been added to force posting to the same page. This is by design and is one of the most characteristic aspects of ASP.NET. The various hidden fields you see are essential to the implementation of the postback mechanism and are generated automatically. The same can be said for the embedded script code. The <input> tags are nearly identical to their counterpart in the .aspx source only the runat attribute disappeared.

Now that we've dirtied our hands with some ASP.NET code, let's step back and review the layers that actually make ASP.NET pages work in the context of an application.

 


Programming Microsoft ASP. Net 2.0 Core Reference
Programming Microsoft ASP.NET 2.0 Core Reference
ISBN: 0735621764
EAN: 2147483647
Year: 2004
Pages: 112
Authors: Dino Esposito
BUY ON AMAZON

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net