看nettiers整理出來的開發codesmith模板技術要點

stepwin原創,轉載請註明來自於www.softboss.com原創

//模板的基礎知識

//任何模板都需要的第一句,用來指定模板編輯語言是什麼,目標語言是什麼:
<%@ CodeTemplate Language="C#" TargetLanguage="T-SQL" Description="Generates a update stored procedure." %>

//接下來寫模板需要從外界引入的參數
<%@ Property Name="SourceDatabase" Type="SchemaExplorer.DatabaseSchema" Category="Context" Description="Database" %>

//在模板裏面用到了codesmith的函數和方法,需要引入對應的包,一般是
<%@ Assembly Name="SchemaExplorer" %>

<%@ Import Namespace="SchemaExplorer" %>

//所有codesmith函數都在script標籤裏面定義,包括變量
<script runat="template">
private string _outputDirectory = String.Empty;

</script>

調用用<% %> 括起來,一般有一個主函數來執行整個模板的函數
<%
this.Go();
%>




//一般模板的函數和用法


/// <summary>
/// 拷貝指定文件
/// </summary>
public void SafeCopyFile(string path, string destination)
{
FileInfo file1 = new FileInfo(path);
file1.CopyTo(destination, true);
}

/// <summary>
/// 創建指定目錄
/// </summary>
public void SafeCreateDirectory(string path)
{
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
}


/// <summary>
/// 根據指定模板生成指定文件
/// </summary>
public void RenderToFile(string templateName, string path, bool overwrite)
{
this._CurrentFileName = path;
this.GetTemplate(templateName).RenderToFile(path, overwrite);
this._counter++;
}


/// <summary>
/// 打開文件目錄,[Editor]標籤表示調用指定的編輯器;category表示參數所屬目錄;Descript表示對參數的描述;defaultvalue表示缺省值
CodeTemplateProperty表示該參數是可選還是必須的,CodeTemplatePropertyOption.Optional是可選,CodeTemplatePropertyOption.Required是必


/// </summary>
private string _outputDirectory = String.Empty;
[Editor(typeof(System.Windows.Forms.Design.FolderNameEditor), typeof(System.Drawing.Design.UITypeEditor))]
[CodeTemplateProperty(CodeTemplatePropertyOption.Optional)]
[Category("General")]
[Description("The directory to output the results to.")]
[DefaultValue("")]
public string OutputDirectory
{
get
{
if (_outputDirectory.Length == 0)
{
return @"c:/NetTiers/" + (SourceDatabase != null ? SourceDatabase.Name : "Output");
}
else
{
return _outputDirectory;
}
}
set
{
if (value.EndsWith("//")) value = value.Substring(0, value.Length - 1);
_outputDirectory = value;
}
}


//獲取當前打開模板所在路徑
this.CodeTemplateInfo.DirectoryName


//對於模板,當前打開的模板可以用codeTemplateInfo訪問,其他的子模板需要先根據文件名和路徑載入,然後編輯模板,最後賦予參數,生成文件。

//設定模板路徑
private string[] _templatesFileNames = new string[] {


"vsnet2003.project.cst",


"vsnet2005.project.cst",


"vsnet2003.solution.cst",


"vsnet2005.solution.cst",
"nAnt.cst",


"AssemblyInfo.cst",







"Entities//Enum.cst",


"Entities//IEntity.cst",


"Entities//Filter.cst",


"Entities//EntityHelper.cst",


"Entities//EntityPropertyComparer.cst",


"Entities//GenericTypeConverter.cst",



"Entities//EntityBase.cst",


"Entities//EntityData.cst",


"Entities//Entity.cst",


"Entities//EntityCollectionBase.cst",


"Entities//EntityCollection.cst",



"Entities//Views//EntityViewBase.cst",


"Entities//Views//EntityView.cst",


"Entities//Views//EntityViewCollectionBase.cst",


"Entities//Views//EntityViewCollection.cst",



"DataAccessLayer//App.config.cst",


"DataAccessLayer//cachingConfiguration.config.cst",


"DataAccessLayer//dataconfiguration.config.cst",


"DataAccessLayer//nettiersconfigdata.config.cst",



"DataAccessLayer//App.config.2005.cst",


"DataAccessLayer//cachingConfiguration.config.2005.cst",


"DataAccessLayer//dataconfiguration.config.2005.cst",


"DataAccessLayer//nettiersconfigdata.config.2005.cst",



"DataAccessLayer//Configuration.cst",








"DataAccessLayer//DataRepository.cst",


"DataAccessLayer//Utility.cst",


"DataAccessLayer//TransactionManager.cst",







"DataAccessLayer//Bases//DataProviderBase.cst",



"DataAccessLayer//Bases//EntityProviderBase.cst",




"DataAccessLayer//Bases//Views//EntityViewProviderBase.cst",











"DataAccessLayer.SqlClient//SqlDataRepository.cst",


"DataAccessLayer.SqlClient//SqlDataProvider.cst",


"DataAccessLayer.SqlClient//SqlEntityProviderBase.cst",


"DataAccessLayer.SqlClient//SqlEntityProvider.cst",



"DataAccessLayer.SqlClient//StoredProcedureProvider.cst",


"DataAccessLayer.SqlClient//StoredProceduresXml.cst",





"DataAccessLayer.SqlClient//Views//SqlEntityViewProviderBase.cst",


"DataAccessLayer.SqlClient//Views//SqlEntityViewProvider.cst",



"DataAccessLayer.WebService//WebService.cst",


"DataAccessLayer.WebService//WebInfo.cst",



"DataAccessLayer.WebServiceClient//WsDataProvider.cst",


"DataAccessLayer.WebServiceClient//WsEntityProvider.cst",


"DataAccessLayer.WebServiceClient//WsEntityProviderBase.cst",


"DataAccessLayer.WebServiceClient//Views//WsEntityViewProvider.cst",


"DataAccessLayer.WebServiceClient//Views//WsEntityViewProviderBase.cst",






"UnitTests//EntityRepositoryTest.cst",


"UnitTests//EntityViewRepositoryTest.cst",



"ASP.Net//2.0//AdminEntityUC_Designer.cst",


"ASP.Net//2.0//AdminEntityUC_CodeBehind.cst",



"ASP.Net//2.0//Entty_aspx.cst",


"ASP.Net//2.0//Entty_aspx_cs.cst",


"ASP.Net//2.0//Entty_aspx_resx.cst",
};

