To compile an ASPX file into a DLL file

Source: Internet
Author: User
Tags bool command line config empty html page http request iis implement
Compiling preface

ASP.net is not an ASP's simple upgrade, but an important part of Microsoft's. NET plan, which relies on. NET's multilingual and powerful class library support to introduce server-side HTML controls and Web controls to automate the interaction between the client and server side of the control. Provides developers with a Windows-like window programming interface that provides a good programming interface for developing large network application functionality and can greatly improve the productivity of developers.


However, the "one conversion, two compile" process makes an ASPX file appear slightly inadequate when it is first executed (or first run after the update), especially in an application environment that has a large number of ASPX and Codebehind code files. By compiling the ASPX file into a DLL (called an application set in. net) and then releasing it, eliminating the "one-time, one-compile" time and the CPU occupancy rate will improve the overall performance of the Web service. Of course, after compiling into a DLL, the confidentiality of the source code also has a certain degree of improvement.


This paper introduces how to establish the mapping of ASPX to DLL in asp.net, how to develop a DLL that can handle HTTP request/response, and how to set up "traps" by analyzing the basic processing flow of asp.net and a secret of accidental discovery. The process of compiling a ready-made single aspx file with a codebehind aspx file into a DLL, and at the end of the article, introduces a small skill in the actual operation process.


Because this article involves ASP.net applications, command-line compilation, Web.config configuration file concepts, in order to enable readers to better understand the content of this article, but also to make this article appears to be cumbersome, first on the corresponding system environment for this article is introduced:


System environment:

Win2000 (SP3) + IIS5 +. Net Framework 1.0 (Chinese version).

Server name:

Because the examples in this article are tested on this machine, the server name is localhost.

IIS settings:

Create the virtual directory Dlltest (the real path is w:\wwwroot\dlltest) and set it as an application, and create the bin directory under Dlltest. All source files will be placed in the Dlltest directory, and all DLL files will be placed in the Dlltest\bin directory.

asp.net application configuration file--web.config

Create a Web.config file in the Dlltest directory, which initially reads as follows:

<?xml version= "1.0"?>

<configuration>

<system.web/>

</configuration>

Command Window (DOS window)

Open the Command window and use the CD command to w:\wwwroot\dlltest the current directory.


I. Creating a mapping of ASPX to DLLs


Let's take a look at how ASPX files are typically handled by asp.net in general:

When an HTTP request, such as "http://webserver/webapp/webpage.aspx", is sent from the client to the IIS server, IIS captures and analyzes the request, and when it analyzes that the request is an ASPX page, immediately "/webapp /webpage.aspx calls the ASP.net run environment (aspnet_wp.exe) for parameters, asp.net when the environment is started, checks "/webapp/webpage.aspx" for existence, and if not, returns HTTP 404 to the Client ( File not found) error, otherwise locate the appropriate DLL file in ASP.net's temporary directory, or invoke the CSC compiler if it does not exist or if the DLL is older than the ASPX source file (if the server-side scripting language for ASPX is VB or JScript, The corresponding VBC compiler is invoked, the JSC compiler compiles the aspx file into a DLL, and then asp.net calls the DLL to handle the specific customer request and returns the server response.


As you can see from this process, the ASP.net running environment automatically recognizes, checks, and updates the DLLs that correspond to ASPX. Is there any other way to force the "route" of an ASPX file to a compiled existing DLL? The method is to add the ASPX to DLL mapping entry in the httphandlers section of the system.web section of the asp.net application configuration file web.config, as follows:

<add verb= "*" path= "aspx filename" type= "class name, dll file"/>

aspx files: Virtual names that need to be "routed", the extension must be ASPX, or IIS will process the file before the ASP.net run environment.

DLL file: The name of the DLL file (the application set) without having to enter ". dll". asp.net first searches the application's private \ Bin directory for the assembly DLL, and then searches the system assembly cache for the assembly DLL.

Class name: Because a DLL may have more than one namespace or multiple classes, you must indicate which class is loaded automatically when the DLL is called.


For example, a Web.config file for a asp.net application is as follows:

<?xml version= "1.0"?>

<configuration>

<system.web>


<add verb= "*" path= "index.aspx" type= "BBS. Indexpage, BBS "/>


</system.web>

</configuration>


This profile tells ASP.net that when the client requests the Index.aspx file for this application, it directly invokes the Bbs.dll in the application Bin directory and automatically loads the Bbs.indexpage class in it.


Ii. developing DLLs that can handle HTML pages


It should be noted that not all application set DLLs implement the HTTP request/response pattern. Let's take a look at the description of "HTTP Handlers and factories" in the Microsoft ASP.net QuickStart tutorial (http://chs.gotdotnet.com/quickstart/aspplus/):


