
C# ПІДРУЧНИКИ / c# / Hungry Minds - ASP.NET Bible VB.NET & C#
.pdf
End Function
The return type of the GetHandler method is IHttpHandler. The different parameters include:
§context: Represents the object of the HttpContext class that provides reference to built-in server objects
§requesttype: Represents a string value that refers to the method used for HTTP data transfer, such as Get and Post
§url: Represents a string value that refers to the URL that is requested by the client
§pathtranslated: Represents the string value that refers to the physical path of the application's root directory
ReleaseHandler
The ReleaseHandler method allows releasing an IHttpHandler instance so that it can be reused. The Visual Basic syntax for the ReleaseHandler method is given as follows.
Sub ReleaseHandler( ByVal handler As IHttpHandler)
End Sub
In this code, handler is the IHttpHandler instance that needs to be released.
HttpContext class
The HttpContext class provides reference to the built-in server objects to process Web requests. Some of the properties that retrieve the built-in server objects are described in Table 16-1.
Table 16-1: Properties of the HttpContext class
Property
Application
Description
Gets the HttpApplicationS tate object associated with the current HTTP request.
Session |
|
Gets the |
|
|
|
|
|
SessionState |
|
|
object |
|
|
associated with |
|
|
the current |
|
|
HTTP request. |
|
|
|
Request |
|
Gets the |
|
|
|
|
|
HttpRequest |
|
|
object |
|
|
associated with |
|
|
the current |
|
|
HTTP request. |
|
|
|
Response |
|
Gets the |
|
|
|
|
|
HttpResponse |
|
|
object |
|
|
associated with |
|
|
the current |
|
|
HTTP request. |
|
|
|
Server |
|
Gets the |
|
|
HttpServerUtility |
|
|
object |

Table 16-1: Properties of the HttpContext class
Property
Description
associated with the current HTTP request. The HttpServerUtility class provides certain utilities that can be used while processing HTTP requests. For example, the
MachineName property of this class returns the name of the server machine.
HttpRequest class
The HttpRequest class enables you to handle communication from a browser to a Web server. You can use this class to access the data supplied by clients during HTTP requests. Table 16-2 describes some of the properties of this class.
Table 16-2: Properties of the HttpRequest class
Property
Browser
RequestType
Description
Gets the information related to the capabilities of the browser from which the HTTP request is made. This property returns a reference to the HttpBrowserCapabili ties class, which is also a member of the System.Web namespace.
Gets the data transfer method that is used by the client.
ApplicationPath |
|
Gets the virtual |
|
|
|
|
|
application root path |
|
|
of the current |
|
|
application that is |
|
|
executing on a |
|
|
server. |
|
|
|
FilePath |
|
Gets the virtual path |
|
|
|
|
|
of the current HTTP |
|
|
request. |
|
|
|
PhysicalApplicationPath |
|
Gets the physical |
|
|
|
|
|
path of the |
|
|
application that is |
|
|
executing on a |

