Chapter 1: Web Sharp Technology
How to start Web Sharp ActiveX
Chapter 2: Creating Your First Web Application
Chapter 4: Working with Template
Chapter 5 Work with Web Sharp in other Programming Languages
Web Sharp, the best dynamic web template technology in the world! Probably it is also the best web technology in the world!
If you have no idea which web technology you will take for your web development, you can try it.
Web Sharp is so powerful that can be applied to almost all popular development tools, IDE or programming languages, such as ASP, ASP.Net, Java, Delphi and so on. In order to applying Web Sharp to so many language environments, Web Sharp provider a few different packs. Now ActiveX pack is usable. ActiveX pack can be used in most Windows development tools. Before long we will provide Web Sharp for Java. We also plan to develop Web Sharp for .Net only and Web Sharp for Delphi only.
The following lists some great features of Web Sharp.
Simple – If you are familiar with HTML (Hyper Text Markup Language) and any programming language, you will learn Web Sharp only in 10 minutes. You do not need to learn a lot of components, a lot of tags or a very complex engine or framework.
Pure – Web page and logic code are 100% separate. It is the most perfect Model-View-Controller (MVC) design pattern.
Powerful – Because Web Sharp is an independent technology, so it can be easily and widely used in web development work for outputting dynamic web page, resource internationalization and creating complex, exciting web applications. What HTML can display, Web Sharp does.
Easily to maintain – On one hand it is simple, on the other hand it owns the best MVC design pattern, it is easily to maintain. The web pages are easily to be designed and the programming code is easily to be read or written.
WYSIWYG – What you see is almost what you get.
Low cost –Compare with the cost of the expensive web system, it is very cheap but high produce.
A Web Sharp demo – Display some colors. This simple demo will show you what Web Sharp can do. For more info about how you start, you must study the Web Sharp course.
Note: You can find this demo in the directory “Demo\C#\WebTest\”
Here is the result view of the demo in a web browser.

Now let me show you how to do the job.
Step I—Design a web template named Colors.htm. You can use FrontPage or any other HTML Editor to make it out quickly. Figure 2 is the template and the Figure 3 is HTML code of this template. Though code of this template is 100% pure HTML, you can find some strange tags such as {%%} and <!-- BEGIN LOOP --><!-- END LOOP --> in it. It is easy to understand what they mean. You just consider {%HeadText%} is a variant and <!-- BEGIN LOOP: Colors--><!-- END LOOP:Colors --> is a loop which will repeat a block of code.

Figure 2

Figure 3
Step II – Build Logic code framework. We provider a code produce tool called “Code Framework” to make code automatically. This helps you very much. Run CodeFramework.exe, click “Open Template” button and select the template file Colors.htm, and then you will see the auto complete code result in something like the code in the following figure. The following code shows how to control the template to output the result page. This code is written in C# (ASP.NET). This code is pure C# code without outputting any HTML element in it.

Step III – Modify Logic code framework. What you do is just to fill the code framework with real data. The highlight code below is the modified result. What you do is a little. In order to reading easily, we also add some comments in it. Please read the comments in the code, and you will well understand the code. In fact, it is easy to understand.
//--1. Create a new WebTempalte instance and assign Colors.htm to it.
WebTemplate template = new WebTemplate();
template.FileName =@ " G:\WebTest\Template\ Colors.htm";
//--2. Create a root valueNode and Assign value to {%HeadText%}
ValueNode vnRoot = new ValueNode();
string strHeadText = "Welcom to WebSharp world!";
vnRoot.SetValue("HeadText", strHeadText);
string[] colors ={ "Red", "Blue", "Yellow", "Green", "Black" };
//--3.Create a ValueNode for Colors loop block
ValueNode vnColors = vnRoot.CreateChild("Colors");
for (int i = 0; i < 5; i++)
{
ValueNode vnChild = vnColors.CreateChild("");
//--4. Assign value to each {%Color%} in the loop
string strColor = colors[i];
vnChild.SetValue("Color", strColor);
}
//--5.Combine template and code , render result
Response.Write(template.Rendered(vnRoot, ""));
Step IV – Save code to file Colors.aspx and browse it.
Now, the figure below shows the relations between template and ValueNode object.

