I am glad to share my latest article at code project..
Write your own Code Generator or Template Engine in .NET
Abstract
This paper demonstrates building a code generator, template engine, template parser, or template processor in .NET. The demo implementation uses cutting edge .NET technologies available today such as C# .NET 2.0, MS Provider Pattern, Enterprise Library January 2006, CodeDom etc.
Introduction
If you have used Code Smith or similar tools, you may be wondering how this type of tools work. I am going to reveal in this article how easy it is to write a code generator or template engine in .NET. A template engine is a software or a software component that is designed to transform pre-formatted input into various kinds of text output. One of the major benefits of using a template engine is that it enhances productivity by reducing unnecessary reproduction of effort. For example, while designing an application, whether we implement famous design patterns (like MVC) or invent some of our own, we tend to come up with a generic structure of code throughout the application. Later on, we can write templates for the generic parts, and use template engines to quickly generate the code for us.
Template Engines makes a huge difference in development productivity. For example, if you have a database with 300 tables, and each table having at least 5 columns, imagine how long it will take to hand write all the Business Objects for all those tables. Not only this, when you complete that, you have to write your data access layer, business logic layer, and finally, the application code, and this adds up to a lot of work. However, with the help of a template engine, you can generate generic pieces of code (code that follows a similar design pattern) in minutes. You only need to write a single template, and then you simply ask the template engine to loop through each of the tables and their columns in the database, and it will generate your code for you.
So, we can all agree on how template engines can be a very helpful tool for a developer and save heaps of time. Without spending any more time on an introduction to template engines, we will jump straight into writing one.