Thursday, May 26, 2011

Automatically Generate Code Using Visual Studio's Text Template Transformation Toolkit (T4)

Introduction
How many times have you found yourself creating a class that has a property for each field in a table, or creating select, insert, update, and delete stored procedures for each table in a database?  As a developer even we are subject to such mundane tasks which, as a developer, we are supposed to automate.  Did you know that Visual Studio has a built in toolkit which will allow you to automatically generate code for these tasks and it is free?  If you've installed Visual Studio then you already have it.  It's called the Text Template Transformation Toolkit (T4) and it works right within Visual Studio.

This article will demonstrate how to create a C# class file that is generated by T4.  The class will contain a property for each field in the database.  The example is simple but it will demonstrate the power of the toolkit and you can enhance the code to match the patterns you follow.  The code for the sample can be found here.

The example code uses the AdventureWorks sample database which you can download here.  Once you've installed the database you need to create a SQL Login that the application can use to connect to the database.  My sample code expects a SQL Login to be called "aspalliance" and the password should be set to "aspalliance".

Generating the Code

Step 1: Create the Code Generator Project
1.   Launch Visual Studio 2010.
2.   From the Start page click on the "New Project…" link.
3.   Select Class Library from the list of installed templates.
4.   Name the project CodeGeneratorT4.
5.   Click the OK button.  Visual Studio will create your project and add the Class1.cs file.
6.   Right click on the Class1.cs file in the Solution Explorer and delete this file from the project.
Step 2: Create a Text Template that Creates a Class
1.   Right click on the CodeGeneratorT4 project in the Solution Explorer and select AddàNew Item… from the pop-up menu.
2.   Select Text Template from the list of installed templates.
3.   Name the file BusinesObject.tt and click the Add button.

Read more: Asp alliance