Code Generation in Microsoft .NET

Kathleen Dollard

Mentioned 3

Code generation has the potential to revolutionize application development. Rather than handcrafting each piece of code, developers are increasingly turning to code generation based on templates and applications of business logic to automatically perform a variety of tasks. This book teaches the technical details of code generation in .NET through a coherent series of steps that will help you to incorporate code generation into your own development efforts. Veteran author Kathleen Dollard teaches code generation as a scripted repeatable process using templates you control, so you're not tied to a particular framework or style. Because you can regenerate code at any time, you can incorporate changes, including database changes, throughout the life of your application. The templates are flexible and designed to work smoothly with the handcrafted code youll use to customize your application. The underlying fundamentals are explained along with three specific techniques: outputting code to a stream, using the Code DOM, and using XSLT-based code generation. In addition to the text, the tools in the book (downloadable in both VB .NET and C#) include a mechanism to extract information from SQL Server; a tool for editing and running code-generation scripts; a simple, flexible ORM tool that relates your database structure to your runtime class model; and a set of templates you can use as the starting point for your adventures in code generation. Generating repetitive sections of code frees you to focus on the features that make your application unique. Code generation will turbo-charge your development cycles by offering speed, reusability, agility, and consistency. Go forth and generate!

More on

Mentioned in questions and answers.

While programming in C# using Visual Studio 2008, I often wish for "automatic" code generation. If possible, I'd like to achieve it by making my MSBuild solution file call out to Rake, which would call Ruby code for the code generation, having the resulting generated files automatically appear in my solution.

Here's one business example (of many possible examples I could name) where this kind of automatic code generation would be helpful. In a recent project I had an interface with some properties that contained dollar amounts. I wanted a second interface and a third interface that had the same properties as the first interface, except they were "qualified" with a business unit name. Something like this:

public interface IQuarterlyResults
     double TotalRevenue { get; set; }
     double NetProfit { get; set; }

public interface IConsumerQuarterlyResults
     double ConsumerTotalRevenue { get; set; }
     double ConsumerNetProfit { get; set; }

public interface ICorporateQuarterResults
     double CorporateTotalRevenue { get; set; }
     double CorporateNetProfit { get; set; }

In this example, there is a "Consumer Business Unit" and a "Corporate Business Unit". Every property on IQuarterlyResults becomes a property called "Corporate" + [property name] on ICorporateQuarterlyResults, and likewise for IConsumerQuarterlyResults.

Why make interfaces for these, rather than merely having an instance of IQuarterlyResults for Consumer and another instance for Corporate? Because, when working with the calculator object I was building, the user had to deal with 100's of properties, and it is much less confusing if he can deal with "fully qualified" property names such as "ConsumerNetProfit".

But let's not get bogged down in this example. It is only an example and not the main question.

The main question is this: I love using Ruby and ERB for code generation, and I love using Rake to manage dependencies between tasks. To solve the problem above, what I'd like to do is have MSBuild call out to Rake, and have Rake / Ruby read the list of properties on the "core" interface and then generate the code to make all the dependent interfaces and their properties. This would get triggered every time I do a build, because I'd put it into the MSBuild file for the VS.NET solution.

Has anyone tried anything like this? How did it work out for you? What insights can you share about pros, cons, tips for success, etc.?


We did it with Nant/ruby+ERB - it generates a tone of CRUD in our DAL and data entry form input for our web app. for us it works really well, but there was a good amount of setup time in the beginning that made my boss/customer nervous becuase they figured we should be showing more production than prototype.

Also be sure what the generation is doing - there are differences between generate & modify and generate + integrate. generate & modify is more like using a wizard and is one off. when you generate + integrate you need to understand where/how you will exploit the generated code either through inheritance or through library calls from hand written code into the generated code.

Ruby/erb is not fast executing. A method to determine when you do/dont have to generate are helpful becuase compile cycles start to become long and unproductive. We also found it helpful to always build a small test case to generate even a single set of artifacts before integrating it into the work flow - you have a test of the product and it doesnt slow down anyone while you work on the cg element(s).

I would read Jack Herringtons Code Generation in Action as its geared toward Ruby. Its got me into CG.

I would also rea Kathleen Dollards Code Generation in Microsoft .NET. It built for using XSLT but the principles are the same for developing the metdadata, transformation and integration stages. Her articles are also helpful that you find in magazines and around the web.

i want to generate scripts for database objects, e.g.

  • tables
  • views
  • stored procedures
  • functions


are not installed on a fresh install of:

  • Windows XP
  • Windows Vista
  • Windows 7

nor are they redistributable, they are not an option (it will run on a customer's machine).

(EDIT: It looks as if SMO is actually redistributable as of today.)

Is there any source code that converts SELECTs from system tables into associated scripts?

i'll start us off with the pseudo-code that scripts a stored procedures, views, triggers, or user-defined functions:

String GetStoredProcedureScript(String storedProcedureName)
   return GetHelpText(storedProcedureName);

String GetViewScript(String viewName)
   return GetHelpText(viewName);

String GetTriggerScript(String triggerName)
   return GetHelpText(storedProcedureName);

String GetUserDefinedFunctionScript(String userDefinedFunctionName)
   return GetHelpText(userDefinedFunctionName);

All which can internally use a single helper function:

String GetHelpText(String objectName)
   String szQuery = 'EXECUTE sp_helptext '+QuotedStr(objectName);

   String sql := '';

   using (Recordset rs = connection.Execute(szQuery))
      while not rs.EOF do
         sql = sql+rs['text'];

   return sql;

Edit: Thanks servicesharvest316 for pointing out sp_helptext. That's why i have a class that abstracts these things away.

This is the book for you. It explains how to make a code generator that will do what you asked.

I use a modified version for MySql and it worked like a charm. Code Generation in Microsoft .NET

Is anyone using the built-in code generation provided via text templates (using .tt files)? If so what are the main pro's/con's over other solutions like codesmith?

I would say before you use T4 look at your other options:
- CodeSmith
- CodeDom
- other apps like CodeSmith

One thing that I do like is T4 is built into the compile process for free.

I second what Travis says about Oleg / Clarius.

You might also want to read this site as a resource:
Kathleen Dollard at gendotnet

Her book: Code Generation in Microsoft .NET
If I remember correctly this mostly touches on XML/XSLT and CodeDom but might give you some ideas / contrast

A page of T4 resources from Hanselman:
T4 (Text Template Transformation Toolkit) Code Generation - Best Kept Visual Studio Secret

Extra: Kathleen Dollard on DotNetRocks

I would say I have used T4 for some Code Generation but about the time I got the hang of it, I had moved towards using some Open Source frameworks to remove the need to write tedious code.