Note: Tools of Code Framework can product the framework code from the template automatically. This tool can help you to reduce a lot of coding.
OK, have you understood what Web Sharp is now? Because of a short show of Web Sharp, if you don’t understand it, you can learn more about it here. If you have understood it, you will find it is a really super and exciting technology that can lead you from victory to victory.
The mode of normal web application development can be these-- design static pages or write HTML code, add logic code to the web pages mixed html code together. What will this happen? You will waste a lot of time to read, understand and write the code in these mixed and complex pages. You may often make mistakes for the wild web pages. Many hidden bugs are not easy to find out. What is the problem of this mode? This mode is difficult to separate page and logic. When people-- web designers and programmers are working together, you won’t be easy to divide the work for them. These web pages are not easy to maintain too.
So let me lead you into a new web development world— Web Sharp --the best web template technology. How dare I say that? Now, let me show you the excellence of Web Sharp.
l 100% pure HTML template. Pure HTML template means there is not logic code in the template. There is only HTML code, client script (such as JavaScript), CSS and other HTML elements in it. This gives you 100% freedom to design the page and what you design is what you will see. You are very clear about what you will do. You can design the template freely until you are satisfied with it.
l Extremely easy to learn. You do not need to learn a lot of grammars. You do not need to understand a lot of components. You only need to take a litter time to know a few tags of Web Sharp.
l Run fast. The template is only loaded from file to memory and parsed at its first use. And then it will be kept in the memory until it is modified.
l Code reuse. One template can be used by different block of logic code. And a block of logic code can be applied to more than one template. And thus make applications easier to maintain.
l Install Web Sharp ActiveX pack first.
l If needed, import WebSharp.dll into your working environment. Here shows how to import it to your IDE in Microsoft Visual Studio 2005(VS2005). If you are working with other environments, please go to Chapter 5 to find more info.
1. Create a New Web Site called WebTest in VS2005.
2. Create a subdirectory Bin under to web root if Bin does not exist.
3. Right click Bin and select the menu command “Add Reference”.
4. In “Add Reference” dialog, turn to “COM” tab page and select “Web Sharp Library” in the COM listbox. You can also turn to “Browse” tag page and directly select the WebSharp.dll from your Web Sharp setup path.
5. Click ok to close the dialog, you will find a file called Interop.WebSharp.dll in your Bin directory. Now you can enjoy the travel of Web Sharp now.
l Create your Web Sharp web application. Please learn Chapter 2.
Note: Programming code of all demos is written in C# (VS2005). If you use other programming languages, please refer Chapter 5 for more info.
The first web application is creating a dynamic listbox in web browser which looks something like the one in the following figure. This example is simply to display a few names of people in a listbox.

The HTML source code of this page is:
<html>
<body>
<select size="5">
<option value="1">Mike</option>
<option value="2">Jack</option>
<option value="3">Kate</option>
<option value="4">Tom</option>
</select>
</body>
</html>
--- Code A
Now our task is to output this source code. You can follow these steps:
1. If you have not created web site in VS2005, create it. Here a web site g:\WebTest\ is created.
2. Create a new html file named ListBox.htm which is placed in the path g:\WebTest\Template\. This is a template page for Web Sharp. The content of ListBox.htm is:
<html>
<body>
<select size="5">
<!-- BEGIN LOOP : ListBox -->
<option value="{%Value%}">{%Text%}</option>
<!-- END LOOP : ListBox -->
</select>
</body>
</html>
--- Code B
You can find code of this template page (Code B) is similar to the final HTML source code above (Code A). Yes, they have the same structures. But there are 4 lines of text in Code A for output 4 different listbox items while there only one item exists in Code B. You can also find two strange comment lines in Code B. These comments are actually the template elements. We call this template element “Loop Element”. Loop element is one of the block elements in template. You can know more in Chapter 3.
<!-- BEGIN LOOP : ListBox -->[Statement Block] <!-- END LOOP : ListBox --> means a loop which is like “for” loop or “while” loop ( e.g. while(true) { Statement Block} ) in programming languages.
The code inside the loop element can be repeated. But how many times it can be repeated? This will be controlled by the programming code. You can find {%Value%} and {%Text%} in the template page. We call them “Variant Element”. It is similar to the variant in programming languages.
3. Build programming code framework. Run code auto complete tool codeframework.exe, click “Open Template” button to open “g:\WebTest\Template\ListBox.htm”, then following code is automatically produced:

