达达's 胡搞瞎搞工作室

此Blog搬到www.unbe.cn 去了,要找我讨论问题请到我的新Blog

CodeSmith自动保存输出结果

    看到百度上有同志在搜索“CodeSmith输出目录”,偶正好会,就写篇经验帖,于需要的朋友可以共享下经验。

    要CodeSmith生成完代码可以自动保存到某个目录,一般需要让自己的模板继承CodeSmith类库中的OutputFileCodeTemplate类。

    C#脚本示例代码如下:

using System;
using
 System.Text;
using
 System.ComponentModel;
using
 CodeSmith.Engine;
using
 System.Data;
using
 SchemaExplorer;
using
 CodeSmith.BaseTemplates;

public class
 TestTemplate : OutputFileCodeTemplate
{
    
public string
 Hello()
    
{
        
return "Hello!!!"
;
    }

}

    编写完这个模板的脚本后我们需要把我们的模板与这个脚步关联起来。

    先将上面的代码保存到TestTemplates.cst.cs文件,然后编写一下模板:

<%@ CodeTemplate Language="C#" TergetLanguage="C#" src="TestTemplates.cst.cs" Inherits="TestTemplate" %>
<%@ Assembly Name="SchemaExplorer" %>
<%@ Assembly Name="System.Data" %>
<%@ Assembly Name="CodeSmith.BaseTemplates" %>
<%@ Import Namespace="SchemaExplorer" %>
<%@ Import Namespace="System.Data" %>
<%@ Property Name="FoldName" Type="System.String" Default="D:\\GeneratorCode" %>
<%=Hello()%>
<% if(!System.IO.Directory.Exists(FoldName)) System.IO.Directory.CreateDirectory(FoldName); %>
<% this.OutputFile = FoldName + "\\" + "Hello.cs"; %>
<% System.Diagnostics.Process.Start(FoldName); %>

    模板第一句就是用于关联模板与脚本文件的了,接下来是引入我们用到的CodeSmith类库的程序集,还有Import在脚本中using的.NET命名空间,然后那个Property就是我们的输出目录,默认值是D:\GeneratorCode,这个属性会出现在CodeSmith的属性栏里到时候我们可以根据需要改,用过的人应该都知道,呵呵。
   
    中间调用Hello函数就不用说了,后面2句脚本就是我用于保存文件的代码了,先判断目录存在不存在,不存在创建目录,然后保存文件。最后一句用于弹出Explorer查看代码目录。

    呵呵,本文到此结束,是不是很简单~~如果大家有什么更好的方式希望可以交流交流。

posted on 2006-04-28 13:38  BG5SBK  阅读(1446)  评论(4编辑  收藏  举报

导航