Breaking Down the Parts of ASP.NET

only for RuBoard

Breaking Down the Parts of ASP.NET

Now that you know a little about what ASP.NET is, it's time to go into some more detail on the parts of ASP.NET that are relevant to this book:

  • Server controls

  • Server-side event handling

  • Multilanguage support

  • Web services

  • Session state management

  • Caching

Server Controls

As mentioned previously, ASP.NET ships with a set of stock server controls for executing commonly used page functions, such as input validation, data-driven tables, and so on. Server controls can be broken into two major categories: HTML server controls and ASP.NET server controls.

HTML Server Controls

Any HTML element can be converted to an HTML server control with the addition of the runat ="server" attribute. Once you've added this attribute, the .NET Framework will create an instance of the control for server-side page processing. Some interesting things happen once the runat="server" attribute is added:

  • The HTML elements become visible to the server and can be accessed programmatically.

  • The object model maps closely to that of the corresponding element. For example, if an input element is set to type="text" and is marked to be an HTML server control, you can set its background color on the server programmatically by referencing its ID attribute ( TextBoxID.BackColor= "blue" ).

  • Automatic state management of page elements. That is, if you have a text box, the value will be maintained on the round trip from the client to the server and back.

  • The element now supports data binding (discussed in Chapter 3, "ADO.NET Managed Providers").

  • The element maintains client-side script capability.

In Listing 1.2 you added the runat="server" attribute to a <select> list HTML server control. When the page was successfully posted a welcome message was displayed to the user , and the state of the <select> list was maintained.

Figure 1.2 shows the output of the form after the form post. The values entered are displayed at the top of the page, and are maintained in the form fields.

Figure 1.2. HtmlControls maintain the values given before the form post.
graphics/01fig02.gif

ASP.NET simplifies this programming approach through HTML server controls, which maintain their state through ViewState . ViewState uses a hidden field named __VIEWSTATE to maintain the server control values. The __VIEWSTATE field contains a reference to an in-memory copy of the values for each stateful server control, for example, every server control whose values are to be maintained.

When the ASP.NET form is posted and the results are rendered, you'll notice that the form elements, the text box and the <select> list, have maintained their values without any additional code. The state of these controls is maintained through ViewState (the __VIEWSTATE field). You can see this in Listing 1.3, which is part of the HTML source of the rendered page viewed in the browser.

Listing 1.3 The Rendered Output of an ASP.NET Page
 01: <html> 02: <head> 03: <title>Programming Datadriven Web Applications with ASP.NET - Chapter 1</title> 04: </head> 05: <body> 06: <form name="ctrl0" method="post" action="01.02.aspx" language="javascript" graphics/ccc.gif onsubmit="ValidatorOnSubmit();" id="ctrl0"> 07: <input type="hidden" name="__VIEWSTATE" graphics/ccc.gif value="dDwtMTc0NjQxMDYxMzt0PDtsPGk8MT47PjtsPHQ8O2w8aTwxPjs+O2w8dDxwPHA graphics/ccc.gif 8bDxUZXh0Oz47bDxIZWxsbyBNci4gTWlsdG9uIFBhdmxvdlw8YnJcPlw8YnJcPjs +Pjs+Ozs+Oz4+Oz4+Oz4="/> 08: 09: <script language="javascript" 10: src="/ aspnet_client/system_web/1_0_2914_16/WebUIValidation.js"></script> 11: 12: 13:  <span id="Welcome">Hello Mr. Milton Pavlov<br><br></span> 14:  <input name="txtName" type="text" value="Milton Pavlov" id="txtName" /> 15:  <span id="ctrl1" controltovalidate="txtName" errormessage="Please enter your name." graphics/ccc.gif evaluationfunction="RequiredFieldValidatorEvaluateIsValid" initialvalue="" style="color: graphics/ccc.gif #CC3300;visibility:hidden;">Please enter your name.</span> 16:  <br> 17:  Prefix:<br> 18:  <select name="selPrefix" id="selPrefix"> 19:  <option value="--Select One--">--Select One--</option> 20:  <option selected="selected" value="Mr.">Mr.</option> 21:  <option value="Ms.">Ms.</option> 22:  <option value="Mrs.">Mrs.</option> 23: </select> 24:  <span id="ctrl2" controltovalidate="selPrefix" errormessage="Please select your graphics/ccc.gif prefix." evaluationfunction="RequiredFieldValidatorEvaluateIsValid" graphics/ccc.gif initialvalue="--Select One--" style="color:#CC3300;visibility:hidden;">Please select your graphics/ccc.gif prefix.</span> 25:  <p><input onclick="javascript:{ if (typeof(Page_ClientValidate) == 'function') { graphics/ccc.gif Page_ClientValidate();} }  " name="ctrl3" type="submit" value="Submit" /></p> 

