繁体   English   中英

将T4模板用于ENum

[英]Using T4 Templates for ENum's

我已经为我的应用程序开发了一个令人困惑的部分。

我正在使用称为“允许的”身份验证的自定义属性,然后使用用户类型。

例如,按方法将具有数据注释[Allowfor(UserType.Admin)]但我遇到的问题是我想在数据库中存储以下类型的UserTypes列表:

  • ID
  • 删除
  • 名称
  • 说明

因此,在运行时甚至单击一个按钮,我都想构建一个Enum类,其中包含未删除的Enum的列表。

任何人都可以以此方式提出一些建议,因为我似乎无法做到这一点,也无法在谷歌搜索中找到很多帮助。

我只需要了解以下内容:

  • 如何使用T4模板或类似方法在VS 2013中创建类
  • 如何在每次构建开始时做到这一点/或者我在UI中按下按钮
  • 最好使用Web配置文件中的字符串或DbContext(如果可能的话,使用EF)查找任何数据库

我对T4模板做了非常相似的事情。 诀窍是要知道需要哪些dll,找到它们等等(例如,在Visual Studio 2013中,EnvDET被引用为“ import namespace =” EnvDTE“而不是EvnDTE.dll)。

基本上,您需要与他们一起玩以尝试获得所需的结果。 在您的解决方案中创建一个T4项目,然后开始填写。

我使用命令对象(并在下面的代码中使用MySQL库),但是它应该使您了解如何运行它。

<#@ template debug="true" hostSpecific="true" #>
<#@ output extension=".generated.cs" #>
<#@ Assembly Name="EnvDTE" #>
<#@ Assembly Name="System.Data" #>
<#@ Assembly Name="$(SolutionDir)Services.Entities\bin\DevTest\Libraries.DB.dll" #> **// * custom location for custom libraries**
<#@ Assembly Name="$(SolutionDir)Services.Entities\bin\DevTest\MySql.Data.dll" #> **// custom location for custom libraries**
<#@ import namespace="EnvDTE" #>
<#@ import namespace="System.Data" #>
<#@ import namespace="System.Data.SqlClient" #>
<#@ import namespace="System.IO" #>
<#@ import namespace="System.Text.RegularExpressions" #>

<#
        string tableName = "";
        //string path = Path.GetDirectoryName(Host.TemplateFile);
        string connectionString = "mysqlConnectionString"; **// replaced with regular value, could pull from web.config but it's only updated rarely**

        // Get containing project
        IServiceProvider serviceProvider = (IServiceProvider)Host;
        DTE dte = (DTE)serviceProvider.GetService(typeof(DTE));
        //Project project = dte.Solution.FindProjectItem(Host.TemplateFile).ContainingProject;
#>
using System;
using System.CodeDom.Compiler;

namespace Services.Entities
{
    [GeneratedCode("TextTemplatingFileGenerator", "10")]
    public enum Store
    {
<#

    using (var cmd = new Libraries.DB.Mysql.Command(connectionString)) **//Custom libraries to open a disposable command object**
    {
      cmd.Clear();
      cmd.AppendCmd("select id, storecode, StoreName \n");
      cmd.AppendCmd("from stores \n");

      var reader = cmd.ExecuteReader();
          while(reader.Read())
          {
          int storeId = Convert.ToInt32(reader["id"]);
          string storecode = reader["storecode"].ToString();
          string description = reader["StoreName"].ToString();
#> //We now have the data, let's use it!  The code in <#= gets populated #>**
    [Libraries.Utils.Enums.Info(Code = "<#= storecode #>", Name = "<#= description #>")] <#= Sanitize(description) #> = <#= storeId #>,
<#
          }
    }
#>  
  }
}
//This is a method which takes a name like "Some Descripton" and Sanitizes it to Some_Description so it can be usable as an enum**
<#+
        static string Sanitize(string token) 
        {
                // Replace all invalid chars by underscores
                token = Regex.Replace(token, @"[\W\b]", "_", RegexOptions.IgnoreCase);

                // If it starts with a digit, prefix it with an underscore
                token = Regex.Replace(token, @"^\d", @"_$0");

                // Check for reserved words
                // TODO: Clean this up and add other reserved words (keywords, etc)
                if (token == "Url") token = "_Url";

                return token;
        }
#>

关于这些文件的关键注意事项是<##>之间的所有内容都是运行的代码,您可以在该代码中创建变量。 要显示,很像ASP,<#=变量#>。

我不确定这些文件是否在您每次构建解决方案时自动生成,但这似乎是一个简单的生成脚本。 要构建它们,请在编辑时保存。 您可以右键单击该文件,然后从上下文菜单中单击“运行自定义工具”。 您会看到该文件有错误,并带有相关的已生成文件进行检查。

顺便说一句,上面的内容可能会生成如下内容:

using System;
using System.CodeDom.Compiler;

namespace Services.Entities
{
  [GeneratedCode("TextTemplatingFileGenerator", "10")]
  public enum Store
  {
    [Libraries.Utils.Enums.Info(Code = "ST1", Name = "Store 1")] Store1 = 1,
    [Libraries.Utils.Enums.Info(Code = "ST2", Name = "Store 2")] Store2 = 2,
  }
}

顺便说一句,标记之外的所有内容(<#,<#=,<#+)都将作为输出发送到该类。 您需要确保模板在运行时正确设置,否则可能会因缺少括号等类而出现编译错误。

暂无
暂无

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

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