Search code examples
c#visual-studiovisual-studio-2010auto-generate

How to create a custom tool to generate code in Visual Studio 2010?


I simply want to generate a class with attributes that comes from a Database table.

If I have a Database table like the following:

+-------------------+
| Id | Name         |
+----+--------------+
| 1  + foo          |
| 2  + hello.world  |
| 3  + null         |
+-------------------+

I would like to auto-generate a class that will looks like the following:

class MyTable {
  public static int Foo = 1;
  public static int HelloWorld = 1;
  // null was omitted for Id = 3
}

Solution

  • You could use a T4 transformation to do the work. Use "Add new item" and "Text template".

    The T4 language is a way to use C# code to genarate C# code. Most text is parsed directly to the output file, and new code can be written inside <# and #> tags. The file starts with wrapped imports and using statements, so a very simple template could be something like:

       <#@ template debug="false" hostspecific="false" language="C#" #>
       <#@ import namespace="System.Data" #>
       <#@ import namespace="System.Data.SqlClient" #>
       <#@ assembly name="System.Data" #>
    
       namespace Some.Namespace
       {
           public class TestClass 
           {
        <# 
    
        using(var cnn = new SqlConnection(@"server=.\sqlexpress;Integrated Security=SSPI;Database=ApplicationManagement"))
        {
            cnn.Open();
            var cmd = new SqlCommand("SELECT TextKey, TextValue FROM TblBrandingKeyValues WHERE BrandingIdentifier = 'Default'", cnn);
    
            var reader = cmd.ExecuteReader();
    
            while (reader.Read())
            {
                var defaultText = reader.GetString(1);
                var name = reader.GetString(0);
    
    
        #>
        public string <#= name #> 
        {
            get { return "<#= defaultText #>"; } 
        }
    
        <#
            }
        }
    
         #>
    
        }
    }
    

    } <#@ output extension=".cs" #>

    This template would create a class TestClass with a set of read only properties retrieved from database table TblBrandingKeyValues.

    I would recommend these T4 tutorials.