Professional ASP.NET 1.0 Special Edition- P22 pot

40 246 0
Professional ASP.NET 1.0 Special Edition- P22 pot

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

Thông tin tài liệu

Log.Source = LogName Log.WriteEntry(Message, EventLogEntryType.Error) End Sub </script> In the above example, we first Import the namespace System.Diagnostics since we will be using some of the classes found in this namespace to write to the event log. We then implement our Application_Error event handler and create some local variables, before using the EventLog class's static method SourceExists() to determine if the event log we're going to write to already exists - if it doesn't we create it. Finally, we create a new EventLog instance named Log and use the WriteEntry() method to enter our Message into the Windows Event Log. Whenever an error occurs within our application, that error is now logged into a custom event log named Web_Errors. It should be noted here that we wrote little more than 10 lines of code to accomplish a task that could potentially be 50 to 60 lines in VB/ASP. Now that we have covered each of the application events, let's look at some advanced topics. These are areas that are left to the more advanced ASP.NET developer and the understanding of these topics is not required to build great ASP.NET applications, but they do help! Advanced Topics In this Advanced Topics section, we will cover four advanced topics related to building superior ASP.NET applications:  Using static variables - It is not necessary in all cases to use Application to store persistent values in memory. Since ASP.NET is compiled, and the application is represented in an object-oriented manner, we can use global static variables in addition to Application.  Using our own base class for global.asax - The earlier discussion of the Application directive for global.asax mentioned the Inherits attribute. We will examine how we can use this to create our own class for global.asax to instantiate.  Mapping file extensions - If we want ASP.NET to support file extensions other than the defaults, such as the file extension .wrox, we must map the extension in IIS first. This is because IIS gets the first look at the request and acts as the router determining where to send requests.  Asynchronous application events - Earlier in the chapter, we discussed the application events that ASP.NET supports. What we didn't discuss in detail is the fact that ASP.NET also supports some asynchronous representations of these events too. Let's start with using static variables. Static Variables Although not covered in our earlier discussion of global.asax, another supported attribute of the Application directive is Classname. This attribute allows us to control the name of the class generated for our global.asax code when it is compiled. If we provide a Classname value, we can access the instance of global.asax. Since we now have access to the global.asax instance, this also means that public methods, properties, or variables declared within it are accessible anywhere in our application. An advanced design choice we can elect to make is to take advantage of one of the object-oriented features of ASP.NET, static members. When a class is created, such as an instance of global.asax, each instance of the class also uses its own methods, properties, and variables to perform work. We can declare a method, property, or variable static and all instances of the class will share the one instance of that method, property, or variable. These static members can be used to store commonly accessed data, for instance, a string array containing the 50 states of the USA. Using static members, in some cases, can be faster than accessing Application state. Application is an object, and loading Application requires memory allocations, and so on. A simple example is the discount rate applied to all products for a one-time sale. Below is a sample global.asax file in C#: <%@ Application Classname="CommerceApplication" %> <Script Language="C#" runat=server> // Set discount to 10% public static float discountRate = .1F; </Script> and in Visual Basic .NET: <%@ Application Classname="CommerceApplication" %> <Script runat=server> ' Set discount to 10% Public Shared discountRate As Single = .1F </Script> In the above code sample we first identify the name of the global.asax's class using the Classname attribute of the Application directive. Then we declare a static member variable, discountRate. We can now write code that accesses this class and its static member, discountRate. Below is a sample ASP.NET page, default.aspx: <Script runat="server" > Public Sub Page_Load(sender As Object, e As EventArgs) ' Calculate the discount rate Dim discountRate As Single Dim productCost As Single ' Determine productCost value productCost = 19.99F ' Calculate discount rate and apply to product cost discountRate = CommerceApplication.discountRate productCost = productCost - (productCost * discountRate) ' Display calculation lblCost.Text = productCost.ToString() End Sub </Script> The cost of the product is: $<asp:label id="lblCost" runat="server" /> In the above example we have a simple Visual Basic ASP.NET page that calculates a product's cost with the applied discount rate. The value for discountRate is obtained from the static member defined in our global.asax file CommerceApplication.discountRate. Using our own Base Class for global.asax The Inherits attribute of the global.asax Application directiv e all ows us to name a .NET c lass th at global.asax will use as the base class for all compiled instances of global.asax. This is useful if we want to add our own methods or properties as part of global.asax. It allows us to create a global.asax file that is customized to a particular application. For example, a commerce solution may provide a commerce-oriented global.asax that exposes properties or methods that are specific to its application, for example, a global.asax property such as AdTargetingEnabled. Developers who use this commerce framework don't see the implementation of this property, instead it's encapsulated within global.asax and they just need to know what happens when they set AdTargetingEnabled = true. Inherits To use Inherits, we first need to create our own custom class that inherits from the HttpApplication class. HttpApplication is the default base class used by global.asax, and it is what exposes the application and session events as well as any default properties. After creating a new class that inherits from HttpApplication, and adding the new functionality we desire, we can then use the global.asax Inherits directive to instruct ASP.NET to use our base class instead of HttpApplication. Let's illustrate this with an example. An Example Below is a simple class, MyApplication, that inherits from HttpApplication. The MyApplication class implements a CurrentTime() method that simply returns the current date/time. Using the Inherits keyword, we have told the compiler that the MyApplication class inherits all the methods, properties, events, and so on, that HttpApplication implements. Essentially, all this class does is add one more method: Imports System Imports System.Web ' To compile: vbc /t:library /r:system.web.dll /r:system.dll Inherits.vb Public Class MyApplication Inherits HttpApplication Public Function CurrentTime() As String ' Use ToString("r") to show seconds in Now output Return DateTime.Now.ToString("r") End Function End Class Next, we need to compile and deploy the generated assembly to our web application's bin directory. To compile, we can either create a new Visual Basic .NET Class project in Visual Studio .NET, or we can use the command line compilers. Either will work equally well. Here is the command line compiler commands to compile this in case you don't have Visual Studio .NET: > vbc /t:library /r:system.web.dll /r:system.dll Inherits.vb Next, we need to copy the resulting .dll to our web application's bin directory. Remember, deploying it to the bin directory makes it available to our application. We can then write a global.asax file that uses the Application directive's Inherits attribute to inherit from our custom base class. Then, within our global.asax code we have access to our new method: <%@ Application Inherits="MyApplication" %> <Script runat=server> Public Sub Application_OnBeginRequest() Dim TimeStamp As String TimeStamp = CurrentTime() Response.Write("Request Beginning TimeStamp: " + TimeStamp) Response.Write("<HR size=1>") End Sub </Script> Since we inherited from the MyApplication base class (which itself inherits from HttpApplication), we have all of the standard behaviors of global.asax provided with the addition of a new CurrentTime() method. In the above code example, we created a simple local variable of type String named TimeStamp, then set TimeStamp using the inherited CurrentTime() method, before returning the result with Response.Write(). Mapping File Extensions to ASP. NET A more advanced (but no more difficult) option that ASP.NET supports is mapping custom file extensions to ASP.NET resources. If for example, instead of using the extension .aspx for ASP.NET pages we decided to use the extension .wrox, we would need to make two changes to enable ASP.NET to serve default.wrox:  First, we must create the following new entry in the <httpHandlers> section of either our web.config or machine.config files - more about these two files and the <httpHandlers> settings in the next chapter: <configuration> <system.web> <httpHandlers> <add verb="*" path="*.wrox" type="System.Web.UI.PageHandlerFactory.System.Web" /> </httpHandlers> </system.web> </configuration>  Second, we must tell IIS to send requests with the extension .wrox to ASP.NET. This is accomplished through the IIS Microsoft Management Console: Open the IIS MMC, and right-click on either a web root or a web application folder (if we want to limit the mapping to a single application) and select the Properties option. Once the dialog is open, press the Configuration button, and select the App Mappings tab: This tab lists all the extensions that IIS maps to ISAPI extensions. ISAPI is a low-level API that lets custom applications plug in to IIS. ASP used an ISAPI named asp.dll, and ASP.NET uses an ISAPI named aspnet_isapi.dll. The ASP.NET ISAPI simply takes the entire request from IIS and hands it to ASP.NET. If we want ASP.NET to handle the .wrox extension, we need to map it onto the aspnet_isapi.dll so that IIS sends the request to ASP.NET. To add this application mapping press the Add button. This brings up the Add/Edit Application Extension Mapping dialog. We can then name the ASP.NET ISAPI (aspnet_isapi.dll), found in the directory: C:\[WINNT]\Microsoft.NET\Framework\[version]\. We can then also name our extension .wrox. Our completed entry should look similar to this: In the next chapter, we will look at how we can map the .wrox extension to ASP.NET resources through the ASP.NET configuration system. Asynchronous Application Events This is a more advanced discussion than the previous topics. Understanding asynchronous application events is not necessary to build good ASP.NET applications. It is, however, an advanced feature that can prove very useful in some cases. As we have mentioned earlier, ASP.NET code is executed in an ASP.NET worker process, not in the IIS process. Within this worker process, threads are used to execute code. A thread is a resource, and there are a finite number of threads that ASP.NET will be able to use, otherwise the processor would spend all its time context switching (that is, switching threads of execution in the processor) rather than executing user code. ASP.NET creates and manages a threadpool expanding and contracting the number of threads as required throughout the life of the application. This is in contrast to ASP, which used a fixed number of threads. In some cases application code, such as network I/O, can potentially stall threads in the ASP.NET process. This is because the ASP.NET thread has to wait (it is blocked) until this slow operation is complete. When a thread is blocked, it can't be used to service requests, resulting in queuing of requests and degraded application performance. The ASP.NET team took this into consideration, and has added support for asynchronous events in addition to the existing synchronous ones we discussed earlier. The only reason for using these asynchronous events in global.asax is in application code, within an event, that performs operations over the network where the network class supports I/O completion ports, such as a web service proxy. Supported Events There are ten supported asynchronous events, which are raised in the following order:  AddOnBeginRequestAsync  AddOnAuthenticateRequestAsync  AddOnAuthorizeRequestAsync  AddOnResolveRequestCacheAsync  AddOnAcquireRequestStateAsync  AddOnPreRequestHandlerExecuteAsync  AddOnPostRequestHandlerExecuteAsync  AddOnReleaseRequestStateAsync  AddOnUpdateRequestCacheAsync  AddOnEndRequestAsync No descriptions are given, as these events are synonymous with their synchronous counterparts described earlier. When to Use Asynchronous Events In Chapter 19, we will start looking at ASP.NET web services. In a nutshell, ASP.NET allows us to easily build XML interfaces for application code. All we need to do is write the application logic and mark the methods with the WebMethod attribute. Web services are very powerful, and easy to use. However, since they make calls over the network, and are subject to all the limitations of that network, we don't want to make a lot of web service calls within a web application (this is applicable to any web application, not just ASP.NET) because those network calls can potentially stall the threads used to process ASP.NET requests. For example, if our application gets twenty simultaneous requests and the application code that services each request makes a call to a web service, we will potentially stall and queue subsequent requests as we wait for the threads making the web service calls to return. However, by using asynchronous events, we could at least free up the threads that ASP.NET isn't using for the web service calls. Let's look at a sample of this. The Web Service First we need a sample web service. Below I have created a simple StockQuote web service, in a file named StockQuote.asmx: <%@ WebService Class="QuoteService" %> Imports System.Web.Services Public Class QuoteService <WebMethod()> Public Function GetQuotes() As QuoteDetails() ' Create an array of 3 Quote objects for our return Dim quotes(3) As QuoteDetails quotes(0) = New QuoteDetails() quotes(0).Symbol = "MSFT" quotes(0).Price = 89.34F quotes(1) = New QuoteDetails() quotes(1).Symbol = "SUNW" quotes(1).Price = 11.13F quotes(2) = New QuoteDetails() quotes(2).Symbol = "ORCL" quotes(2).Price = 22.93F Return quotes End Function [...]... by all ASP.NET web applications ASP.NET will install a single machine.config file on the server We can find machine.config in [WinNT\Windows]\Microsoft.NET\Framework\[version]\CONFIG\ We will have a single machine.config file installed for each version of ASP.NET installed The CLR, and thus ASP.NET, supports the concept of sidebyside execution Future versions of ASP.NET can run sidebyside with ASP.NET. .. character encoding for ASP.NET to use Compilation - The compilation options allow us to control some of the compilation behaviors of ASP.NET, such as changing the default language from Visual Basic NET to C# Identity - ASP.NET allows us to impersonate the user that ASP.NET acts on the behalf of HTTP Handlers - HTTP Handlers are responsible for servicing requests for a particular extension in ASP.NET, such as... ASP.NET, unlike ASP, does not require extensive use of the IIS metabase Instead, ASP.NET uses an XML-based configuration system As we will see in this chapter, ASP.NET' s configuration system is much more flexible, accessible, and easier to use Below is a breakdown of what we'll cover: Configuration Overview - We will start with a high-level overview of configuration, discussing both what's new in ASP.NET. .. obviously not ideal, especially when running a web server farm! Application Center can replicate IIS settings to other IIS servers in our farm Additionally, it includes other web farm manageability tools Let's look at ASP.NET configuration ASP.NET Configuration For completeness, we need to show the same configuration example of setting Session timeout from 20 minutes to 10 minutes for an ASP.NET application... configuration Configuration Overview ASP.NET configuration can be summarized in a single statement: a simple, but powerful, XML-based configuration system Rather than relying upon the IIS metabase, as we have to for ASP applications, ASP.NET uses an XML-based configuration system XML is used to describe the properties and behaviors for various aspects of ASP.NET applications The ASP.NET configuration system... the previous chapter for details on creating a web application) While ASP.NET does not use the IIS metabase for application settings, the administrator is still required to mark folders as web applications That's all there is to it - the ASP.NET application will now timeout the Session after 10 minutes of inactivity Similar to ASP, ASP.NET default session timeout is set to 20 minutes Although not shown,... straightforward to use We simply write a configuration file and save that file to a web application, and ASP.NET will automatically apply the changes More on how all this works later Benefits of ASP.NET Configuration As demonstrated above, instead of relying on the metabase for application configuration information, ASP.NET uses XML configuration files The benefits of this include: Human readable configuration... allows ASP.NET to treat components, files, and configuration information as a web application This process must still be accomplished either by using script that modifies the IIS metabase, through the IIS Manager snap-in, or automatically when we create a new ASP.NET project with Visual Studio NET The task of marking a web application forces the administrator to decide what is or is not an ASP.NET. .. and server configuration options, such as configuring Session timeout, the execution timeout (how long an ASP.NET application executes before being timed out), or new settings such as timing out the worker process, we will use the ASP.NET configuration exclusively How Configuration is Applied When ASP.NET applies configuration settings for a given request, a union of the machine.config as well as any... their respective application Detecting Configuration File Changes ASP.NET detects when files, such as machine.config or web.config, are changed by listening for file change notification events provided by the operating system Behind the scenes, when an ASP.NET application is started, the configuration settings are read and stored in the ASP.NET Cache A file dependency is then placed upon the entry within . IIS. ASP used an ISAPI named asp. dll, and ASP. NET uses an ISAPI named aspnet_isapi.dll. The ASP. NET ISAPI simply takes the entire request from IIS and hands it to ASP. NET. If we want ASP. NET. each version of ASP. NET installed. The CLR, and thus ASP. NET, supports the concept of sidebyside execution. Future versions of ASP. NET can run sidebyside with ASP. NET version 1. 0 code. Each version. start our discussion of ASP. NET configuration with a brief discussion of ASP configuration (for those of us that used ASP) . ASP Configuration Prior to ASP. NET, ASP web application configuration

Ngày đăng: 03/07/2014, 07:20

Tài liệu cùng người dùng

Tài liệu liên quan