4. Create a new Web Window named ListBox.apsx and copy the code above in it. Modify the code to result in the following code. The highlight code below is the modified result. What you have done is a little – You just only add some real data. Oh, do you think it is very simple?
protected void Page_Load(object sender, EventArgs e)
{
string[] values ={ "1", "2", "3", "4" };
string[] names ={ "Mike", "Jack", "Kate", "Tom" };
//--1. Create a new WebTempalte instance and assign ListBox.htm to it.
WebTemplate template = new WebTemplate();
template.FileName = @"g:\WebTest\Template\ListBox.htm";
//--2. Create a root valueNode
ValueNode vnRoot = new ValueNode();
//--3.Create a valueNode for ListBox Loop block
ValueNode vnListBox = vnRoot.CreateChild("ListBox");
for (int i = 0; i < 4; i++)
{
//--4. Create child of ListBox and assign value to each {%Value%} and {%Text%} in the loop
ValueNode vnChild = vnListBox.CreateChild("");
vnChild.SetValue("Value", values[i]);
vnChild.SetValue("Text", names[i]);
}
//--5.Combine template and code , render result
Response.Write(template.Rendered(vnRoot, ""));
}
--1.WebTemplate object is an object which loads and control template page. It also produces the final output of HTML code. After it is created, we must assign a template file to it and is will be related to the template file. In this demo, the template filename is an absolute path. This path may seem too long. In Chapter 4, we will tech you how to use the relative path.
--2.ValueNode object is a DOM object which is related to the template elements. That is, it will assign the values to the template elements. At first, we must create a root ValueNode vnRoot for the whole template.
--3. Create a child ValueNode vnListBox which is related to the ListBox loop element in the template page. Loop element is a loop statement. Here it repeats 4 times to create 4 listbox items.
--4.We regard each repeating block of the ListBox loop element as a child of it. So we create 4 ValueNode vnChild for each repeating block and set the different value to the Variant element {%Value%} and {%Text%}.
--5.Put the root ValueNode into the WebTemplate and output the final result. The result is like the first figure you see in this chapter.
For more demos you can go to Chapter 4
Web Sharp Template is really a light-level DOM which is like a tree. It only contains three kinds of base elements:
1) Static HTML Element. Static HTML Element is the normal HTML code.
2) Template Variant Element. Its tag is like {%VarName%}.There are four kinds of Variant Element:
|
Element Name |
Tag |
Example |
Memo |
|
Normal Variant |
{%VarName%} |
{%WebTitle%} |
a normal variant |
|
Ignored Variant |
{% /VarName%} |
{% /Hello%} |
If you want to comment a variant, then add a “/” on its left. |
|
Resource Variant |
{% #VarName%} |
{%#Language %} |
International Resource. |
|
Include Variant |
{%@VarName%} |
<%@demo1.html%> |
Include another template file |
Normal Variant is the normal template element. It holds the places which need to dynamic output. These places will be replaced with actual dynamic contents from database or user-custom data. Sometimes you want to cancel this variant temporarily, you can add a “/” on the left of the variant, then this Ignored variant is invalid until you delete the “/” . For Resource Variant and Include Variant, we will introduce more in Chapter 4.
3) Template Block Element. Its tag is like <!--BEGIN --><!--END -->.There are three kinds of Block Element:
|
Element Name |
Tag |
Memo |
|
Normal Block |
<!-- BEGIN BLOCK: Name --> [Statement Block] <!-- END BLOCK: Name --> |
It’s only a block. |
|
Loop Block |
<!-- BEGIN LOOP : Name --> [Statement Block] <!-- END LOOP : Name --> |
It’s a loop block. |
|
Ignored Block |
<!-- BEGIN IGNORED: Name --> [Statement Block] <!-- END IGNORED: Name --> |
This block is ignored. |
The difference between Normal Block and Loop Block is that Loop Block is a loop which can be repeated as many times as need. The Normal Block is not a loop, you can regard it can be repeated only once. Ignored Block is a comment block. This block will not be output.
l
You may ask why we
need the Normal Block Element. Consider the table below. You may regard Code I
is the same as Code II. Yes, they seem same in general situation. Code I is
always output no matter the image file exists or not. So sometimes you will see
a
in the
web browser if the image file doesn’t exist. Block Element can avoid this. It
can control showing or hiding the code embed in it. If the image file exists,
show it, or hide it. For how to show/hide a normal block element, see the Normal
Block Demo in Chapter 4.
|
Code I |
<img src="{%ImageURL%}" width="100" height="100"> |
|
Code II |
<!--BEGIN BLOCK :DisplayImage--> <img src="{%ImageURL%}" width="100" height="100"> <!--END BLOCK :DisplayImage--> |
If you want to display two images, you can see code I below. There are two Normal Variants named {%ImageURL1%} and {%ImageURL2%} in the code. But if you want to display ten, hundred or more images, what should you do? You can see Code II. Code II is short but can do the thing.
|
Code I |
<!--BEGIN BLOCK :DisplayImage--> <img src="{%ImageURL1%}" width="100" height="100"> <img src="{%ImageURL2%}" width="100" height="100"> <!--END BLOCK :DisplayImage--> |
|
Code II |
<!--BEGIN LOOP :DisplayImage--> <img src="{%ImageURL%}" width="100" height="100"> <!--END LOOP :DisplayImage-->
|
OK. That is all. You can quickly learn them within a few minutes.
Let us have a look at the template code below:
<html>
<body>
<select size="5">
<!-- BEGIN LOOP : ListBox -->
<option value="{%Value%}">{%Text%}</option>
<!-- END LOOP : ListBox -->
</select>
</body>
</html>
Now we analyze the code:
|
Code (Level 1) |
Code (Level 2) |
Element Type |
|
<html> <body> <select size="5">
|
|
Static HTML Element |
|
<!-- BEGIN LOOP : ListBox --> |
|
BEGIN of the Loop Block |
|
|
<option value=" |
Static HTML Element |
|
|
{%Value%} |
Normal Variant |
|
|
"> |
Static HTML Element |
|
|
{%Text%} |
Normal Variant |
|
|
</option> |
Static HTML Element |
|
<!-- END LOOP : ListBox -->
|
|
END of the Loop Block |
|
</select> </body> </html>
|
|
Static HTML Element |
From the table you can see the whole template is composed of the template elements. This is a DOM structure. We call it Template DOM. Because it is a DOM, nesting is allowed and there is no max level limit. It can deal with all kind of complex requirement. That is, what HTML can display, it does.
After we have the Template DOM, how can we get the dynamic output from the Template DOM? ValueNode does. We load data to the ValueNode DOM (composed of ValueNode objects) and then map each ValueNode to the related template block element. At last, template combines the data in ValueNode objects and produces dynamic output. ValueNode only cares for the block and variant template elements in spite of the static HTML elements which often occupy the most content of the template, so you needn’t write too much programming code for the template.
Designed
templates are for programming. After templates are designed, we must write
programming to drive them.
What we do is to replace the template elements with the dynamic contents. We
have known there are three kinds of base elements in Template DOM: Static HTML
Element, Variant Element and Block Element. We also know that ValueNode DOM
stores the dynamic contents. Since you needn’t assign values to Static HTML
Elements, you can find out the relation between template elements and
ValueNode:
|
Template DOM |
ValueNode DOM |
|
Block Element |
ValueNode Object |
|
Variant Element (child of Block Element) |
ValueNode Property (child of ValueNode) |
One Block Element is related to one ValueNode Object via their names. If the Block Element and the ValueNode Object are the same level and the same name, then they are relational. One Variant Element is related to one property of the related ValueNode Object via their name, too. Variant Element is always embedding in the Block Element, so we can regard the Variant Element as the child of the Block Element. The same to a ValueNode and its properties.
The framework of programming code is like the code below:
WebTemplate template = new WebTemplate();
template.FileName = @"g:\WebTest\Template\ListBox.htm";
ValueNode vnRoot = new ValueNode();
....
string strOutput=template.Rendered(vnRoot, "");
These lines are needed in any Web Sharp programming.
See the code below, we must create a WebTemplate object and point to a template file. WebTemplate object will automatically parse the template file and build the Template DOM. These are hidden from us. Web needn’t know about these details.
WebTemplate template = new WebTemplate();
template.FileName = @"g:\WebTest\Template\ListBox.htm";
But we need to build the ValueNode DOM related to the Template DOM. A root ValueNode related to the root of Template DOM is needed.
ValueNode vnRoot = new ValueNode();
After building the ValueNode DOM, we can pass this DOM to WebTemplate’s Rendered() method and return the final output
Do you think the filename "g:\WebTest\Template\ListBox.htm" is too long? Yes. The solution is that you can configure the template path at the start of the whole web application. In .Net you can create a Global.asax file if it doesn’t exists. Then add the following code:
void Application_Start(object sender, EventArgs e)
{
new WebSharp.WebConfig().TemplatePath = Server.MapPath("~/Template");
}
In the previous code snippet, a WebConfig object is created and assigned the physical path ("g:\WebTest\Template”) of the virtual path “/Template” to its TemplatePath property. This will affect the whole web application until you changed the TemplatePath again. After that you can use "ListBox.htm" instead of "g:\WebTest\Template\ListBox.htm" in your code:
template.FileName = "ListBox.htm";
Note: You can find all demos in “Demo\C#\WebTest\WS\”
l Normal Variant Demo
|
Create a NormalVariant.htm file in template path and create a NormalVariant.ashx file. Of course you can create a web window file (.aspx) instead of web handler file (.ashx). Because this is a simple demo, a web handler file is enough. It just displays a line text “Hello World!” in this demo.
|
|
|
NormalVariant.htm |
NormalVariant.ashx |
|
<html><body> {%Hello%} </body></html> |
public void ProcessRequest(HttpContext context) { context.Response.ContentType = "text/html";
WebTemplate template = new WebTemplate(); template.FileName = @"NormalVariant.htm"; ValueNode vnRoot = new ValueNode(); vnRoot.SetValue("Hello", "Hello World!"); string output = template.Rendered(vnRoot, ""); context.Response.Write(output);
} |
|
Memo In this demo, there is only one normal variant element {%Hello%} in the template, so after root ValueNode is created, call SetValue() method to assign the real value “Hello World!” to {%Hello%} |
|
|
Screen
|
|
l Normal Block Demo
|
This demo shows how to display an Image. If the image file does not exist, do not display it. Copy a image1.gif to your web path “/Images”. Create a NormalBlock.htm file in template path and create a NormalBlock.ashx file. |
|
|
NormalBlock.htm |
NormalBlock.ashx |
|
<html> <body> {%Tip1%} <!--BEGIN BLOCK : ImageBlock1--> <img src="{%ImageURL%}" /> <!--END BLOCK : ImageBlock1--> <br /><br /> {%Tip2%} <!--BEGIN BLOCK : ImageBlock2--> <img src="{%ImageURL%}" /> <!--END BLOCK : ImageBlock2--> </body> </html>
|
public void ProcessRequest (HttpContext context) { context.Response.ContentType = "text/html"; WebTemplate template = new WebTemplate(); template.FileName = "NormalBlock.htm"; ValueNode vnRoot = new ValueNode();
string strImagesPath = context.Server.MapPath("~/Images/"); //--ImageBlock1 if (File.Exists(strImagesPath + "image1.gif")) { vnRoot.SetValue("Tip1", " image1.gif exists "); ValueNode vnNode = vnRoot.CreateChild("ImageBlock1"); vnNode.SetValue("ImageURL", "/Images/image1.gif");
} else vnRoot.SetValue("Tip1", " image1.gif doesn't exists ");
//--ImageBlock2 if (File.Exists(strImagesPath + "image2.gif")) { vnRoot.SetValue("Tip2", " image2.gif exists "); ValueNode vnNode = vnRoot.CreateChild("ImageBlock1"); vnNode.SetValue("ImageURL", "/Images/image2.gif");
} else vnRoot.SetValue("Tip2", " image2.gif doesn't exists ");
string output = template.Rendered(vnRoot, ""); context.Response.Write(output);
} |
|
In this demo, there are two normal block elements: ImageBlock1 and ImageBlock2. Each of these two block elements is just to display an image file. If the image file exists, then create a child ValueNode of the root ValueNode and assign a value to {%ImageURL%}( value of image’s src ). When the child ValueNode is created, it must be assigned a same name as the normal block element’s name: ImageBlock1 or ImageBlock2. If you do not create a child ValueNode for the related normal block element, this normal block element will be hidden—can not output and display in client. So if you want to hide a block element, just do not handle it in your programming code. Look back the code of this demo: Before display the image, judge if the file exists or not. If it exists, display it, or just display some text describes that the file doesn’t exist. In this demo, image1 exists and image2 does not exist, and you can see the result blow. |
|
|
|
|
l Loop Block Demo
|
This demo shows how to display 12 images in 3 rows and 4 columns. First, you have to copy 12 images to the image path “/Images” and these images must be named as Icon11.gif, Icon12.gif, Icon13.gif, Icon14.gif, Icon21.gif ... Icon34.gif. Second, create template file and a code file. |
|
|
LoopBlock.htm |
LoopBlock.ashx |
|
<html> <body> <table cellspacing="5"> <!--BEGIN LOOP : TRLoop--> <tr> <!--BEGIN LOOP : TDLoop--> <td> <img src="{%ImageURL%}" width="16" /> </td> <!--END LOOP : TDLoop--> </tr> <!--END LOOP : TRLoop--> </table> </body> </html>
|
public void ProcessRequest(HttpContext context) { context.Response.ContentType = "text/html"; WebTemplate template = new WebTemplate(); template.FileName = "LoopBlock.htm"; ValueNode vnRoot = new ValueNode();
string strImagesPath = context.Server.MapPath("~/Images/"); //--TRLoop ValueNode vnTR = vnRoot.CreateChild("TRLoop"); for (int i = 1; i <= 3; i++) { ValueNode vnTRItem = vnTR.CreateChild(""); //--TDLoop ValueNode vnTD = vnTRItem.CreateChild("TDLoop"); for (int j = 1; j <= 4; j++) { ValueNode vnTDItem = vnTD.CreateChild(""); string strURL = String.Format( strImagesPath + "Icon{0}{1}.gif", i, j); vnTDItem.SetValue("ImageURL", strURL); } } string output = template.Rendered(vnRoot, ""); context.Response.Write(output); } |
|
In this demo, it is a nesting loop which has two levels and your ValueNode DOM must have the same structure. First, create a child ValueNode named TRLoop of the root ValueNode. Then enter the loop and repeat for 3 times in order to outputting 3 rows of images. Take notice to another difference between normal block element and loop block element. For normal block, after the ValueNode is created, you can assign values (call SetValue () method) to its variant elements immediately. But for loop block, after the main ValueNode is created, you have to continue to create a child ValueNode with an empty name for each repeat. The values are assigned in each child ValueNode, not their parent ValueNode—main ValueNode. In the code snippet previously, after main ValueNode vnTR is created, a child ValueNode vnTRItem is created in each repeat. The whole flow is below: vnTR-->vnTRItem-->vnTD-->vnTDItem-->SetValue() 1 --> i --> i ---> i*j If the image files exist and correctly named, you can see the output result below.
|
|
|
|
|
l Resource Demo
|
This demo shows how to use resource files in Web Sharp. Benefiting from resource file, you build international web applications. You can display a page in two or more languages. 1) Create a directory “Resource” in your web root and add the code below to Global.asax. This code will set up the resource path in your web application and then you will not need to write the full path of your resource filename in your programming code. void Application_Start(object sender, EventArgs e) { WebConfig webConfig= new WebConfig(); webConfig.TemplatePath = Server.MapPath("~/Template"); webConfig.ResourcePath = Server.MapPath("~/Resource"); } 2) Create two resource files in your directory “Resource” named English.txt and Spanish.txt. Note that you had better save them as Unicode format. Add two lines of text to English.txt : Hello=Hello Welcome=Welcome And add two lines of text to Spanish.txt: Hello=Hola Mundo Welcome=Recepción The format of each line in resource file is “Name=Value”. 3) Create template and write programming code. |
|
|
Resource.htm |
Resource.ashx |
|
<html> <body> <p> <a href="{%EnglishURL%}">English</a> <a href="{%SpanishURL%}">español</a> <p /> <p> Current Language is <font color="green">{%Language%}</font> </p> <font color="red">{%#Hello%}</font> <br /> <font color="blue">{%#Welcome%}</font> </body> </html> |
public void ProcessRequest(HttpContext context) { context.Response.ContentType = "text/html";
//--Set Resource file string strParam = context.Request["Lang"]; string strResourceFile = ""; string strLanguage = ""; if (String.IsNullOrEmpty(strParam) || strParam == "1") { strResourceFile = "English.txt"; strLanguage = "English"; } else { strResourceFile = "Spanish.txt"; strLanguage = "Spanish"; }
//--Create WebTemplage WebTemplate template = new WebTemplate(); template.FileName = @"Resource.htm"; ValueNode vnRoot = new ValueNode();
vnRoot.SetValue("EnglishURL", "Resource.ashx?Lang=1"); vnRoot.SetValue("SpanishURL", "Resource.ashx?Lang=2"); vnRoot.SetValue("Language", strLanguage);
string output = template.Rendered(vnRoot, strResourceFile); context.Response.Write(output);
} |
|
|
|
|
In the template page, there are two resource variant elements :{%#Hello%} and {%#Welcome%}. In order to display these two resource variant elements, you must define them in Englsih.txt and Spanish.txt (You do not need to assigned values to these resource variant elements in programming code) and pass the resource filename as the second parameter to WebTemplate’s Rendered() method such as template.Rendered(vnRoot, “English.txt”). The second parameter of Rendered() method is an empty string if you do not need any resource file. But while you want to use a resource file such as “English.txt”, you need to assign the resource filename to this parameter. If you have set up the resource path ago and your resource file is just in your resource path, you can pass only the filename (without path) to this parameter. If the resource path has not been set up, you need to use the full path filename, or the resource file will not be found and an exception will be thrown. Look at the
figures below: The figure on the left is the default interface of output
result. If you want to see the Spanish result, just click the Now you will know the steps of building an international web application are: 1) Create resource files. 2) Create resource variant elements in needful places in template file. 3) Write programming code. You must assign a resource filename to the second parameter of WebTemplate’s Rendered() method before output.. |
|
|
|
|
l Include Demo
|
Include1.htm |
<html> <body> <p> <font color="blue">This is include1.htm</font> </p> {%@Include2.htm%} </body> </html> |
|
Include2.htm |
<font color="red">This is Include2.htm</font> |
|
Include.ashx |
public void ProcessRequest(HttpContext context) { context.Response.ContentType = "text/html"; WebTemplate template = new WebTemplate(); template.FileName = @"Include1.htm"; ValueNode vnRoot = new ValueNode(); string output = template.Rendered(vnRoot, ""); context.Response.Write(output); } |
|
Use {%@Filename%} to include another template file to the current template file. Filename may be an absolute path or a relative path. In this demo, Include2.htm in {%@Include2.htm%} is a relative path.Include1.htm and Include2.htm are under a same directory. |
|
|
|
|
l Event Demo
|
In each demo above, output result is assigned to a string variant named output. e.g. string output = template.Rendered(vnRoot, ""); But you can also output the result in an OnRender event. If OnRender event has been defined, as soon as output happens, this event occurs. Sometimes event may be more effective than one-off string output. Read the code in Event.ashx, you find two differences in the code: The line of code “template.OnRender += OnRender; “ defines the OnRender event and points to the OnRender(string Value) function. The method in the last line of the code is Render(), not Rendered(). Rendered() return a string while Render() is a void and return nothing. In OnRender function, you can add a counter depending on which you can find out how many time the OnRender event are triggered.Of course you can do other things in OnRender function such as formating output, adding more output info and so on. |
|
|
Event.htm |
Event.ashx |
|
<html> <body> The Event Demo<br /> The output happens in event. {%Hello%} Oh,End. </body> </html>
|
HttpResponse Response = null; private int Count = 0; private void OnRender(string Value) { Response.Write("<P>Render Times:"); Response.Write(++Count); Response.Write("<br>"); Response.Write(Value); Response.Write("</P>");
} public void ProcessRequest(HttpContext context) { Response = context.Response; Response.ContentType = "text/html";
WebTemplate template = new WebTemplate(); template.FileName = @"Event.htm"; ValueNode vnRoot = new ValueNode(); vnRoot.SetValue("Hello", "Hello World!"); template.OnRender += OnRender; template.Render(vnRoot, "");
} |
|
|
|
Here tech you how to start Web Sharp in some other programming languages. If you want to know to the details of programming with Web Sharp, learn previous chapters.
Note: Source code of this demo is in the directory “Demo\ASP\”
l Work with Web Sharp in ASP
1) Install Web Sharp pack.
2) Install and start IIS (Internet Information Server)
3) Create a template file named WebSharp.htm under web root such as C:\inetpub\wwwroot\WebSharp.htm with the following code:
<html>
<head>
<title>Web Sharp </title>
</head>
<body>
<font color="red">{%HeadLine%} </font>
<p>
<!--BEGIN LOOP: NumberBlock-->
{%Number%}
<!--END LOOP : NumberBlock -->
</p>
Please visit my homepage: <a href="{%URL%}">{%Text%}</a>
</body>
</html>
4) We provider a code produce tool called “Code Framework” to make programming code automatically. It can produce most of the programming code. Run CodeFramework.exe, select asp.def from the languages combobox, and then click “Open Template” button and select the template file WebSharp.htm, and then you will see the auto complete code result in something like the code in the following figure:

