CodSmith自动生成问题

发布时间 2023-06-12 16:47:09作者: 浅笑~过去

1.自动生成vue页面报错:Internal service error: Illegal tag name. Use '&lt;' to print ‘<’.

 

可能原因,输出保存的格式不对,使用UTF-8格式写文件,代码如下:

public override void Render(TextWriter tw)
{
   //使用UTF-8格式写文件
   StreamWriter fs1 = new StreamWriter(_savefile,false, new System.Text.UTF8Encoding(false));
   this.Response.AddTextWriter(fs1);
   base.Render(tw);
   fs1.Close();
}

2.CodeSmith 适用主从代码模板(简言之主模板给子模板中的属性值赋值)
主模板代码:引用了子模板
NewTemplate2.cst
 
<%@ Template Language="C#" TargetLanguage="Text" %>
<%-- 注册要生成的模板 --%>
<%@ Register Name="TableClumTemplate" Template="NewTemplate2.cst" MergeProperties="Flase" ExcludeProperties=""%>

<%--声明数据库的参数,在左下角的Database属性中,选择要操作的数据库名称--%>
<%--Type数据类型为TableSchema,表明参数Table是一个表对象。--%>
<%@ Property Name="SourceTable" Type="TableSchema" DeepLoad="True" Optional="False" Category="Table" Description="Table Name"%>
<%-- 执行输出文件的函数 --%>
<% this.OutPutFile(); %>
<script runat="template">
    //输出文件
    private void OutPutFile()
    {
       
        
        //生成列表表字段的模板
        CodeTemplate cloumn =new TableClumTemplate();
        //指定输出路径
        string cloumnFilePath = OutputDirectory +"\\"+ this.SourceTable.Name +".cs";
         //给子模板参数赋值
        cloumn.SetProperty("SourceTable",this.SourceTable);
        cloumn.RenderToFile(cloumnFilePath,true);
    }
    //解决方案输出路径
    private string Directory = String.Empty;
    [Editor(typeof(System.Windows.Forms.Design.FolderNameEditor), typeof(System.Drawing.Design.UITypeEditor))] 
    [Optional, NotChecked]
    [DefaultValue("")]
    public string OutputDirectory 
    { 
        get
        {
            return Directory;
        }
        set
        {
            if (value.EndsWith("\\")) value = value.Substring(0, value.Length -1);
            Directory = value;
        } 
    }
</script>

子模板代码:
<%--目标语言C#--%>
<%@ CodeTemplate Inherits="CodeTemplate" Language="C#" TargetLanguage="Text" Description="" Debug="True" ResponseEncoding="UTF-8"%>
 
<%--Type数据类型为TableSchema,表明参数Table是一个表对象。--%>
<%@ Property Name="SourceTable" Type="TableSchema" DeepLoad="True" Optional="False" Category="Table" Description="Table Name"%>
 
<%--引入数据库操作组件--%>
<%@ Assembly Name="SchemaExplorer"%>
<%@ Import Namespace="SchemaExplorer"%>
### <%=SourceTable.FullName %>表描述
 
|字段名|数据类型|是否可空|数据库类型|长度|描述|
|--|--|--|--|--|--|
<%for(int i=0;i<SourceTable.Columns.Count;i++){%>
|<%=SourceTable.Columns[i].Name.ToString()%>|<%=SourceTable.Columns[i].SystemType.ToString()%>|<%=SourceTable.Columns[i].AllowDBNull?"Yes":"No" %> |<%=SourceTable.Columns[i].NativeType.ToString() %>|<%=SourceTable.Columns[i].Size %>|<%=SourceTable.Columns[i].Description.ToString()%>|
<%}%>  

 

可以参考地址(多看几遍就看懂了):https://www.cnblogs.com/knowledgesea/p/5016077.html