繁体   English   中英

在Visual Studio中使用T4模板类型

[英]Use of the T4 Template Type in Visual Studio

我想知道是否可以使用Visual Studio 2010的T4模板功能从数据库读取数据并生成配置文件。

基本上,我将项目部署为Visual Studio外接程序。 因此,当用户从我的模板创建一个新的应用程序时,我需要从数据库中获取一些数据,然后生成一个用户可以在其应用程序中使用的配置文件。

是否可以在T4 [.tt]中实现此功能,或者是否可以通过其他任何方式在Visual Studio 2010中完成此功能。如果可以,请给我链接,以便在遇到问题时可以动手操作并返回。

是的,当然可以。 您可以在t4中编写任何 c#代码,因此,如果可以在c#中编写,则可以在tt中编写。

例如,此TT文件会将某些表的内容输出到所需文件:

    <#@ template language="C#v3.5" hostspecific="true"#>
    <#@ output extension="cs" #>
    <#@ assembly name="System.Core" #>
    <#@ assembly name="System.Data" #>
    <#@ assembly name="System.Data.DataSetExtensions" #>
    <#@ assembly name="System.Xml" #>
    <#@ assembly name="System.Xml.Linq" #>
    <#@ import namespace="System.IO" #>
    <#@ import namespace="System.Data.SqlClient" #>
    <#@ import namespace="System.Data" #>
    <#@ import namespace="System.Collections.Generic" #>
    <#@ import namespace="System.Xml" #>
    <#@ import namespace="System.Xml.Linq" #>
    <#@ import namespace="System.Text" #>
    <#@ import namespace="System.Linq" #>
    <#
    string outputFileName = @"tableContent.txt";

    string dbConnection = @"Data Source=local;Initial Catalog=mydb;user=sa;password=sa";


    System.Data.SqlClient.SqlConnection sqlConnection = new System.Data.SqlClient.SqlConnection(dbConnection);

    #>

    //Some info like 'this is generated code, do not modify' or similar... 
    //this text (because it's out of the tt region) goes into the output file

    <#
    //again, the c# code...
            SqlConnection conn = new SqlConnection(dbConnection);
            conn.Open();
            PushIndent("\t");
            string query = "SELECT something FROM myTable";
            using (IDataReader reader = new SqlCommand(query, conn).ExecuteReader())
            {
                Write("Undefined = 0");
                while(reader.Read())
                { 
                    if (reader[0] != DBNull.Value) 
                    {
                        Write("Value=" + reader[0].ToString() + Environment.NewLine);
                    }
                }
                WriteLine("");
            }
            PopIndent();
            conn.Close();

    #>
    //this goes into file end (could've also be there with Write function)

    <#
    //output to the desired file
    if (!String.IsNullOrEmpty(outputFileName))
    {
        File.WriteAllText(outputFileName, this.GenerationEnvironment.ToString());
        this.GenerationEnvironment.Remove(0, this.GenerationEnvironment.Length);
    }

    #>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM