Compile the asp.net 2.0 project to the dll file for reprinting

Source: Internet
Author: User
Asp.net is not a simple asp upgrade, but Microsoft. It is an important part of the Net plan. Net multi-language and powerful class library support, introduced the Server HTML control and WEB control, automatic processing of control client and server interaction, it provides developers with a window programming interface similar to Windows, provides a good programming interface for developing large-scale network application functions, and greatly improves the efficiency of developers.

However, the "one-time conversion and two-time compilation" process makes the aspx file slightly inadequate when it is executed for the first time (or when it is updated for the first time, especially in the application environment with a large number of code files aspx and codebehind, compile the aspx file into a DLL (in. . Net, called Application assembly) and then released, saving the time for "one conversion, one compilation" and CPU usage, greatly improving the overall performance of WEB Services. Of course, after being compiled into a DLL, the confidentiality of the source code is also improved to a certain extent.

This article through Asp. the basic processing process of Net and the analysis of an accidental secret are introduced in Asp. net, how to establish aspx to DLL ing, how to develop a DLL that can handle HTTP requests/responses, and how to set "traps ", compile a single off-the-shelf aspx file and the codebehind aspx file into a DLL process. At the end of the article, I also introduced a small skill in the actual operation process.

This article involves Asp. net application, command line compilation, web. config configuration file and other concepts, in order to make readers better understand the content of this article, but also to make this article not seem cumbersome, first introduce the system environment corresponding to this article:

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

Server Name: as the examples in this article are all tested on the local machine, the server name is localhost.

IIS settings: Create the virtual directory dlltest (the actual path is w: \ wwwroot \ dlltest), set it as an application, and create the bin directory under dlltest. All source files are stored in the dlltest directory, and all dll files are stored in the dlltest \ bin directory.

Asp. Net application configuration file-web. config creates a web. config file in the dlltest directory. The content of the file is as follows:

<? Xml version = "1.0"?>
<Configuration>
<System. web/>
</Configuration>

Command window (DOS window)

Open the command window and run the cd command to make the current directory w: \ wwwroot \ dlltest.

(1) create a dll ing from aspx to dll

First, let's take a look at how the aspx file is processed 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,

When it analyzes that this request is An aspx page, it immediately calls the asp.netruntime environment (aspnet_wp.exe) for "/webapp/webpage. aspx ),

After the Asp. Net environment is started, check whether "/webapp/webpage. aspx" exists. If not, return the HTTP 404 (File not found) error to the client,

Or else in Asp. find the corresponding dll file in the temporary directory of. Net. If the dll does not exist or is earlier than the aspx source file, call the csc Compiler (if the aspx server script language is VB or JScript, then, the corresponding vbc compiler and jsc compiler are called to compile the aspx file into a dll,

Then Asp. Net calls the dll to handle the specific customer request and return the server response.

This process shows that Asp. the. Net runtime environment automatically identifies, checks, and updates the dll corresponding to the aspx. is there any other way to forcibly route the processing of An aspx file to a compiled DLL? In the httpHandlers section of the system. web section of the web. config file of the Asp. Net application configuration file, add the ing items from aspx to dll. The syntax is as follows:

<Add verb = "*" path = "aspx file name" type = "Class Name, dll file"/>

Aspx file: Virtual name to be "routed". The extension must be aspx. Otherwise, IIS will process the file before the Asp. Net runtime environment.

Dll file: the name of the dll file (Application assembly). You do not need to enter ". dll ". ASP. NET first searches for the Assembly DLL in the dedicated \ bin directory of the application, and then searches for the Assembly DLL in the system assembly cache.

Class Name: because a dll may have multiple namespaces or classes, you must specify the class automatically loaded when the dll is called.

For example, the web. config file of an Asp. Net application is as follows:

<? Xml version = "1.0"?>
<Configuration>
<System. web>
<HttpHandlers>
<Add verb = "*" path = "index. aspx" type = "BBS. IndexPage, bbs"/>
</HttpHandlers>
</System. web>
</Configuration>

The configuration file tells Asp. net, in the client request the index of the application. when the aspx file is used, the bbs under the application bin directory is called directly. dll, and automatically load the BBS. indexPage class.

(2) develop DLL for processing HTML pages

It should be noted that not all application Assembly DLL can implement the HTTP Request/response mode. Let's take a look at the description of "Http processing programs and factories" in Microsoft Asp. Net quick start tutorial (http://chs.gotdotnet.com/quickstart/aspplus:

ASP. NET provides low-level request/response APIs, allowing developers to use the. NET Framework class to provide services for incoming HTTP requests. Therefore, developers need to create classes that support the System. Web. IHTTPHandler interface and ProcessRequest () method. The processing program is usually useful when processing HTTP requests without services abstracted by a high-level page framework. Common uses of handlers include filters and CGI-like applications, especially those that return binary data.

Each HTTP request received by ASP. NET is finally processed by a specific instance of the IHTTPHandler class. IHttpHandlerFactory provides the structure for actual resolution of IHttpHandler instance URL requests. In addition to the default IHttpHandlerFactory class provided by ASP. NET, developers can also choose to create and register factories to support a large number of Request Parsing and activation schemes.

From this text, we can see that when the aspx page is not involved. Net Framework provides advanced interface technologies (such as data caching, status persistence, Web form Control Reference, etc.), and does not output complex HTML text to the client, in particular, you can use one to only return binary data (slice, sound, etc.) to the client. Cs application file (This article uses the c # language, if it is VB or JScript ,......) The application must have a class that implements the System. Web. IHTTPHandler interface and ProcessRequest () method. A simple example is as follows:

1
2/* Source File: ex1.cs start */
3 using System. Web;
4 namespace DllTest
5 {
6/* The class must implement the IHttpHandler interface. If the program accesses the Session state (Session), The IRequiresSessionState interface must be implemented (the flag interface that does not contain any methods ). */
7
8
9 public class Ex1Page: IHttpHandler
10 {
11/* Indicate the IsReusable attribute. Net framework, whether the program can be used by multiple threads at the same time.
12 true corresponds to yes; false corresponds to whether or not. */
13
14 public bool IsReusable
15 {
16 get {return true ;}
17}
18
19
20
21/* implement the ProcessRequest method and return response data to the client.
22 In this example, a simple HTML page is returned to the client */
23
24 public void ProcessRequest (HttpContext context)
25 {
26 HttpResponse res = context. Response;
27
28 res. Write ("29 res. Write ("30 res. Write ("this page is directly processed by DLL ");
31 res. Write ("32 }}}
33/* Source File: ex1.cs ended */

In the command line status, use the following compilation command to compile ex1.cs into ex1.dll and store it in the bin directory.

Csc/t: library/out: bin \ ex1.dll ex1.cs
Yes, but you need to write the full path.
Csc/t: library/out: j: \ WebSite \ WebTest \ bin \ ex1.dll
J: \ WebSite \ WebTest \ App_Code \ ex1.cs

Add aspx-> dll ing to the configuration file web. config. After adding the map, web. config should be like this:

<? Xml version = "1.0"?>
<Configuration>
<System. web>
<HttpHandlers>
<Add verb = "*" path = "dlltest1.aspx" type = "DllTest. ex1Page, ex1"/>
</HttpHandlers>
</System. web>
</Configuration>

Now, when the browser accesses http: // localhost/dlltest/dlltest1.aspx, it actually calls the ProcessRequest method of the DllTest. Ex1Page class in ex1.dll. You can see a simple page during browsing.

(3) Compile a single aspx file into a DLL

Microsoft does not allow developers to directly compile the aspx file into a DLL from the "Implication" publicly described by Microsoft in the previous section. However, Asp. net Advanced Interface Technology (server-side HTML controls, WEB controls, and so on) All need to be presented through the aspx file. If the advanced features of aspx are abandoned for DLL running efficiency, it is obvious that you have never had to give it a try.

Now let's take a look:

The csc compiler is only a c # Language compiler. It can only compile files that comply with the C # language specification, while the aspx file format obviously does not comply with the c # language specification, therefore, the csc compiler cannot compile the aspx source file.

To compile the aspx file into a dll file, you must first convert the aspx file into a cs source file that the csc compiler can recognize. So what tools are used for conversion? Although I believe that this tool must be hidden. Net Framework, but a large number of Asp. Net and. . Net.

Oh, there is no path to death, and I am still able to discover this secret by chance.

Let's take a look at the source file ex2.aspx:

/* Source File: ex2.aspx start */
<% @ Page Language = "c #" %>
<Script runat = "server">
/* You are not mistaken. The next line is "abcdefg", which gives me the opportunity to write this article ^_^. In this article, I call this line "code trap "*/

Abcdefg // code trap

Void Page_Load (Object src, EventArgs args)
{
If (! IsPostBack) NoteLabel. Text = "enter your name :";
}

Void OnNameSubmit (Object src, EventArgs args)
{
String name = f_Name.Value;
NoteLabel. Text = (name = "")? "Name cannot be blank": name + ", hello. Welcome! ";
}
</Script>
<Html>
<Body>
<Form runat = "server">
<H1> DllTest-Ex2 (Example 2) <Hr>
<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>
</Html>

/* Source File: ex2.aspx ended */

If you comment out or delete the "Code trap", ex2.aspx is a simple Asp. Net file. You can use IE to browse this page and find that it works properly.
Now let's open the "trap" to see what Asp. Net returns?

A "Compilation error" page is returned, and the report source file cannot be compiled. We are interested in a hyperlink at the bottom of the page named "show complete compilation sources". Click some links, you can see the complete content of the cs source file ("Complete Compilation source") converted from ex2.aspx. Remove the preceding line number information from the "Complete Compilation source" and some other compilation switches (mainly # line compilation commands ), close the cute "code trap" (use // to comment it out or delete it directly) and save it as ex2_aspx.cs:

/* Source File: ex2_aspx.cs start */
/*
It can be seen from the following illustration that there is indeed an undisclosed tool to convert the aspx file into the cs source file.
*/
//--------------------
// <Autogenerated>
// This code was generated by a tool.
// Runtime Version: 1.0.3705.0
//
// Changes to this file may cause incorrect behavior and will be lost if
// The code is regenerated.
/// </Autogenerated>
//--------------------
/*
The strange thing is that the namespace is actually ASP rather than ASPX.
We recommend that you change the name to a suitable application name to prevent name conflicts. For example, you can change the name to DllTest for this article.
I didn't change it here to make it clear to everyone.
*/

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, you can change it to Ex2Page for this article.
2. Pay attention to its base class. Javase. Web. UI. Page implements the IHttpHandler interface. To access the Session, the IRequiresSessionState interface is also implemented.
*/

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 you can turn off the "trap */

// Abcdefg

Void Page_Load (Object src, EventArgs args)
{
If (! IsPostBack) NoteLabel. Text = "enter your name :";
}

Void OnNameSubmit (Object src, EventArgs args)
{
String name = f_Name.Value;
NoteLabel. Text = (name = "")? "Name cannot be blank": name + ", hello. Welcome! ";
}

/* Constructor */

Public ex2_aspx ()
{
System. Collections. ArrayList dependencies;
If (ASP. ex2_aspx. _ intialized = false ))
{
Dependencies = new System. Collections. ArrayList ();

/*
Comment out the following line to make the DLL a dependency-free independent file.
Prevent searching and comparing the New and Old "dependency" files when the DLL is running.
*/

// 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 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 ended */

 

I believe that after analyzing this file, you will have a better understanding of the operating principles of Asp. Net (it is irrelevant to this article and will not be detailed in this article ).

In the command line status, use the following compilation command to compile ex2_aspx.cs into ex2.dll and store it in the bin directory.

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

In the configuration file web. add aspx-> dll ing in config, that is, in system. add the following line to httpHandlers in the web Section: <add verb = "*" path = "dlltest2.aspx" type = "ASP. ex2_aspx, ex2 "/>

Now, when the browser accesses http: // localhost/dlltest/dlltest2.aspx, it is like accessing ex2.aspx. Of course, even if ex2.aspx does not exist or has been updated, the page access will not be affected unless the bin \ ex2.dll is regenerated.
(4) Compile the aspx file of codebehind into a dll

For compiling the aspx file of codebehind into a dll, the principle of converting the aspx file into a cs source file is the same as above. It is also the first "code trap ", then, sort the "Complete Compilation source" and save it as the cs source file. The difference is the step for compiling and translating the SDK into dll: (for the convenience of description, assume that the interface file is ex3.aspx, The codebehind file is ex3.aspx. cs, and the "Complete Compilation source" of ex3.aspx is saved as ex3_aspx.cs)

Step 1: 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 2: 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 ing in the configuration file web. config, that is, add the following line in the httpHandlers section of system. web:
<Add verb = "*" path = "dlltest3.aspx" type = "ASP. ex3_aspx, ex3"/>

Open your browser and access http: // localhost/dlltest/dlltest3.aspx.

(5) Tips

When setting the "trap" to convert the aspx file to the cs source file, you generally use the copy and paste methods to save the "Complete Compilation source" in notepad, vs.net, or other asp.net development environments, and save it as the cs source file.

Sort out the row number information of paste and the "# line" Compilation command. If you manually delete this information, it will be too troublesome. Even a simple file such as ex2.aspx will generate about 270 rows of "Complete Compilation source ".

One of my tips is to use the replacement method in notepad to quickly sort out.

Replace all rows ",

Replace all ":",

Use "// # line" to replace all "# line ",

After the replacement, comment out the "Code trap" and comment out all the statements for setting "dependency Files" in the main class constructor. This completes the sorting.

Related Article

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.