//設定編輯好的子模板保存的hashtable,在hashtable裏面,key是文件名,所以全套模板不能有重複的文件名
// Compile and load all them in a collection
private System.Collections.Hashtable _CodeTemplates = new System.Collections.Hashtable();

//載入模板
// load all the templates and put them into an hashtable
public void LoadTemplates()
{
foreach(string _templatesFileName in _templatesFileNames)
{
string key = System.IO.Path.GetFileName(_templatesFileName);

if (_CodeTemplates.Contains(key))
{
continue;
}

_CodeTemplates.Add(key, this.CompileTemplate(this.CodeTemplateInfo.DirectoryName + _templatesFileName));

// Set the properties that all the commonsqlcode inherited templates should set
// TODO : use reflection to check that the templates inherits from commonsql
try
{
((CodeSmith.Engine.CodeTemplate)_CodeTemplates[key]).SetProperty("EntityFormat", EntityFormat);
((CodeSmith.Engine.CodeTemplate)_CodeTemplates[key]).SetProperty("CollectionFormat",

CollectionFormat);
((CodeSmith.Engine.CodeTemplate)_CodeTemplates[key]).SetProperty("ProviderFormat", ProviderFormat);
((CodeSmith.Engine.CodeTemplate)_CodeTemplates[key]).SetProperty("InterfaceFormat", InterfaceFormat);
((CodeSmith.Engine.CodeTemplate)_CodeTemplates[key]).SetProperty("BaseClassFormat", BaseClassFormat);
((CodeSmith.Engine.CodeTemplate)_CodeTemplates[key]).SetProperty("EnumFormat", EnumFormat);
((CodeSmith.Engine.CodeTemplate)_CodeTemplates[key]).SetProperty("ManyToManyFormat",

ManyToManyFormat);
((CodeSmith.Engine.CodeTemplate)_CodeTemplates[key]).SetProperty("AliasFilePath", AliasFilePath);
((CodeSmith.Engine.CodeTemplate)_CodeTemplates[key]).SetProperty("StrippedTablePrefixes",

StrippedTablePrefixes);
}
catch(Exception) {}
}
}


//載入的時候都需要編譯模板
public CodeTemplate CompileTemplate(string templateName)
{
this._CurrentFileName = 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 CodeTemplate GetTemplate(string templateType)
{
return (CodeSmith.Engine.CodeTemplate)_CodeTemplates[templateType];
}


//給模板賦值
this.GetTemplate("EntityProviderBase.cst").SetProperty("SourceTable", SourceTable);



//數據庫屬性
<%@ Property Name="SourceDatabase" Type="SchemaExplorer.DatabaseSchema" Optional="False" Category="DataSource"

Description="Database that the stored procedures should be based on." %>


//遍歷數據庫裏面的所有數據表
private TableSchemaCollection _sourceTables;
private ViewSchemaCollection _sourceViews;
for (int i=0; i < SourceDatabase.Tables.Count; i++)
{
_sourceTables.Add(SourceDatabase.Tables[i]);
}

//遍歷數據庫裏面的所有視圖
for (int i=0; i < SourceDatabase.Views.Count; i++)
{
_sourceViews.Add(SourceDatabase.Views[i]);
}

//獲取表格名
SourceTables[i].Name

//遍歷表的結構
for (int i=0; i< SourceTable.Columns.Count; i++) {
Response.Write("/""+ SourceTable.Columns[i].Name + "/""); }

//指定打開哪個或者哪幾個表
[Category("DataSource")]
[Description("The tables to generate.")]
[CodeTemplateProperty(CodeTemplatePropertyOption.Optional)]
public TableSchemaCollection SourceTables
{
get
{
if (this._sourceTables != null && this._sourceTables.Count > 0 )
return this._sourceTables;
else
return null;
}
set
{
this._sourceTables = value;
}
}


我在網上找了半天,發現codesmith遍歷文件夾和拷貝文件夾的函數,我知道能夠引入system.io這個包,然後自己寫這個函數出來,哪位達人寫過這樣的函數或者有更好的辦法可以發過來共享啊

Trackback: http://tb.blog.csdn.net/TrackBack.aspx?PostId=743855

 
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章