Rubens Mariuzzo
Rubens Mariuzzo

Reputation: 29241

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
}

Upvotes: 3

Views: 3939

Answers (3)

Massimiliano Peluso
Massimiliano Peluso

Reputation: 26737

if you want to create your own custom tool you better look at the System.CodeDom Namespace which contains all you need for generating code. Of course you have to code the algorithm that generate the class.

more info at the below link:

http://msdn.microsoft.com/en-us/library/ms404245.aspx

Bear in mind anyway that .NET already offers lots of "build-in" tool/namespace that does exactly the same job (for example using Entity Framework)

Upvotes: 0

faester
faester

Reputation: 15076

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.

Upvotes: 4

mellamokb
mellamokb

Reputation: 56769

Use T4 Templates. I generate lots of classes that way.

Upvotes: 0

Related Questions