在.NET项目上生成JSON post build

时间:2016-09-12 08:56:58

标签: javascript .net enums build

我试图在我的共享.NET库中生成包含枚举的javascript文件(因此我的web api和客户端将自动同步,并且不会编写多个代码)。 我听说过.NET post-build事件,但不太确定我们是否应该以及如何使用它。

有什么建议吗?

1 个答案:

答案 0 :(得分:1)

您可以通过T4 templates生成代码。

为了帮助您自己使用T4模板,建议您下载AutoT4Devart T4 editor。每次构建项目时,AutoT4都会自动执行与T4文件关联的代码生成工具(确保运行的自定义工具是'TextTemplatingFileGenerator'); Devart T4编辑器将为T4语法提供文本着色和智能感知。 (从visualStudio转到工具 - >扩展和更新 - >在线并安装这些扩展程序)

您可以使用反射从.NET类中提取相关信息 输出一个.js文件,其中包含正确格式化的信息。

我举个例子:我需要在应用程序的层边界处拥有一些类的无行为精确副本。特别是我需要有EntityFramework实体的DTO,所以我写了这个T4模板,搜索实体并生成DTO:

<#@ template hostspecific="false" language="C#" #>
<#@ output extension=".cs" #>
<#@ assembly Name="System.dll" #>
<#@ assembly Name="System.Core.dll" #>
<#@ assembly name="$(TargetDir)EntityFramework.dll" #>
<#@ import namespace="System.Linq" #>
<#@ import namespace="System.Text" #>
<#@ import namespace="System.Collections.Generic" #>
<#@ import namespace="System.Data.Entity" #>
<#@ import namespace="System.Reflection" #>
<#@ import namespace="System" #>
<#@ import namespace="System.IO" #>
<#@ import namespace="System.Diagnostics" #>
<#@ import namespace="System.Linq" #>
<#@ import namespace="System.Collections" #>
<#@ import namespace="System.Collections.Generic" #> 
<#@ import namespace="System.Text.RegularExpressions" #>
<#string _namespace ="DataTransferObjects";#>

namespace <#=_namespace#>
{
<#  
    var entityTypes = typeof(MyDbContext).GetProperties( BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.Instance )
        .Where( property => property.PropertyType.IsGenericType &&
        property.PropertyType.GetGenericTypeDefinition().ToString().Contains( "DbSet" ) )
        .Select( property => property.PropertyType.GetGenericArguments().First() );

    foreach( var entityType in entityTypes )
    {
        Write($"\tpublic class {entityType.Name}{Environment.NewLine}");
        Write("\t{");
        Write(Environment.NewLine);

        var properties = entityType.GetProperties( BindingFlags.Public | BindingFlags.Instance );

        foreach(var property in properties )
        {
            var internalFormat = property.PropertyType.ToString();

            //assign special char to [] to preserve array notation
            internalFormat = internalFormat.Replace( "[]", "^" ); 
            var typeString =  Regex.Replace( internalFormat, @"`(\d)\[", "<" )
                .Replace( ']', '>' ).Replace( "^", "[]" );

            typeString= typeString.Replace(entityType.Namespace+".","");
            Write( $"\t\tpublic {typeString} {property.Name} {{get; set;}}{Environment.NewLine}" );                    
        }

        Write("\t}" + Environment.NewLine + Environment.NewLine);
    } 
#>
}

遵循相同的原则,您可以生成javascript。 希望这会有所帮助。