5) Save the framework code to file C:\inetpub\wwwroot\WebSharp.asp. Modify the framework code and result in the following code. The hightlight code in yellow is the modified result. What you do is only to fill the code framework with the actual data.
<%
Set WebTemplate=Server.CreateObject("WebSharp.WebTemplate")
WebTemplate.FileName= Server.MapPath("WebSharp.htm")
Set RootValueNode=Server.CreateObject("WebSharp.ValueNode")
StrHeadLine="This is my first Web Sharp ASP application"
RootValueNode.SetValue "HeadLine",StrHeadLine
'<!--BEGIN LOOP : NumberBlock -->
Set NumberBlockValueNode=RootValueNode.CreateChild("NumberBlock")
for I=1 to 15
Set NumberBlockValueNodeItem=NumberBlockValueNode.CreateChild("")
StrNumber= "Number"
NumberBlockValueNodeItem.SetValue "Number",StrNumber
Next
'<!--END LOOP : NumberBlock -->
StrURL="http://www.coolmasoft.com"
RootValueNode.SetValue "URL",StrURL
StrText="Coolmasoft"
RootValueNode.SetValue "Text",StrText
Response.Write WebTemplate.Rendered ( RootValueNode,"")
%>
Of course, if you find there are two many variant definitions in the code above, you can see the tidy code below:
<%
Set WebTemplate=Server.CreateObject("WebSharp.WebTemplate")
TemplateFileName=Server.MapPath("WebSharp.htm")
WebTemplate.FileName=TemplateFileName
Set RootValueNode=Server.CreateObject("WebSharp.ValueNode")
RootValueNode.SetValue "HeadLine","This is my first Web Sharp ASP application"
RootValueNode.SetValue "URL","http://www.coolmasoft.com"
RootValueNode.SetValue "Text","Coolmasoft"
Set NumberValueNode=RootValueNode.CreateChild("NumberBlock")
for I=1 to 15
Set Item=NumberValueNode.CreateChild("")
Item.SetValue "Number",I
Next
Response.Write WebTemplate.Rendered ( RootValueNode,"")
%>
6) Result in a web browser.

