【问题标题】:Generate JSON post build on .NET project在 .NET 项目上生成 JSON 后期构建
【发布时间】:2017-01-19 16:08:49
【问题描述】:
我正在尝试在我的共享 .NET 库中生成包含枚举的 javascript 文件(因此我的 web api 和客户端将自动同步,并且不会编写多个代码)。
我听说过 .NET 构建后事件,但不太确定我们是否应该以及如何使用它。
有什么建议吗?
【问题讨论】:
标签:
javascript
.net
enums
build
【解决方案1】:
您可以通过T4 templates生成代码。
为了帮助自己使用 T4 模板,我建议您下载 AutoT4 和 Devart 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。
希望这会有所帮助。