473,749 Members | 2,513 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

A simple Text Template tool

Hi,

I was trying to use Galois.Net to specify code generators and I had to look for
some text template tool to simplify the syntax. I was looking for something similar
to the syntax of an Asp.Net page; for example, a template file could look like
the following:

<%@ Assembly Name="ReturnStr ing.dll" %>
<html>
<title>Testin g generator</title>
<body>
<p>
Hello <%= ReturnString.Va l() %>
<p>
</body>
</html>

and if the ReturnString.dl l is compiled from the following code:

public class ReturnString {
public static string Val() {
return "World";
}
}

we should expect the output to be:

<html>
<title>Testin g generator</title>
<body>
<p>
Hello World
<p>
</body>
</html>

I wrote such a tool and I decided to post here because it might save
other people a few hours of works since it was not completely trivial.

Galois.Net can be found at http://www.a2ii.com/galois/index.htm .And
using it to specify code generators, I have the impression that "I'm going
places".

I haven't done much testing but it was sufficient for my need. To use
it, you should compile the code below e.g. "csc TextTemplateToo l.cs".
And run it, with the command: "TextTemplateTo ol hello.txt" where
you saved the template text above in a file named "hello.txt" . (You
should also have compiled the ReturnString.dl l assembly i.e.
csc /out:library ReturnString.cs ). NOTE: the "code behind" facility
expect the dll to be in the same directory as the application).

I have tried to keep the code to a strict minimum. You shouldn't
have problems extend it to suit your needs.

Cheers,

-daniel

=============== =========
Daniel Perron, Ph.D.
Lead Developer, Galois.Net

+++++++++++++++ +++++++++++++++ +++++++++++++++ ++
using System;
using System.Text;
using System.Text.Reg ularExpressions ;
using System.IO;
using System.Collecti ons;
using System.Reflecti on;
using System.CodeDom. Compiler;
using Microsoft.CShar p;

class TextTemplateToo l {

//the code that is included at the beginning of
//every program
static string prologue = @"
using System;
using System.Collecti ons.Specialized ;
public class _templateGenera tion
{
public static void Main()
{
";

//the code that is included at the end of
//every program
static string epilogue = @"
}
}
";

public static void Main( string [] argv ) {
StreamReader rd = new StreamReader( argv[0] );
string input = rd.ReadToEnd();
StringBuilder buffer = new StringBuilder() ;
buffer.Append( prologue );

//assemblies will contain the list of referenced
//assemblies used in the template
ArrayList assemblies = new ArrayList();

//This regex will be used to identify the processing code
//in the template; we'll be looking for the string <% ... %>.
//To allow for code spanning multiple lines, we want to let
// the . in a regex to match a end of line so we use the given option
Regex exp = new Regex( "(<%.*?%>)" , RegexOptions.Si ngleline );

string [] chunks = exp.Split( input );
string cleanup;
for( int i = 0; i < chunks.Length; i++ )
{
if( chunks[i].StartsWith("<% =") )
{
cleanup = chunks[i];
cleanup = cleanup.Substri ng(3,cleanup.Le ngth-5);
buffer.Append( string.Format(" Console.Write({ 0});", cleanup.Trim() ));
}
else if( chunks[i].StartsWith("<% @" ) )
{
//we want to get the name of the assembly
//inside the "..."
Regex asm = new Regex( "\".*\"" );
cleanup = asm.Match( chunks[i] ).Value;
cleanup = cleanup.Substri ng(1,cleanup.Le ngth-2);

//we allow to use "code behind" from assembly in
//the same directory as the application
string path = AppDomain.Curre ntDomain.BaseDi rectory;

assemblies.Add( path + cleanup.Trim() );
}
else if( chunks[i].StartsWith("<% ") )
{
cleanup = chunks[i];
cleanup = cleanup.Substri ng(2,cleanup.Le ngth-4);
buffer.Append( cleanup.Trim() );
}
else
{
buffer.Append( string.Format(" Console.Write(@ \"{0}\");", chunks[i] ));
}
}
buffer.Append( epilogue );

//get ready to generate an assembly
CSharpCodeProvi der provider = new CSharpCodeProvi der();
ICodeCompiler compiler = provider.Create Compiler();
CompilerParamet ers options = new CompilerParamet ers();
options.Generat eInMemory = true;
options.Generat eExecutable = true;
options.Referen cedAssemblies.A dd("System.dll" );
if( assemblies.Coun t > 0 )
foreach( object asm in assemblies )
options.Referen cedAssemblies.A dd( (string)asm );

CompilerResults results = compiler.Compil eAssemblyFromSo urce(options,
buffer.ToString ());
if (results.Errors .Count == 0)

//if there is no error run the generated program
//that will write to the console the template with
//the given substitution
results.Compile dAssembly.Entry Point.Invoke(nu ll, null);

else
Console.WriteLi ne("*** Syntax Errors ***");
}
}