asp.net provides a low level request/response API that enables developers to use the. NET Framework classes to service incoming HTTP requests. To do this, developers need to create classes that support the System.Web.IHTTPHandler interface and implement the ProcessRequest () method. Handlers are often useful when processing HTTP requests without the need to abstract the services provided by a high-level page framework. Common uses of handlers include filters and CGI-like applications, especially those that return binary data.


Each incoming HTTP request received by ASP.net is ultimately handled by a specific instance of the class that implements IHttpHandler. IHttpHandlerFactory provides a structure that handles the actual parsing of IHttpHandler instance URL requests. In addition to the default IHttpHandlerFactory classes provided by ASP.net, developers can choose to create and register factories to support a large number of request resolution and activation scenarios.


As you can see from this passage, when an ASPX page does not involve advanced interface technologies provided by the. NET Framework (such as data caching, state retention, Web Forms control references, and so on), and the output to the client is not complex HTML text, especially when only binary data (such as pictures, sounds, etc.) is returned to the client, You can use a. cs application file (this article uses the C # language, if it is VB or JScript, ...). Instead, the application must have a class that implements the System.Web.IHTTPHandler interface and implements the ProcessRequest () method. A simple example is as follows:


/* source file: Ex1.cs Start * *


Using System.Web;


Namespace Dlltest

{

/*

Class must implement the IHttpHandler interface. If your program accesses session state (sessions), you must implement the IRequiresSessionState interface (a markup interface that does not contain any methods).

*/

public class Ex1page:ihttphandler

{

/*

The IsReusable property tells the. NET Framework whether this program can be used by multiple threads at the same time.

True is; false corresponds to No.

*/

public bool IsReusable

{

get {return true;}

}


/*

Implement the ProcessRequest method to return response data to the client.

In this case, return a simple HTML page to the client

*/

public void ProcessRequest (HttpContext context)

{

HttpResponse res = context. Response;


Res. Write ("
Res. Write ("
Res. Write ("This page is handled directly by the DLL");

Res. Write ("
}


}

}


/* source file: Ex1.cs End * *



In the command line state, compile the Ex1.cs into Ex1.dll with the following compiler command and store it in the bin directory.

Csc/t:library/out:bin\ex1.dll Ex1.cs
Add Aspx->dll mappings to the configuration file Web.config, and after adding, Web.config should be like this:

<?xml version= "1.0"?>

<configuration>

<system.web>


<add verb= "*" path= "dlltest1.aspx" type= "Dlltest.ex1page, Ex1"/>


</system.web>

</configuration>


Now when the browser accesses the http://localhost/dlltest/dlltest1.aspx, it actually calls the ProcessRequest method of the Dlltest.ex1page class in Ex1.dll, and you should see a simple page in the browsing.



C. Compile a single ASPX file into a DLL


Microsoft does not support allowing developers to compile ASPX files into DLLs directly from the "overtones" that Microsoft has publicly described in the previous section. However, ASP.net advanced interface Technology (server-side HTML controls, Web controls, and so on) need to be demonstrated through ASPX files, and it is obviously not a good way to discard the advanced features of ASPX for the efficiency of the DLL.


Now calm down to analyze:

The CSC compiler is just a C # language compiler that compiles only files that conform to the C # Language specification, and the ASPX compiler is unable to compile the ASPX source file because its format is clearly inconsistent with the C # language specification.

Therefore, in order to compile the ASPX file into a DLL file, the aspx file must be converted into a CS source file that can be recognized by the CSC compiler. So what tools do you use to convert? Although I am convinced that this tool must be hidden within the. NET Framework, there is still no information available after consulting a large number of asp.net and. NET public documents and reference manuals.


Oh, despair, a chance, or let me find the secret.


To see the source file ex2.aspx:


/* source file: ex2.aspx Start * *


<%@ Page language= "C #"%>


<script runat= "Server" >


/*

You are right, the next line is "ABCDEFG", it is this line, just let me have the opportunity to write this article ^_^;

In the article, I call this line "code trap."

*/


ABCDEFG//Code traps


void Page_Load (Object src, EventArgs args)

{

if (! IsPostBack) Notelabel.text = "Please enter your name:";

}


void Onnamesubmit (Object src, EventArgs args)

{

String name = F_name.value;

Notelabel.text = (name== "")? "Name cannot be empty": Name + ", hello." Welcome to our visit! ";

}

</script>



<body>

<form runat= "Server" >



<asp:label runat= "Server" id= "Notelabel" style= "color:red"; Font-weight:bold "/>

<input runat= "Server" id= "F_name" size= "8" >

<button runat= "Server" onserverclick= "Onnamesubmit" > OK </button>

</form>

</body>



/* source file: ex2.aspx End * *


If the "code trap" commented out or deleted, then ex2.aspx is a simple asp.net file, use IE to browse this page can be found that it works.


Now let's open the trap and see what asp.net returns.


Returns a "Compile error" page that reports that the source file is not compiled. What interests us is that the bottom of the page is a hyperlink called "Show Complete compilation source," and click on a link to see the full contents of the CS source file ("complete compilation source") that was converted by ex2.aspx. Take this part of the "complete compilation source" to remove the previous line number information and some other compiler switches (mainly #line compilation commands), and close that cute "code trap" (with//annotate it or delete it directly), and then save it as Ex2_aspx.cs:


/* source file: Ex2_aspx.cs Start * *


/*

As you can see from the instructions below, you do have an undisclosed tool to convert the ASPX file into a CS source file.

*/
//------------------------------------------------------------------------------

<autogenerated>

This code is generated by a tool.

Runtime version:1.0.3705.0

//

Changes to this file may cause incorrect behavior and would be lost if

The code is regenerated.

</autogenerated>

//------------------------------------------------------------------------------


/*

Strangely, the namespaces are ASP rather than ASPX.

It is recommended that you change the name to suit the name of the application to prevent naming conflicts, for example, for this article, you can change to Dlltest

It's not a change, it's about getting people to see the original.

*/

Namespace ASP {

Using System;

Using System.Collections;

Using System.Collections.Specialized;

Using System.Configuration;

Using System.Text;

Using System.Text.RegularExpressions;

Using System.Web;

Using System.Web.Caching;

Using System.Web.SessionState;

Using System.Web.Security;

Using System.Web.UI;

Using System.Web.UI.WebControls;

Using System.Web.UI.HtmlControls;


/*

1, pay attention to the composition of the class name, if necessary, you can change it to a meaningful name, for example, for this article, can be changed to Ex2page

2, pay attention to its base class. Syste.Web.UI.Page implements the IHttpHandler interface and realizes the IRequiresSessionState interface because it accesses the session.

*/

public class Ex2_aspx:System.Web.UI.Page, System.Web.SessionState.IRequiresSessionState {


private static int __autohandlers;

protected System.Web.UI.WebControls.Label Notelabel;

protected System.Web.UI.HtmlControls.HtmlInputText f_name;

protected System.Web.UI.HtmlControls.HtmlButton __control3;

protected System.Web.UI.HtmlControls.HtmlForm __control2;

private static bool __intialized = FALSE;

private static System.Collections.ArrayList __filedependencies;


/* Now we can turn off the "trap".

Abcdefg


void Page_Load (Object src, EventArgs args)

{

if (! IsPostBack) Notelabel.text = "Please enter your name:";

}


void Onnamesubmit (Object src, EventArgs args)

{

String name = F_name.value;


Notelabel.text = (name== "")? "Name cannot be empty": Name + ", hello." Welcome to our visit! ";

}


/* Constructor/*

Public ex2_aspx () {

System.Collections.ArrayList dependencies;

if ((asp.ex2_aspx.__intialized = = False)) {

dependencies = new System.Collections.ArrayList ();


/*

The following line should be commented out so that the DLL becomes a standalone file without dependencies

Prevents the DLL from running again to find and compare its "dependent" files to the old and new

*/

Dependencies. ADD ("w:\\wwwroot\\dlltest\\ex2.aspx");

Asp.ex2_aspx.__filedependencies = dependencies;

Asp.ex2_aspx.__intialized = true;

}

}


protected override int Autohandlers {

get {

return asp.ex2_aspx.__autohandlers;

}

set {

Asp.ex2_aspx.__autohandlers = value;

}

}


Protected System.Web.HttpApplication ApplicationInstance {

get {

Return (System.Web.HttpApplication) (this. Context.applicationinstance));

}

}


public override string TemplateSourceDirectory {

get {

return "/dlltest";

}

}


Private System.Web.UI.Control __buildcontrolnotelabel () {

System.Web.UI.WebControls.Label __ctrl;

__ctrl = new System.Web.UI.WebControls.Label ();

This. Notelabel = __ctrl;

__ctrl.id = "Notelabel";

((System.Web.UI.IAttributeAccessor) (__ctrl)). SetAttribute ("Style", "color:red; Font-weight:bold ");

return __ctrl;

}


Private System.Web.UI.Control __buildcontrolf_name () {

System.Web.UI.HtmlControls.HtmlInputText __ctrl;

__ctrl = new System.Web.UI.HtmlControls.HtmlInputText ();

This.f_name = __ctrl;

__ctrl.id = "F_name";

__ctrl. Size = 8;

return __ctrl;

}


Private System.Web.UI.Control __buildcontrol__control3 () {

System.Web.UI.HtmlControls.HtmlButton __ctrl;

__ctrl = new System.Web.UI.HtmlControls.HtmlButton ();

This.__control3= __ctrl;

System.Web.UI.IParserAccessor __parser = ((System.Web.UI.IParserAccessor) (__ctrl));

__parser. AddParsedSubObject (New System.Web.UI.LiteralControl ("OK"));

__ctrl. ServerClick + = new System.EventHandler (this. Onnamesubmit);

return __ctrl;

}


Private System.Web.UI.Control __buildcontrol__control2 () {

System.Web.UI.HtmlControls.HtmlForm __ctrl;

__ctrl = new System.Web.UI.HtmlControls.HtmlForm ();

This.__control2= __ctrl;

System.Web.UI.IParserAccessor __parser = ((System.Web.UI.IParserAccessor) (__ctrl));

__parser. AddParsedSubObject (new System.Web.UI.LiteralControl ("\ r \ n
This.__buildcontrolnotelabel ();

__parser. AddParsedSubObject (this. Notelabel);

__parser. AddParsedSubObject (new System.Web.UI.LiteralControl ("\ r \ n"));

This.__buildcontrolf_name ();

__parser. AddParsedSubObject (This.f_name);

__parser. AddParsedSubObject (new System.Web.UI.LiteralControl ("\ r \ n"));

This.__buildcontrol__control3 ();

__parser. AddParsedSubObject (THIS.__CONTROL3);

__parser. AddParsedSubObject (new System.Web.UI.LiteralControl ("\ r \ n"));

return __ctrl;

}


private void __buildcontroltree (System.Web.UI.Control __ctrl) {

System.Web.UI.IParserAccessor __parser = ((System.Web.UI.IParserAccessor) (__ctrl));

__parser. AddParsedSubObject (New System.Web.UI.LiteralControl ("\r\n\r\n
This.__buildcontrol__control2 ();

__parser. AddParsedSubObject (this.__control2);

__parser. AddParsedSubObject (New System.Web.UI.LiteralControl ("\r\n</body>\r\n
}


protected override void FrameworkInitialize () {

This.__buildcontroltree (this);

This. Filedependencies = asp.ex2_aspx.__filedependencies;

This. enableViewStateMac = true;

}


public override int GetTypeHashCode () {

return-11574299;

}

}

}


/* source file: Ex2_aspx.cs End * *


I believe that after the analysis of this file, there will be a further understanding of the operation of the ASP.net (this article is irrelevant, not detailed).


In the command line state, compile the Ex2_aspx.cs into Ex2.dll with the following compiler command and store it in the bin directory.

Csc/t:library/out:bin\ex2.dll Ex2_aspx.cs


Add the Aspx->dll mapping in the configuration file web.config, that is, add the following line to httphandlers in the system.web section:

<add verb= "*" path= "dlltest2.aspx" type= "asp.ex2_aspx, Ex2"/>



Now when the browser accesses http://localhost/dlltest/dlltest2.aspx, it is just like accessing ex2.aspx. Of course, now even if ex2.aspx does not exist, or has been updated, it will not have any effect on page access unless the Bin\ex2.dll is regenerated.



Iv. compile the codebehind aspx file into a DLL


For the codebehind aspx file into a DLL, which converts the ASPX file into a CS source file principle, but also set a "code trap", and then "complete the source of the compilation" For proper collation, save as a CS source file. The difference is the steps to compile into a DLL: (for the convenience of narration, assume that the interface file is saved as a "full compilation source" for the ex3.aspx.cs,ex3.aspx ex3.aspx,codebehind file as Ex3_aspx.cs)

The first step: first use the following command to compile Ex3.aspx.cs into Bin\ex3.aspx.cs.dll

Csc/t:library/out:bin\ex3.aspx.cs.dll Ex3.aspx.cs

Step two: Then use the following command to compile Ex3_aspx.cs into Bin\ex3.dll

Csc/t:library/r:bin\ex3.aspx.cs.dll/out:bin\ex3.dll Ex3_aspx.cs


Then add the Aspx->dll mapping in the configuration file web.config, that is, add the following line to httphandlers in the system.web section:

<add verb= "*" path= "dlltest3.aspx" type= "asp.ex3_aspx, ex3"/>


Now open the browser and visit http://localhost/dlltest/dlltest3.aspx to try.


51 Little tricks.


When setting "trap" to convert aspx file into CS source file, it is usually to use copy, paste method to save "complete compilation source" in Notepad or vs.net or other asp.net development environment, and then save it as CS source file after finishing.

Collation, is the paste in the line number information and "#line" compiled instructions to remove. If you delete this information manually, it will be too much trouble, even a simple file such as ex2.aspx will produce a "complete compilation source" of about 270 lines.

One of the tips I've used is to do it quickly in a notepad, using a replacement method. Replace "line" with "/* line", with ":" * * "to replace All": ", with"//#line line "to replace all the" #line ", replace the completion of the" code trap "annotation, the main class constructor set" dependent file "statement all commented out, so even if the finishing finished.


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.