Table 16-2: Properties of the HttpRequest class
Property
Url
Description
server.
Gets the information related to the URL of the current HTTP request.
HttpResponse class
The HttpResponse class enables you to handle communication from a Web server to a browser. This class is used to send the output from the server to the browser. Table 16-3 describes some of the properties of this class.
Table 16-3: Properties of the HttpResponse class
Property
ContentEncoding
Description
Gets or sets the character set of the output from the server.
IsClientConnected |
|
Returns a |
|
|
|
|
|
Boolean |
|
|
value that |
|
|
indicates |
|
|
whether or |
|
|
not the |
|
|
client is |
|
|
connected |
|
|
to the |
|
|
server. |
|
|
|
Cache |
|
Gets the |
|
|
|
|
|
policy |
|
|
information, |
|
|
such as |
|
|
expiration |
|
|
time and |
|
|
privacy for |
|
|
the current |
|
|
Web page. |
The HttpResponse class provides the Write method to display the output in a browser. This method takes a String parameter, which indicates the value to be displayed.
Creating HTTP Handlers
After understanding the different classes and interfaces contained in the System.Web namespace, you can now implement them to handle the communication between a browser and a Web server.
The general steps to create an HTTP handler class are detailed in the sections that follow.
Creating a class that implements the IHTTPHandler interface
To create a class that implements the IHTTPHandler interface, complete the following steps:
1.Create an ASP.NET Web Application project by using either C# or Visual Basic.NET.
2.Add a class to the project.
3.In the class that you added, create a class that implements the IHttpHandler interface. Also, implement the ProcessRequest method and the IsReusable property of the IHttpHandler interface.
4.Build the project to create the DLL file for the handler class.
§verb: Indicates the HTTP verb type that the handler services request. This attribute takes a string value, such as verb = "Get" or verb = "Get; Head; Post". If the attribute takes an asterisk (*) as a value, it instructs the HTTP runtime to match on all HTTP verbs.
§path: Indicates the request path, such as /Trial/Sample.aspx, which the
handler is mapped to.
You can also specify any file extension, such as .Rita. But, for this to work, Tip you must map this file extension in IIS. You can do so in the IIS Microsoft
Management Console (MMC).
§type: Indicates the name of the .NET class that contains the HTTP handler code. This attribute takes the value in the following format: [Namespace].[Class].[Assembly name].
Next, you need to add a reference to the DLL file of the handler class. To do so, select Add Reference from the Project menu. This opens the Add Reference dialog box. In this dialog box, click Browse to select the DLL file of the handler.
After you've added the entry for the handler in the Web.config file and added its reference, when you browse the page (whose path is mentioned in the "path" attribute of the <add> tag), you'll notice that the handler automatically handles this request.
Now that you know the general steps, let's implement them to create a custom HTTP handler.
Custom HTTP Handler Example
Let us now create a simple HTTP handler that displays a hello message to the user and accesses the request and response information when an HTTP request is made for a Web page.
To implement this example, create a Web application project. In this case, the project is a Visual Basic project named SampleHTTPHandler. Then, add a class to the project. To do so, select Project → Add Class. This displays the Add New Item dialog box. In this dialog box, specify an appropriate name for the class. In this case, the name of the class is SampleHandler.vb. In case of a Visual C# project, the class would have a .cs extension. Next, add the following code to the class:
'Importing the System.Web namespace
Imports System.Web
'Creating a namespace
Namespace Acme
'Creating a class that implements the IHttpHandler class Public Class SampleHandler : Implements IHttpHandler
'Implementing the ProcessRequest method of the IHttpHandler
'interface
Public Sub ProcessRequest(ByVal Context As HttpContext)
Implements IHttpHandler.ProcessRequest
Dim str As String
'retrieving the value that is passed to the Name variable
'at the time of request. To do so, you are using the
'Request property of the object of the HttpContext class.
'Notice that the Context object of the HTTPContext class
'is passed as an argument.
str = Context.Request.QueryString("Name")
'Using the Write method of the Response method to
'display a hello message Context.Response.Write("<h1> Hello " + str + "</h1>")
'Using the write method of the Response object to display
'a message in a browser. Notice that the HTML elements
'are also used.
Context.Response.Write("<b>This is an HTTPHandler demo</b>")
Context.Response.Write("<hr align=left width=205> <Br>")
'Using the Browser property of the Request object to get
'an object of the HttpBrowserCapabilities class
Dim hBrC As HttpBrowserCapabilities = Context.Request.Browser
'Displaying the name and version of the browser Context.response.Write("<b>Browser capabilities:</b><br>") Context.Response.Write("Name = " & HBrC.Browser & "<br>") Context.Response.Write("Version=" & HBrC.Version & "<br>")
'Using the PhysicalApplicationPath and the
'Applicationpath properties of the Request object to get
'the physical path and the virtual path of the
'application respectively
Dim pPath As String
Dim vPath As String
pPath = Context.Request.PhysicalApplicationPath
vPath = Context.Request.ApplicationPath
'Displaying the virtual and physical path of the
'application
Context.Response.Write("<Br><b>Virtual path of the application:</b><Br>")
Context.Response.Write(vPath & "<br>")
Context.Response.Write("<Br><b>Physical path of the application:</b><Br>")
Context.Response.Write(pPath & "<Br>")
'Using the IsClientConnected property of the Response
'object to determine whether the client is connected to
'the server
Dim connect As Boolean
Dim connectStr As String
connect = Context.Response.IsClientConnected connectStr = connect.ToString
Context.Response.Write("<Br><b>Client connection status:</b><br>") Context.Response.Write(connectStr)
End Sub
'Implementing the IsReusable method of the IHttpHandler
'interface