Nov 16 '05 #1
0 1579

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

1
1619
by: Wensheng | last post by:
Hi, I wrote a small template engine called spytee. Like any template enigne, it take a text(html) template file as input, process the variable tags in the file, and display the resulted text. The difference from most templates are: you can edit the template file in the html editor(Frontpage, Dreamweaver, whatever), thus a near Complete seperation of presentation and logic. It's very simple and easy, you only need 3 types of tags to...
3
7925
by: pradeep gummi | last post by:
I have an XML FILE that is to be converted to Plain Text using an XSL file. Since I just want plain text, I do not want to set any root element during transformation.And if I do not any root element during transformation, it return s "java.lang.IllegalStateException: Root element not set" exception. If I add any element for the enclosed root, it works. Note: I am using XMLOutputter object of JDOM API, packages javax.xml.transform and...
1
1788
by: Scott | last post by:
The following is the XML I have to work with. Below is the question <Table0> <CaseID>102114</CaseID> <CaseNumber>1</CaseNumber> <DateOpened>2005-06-14T07:26:00.0000000-05:00</DateOpened> <OnCallPerson /> <CallType>Exposure</CallType> <ExposureReason>General</ExposureReason> <OtherExposureReason>Unintentional</OtherExposureReason> <ClientName>Test Client</ClientName>
0
1005
by: David Rose | last post by:
Hello I know nothing of XSL but was wondering if it was possible to do the following: Given an XML template: <template> <register TagPrefix="whatever" TagName="Template" src="Common/Template.ascx" />
0
1893
by: 42 | last post by:
I implemented a simple class inherited from Page to create a page template. It simply wraps some trivial html around the inherited page, and puts the inherited page into a form. The problem I have run into is that the emitted html at the end of the process is slightly different and doesn't work. Please don't be put off by all the source code. All the guts are in this first base class, and it doesn't do much. The rest is trivial...
3
1754
by: John Baker | last post by:
Hi:7 Newby here to ASP, and using the ASP.NET Web Matrix development tool. While that tool looks great for a Newby, I have run into a snag. I have an HTML Text Box which I have named HireInput, and a table (Access Table in fact) that has on it a field called HIREID. I wish to select records where the two match! It sounds simple, but I am having trouble setting up the text box name so that it is recognized in the query. Can someone...
2
1683
by: Yarik | last post by:
Hello, I am not sure the subject of my post adequately describes the problem I am trying to solve, so I think a specific example would be helpful. Let's say there are XML descriptions of products like this one: <!-- File: Products.xml --> ... <Product id="p1">
3
2329
by: Chrism2671 | last post by:
I'm new to XSLT/XML and I have a very simple, quick question. i've been trying to convert simple xml files into CSV files and have made a simple XSLT template using the w3 tutorials, but it doesn't seem to display anything. It does display plain text I enter into the templates, the value-of tags just render whitespace. If anybody can write a template of just a few lines just to demonstrate how to get it to display something from this XML...
17
5816
by: Chris M. Thomasson | last post by:
I use the following technique in all of my C++ projects; here is the example code with error checking omitted for brevity: _________________________________________________________________ /* Simple Thread Object ______________________________________________________________*/ #include <pthread.h> extern "C" void* thread_entry(void*);
0
8997
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9389
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
9256
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
6801
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6079
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4709
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4881
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3320
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
3
2218
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.