The whole development flow is very clear. After one person designs the web template, the other one continues to write the programming code. With the help of “Code Framework”, programmers can save a lot of time.
If you do not use Web Sharp, you can open a new file C:\inetpub\wwwroot\normal.asp with the following code:
<html>
<head>
<title>ASP Demo</title>
</head>
<body>
</HEAD>
<body>
<font color="red">This is my first Web Sharp ASP application </font>
<p>
<%
For I = 1 To 15
%>
<%=I%>
<%
Next
%>
</p>
Please visit my homepage: <a href="http://www.coolmasoft.com">Coolmasoft</a>
</body>
</html>
There are many <% or %> in the code and this code is not very easy to read. Of course, this is a very simple demo, you can’t find out the advantage of Web Sharp. But if you develop a complex page without Web Sharp, you will be lost in the interlaced HTML code and ASP code, and then you will spend more time to find errors and bugs. ASP.Net can solve these in a certain extent, but you have to learn a lot of new components and engines in it. If one day you develop a web application with another language, you still have to learn a lot of new features of the strange language. What’s more, when a new version of a programming language comes out, you have to learn the new features in it, too. Yet Web Sharp can avoid all these: perfect structure; learn once but benefit many programming languages.
l Work with Web Sharp in Delphi
It is well known that Delphi is short in web applications though it has many web solutions (e.g. Web Broker, WebSnap, IntraWeb) and owns a lot of web components(e.g. PageProducer,WebDispatcher). You have to spend much time to learn how to use these components which are not easily used or high produces in fact. Yet Web Sharp can give Delphi programmers a satisfied result. If you own Web Sharp and Delphi’s powerful database technology, nothing is difficult.
We now Create an ISAPI demo in Delphi 7.
Note: Source code of this demo is in the directory “Demo\Delphi\”
1) Install Web Sharp pack.
2) Import it into Delphi. Click [Project] menu, select [Import Type Library]. Select “Web Sharp Library”. Click “Install” button or “Create Unit” button. If you do not import it into Delphi, you have to create the Web Sharp objects as ASP does above (invoke CreateOleObject () function in Delphi)
2) Create a new Web Server Application.

