CodeSmith批量代码生成并存放到指定目录

时间:2021-10-30 13:48:09

其实CodeSmith自带的例子是很好的学习材料,其中一个例子就有批量生成所有表(指定表)并存放到指定目录的,但例子还是归例子,要符合实际需要的使用,还是得改一下的。下面发布下本人修改后的批量生成多种模板多个表的代码文件,并存放到指定目录下:

<%@ CodeTemplate Language="C#" TargetLanguage="C#" Src="" Inherits="" Debug="True" CompilerVersion="v3.5" ResponseEncoding="UTF-8" Description="输出所有模块文件" %>
<%-- Context --%>
<%-- Object --%>
<%@ Property Name="NameSpace" Type="System.String" Default="NameSpace" Category="Object" Description="项目的命名空间" %>
<%@ Property Name="Assembly" Type="System.String" Default="Assembly" Category="Object" Description="项目的程序集" %>
<%@ Property Name="TableDivideMark" Type="System.String" Default="_" Category="Object" Description="表名分隔符" %>
<%@ Property Name="TablePrefix" Type="System.Boolean" Default="true" Category="Object" Description="是否有表前缀,如果存在表前缀的,会自动把第一个表名分隔符前的表前缀删除掉。" %>
<%@ Property Name="TablePrefixLength" Type="System.Int32" Default="4" Category="Object" Description="表前缀长度,如果表前缀大于这个值,则认为没有表前缀" %>
<%@ Property Name="ColumnDivideMark" Type="System.String" Default="_" Category="Object" Description="字段名分隔符" %>
<%@ Property Name="ColumnPrefix" Type="System.Boolean" Default="false" Category="Object" Description="是否有字段前缀,如果存在字段前缀的,会自动把第一个字段名分隔符前的字段前缀删除掉。" %>
<%@ Property Name="ColumnPrefixLength" Type="System.Int32" Default="0" Category="Object" Description="字段前缀长度,如果字段前缀大于这个值,则认为没有字段前缀" %>
<%@ Property Name="ForceId" Type="System.Boolean" Default="true" Category="Object" Description="强制性自增量标识主键" %>
<%@ Property Name="ForceIdProperty" Type="System.String" Default="ID" Category="Object" Description="强制性自增量标识主键的属性名称" %>
<%@ Property Name="SourceTableNames" Type="System.String" Default="" Category="Object" Description="当指定表名时,只执行字符串中表名列表中的表" %>
<%-- Context --%>
<%@ Assembly Name="System.Design" %>
<%@ Assembly Name="SchemaExplorer" %>
<%@ Import Namespace="SchemaExplorer" %>
<%@ Import Namespace="System.IO" %>
<%@ Import Namespace="System.Xml" %>
<%@ Import Namespace="System.Text" %>
<%@ Import Namespace="System.Windows.Forms.Design" %>
<%@ Import Namespace="System.Text.RegularExpressions" %>
<%@ Import Namespace="System.Collections.Specialized" %>

<script runat="template">


private DatabaseSchema _sourceDatabase;
private string _outputDirectory;
private bool _implementNotification = true;

//模板对象列表(根据模板名称产生出来的模板对象)
public CodeTemplate[] CurrentTemplates;
//模板名称数组
public string[] TemplateNames = {"piggy_projectFileInclue.cst","piggy_SqlMap.config.cst","piggy_dao.config.cst","piggy_service.config.cst","piggy_Model_Auto.cst","iBatis_sqlmap_Auto.cst","piggy_Service.cst","piggy_Model.cst","piggy_DAL.cst","piggy_BLL.cst","iBatis_sqlmap.cst"};
//模板输出格式数组
public string[] strFormats = {"projectFileInclue.txt","sqlmap.config","Dao_Auto.config","Service_Auto.config","{0}_Auto.cs","{0}_Auto.xml","I{0}BLL.cs","{0}.cs","{0}DAO.cs","{0}BLL.cs","{0}.xml"};
//模板输出路径
public string[] OutputPaths={"","\\Data","\\Data\\config","\\Data\\config","\\Data_Auto\\Model","\\Data_Auto\\Map","\\Data\\service","\\Data\\Model","\\Data\\DAL","\\Data\\BLL","\\Data\\Map"};
[Category("Database")]
[Description("Database that the mapping file should be based on.")]
public DatabaseSchema SourceDatabase {
get { return _sourceDatabase; }
set { _sourceDatabase = value; }
}

[Editor(typeof(System.Windows.Forms.Design.FolderNameEditor), typeof(System.Drawing.Design.UITypeEditor))]
[Category("Class")]
[Description("The folder to save the generated class files.")]
public string OutputDirectory
{
get {return _outputDirectory;}
set {_outputDirectory= value;}
}

//根据模板名称产生出来的模板对象列表
public void CreateTemplate()
{
if (CurrentTemplates==null)
{
CurrentTemplates=new CodeTemplate[TemplateNames.Length];
for (int i = 0; i < TemplateNames.Length; i++)
{
CurrentTemplates[i]=CompileTemplate(CodeTemplateInfo.DirectoryName + TemplateNames[i]);
}
}
}
//单独生成一个模板对象
public CodeTemplate CompileTemplate(string templateName)
{
CodeTemplateCompiler compiler = new CodeTemplateCompiler(templateName);
compiler.Compile();

if (compiler.Errors.Count == 0)
{
return compiler.CreateInstance();
}
else
{
for (int i = 0; i < compiler.Errors.Count; i++)
{
Response.WriteLine(compiler.Errors[i].ToString());
}
return null;
}

}

