ASP.NET provides us with many easy ways to build our web system, especially the code-behind technique which amazingly allows a separation of layout and code. However, ASP.NET also offers some mechanisms to allow you to build a custom programming model more than that offered by code-behind. One mechanism is HTTP Handler which gives you a means of interacting with the low-level request and response services of the IIS Web server, and provides functionality much like ISAPI extensions but with a simpler programming model. Great !.................. ..
But when you are writing custom HTTP handlers, hard-coding the page layout is boring and error-prone. We do need a way to separate layout from code. Thus, class TmplParser, TemplatePool etc. were born. The main job of class TmplParser is to parse a layout template file with some tags and labels whose rules are simple and defined by myself :-). The class TemplatePool is used to buffer a set of templates, which can reduce the I / O operations with less template file reading, And Improve The Performance. I Will Illustrate How To Use Them To Separate Layout from Code, Later in this article.
Notes: It's the first time that I programmed ASP.NET, the first time that I programmed in C #, the first time that I touched IIS, the first time that I submitted an article to Code Project So, there must be some problems or. Something Not Good Enough In The Article and Code. And i do welcome any feedback. Thanks!
USING THE CODE
First, I will tell you the rules of using the parser and some basic information as well.A template file consists of two and only two basic elements They are block and label A block is defined with begin-flag <-..! BEGIN : Blockname -> and end-flag . A label is defined as {labelname}. Let's look at an example template file example .html to you. EXAMPLE. HTML
example title>
hEAD>
{THEAD1} th> tr>
{Value1} td> tr>
{THEAD1} tH>
{THEAD2} tH> tr>
{Value1} td>
{value2} td> tr>
TABLE>
body>
Html> In the template file example.html, there are four blocks: FORMAT1, ROW1, FORMAT2 and ROW2 Block FORMAT1 has one label: THEAD1; block ROW1 has one label:. VALUE1; block FORMAT2 has two labels: THEAD1 and THEAD2 ; block ROW2 has two labels: VALUE1 and VALUE2 FORMAT1 and FORMAT2 are parent blocks of ROW1 and ROW2 respectively Actually, there is one more block It's the root block, namely the template file itself Let's call it DOCUMENT-BLOCK Rules..... Of template file definition
.. A block name must be unique in one template file It's not only for code readability but also for easy use And my principle is:.. The simpler, the better A block can be a parent by enclosing other blocks But any two blocks can not overlap And there is no sibling relation, but parent-children relation is maintained between blocks A Deep Look When the template file is parsed by TmplParser as the following code:.. // tmplDir is the path of the directory in which example.html Is Placed.// IT's in The Format Like this: E: / DEMO / TMPL /
// 50 is The capacity of the pool.
// The pool Uses lru algorithm for template replacement.
TemplatePool.singleton (TMPLDIR, 50);
// What getTemplate Does is to load the template file,
// Create and Initialize a New Instance
// of tmparchser for this template file,
// do the Parsing and return it if the filename
// passed is not found in the pool,
// Otherwise Just Return A Clone
// of the instance find in pool.
// it's thread-safe.
// itemplate is an interface inherited by TmpLParser.
. ITemplate tmpl2 = TemplatePool.Singleton () GetTemplate ( "example.html"); Then five BlockParser (a private class nested in TmplParser) instances will be built and maintained in TmplParser The contents of the five blocks are below: ROW1
{Value1} td> tr> row2
{value1} td>
{value2} td>
Format1
{THEAD1} tH> tr>
Format2
{THEAD1} th>
{THEAD2} th> TR> Document-block
example title>
hEAD>
TABLE>
body>
html> Once A Child Block (Example: Row1) IS out, ITS Current Content Will Be Placed Just Before The Tag (Example: ) in ITS Parent Block and It Will Return To the Original Raw Content. after the folding code is executed, the content of document-block will be ... itMplblock tmplrow1 = tmpl.Parseblock ("Row1");
// the next step will usually be like the code below
// Which Just Sends The Result Content to the Client.
Response.write (TMPLDoc.blockstring); THE RESULT Content of Document-Block Is Shown As Follows:
example title>
hEAD>
OS th> tr>
{THEAD1} th> tr>
Tools th> tr>
Visual Studio .NET TD> TR>
Visual Studio .NET TD> TR>
Country th>
City tH> tr>
China TD>
Pekin TD> TR>
China TD>
Shanghai
Tr>
China TD>
Tianjin TD> TR>
China TD>
CHONGQIN TD> TR>
China TD>
Shenzhen TD> TR>
TABLE>
body>
Html> The comments in the result content are added just for your convenience to contrast to the C # code above. They do not exist in the real result content. As you all see, the presentation code (HTML) can be reused much WITH THIS TECHNIQUE.
Now, I believe that you have known much about this technique, which really will makes me happy :-) One point should be accentuated That is:.. With one block's Out method being not called, its content will not be placed in its Parent.
Second, I will illustrate how to use the code with a simple demo project. Actually, it's a framework shown with the template parser and pool more than a usage instruction. However, I'll just list the main code. Details should be viewed in The source code by yourself. All the source code can be downloaded through the link.
Build a web site called Demo whose virtual directory is the one that you extract the demo project's source files to. Below I will use $ DEMO to refer to this virtual directory. In the IIS, disable all the access privilege of the directory $ DEMO / tmpl under which our web page template files are placed, and $ DEMO / src under which our source code files are placed. It just prevents clients from accessing to any resources under the two directories in any way. View the config file web.config. Each request whose path matches * do.aspx will be handled by Demo.Handler.Controller $ DEMO is the absolute path of your website virtual directory For example, if your virtual directory is E:.. / MyWebsite / demo, then the config below Should be:
...
httphandlers>
...
appsettings>
configuration> The Following Code in the file global.asax.cs is to create a single instance of templatepool with the singleton pattern. public class global: system.web.httpApplication
..} What TemplatePool.Singleton does is shown below As you all see, it is thread-safe and uses the double-check trick to improve the performance And the pool instance will exist through the process life.public sealed class TemplatePool: ITmplLoader {
...
Public Static TemplatePool Singleton (String Tmpldir, Int Capacity)
{
IF (pool == null)
{
Lock (Objlock)
{
IF (pool == null)
Pool = New TemplatePool (TMPLDIR, CAPACITY);
}
}
Return pool;
}
...
Private static templatepool pool = null;
Private static object objlock = new object ();
} View class demo.handler.controller to see how the handler deals with the request. Public class controller: IHTTPHANDAL, IREQUIRESSESSITIONSTATE
{
Public void processRequest (httpcontext context)
{
...
// a more Sophistated Way Is To Put the Info,
// Such as demo.application.menudealer, MenuPanel.html ETC,
// INTO A Config (An XML File OR A Table In DB Or Others).
View class demo.application.menudeler to see what method doprocess does. It just composites the data with the template to generate a string to be responded. Public class menudealer: dealer
At last, build the system with Visual Studio .NET, and you will see what the image above shows. And I believe you will find more useful code in the demo project's source code. As I already said, the demo project is just a framework For A Small Project. May You like it!
Points of interest
When I implement class TemplatePool, I need a class for linked list. But, I can not find one in the namespace System.Collections. There may be someone shouting why not use ArrayList. Good question! But I guess that ArrayList will do the elements copying to move their positions when operations Insert and Remove are being done, which does raise performance penalty when the two operations are done frequently in LRU algorithm. So, I implemented a simple double linked list Agemo.Utility.DoubleLinkedList to meet my needs. It's really simple. Again, the simpler, the better. The non-recursive DFS algorithm is used to disassemble the template into blocks. The HttpHandler class must inherit the interface IRequiresSessionState which is just a marker interface if it will use the session object. I Was Harassed for a long time by this problem.agemo