The ViewState is set on line 7. Although the ViewState isn't meant for people to read, it does refer to an in-memory copy of the server controls' values.

ASP.NET Server Controls

ASP.NET server controls don't map one-to-one with HTML server controls. An ASP.NET server control is essentially a black box that renders all the HTML code necessary for the control to function properly. For example, the ASP.NET Calendar control doesn't render a calendar per se; it renders a group of HTML elements, including tables, cells , rows, and hyperlinks , resulting in an object that looks like a calendar. The differences between HTML server controls and ASP.NET server controls are as follows :

  • Template support for some controls (see Chapter 7, "Working with ASP.NET Server Controls Templates").

  • A rich set of programming capabilities, including raising events, caching, and access to many other properties, methods , and events not available to HTML server controls.

  • Browser compatibility. All server controls will nearly always render as browser-compatible HTML. The .NET Framework evaluates the browser on the request and renders either HTML 3.2 or HTML 4.0 and JScript. The latter is for Internet Explorer 4.0 and above, while the former is for all other browsers.

ASP.NET server controls are subdivided into four groups:

  • Intrinsic controls render as basic HTML elements, such as <span> or <input type="text"> . They're intelligent , meaning that they can maintain their state.

  • List controls render as a variety of lists. Using a data source, they can be set to render as lists or tables of data.

  • Validation controls are used to validate user input, such as a required field, range validation, or even custom validation.

  • Rich controls render as complex HTML structures and can include client-side script. One example of a rich control is the Calendar control.

Server-Side Event Handling

Every ASP.NET page is compiled at runtime using Just-In-Time (JIT) compilers. The page is compiled to a tree structure of .NET objects. This enables programmatic control over all server controls on the page, exposing properties and methods available for the specified control. The ASP.NET page itself is the parent object, and it has properties, methods, and events such as the Load event. You can write your own custom event handlers or methods to execute when events are fired , or when called.

Listing 1.4 modifies the same page with which you've been working to use a server-side method to explicitly control the rendering of your page.

