1. Trang chủ
  2. » Công Nghệ Thông Tin

ASP.NET Bible 2002 PHẦN 5 potx

68 147 0

Đ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

Thông tin cơ bản

Định dạng
Số trang 68
Dung lượng 1,09 MB

Nội dung

§ They are self-describing: Assemblies are self-describing deployable units. .NET stores the metadata about the components in assembly manifests, which include the identity of the assembly (such as the name and the version number), security information, information about the dependencies, and the list of files that constitute the assembly. In .NET, an application is also made up of assemblies. Therefore, the information about the version of a component used by an application is also maintained in the assembly. § They record the version information and enforce it at run time: The assembly manifest also includes the information about the dependencies between different assemblies, such as the name of the referenced assembly and its version number. This version number is used at run time to ensure that the correct version of the dependency is loaded. § They provide the ability to work with side-by-side components: This feature allows multiple versions of a component to be installed and run simultaneously. The caller of the assembly can specify the version to be loaded. Thus, the .NET Framework allows multiple versions of a single component to coexist on a machine. This feature also isolates the application from the changes made to the system by other applications. Creating a single-file assembly You can create a single-file assembly by using command-line compilers such as vbc and csc. A single-file assembly includes all the information about the component. You can use the following statement to create an assembly file with the .exe extension. C#: csc filename.cs VB.NET: vbc filename.vb These statements create an assembly that has the same name as that of the VB or CS file and with an .exe extension. To create an assembly file with a different filename, you can use the /out: option of the compiler command, as follows: C#: csc /out:outputfile.exe sourcefile.cs VB.NET: vbc /out:outputfile.exe sourcefile.cs In these examples, the source file must contain a single entry point, such as the Main() function. If you do not have an entry point, the compiler gives you an error message. If you do not want your source file to contain any entry point and want it to contain only other classes and methods, you must create a library assembly. A library assembly contains components that will be accessed by other assemblies. It is very similar to class libraries. You can create a library assembly by typing the following command: C#: csc /t:library /out:outputfile.dll sourcefile.cs VB.NET: vbc /t:library /out:outputfile.dll sourcefile.cs After you have created assemblies for all the files to be used in a project, you can create a deployment project. Creating a multifile assembly You might be required to create a multifile assembly if you want to use classes written in different languages. You might also be required to create a multifile assembly if you want to optimize the process of downloading components. For example, you might want to combine rarely used components into a single assembly. When you create a multifile assembly, one of the files in the assembly must contain the assembly manifest. Let us look at the process of creating a multifile assembly with the help of an example. Consider the class ConnectDB: 'ConnectDB.VB ' Imports System.Data Imports System.Data.SQL Namespace DB Public Class ConnectDB : Functions for establishing connection : End Class End Namespace Consider another class, Calculate, which uses the class ConnectDB to connect to the sales database and returns the price of a product after calculating the discount: 'Calculate.VB ' Imports System.Data Imports System.Data.SQL Imports DB Public Class Calculate : Call functions from the ConnectDB class Calculate the discounted price : End Class To create an assembly with these two files, you need to follow these steps: 1. Compile all the classes that are created within a namespace, which is referenced by other modules. In this example, the class ConnectDB is created within the namespace DB. The DB namespace is accessed in the Calculate class. Therefore, you first need to build the ConnectDB class into a module by using the following statement: vbc /t:module ConnectDB.vb /r:system.dll /r:system.data.dll When you want to create a module instead of a library assembly or an executable file, you need to specify the /t:module option, which instructs the compiler to create a standard DLL file that does not contain the assembly manifest. The /r option is used to specify references to other libraries. This statement creates a module called ConnectDB.mcm. Note The default extension for a module is .mcm. You can change the default name of the output file generated by the compiler by using the /out: option of the compiler. 2. After compiling classes that are included inside namespaces, you need to compile classes that use other modules. In the example, the Calculate class references the ConnectDB module and makes calls to functions written in the ConnectDB class. Therefore, you must compile the Calculate class file by executing the following statement at the command prompt: vbc /addmodule:ConnectDB.mcm /t:module Calculate.vb In this statement, the /addmodule option is included to specify the name of the module, which is referenced by the file Calculate.vb. When you give this statement from the command prompt, the compiler creates a module called Calculate.mcm, which references another module, ConnectDB.mcm. 3. After compiling various classes into modules, you can create a multifile assembly by using the Al.exe utility. Type the following statement at the command prompt to create an assembly: al /out:App.dll /t:lib ConnectDB.mcm Calculate.mcm In this statement, the /out option specifies the name of the output file to be produced by Al.exe. The /t option specifies the file format of the output file. You can set the option to lib (code library), exe (console application), or win (Windows-based application). Finally, you specify the names of the modules to be included in the assembly. This statement creates a library assembly called App.dll. This file contains the assembly manifest, which describes the types in other modules included in the assembly. Creating a deployment project A deployment project enables you to specify the files to be included in the deployment and the name of the remote machine where the application or component needs to be deployed. You can create a deployment project by completing the following steps: 1. Open the CalcNetAmt project. 2. Select File → New → Project. Select Setup and Deployment projects from the Project Types list box. 3. The Templates list box provides various options, such as Cab Project, Merge Module Project, Setup Project, Setup Wizard, and Web Setup Project, for performing different types of installations. Select Setup Wizard. Click the Add To Solution radio button. 4. The Setup Wizard guides you through various steps of creating a deployment project. It enables you to specify whether you want to deploy a client application or Web application, and the files to be included in the deployment project. 5. The first step in the Setup Wizard is to choose the project type of the deployment application. This screen provides four options: Create A Setup For Windows Application, Create A Setup For A Web Application, Create A Merge Module For Windows Installer, and Create A Downloadable CAB File. Select Create A Setup For A Web Application. 6. The next screen asks you to specify the project output groups to be included in the setup project. Select the Project Output check box. Project output includes the EXE or DLL files in a project. 7. The last screen asks you to specify any additional files that you want to be included in the setup project. These files may include the Readme.txt file or an HTML page containing instructions for installation. Add the files that you want to be included in the setup project. Click the Finish button. 8. If you want to change any of the properties of the deployment project that you have created, right-click the project in the Solution Explorer window and select Properties from the pop-up menu. This will invoke the Setup Property Pages dialog box, shown in Figure 15-11. Figure 15-11: Setup Property Pages dialog box 9. If you forgot to specify some files that are required to deploy the application in the wizard while creating the setup project, you can add them by right-clicking the setup project in the Solution Explorer window and clicking Add → File. 10. After you have specified all the options and the files to be included in the deployment project, right-click the project in the Solution Explorer and click the Build option. This will create a MSI (Windows Installer Package) file in the Debug folder of your project. You can now use this file to deploy your components and application. Cross- Reference For a detailed discussion on deploying classes and assemblies, see Chapter 21. Working with Business Object Namespaces Namespaces enable you to organize your classes in a hierarchical manner and organize all the classes and methods that perform related tasks. You can use namespaces to organize your business objects as well. For example, you might create a namespace called SalesData, which might contain all the components that perform the tasks of inserting, manipulating, and validating the data from the sales database. You can create a business object namespace by using the Namespace keyword, as follows: Namespace SalesData Class AddSalesData : code for adding sales data : End Class End Namespace While using this business object in your Web application, you must import the namespace SalesData by including the following statement in the ASPX file: <%@ Import Namespace="SalesData" %> You might alternatively include the following statement in the VB file of the Web project: Imports salesdata Cross- Reference For a detailed discussion on creating and using namespaces, refer to Appendix F. Summary In this chapter, you learned about the business objects and the different types of business objects. You also learned to create UI-centric business rule objects and data- centric business rule objects. Next, you learned to use business objects in your application. Then, you looked at the process of deploying business objects. Finally, you learned about working with business object namespaces. Chapter 16: Building HTTP Handlers Overview The World Wide Web (WWW) uses the Hypertext Transfer Protocol (HTTP) as the underlying protocol for communication. It is an application-level protocol that is responsible for establishing a connection between a client (browser) and a Web server and transmitting the information requested by the client. In fact, the day-to-day life of a Web server involves receiving requests from clients and responding to them by using HTTP. ASP.NET works by dispatching the client requests to user-defined HTTP handler objects called HTTP handlers. With ASP.NET, you can create these user-defined HTTP handlers by implementing a .NET interface named IHttpHandler. After you've created a user-defined handler, you can bind a specific URL request to the handler for handling specific requests. For example, you can bind a URL request for a file, with your name as an extension, to a user-defined handler for processing. However, if a specific URL request is not mapped to a handler, the default handler of ASP.NET handles it. In this chapter, you will learn about HTTP runtime provided in ASP.NET, which allows you to process HTTP requests coming from clients. You will also learn about the interfaces and classes involved in creating HTTP handlers. Finally, you will learn to create a custom HTTP handler. Introduction to HTTP Runtime and HTTP Handlers When you enter a URL in a browser, the browser builds an HTTP request and sends it to the address specified in the URL. While building the HTTP request, various methods are used. These methods indicate the purpose of the request. These methods include the following: § Get: Used when a request for a particular page is made. When a user enters a link in the Address box of the browser or clicks a hyperlink, the HTTP Get method is used to build the HTTP request. The Get method is usually used when the request does not alter the state of a database. § Head: Used when a user wants to retrieve only the information about the document and not the document itself. § Post: Used when a user requests a resource that interacts with a database. The Web server, which contains the requested page, performs necessary processing based on the method used for sending the request, and returns the page requested by the client. In addition to these methods, you can have a lower-level control over the processing of requests on the Web server. This is possible with the help of application programming interfaces (APIs), which are covered in the next two sections. ISAPI and HTTP Runtime A number of APIs have been developed that enable developers to have lower-level control over the processing of requests on the Web server. For example, the Internet Services API (ISAPI) developed for IIS Web Server enables developers to create high- performance applications. At the same time, it enables developers to have low-level control over the way requests are processed by IIS. With ISAPI, you can create your own dynamic link libraries (DLLs) that specify the tasks that need to be performed when a request is sent to the Web server. The DLLs provided in ISAPI can be of two types, filters and extensions. Filters enable you to write code that can receive notifications from the Web server during the processing of a request. Thus, filters are used to alter the standard behavior of the Web server. You can use filters to perform tasks such as compressing and encrypting the data to be sent and authenticating a user. On the other hand, ISAPI extensions accept user requests, perform tasks such as retrieving data from a database and generating an HTML page, and send a response to the client. In ASP.NET Web applications, low-level control over client requests is achieved by using the HTTP runtime. The HTTP runtime is built on the Common Language Runtime (CLR) of the .NET Framework, and provides an environment for processing requests. Thus, the CLR replaces the ISAPI under IIS. The HTTP runtime performs various functions, including receiving requests from the client, resolving the address specified in the URL, and sending the request to the appropriate application for further processing of the request. The HTTP runtime is capable of receiving multiple requests simultaneously. The applications are run in separate address spaces, thereby improving reliability and preventing cross-platform chaos. Therefore, the failure of a single Web application does not affect the working of the HTTP runtime. Just like the ISAPI extensions and ISAPI filters, the HTTP runtime enables developers to have lower-level control over processing Web requests. However, unlike ISAPI, for which developers must know C++, the HTTP runtime is a cleaner model and enables developers to program in any .NET programming language. Therefore, ASP.NET prefers the CLR of the .NET Framework to the ISAPI architecture. Architecture of the HTTP Runtime The architecture of the HTTP runtime is similar to that of a pipeline. It is comprised of a number of HTTP modules and handlers. In simple terms, HTTP modules and HTTP handlers are classes created by developers that implement predefined interfaces of ASP.NET. When a client makes a request that results in executing a Web application, the request passes through a pipeline of HTTP modules. HTTP modules enable a Web application to perform specific tasks, such as encrypting the data, performing custom authentication for providing access to the application, and managing the state of the client session and the application. After passing through a series of HTTP modules, the request is sent to the HTTP handler. An HTTP handler is a replacement for ISAPI extensions that receive the request, fetch the required data, and send the data in response to the request sent by the client. ASP.NET provides higher-level programming models, such as Web services and Web Forms, which are implemented as HTTP handlers. The pipeline architecture of the HTTP runtime enables you to easily implement new functionality by adding new HTTP modules and handlers. Figure 16-1 depicts the pipeline architecture of the HTTP runtime provided in ASP.NET Figure 16-1: Architecture of the HTTP runtime provided in ASP.NET ASP.NET provides various interfaces that can be implemented for creating HTTP modules and HTTP handlers. For example, it provides the IHttpModule interface, which can be used to create modules that perform tasks related to security and compression. State management functions are often implemented in HTTP modules so that they can be easily added or removed from the HTTP runtime pipeline. In addition to the IHttpModule interface, ASP.NET has the IHttpHandler interface that can be implemented by developers to create a lower-level HTTP handler that receives the request and performs various tasks. As you already know, HTTP is used to process requests for the ASP.NET pages. Because HTTP is a connectionless protocol, clients connect to servers only for the duration of HTTP requests. There must be a way in ASP.NET to manage connections within an application. To do so, ASP.NET generates one HttpContext object and passes it to HTTP handlers for each request that is serviced. The HttpContext object provides a way to manage the connections within an application. This object maintains the information about the current request and also provides access to the Request, Response, and Server objects corresponding to a particular HTTP request. The Request object provides access to the values entered by a user while sending a request to the Web server. For example, you may enter values in an HTML form and send a request to the Web server to look up the value in a table stored in a database. This value can be accessed by using the Request object. Similarly, you can use the Response object to send a response from the Web server to the client. The Server object provides methods that are used for processing the request. For example, the Server object has the HtmlDecode method, which decodes the HTTP request sent by the client by removing the HTML characters from the request. You can use all of these built-in objects and their methods to perform different tasks in your HTTP handlers. You learned about the HTTP runtime, HTTP modules, and HTTP handlers provided in ASP.NET. Now, you will learn to create an HTTP handler. Interfaces and Classes Used to Create HTTP Handlers The .NET Framework provides classes that enable you to handle HTTP requests for the ASP.NET Web pages and services. You can handle HTTP requests by creating a class that implements the IHttpHandler interface contained in the System.Web namespace. The System.Web namespace contains classes and interfaces that enable you to handle the communication between browsers and Web servers. Before you can use a class that implements the IHttpHandler interface, you need to write the <httpHandlers> section in the Web.config configuration file to map the class that implements IHttpHandler to a URL request. Cross- Reference For more information on the <httpHandlers> section, refer to Chapter 14. Before you create an HTTP Handler, let us look at the IHttpHandler and IHttpHandlerFactory interfaces, and some of the classes contained in the System.Web namespace. IHttpHandler interface The IHttpHandler interface must be implemented to create user-defined HTTP handlers to process Web requests. Specific instances of the classes that implement the IHttpHandler interface process the Web requests received by ASP.NET. When you create a class that implements the IHttpHandler interface, you need to implement a method and a property of this interface. The method that needs to be implemented is ProcessRequest, and the property that needs to be implemented is IsReusable. ProcessRequest The ProcessRequest method is called whenever an HTTP request is made and has the following Visual Basic .NET syntax: Sub ProcessRequest (ByVal context As HttpContext) End Sub As you can see in the preceding syntax, the ProcessRequest method takes an object of the HttpContext class (discussed later in this section) as a parameter. You use the HttpContext object to handle all Web requests. IsReusable The IsReusable property is an overrideable read-only property that gets a value indicating whether the instance of the class that implements the IHttpHandler interface can be recycled and used for other Web requests. The Visual Basic .NET syntax of the IsReusable property is given as follows: ReadOnly Property IsReusable As Boolean As you can see in this syntax, the IsReusable property gets a Boolean value. If it gets True, the IHttpHandler instance can be reused for other Web requests. However, if the property gets False, the IHttpHandler instance cannot be reused for other Web requests. IHttpHandlerFactory interface As mentioned earlier, the Web requests received by ASP.NET are processed by specific IHttpHandler instances. At run time, the Web requests must be resolved to the IHttpHandler instances. This resolution of the Web requests to the IHttpHandler instances is done by the IHttpHandlerFactory interface. This interface contains two methods, GetHandler and ReleaseHandler. GetHandler The GetHandler method returns an IHttpHandler object that processes the Web request from the client. The Visual Basic syntax for the GetHandler method is given as follows: Function GetHandler( ByVal context As HttpContext, ByVal requesttype As String, ByVal url As String, ByVal pathtranslated As String ) As IHttpHandler 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 Description Application 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 Description Browser 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. RequestType 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 [...]... re-created ASP.NET encapsulates the application data caching in the Cache class The Cache class is always associated with an ASP.NET application When an ASP.NET application starts, an instance of the Cache class is always created The Cache object is destroyed as soon as the ASP.NET application stops Therefore, the lifetime of this Cache object is the same as the lifetime of an ASP.NET application The ASP.NET. .. (in-process), in separat e memory from ASP.NET (out-ofprocess using Windows NT Service), or in a persistent storage (in SQL Server) Since the ASP.NET Session object can be stored out-ofprocess, it is process-independent ASP.NET session state can run in a separate process from the ASP.NET host process Therefore, the session state is available irrespective of the ASP.NET process Of course, you can still... page in ASP.NET Figure 17-6: Processing a Web page in ASP.NET You can mark the output of an ASP.NET Web page for caching by specifying the @OutputCache page directive at the beginning of the page This directive takes a Duration parameter in seconds and causes the ASP.NET cache to store the output of the page in the cache for the specified number of seconds For example, to cache the output of an ASP.NET. .. 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 is interpreted, all code in ASP.NET is compiled before execution, resulting... When the output generated by an ASP.NET page depends on the parameters passed by using QueryString or the Post method, it requires ASP.NET to maintain multiple versions of the same page The HttpCacheVaryByParams class is used to maintain multiple versions of the same ASP.NET page in the cache When the VaryByParam attribute is set with the @OutputCache directive in a page, ASP.NET internally uses the HttpCacheVaryByParams... requested an ASP.NET page, and if the page is browser-specific, you can set the VaryByHeaders property to "User-Agent" This makes ASP.NET maintain a browserspecific cache To achieve this, set the @OutputCache directive as follows: If the ASP.NET page is requested multiple times by the same browser, the first request will cause the ASP.NET page... performance gains After the code for an ASP.NET Web page is compiled, all future requests for that page are handled by the compiled code without requiring any recompilation until a change is made to the original ASP.NET page Also, when a page is accessed for the first time, the code is compiled depending on user needs For example, if there are 10 functions in an ASP.NET Web page, only those functions... is specified at the beginning of an ASP.NET page, the ASP.NET runtime automatically invokes the cache services to store the data output by the Web page The page output that includes all data output from the page (including any data retrieved from a database) is retrieved from this cache for all future requests made to that Web page The first user request to the ASP.NET page will generate HTML; all... Session object over the ASP.NET Session object: § Process dependency: In the case of classical ASP, the ASP Session object is process-dependent If an ASP service on a Web server is restarted, the session state of all the users on that server is lost, and all these users are assigned new sessions On the other hand, the ASP.NET Session object can be stored in the same memory that § § ASP.NET uses (in-process),... servers will receive a no-cache HTTP header value @OutputCache This page-level directive in an ASP.NET page is used to control the cache duration of the page output To control the cache behavior of an ASP.NET page, you can use either the @OutputCache directive or the HttpCachePolicy class However, if the ASP.NET page is parameterized by using QueryString parameters or the Post method, the page cache . pipeline architecture of the HTTP runtime provided in ASP. NET Figure 16-1: Architecture of the HTTP runtime provided in ASP. NET ASP. NET provides various interfaces that can be implemented. 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 example, unlike classic ASP, wherein the code is interpreted, all code in ASP. NET is compiled before execution, resulting in huge performance gains. After the code for an ASP. NET Web page is compiled,

Ngày đăng: 12/08/2014, 08:23