Public ReadOnly Property IsReusable() As Boolean Implements
IHttpHandler.IsReusable
Get
Return True
End Get
End Property
End Class
End Namespace
After creating this class, build the project. After the build is complete, a DLL file is created in the bin directory of the project. Now, the handler is ready, and you can use it to handle any Web request.
Next, you'll use the handler in a new Web application. To do so, create a Visual Basic ASP.NET Web Application project named HandlerTesting. In the Web.config file, in the <httpHandlers> section, add an entry for the handler to map the Web request to the handler class:
<httpHandlers>
<add verb="*" path="Test.aspx" type="SampleHTTPHandler.Acme.
SampleHandler,SampleHTTPHandler" />
</httpHandlers>
In the preceding code, the path attribute is set to Test.aspx. Therefore, rename the WebForm1.aspx file to Test.aspx. The next step involves adding a reference to the DLL of the handler class.
After adding the reference, browse the Test.aspx page by passing your name in the Name variable as QueryString. The URL of the page should appear as follows:
.../Test.aspx?Name=Rita
Figure 16-2 displays the output of this page.
Figure 16-2: Output of the SampleHTTPHandler application
Summary
This chapter introduced you to HTTP handlers. First, you learned about the HTTP runtime provided in ASP.NET for performing low-level processing on the HTTP request
sent by the client. You also learned about HTTP modules and HTTP handlers. Next, you learned about various interfaces, classes, and built-in objects provided in ASP.NET for creating your own HTTP handlers. Finally, you learned how to create an HTTP handler.
Chapter 17: Understanding Caching
Overview
Usually, Web sites (Web applications) are accessed by multiple users. On certain days, a Web site can experience an extremely low load and, as a result, provide faster access. However, in just a few hours, the load on the site can increase exponentially, resulting in slow access. Slow access is the most common problem that plagues a Web site when it is accessed by a large number of users simultaneously. However, load is not the only reason why a Web site is slow. Other physical aspects affect speed, such as the type of modem, Internet connection, and telephone line. Therefore, it might not be good business sense to invest in high-grade hardware that handles the entire load just to improve the access speed, because the heavy load is only temporary and not constant. It would be better if access speeds could be improved without investing in high-grade hardware. In such a scenario, caching provides a solution.
Caching is a technique wherein frequently used data and Web pages are stored temporarily on local hard disks for later retrieval. This technique improves the access time when multiple users access a Web site simultaneously or a single user accesses a Web site multiple times. Caching allows server-side Web applications to scale better, and improves the overall performance of the Web application. Thus, the ASP.NET code does not need to be executed every time to process the same request from multiple clients or from a single client multiple times. This saves on the CPU cycles at the Web server, resulting in improved response time.
This chapter introduces you to caching. You will also learn the concept of caching page output and caching page data for optimizing the ASP.NET Web applications.
Introduction to Caching
Caching, as a technique for improving system performance, is not a new concept. It has been used successfully in various applications, ranging from relational databases such as Microsoft SQL Server to various operating systems. ASP.NET provides a Web cache to store Web objects.
A Web cache is a temporary storage of Web objects, such as HTML documents, for later retrieval. You can specify the cache location to be on the client or on the server. The different locations where caching can be performed are described as follows:
§Client: To provide improved performance, client applications (like browsers) perform caching by storing data from the Web in temporary files on the hard drive or system memory of users' computers. However, these caches cannot be shared across multiple users. Figure 17-1 demonstates caching at the client side.

Figure 17-1: Client caching
§Dedicated server: Caching can be performed at the server side so that caches can be shared across multiple users on a network. Most administrators use proxy servers, such as Microsoft Proxy Server, to store frequently used Web pages on the hard disk of the proxy server. The proxy server fulfills all the requests for the Web page without sending out the request to the actual Web server over the Internet, resulting in faster access. Figure 17-2 shows caching at the proxy side.
Figure 17-2: Dedicated server caching
Proxy caches are often located near network gateways to reduce the Note bandwidth required over expensive dedicated Internet connections.
These systems serve many users (clients) with cached objects from many servers.
The Web objects that are requested by one client are stored in a cache, Note and can be retrieved later when another client requests the same object.
For even greater performance, many proxy caches are part of cache hierarchies, in which a cache can enquire neighboring caches for a requested document, to reduce the need to fetch the object directly. Such an organization of multiple cache servers is also referred to as a cache array.
§Reverse proxy: Caches can also be placed directly in front of a particular Web server, to reduce the number of requests that they receive. This model allows the proxy server to respond to the frequently received requests and pass the other requests to the Web server. This form of proxying is called a reverse proxy, wherein the proxy server is used by the Web server to

speed up request processing. This model is unique in that it caches objects for many clients, but usually from a single server. Figure 17-3 shows the reverse proxy caching.
Figure 17-3: Reverse proxy caching
After discussing the various locations where caching can be performed, let us now look at some of the most significant advantages of Web caching:
§Reduced bandwidth consumption: Because the frequently used data and Web pages are cached and ASP.NET allows developers to configure the cache location to be on the client machine, most requests are fulfilled from the local cache. Therefore, fewer requests and responses need to go over the network between the client and the server. This results in reduced bandwidth consumption.
§Reduced server load: Because frequently used data and Web pages are retrieved from the cache, the server does not need to execute the same ASP.NET code multiple times to produce the same output. This saves valuable CPU time at the server end.
§Reduced latency: Because most requests do not need to go to the server for processing, the access time improves significantly.
Although Web caching provides many advantages, it is one of the most misunderstood technologies on the Internet. Webmasters, in particular, fear losing control of their sites because a cache can hide their users from them, making it difficult to see who's using the sites. In addition, the number of hits is not counted correctly, because the cache server(s) might fulfill some percentage of client requests. However, careful planning and proper location of a proxy server cache will help your Web site load faster, and reduce load on your server and the Internet link. The difference can be dramatic; a site that is difficult to cache may take several seconds to load. Users will appreciate a fast-loading site, and will visit it more often.
Another concern related to Web caching is that the caches might serve outdated content. As you'll see later in the chapter, this issue can be taken care of by configuring your server to control the expiry time for the cached content. The next section describes caching in ASP.NET in detail.
Caching in ASP.NET
ASP.NET has introduced various new features to the server-side programming model. These new features have made it easier to cache application data, and hence enhance the performance of Web applications. For example, unlike classic ASP, wherein the code