3) Select the first Option: ![]()

4) Save the project as WebSharpDemo.dpr. Create a new action called WebActionItem1 in the current Web Module.

5) Create a template file C:\inetpub\wwwroot\WebSharp.htm with the following code:
<html>
<head>
<title>Web Sharp </title>
</head>
<body>
<font color="red">{%HeadLine%} </font>
<p>
<!--BEGIN LOOP: NumberBlock-->
{%Number%}
<!--END LOOP : NumberBlock -->
</p>
Please visit my homepage: <a href="{%URL%}">{%Text%}</a>
</body>
</html>
6) We provider a code produce tool
called “Code Framework” to make programming code automatically. It can produce
most of the programming code. Run CodeFramework.exe, select Delphi.def from the
languages combobox, and then click “Open Template” button and select the template
file WebSharp.htm, and then you will see the auto complete code result in
something like the code in the following figure: 
7)Copy this code to the OnAction event of WebActionItem1 and modify it. The hightlight code in yellow is the modified result. What you do is only to fill the code framework with the actual data.Remember to refer WebSharp_TLB in uses part of current unit. Press Ctrl+F9 to compile the project.
procedure TWebModule1.WebModule1WebActionItem1Action(Sender: TObject;
Request: TWebRequest; Response: TWebResponse; var Handled: Boolean);
var
strText:string;
strURL:string;
strNumber:string;
strHeadLine:string;
vnNumberBlock:IValueNode;
vnNumberBlockItem:IValueNode;
WebTemplate:CoWebTemplate;
vnRoot:CoValueNode;
I, K: Integer;
begin
WebTemplate := CoWebTemplate.Create;
try
WebTemplate.FileName := 'C:\inetpub\wwwroot\WebSharp.htm';
RootValueNode := CoValueNode.Create;
try
strHeadLine:= 'Web Sharp Delphi Application';
RootValueNode.SetValue('HeadLine', strHeadLine);
//<!--BEGIN LOOP : NumberBlock -->
vnNumberBlock:=vnRoot.CreateChild('NumberBlock');
for I := 1 to 15 do
begin
vnNumberBlockItem:=vnNumberBlock.CreateChild('');
strNumber:=IntToStr(I);
vnNumberBlockItem.SetValue('Number',strNumber);
end;
//<!--END LOOP : NumberBlock -->
strURL:= 'http://www.coolmasoft.com';
vnRoot.SetValue('URL',strURL);
strText:= 'Coolmasoft';
vnRoot.SetValue('Text',strText);
Response.Content := WebTemplate.Rendered(vnRoot, '');
finally
RootValueNode := nil;
end;
finally
WebTemplate := nil;
end;
end;
Of course, if you find there are two many variant definitions in code above, you can see the tidy code below:
procedure TWebModule1.WebModule1WebActionItem1Action(Sender: TObject;
Request: TWebRequest; Response: TWebResponse; var Handled: Boolean);
var
WebTemplate: IWebTemplate;
RootValueNode, NumberValueNode, Item: IValueNode;
I, K: Integer;
begin
WebTemplate := CoWebTemplate.Create;
try
WebTemplate.FileName := 'C:\inetpub\wwwroot\WebSharp.htm';
RootValueNode := CoValueNode.Create;
try
RootValueNode.SetValue('HeadLine', 'Web Sharp Delphi Application');
RootValueNode.SetValue('URL', 'http://www.coolmasoft.com');
RootValueNode.SetValue('Text', 'Coolmasoft');
NumberValueNode := RootValueNode.CreateChild('NumberBlock');
for I := 1 to 15 do
begin
Item := NumberValueNode.CreateChild('');
Item.SetValue('Number', IntToStr(I));
end;
Response.Content := WebTemplate.Rendered(RootValueNode, '');
finally
RootValueNode := nil;
end;
finally
WebTemplate := nil;
end;
end;
8) Start IIS manager and configure a virtual path in IIS named WebSharpDemo. This path must be pointed to the path of your Delphi project WebSharpDemo.dpr and it owns the privilege of execute application. If you use IIS6.0, you must go to IIS manager and configure the Web Service Extension—set ISAPI Extension option to permitted state.
9) Navigate to http://localhost/websharpDemo/webSharpDemo.dll and you will see the result.