//执行输出脚本
public void Generate()
{
if (CurrentTemplates==null)
CreateTemplate();
StringCollection ExcludedTables=new StringCollection();
if (SourceTableNames.Length>0)
{
int mIndex=-1;
mIndex=SourceTableNames.IndexOf(',');
while (mIndex>0) {
ExcludedTables.Add(SourceTableNames.Substring(0,mIndex));
SourceTableNames=SourceTableNames.Remove(0,mIndex+1);
mIndex=SourceTableNames.IndexOf(',');
}
ExcludedTables.Add(SourceTableNames);
}
foreach(TableSchema SourceTable in SourceDatabase.Tables)
{
if (SourceTableNames.Length>0)
{
if (!ExcludedTables.Contains(SourceTable.Name))
continue;
}
Response.Write(string.Format("Processing Table {0} ... ", SourceTable.Name));
Response.WriteLine();
try
{
string className = ClearDivideMarkAndPrefix(SourceTable.Name,TableDivideMark,TablePrefix,TablePrefixLength);
for (int i = 0; i < TemplateNames.Length; i++)
{
string FileName;
if (i<=3)
{
CurrentTemplates[i].SetProperty("SourceDatabase", SourceDatabase);
FileName=strFormats[i];
}
else {
CurrentTemplates[i].SetProperty("SourceTable", SourceTable);
FileName=string.Format(strFormats[i],className);
}
FileName=Path.Combine(OutputDirectory+OutputPaths[i], FileName);
//统一属性赋值
CurrentTemplates[i].SetProperty("NameSpace",NameSpace);
CurrentTemplates[i].SetProperty("Assembly",Assembly);
CurrentTemplates[i].SetProperty("TableDivideMark",TableDivideMark);
CurrentTemplates[i].SetProperty("TablePrefix",TablePrefix);
CurrentTemplates[i].SetProperty("TablePrefixLength",TablePrefixLength);
CurrentTemplates[i].SetProperty("ColumnDivideMark",ColumnDivideMark);
CurrentTemplates[i].SetProperty("ColumnPrefix",ColumnPrefix);
CurrentTemplates[i].SetProperty("ColumnPrefixLength",ColumnPrefixLength);
CurrentTemplates[i].SetProperty("ForceId",ForceId);
CurrentTemplates[i].SetProperty("ForceIdProperty",ForceIdProperty);

Response.WriteLine(string.Format("{0} In {1} ", TemplateNames[i],FileName));
CurrentTemplates[i].RenderToFile(FileName, true);
}
}
catch (Exception ex)
{
Response.WriteLine("Error: " + ex);
}
}
}
</script>

<% this.Generate(); %>
<!-- #include file="Function.inc" -->
下面是Function.inc文件的部分代码。截取出来的,如果有遗留了哪些代码,请指正:

<script runat="template">
private Regex cleanRegEx = new Regex(@"\s+|_|-|\.", RegexOptions.Compiled);
private Regex cleanID = new Regex(@"(_ID|_id|_Id|\.ID|\.id|\.Id|ID|Id)", RegexOptions.Compiled);

//清除字符串中的分隔符以及第一个分隔符前的字符串长度小于等于prefixLength的前缀
public string ClearDivideMarkAndPrefix(string name,string mark,bool prefix,int prefixLength)
{
string strResult=name;
//处理表前缀
if (prefix)
{
int mIndex=name.IndexOf(mark);
if (mIndex<=prefixLength)
strResult=name.Remove(0,mIndex+mark.Length);
}
if (mark.Length>0)
strResult=GetFirstUpStr(strResult,mark);
return strResult;
}
//受字母大写且mark分隔符后第一个字母大写
public string GetFirstUpStr(string strValue,string mark)
{
string m_Str=strValue.ToLower();
System.Text.StringBuilder mResult=new System.Text.StringBuilder("");
int mLen=m_Str.Length;
int j=-1;
j=m_Str.IndexOf(mark);
while (j>0)
{
mResult.Append(m_Str.Substring(0,1).ToUpper());
mResult.Append(m_Str.Substring(1,j-1));
m_Str=m_Str.Remove(0,j+mark.Length);
j=m_Str.IndexOf(mark);
}
if (m_Str.Length>0)
{
mResult.Append(m_Str.Substring(0,1).ToUpper());
mResult.Append(m_Str.Substring(1,m_Str.Length-1));
}
return mResult.ToString();
}
</script>
其实,这个批量输出的可以重复使用的,只需要把模板拷贝到对应的模板目录中后,修改变量TemplateNames、strFormats、OutputPaths为自己实际需要的参数就能应用到不同的模板库中了,十分方便,如果看官们的模板参数不一样,那就得修改“//统一属性赋值”下的SetProperty相关的属性就可以了。

原创作品出自努力偷懒,转载请说明文章出处http://blog.csdn.net/kfarvid或 http://www.cnblogs.com/kfarvid/