Listing 1.4 Server-Side Event Handling in ASP.NET
 [VB] 01: <script language="VB" runat="server"> 02:  Protected Sub SayHello(Source As Object, E As EventArgs) 03:   divHello.InnerHtml = "Hello " & _ 04:    selPrefix.Value & " " & _ 05:    txtName.Value 06:   txtName.Visible = False 07:   selPrefix.Visible = False 08:   submitButton.Visible = False 09:  End Sub 10: </script> [C#] 01: <script language="C#" runat="server"> 02:  protected void SayHello(object sender, EventArgs e){ 03:   divHello.InnerHtml = "Hello " + 04:    selPrefix.Value + " " + 05:    txtName.Value; 06:   txtName.Visible = false; 07:   selPrefix.Visible = false; 08:   submitButton.Visible = false; 09:  } 10: </script> [VB & C#] 11: <html> 12: <head> 13: <title>Programming Datadriven Web Applications with ASP.NET - Chapter 1</title> 14: </head> 15: <body> 16: <div id="divHello" runat="server" /> 17: <form method="post" runat="server"> 18: <input type="text" id="txtName" runat="server" 19:   Value="Please Enter Name" ><br> 20: <select id="selPrefix" runat="server"> 21:   <option>--Prefix--</option> 22:   <option>Mr.</option> 23:   <option>Ms.</option> 24:   <option>Mrs.</option> 25: </select> 26: <p><input type="submit" value="Submit" id="submitButton" 27:   OnServerClick="SayHello" runat="server"></p> 28: </form> 29: </body> 30: </html> 

Note

Notice that the SayHello() method is placed inside <script></script> tags marked to run at the server. The .NET compliant language is specified in the <script> tag. In ASP.NET, all server-side programming is placed inside <script> tags rather than <%...%> tags.


In Figure 1.3, the page has been loaded. The HTML server controls are rendered as basic HTML elements.

Figure 1.3. When the form is loaded, the HTML server controls are rendered as basic HTML elements.
graphics/01fig03.gif

In Listing 1.4, the <div> element was set to display the message "Hello" (line 3), followed by the prefix (line 4) and name (line 5) entered in the form, using the InnerHtml property. Next , the input controls were set not to display (lines 6 “8) by setting their Visible properties to False . In Figure 1.4, you see the page after the form has been posted.

Figure 1.4. After the form has been submitted, all the controls' Visible properties are set to False on the server.
graphics/01fig04.gif

If you're a Web developer who's never worked with strong-typed programming languages, using control properties might be new. As you'll see, it's a great way to work with and assign values. Server controls are featured prominently in upcoming chapters, so you'll have time to get familiar with them.

Multilanguage Support

You've already seen some of the benefits of strong-typed languages, such as accessing properties and methods of the page or server controls on the page. One of the ongoing debates among programmers has always been about which language is the best. The .NET Framework seeks to resolve this debate by equalizing the performance of the languages and letting you write ASP.NET applications in whichever language you like. When the ASP.NET page is compiled at runtime, the code you've written is emitted (translated) to Microsoft Intermediate Language (MSIL). Although the MSIL code for each language can be slightly different, the performance is nearly identical. Therefore, the language you prefer is the language you should write code in.

The final release versions of the .NET Framework and ASP.NET will support many different languages, including Visual Basic.NET, C#, Managed C++, Eiffel, COBOL, and others.

Web Services

As the Web grows and Internet data exchange becomes more important to the success of many businesses, developers are seeking new ways of providing richer Web applications. Web services provide functionality that was previously reserved for desktop applications.

A Web service is a class (or set of classes) that doesn't render typical browser-based HTML output, but rather outputs data. A client can consume, manipulate, and display this data in any format that's appropriate. The Web service uses XML and SOAP to expose data for consumption by a client. For example, a shipping company can expose the functionality to accept a shipping number and output the package's current location, or an online book company can expose a service to list their top ten best-selling books. Client applications can consume these services and render the output on a different site with relative ease.

The one requirement for a Web service is that both parties agree to the Web Service Description Language (WSDL) format for the exchange. The WSDL is an XML document that describes the service transports or protocols, the invocation semantics, and the call order.

Figure 1.5 shows how a Web service provider and consumer interact.

Figure 1.5. A provider exposes a Web service that a consumer uses.
graphics/01fig05.gif

A Web service provider (1) makes a Web service publicly available on the Internet. The consumer (2) goes through the discovery process (3) to find out what Web services are available from the provider. The discovery process returns a link to the WSDL document. When the consumer knows where to find the WSDL, she can request it by appending the URL with ?WSDL (4). The WSDL can be used to build classes for consuming the Web service. The consumer can then call the Web service with an Http-Get, Http-Post, or a SOAP message (5). The data is returned to the client as either an XML document, or XML-formatted data in a SOAP message.

In Chapter 14 you'll build your own Web service to expose data to other sites.

Session State Management

In classic ASP, managing state always meant writing a lot of extra code. This process became even more difficult when the ASP application was hosted on multiple servers in a Web farm. State values needed to be either written to hidden fields and passed from page to page or written to a database and accessed on each page view.

Recall how ASP.NET manages state for you in the form of ViewState . The state values are passed from page to page in the hidden ViewState field. All controls that use the runat="server" attribute have their state managed by ASP.NET.

There is a solution for managing session state in the present ASP model, using the ASP Session object, but it can't handle some of today's common server setups, such as Web farms. Most of those problems have been solved in ASP.NET with a Web farm compatible, memory-based ASP.NET State Store, or a Microsoft SQL Server database. The latter is done through the SQL State Store. The state values are stored in a SQL Server database and are accessed with each page view. It takes a minimal amount of code to use either method, making either state management option viable and easy to use.

Caching

Caching is a highly anticipated feature of ASP.NET and will help immensely in your creation of high-performance Web applications. Basically, caching in ASP.NET means taking a figurative snapshot of a page after it's been compiled and rendered once, and then holding it in memory until specific conditions you've set are met. Then the page is recompiled and rendered and the process starts all over.

For example, let's say you have a page that makes a call to a database and returns a rather large result set back to the client. That page might take 10 seconds to render. With ASP.NET, you can add the page directive shown in Listing 1.5 to your page, and the results of that query will be cached for 30 seconds. When a user refreshes the page or the next user visits it, the page will be served from the cache and no query to the database will take place. This can increase performance dramatically.

Listing 1.5 Page Directive to Set Caching to 30 Seconds
 <%@ OutputCache Duration="30" %> 

This example assumes that the page makes the same query to the database every time. But let's say that this is a search engine of some sort that serves up different results every time, based on the user's search criteria. You can't serve up a cached page for every user based on the first query, or the next user would get incorrect data. However, it's conceivable that two users might search using the same criteria. In that case, the second user would indeed get the cached results of the first user's query.

ASP.NET has two types of caching:

  • Output caching ”The caching of a dynamic response generated by a request.

  • Data caching ”Programmatic caching of arbitrary objects across HTTP requests .

Beyond page-level caching, you can cache individual parts of your page. Fragment caching enables you to cache the results of a database query without caching your rotating banner advertisement on the same page. Put all these ingredients together and you have the recipe for a high-performance, highly optimized Web solution. Chapter 16, "Data Caching," will go into some advanced caching techniques.

only for RuBoard


Programming Data-Driven Web Applications with ASP. NET
Programming Data-Driven Web Applications with ASP.NET
ISBN: 0672321068
EAN: 2147483647
Year: 2000
Pages: 170

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