l WebConfig Object
|
Configure the global parameters |
|
string Path This is a read only property which will store the path of current module. |
|
string TemplatePath It is the path where templates are placed in .By default, template path is pointed to a subdirectory named “Template” under the path which is assigned to Path property. If your template files are in this path, you can refer to them with relative filenames instead of full filenames. You can assign a new path to TemplatePath if you do not like the default path. |
|
string ResourcePath It is the path where resource files are placed. It is similar to the TemplatePath. |
l . WebTemplate Object
|
One of the main object in Web Sharp in charge of web output. |
|
public void Render(WebSharp.ValueNode ValueNode, string WebResourceName) Render output. It must work together with OnRender event. Once this method is invoked, the output will be handled in the OnRender event. |
|
public string Rendered(WebSharp.ValueNode ValueNode, string WebResourceName) Render output and return result directly. |
|
public void Write(string Value) Output something. It is invoked in Render() method. But we seldom used it in outer code. |
|
string FileName Specify a template filename for WebTemplate Object. |
|
WebSharp.TemplateNode RootTemplateNode A TemplateNode object. It is a normal block element and is the parent(root) of all elements in a template. |
|
Event OnRender (string Value) Handle output. The Value parameter contains the output content. |
l . ValueNode Object
|
One of the main object in Web Sharp in charge of storing the dynamic data. It is a Value DOM. |
|
public void AddChild(WebSharp.ValueNode Child) Add a child ValueNode to the current ValueNode. ValueNode child=new ValueNode(); parent.AddChild(child); You can use CreateChild() instead. |
|
public WebSharp.ValueNode CreateChild(string NodeName) Create and add a the child ValueNode to current ValueNode. |
|
public WebSharp.ValueNode GetChild(string NodeName) Return a child ValueNode by name. |
|
public WebSharp.ValueNode GetChildById(int Index) Return a child ValueNode by index. |
|
public string GetValue(string Name) return the value of normal variant element by name |
|
public void SetValue(string Name, string Value) set the value for the normal variant element. |
|
int Count return the child count. |
|
string Name return the node name. |
l TemplateNode Ojbect
|
TemplateNode is really the template element but seldom used in programming code. |
|
public void AddChild(WebSharp.TemplateNode Child)
|
|
public WebSharp.TemplateNode GetChild(int Index) |
|
int Count |
|
string Name |
|
int NodeType |
|
WebSharp.TemplateNode Parent |