Friday, May 6, 2011

Problem with T4 Templates

Hi,

I have the following code and it is giving related to curly braces and stuff.

<#@ template language="C#" debug="True" hostspecific="True" #>
<#@ output extension=".cs" #>
<#@ assembly name="System.Data" #>

<#@ assembly name="System.xml" #>
<#@ import namespace="System.Collections.Generic" #>
<#@ import namespace="System.Data.SqlClient" #>

namespace MyProject.Entities 
{   
    public class     
    {
        <#
        string connectionString = 
            "Server=localhost;Database=GridViewGuy;Trusted_Connection=true"; 
        SqlConnection conn = new SqlConnection(connectionString); 
        conn.Open(); 
        System.Data.DataTable schema = conn.GetSchema("TABLES"); 

        foreach(System.Data.DataRow row in schema.Rows) 
        { 

        #> 

        public class <#= row["TABLE_NAME"].ToString() #>            


        {

        }               

        } 

    }   

}

Can anyone spot the problem?

From stackoverflow
  • In your first block, you start a code block

                foreach(System.Data.DataRow row in schema.Rows) 
                { 
    
                #>
    

    but never terminate it. Somewhere below you need this:

                <# } #>
    

    edit - it looks like it would be the closing curly brace just below the nested class definition

  • The reason why it is not compiling is because you don't have a corresponding closing brace for the foreach block inside <# #> tags. You need to make the following change:

    foreach(System.Data.DataRow row in schema.Rows)                 
    {                 
    #>                 
      public class <#= row["TABLE_NAME"].ToString()#> 
      {                
      } 
    <#
      } //this was missing.
    #>
    

    Additionally, keep in mind that your code will create a class with no name followed by a list of nested classes with the names of your tables. Like this:

    public class
    {
      public class Table1
      {
      }
    
      public class Table2
      {
      }
      //... and so on..
    }
    

    This may not be what you are trying to accomplish.

    azamsharp : Thanks man that was really helpful!
    Mel : You should install the Tangible T4 editor plugin for Visual Studio. It will give you matching brace highlighting that makes this sort of thing really easy to figure out. http://visualstudiogallery.msdn.microsoft.com/en-us/1a6c4fb2-7908-4721-92b3-61f2cee92294
    Chad Ruppert : Tangible is cool until you realize the intellisense is slow and spotty at best, and you can't insert a breakpoint into the template.

0 comments:

Post a Comment