代码改变世界

CodeSmith基础(六)

2005-12-22 11:22  努力学习的小熊  阅读(12330)  评论(2编辑  收藏  举报

       本文主要介绍CodeSmith对象。

       CodeSmith Object
       CodeSimth中有许多对象可以在编写模板的时候使用,这里将介绍这些对象的一些公用方法和属性以及怎么使用它们。
 

代码模板对象(CodeTemplate Object
在模板中,“this”(或者“Me”在VB.NET中)在当前模板中代码代码模板对象。 

代码模板的方法(CodeTemplate Methods

1
public virtual void GetFileName()
可以重载这个方法设置模板输出到文件的名称。否则CodeSmith将基于模板名称和TargetLanguage设置它的文件名。

2public void CopyPropertiesTo(CodeTemplate target)
这个方法可以实现从一个模板中将其所有属性的值拷贝到另一个模板所有对应属性中,并按照相应的属性值类型进行匹配。

3public object GetProperty(string propertyName)
这个方法将返回一个给定名称的属性的值。

4public void SetProperty(string propertyName, object value)
此方法可以根据给定名称的属性设置其值。

5public string SavePropertiesToXml ()
这个方法将现有的属性值保存成一个XML的属性字符串。

6public void SavePropertiesToXmlFile (string fileName)
这个方法将当前属性值保存成一个XML的属性文件。

7public void RestorePropertiesFromXml(string propertySetXml, string baseDirectory)
从保存在XML文件中的属性字符串,将模板的属性值恢复。

8public void RestorePropertiesFromXmlFile(string fileName)
从保存在XML文件中的属性文件,将模板的属性值恢复。 

代码模板的属性(CodeTemplate Properties
Response:此属性可以访问当前的TextWriter对象,这个对象是用来输出模板用的。

CodeTemplateInfo:这个属性用来访问当前的CodeTemplateInfo对象,这个对象包含当前模板的一些信息。

Progress:这个属性用来报告当前模板的执行过程。

 

Response Object
这个对象提供直接写输出模板的方法。与ASP.NETresponse对象很相似。下面是一个利用ResponseWrite方法在模板上输出一段文字的例子。

<% Response.Write("This will appear in the template") %>

IndentLevel (Int32)
当使用Response对象时输出文本的缩进级别。

Indent() Method
将输出缩进一个级别。

Unindent() Method
将输出少缩进一个级别。

AddTextWriter(TextWriter writer) Method
Response对象增加一个TextWriter。这样可以使在同一时间用多个TextWriter输出模板。

 

CodeTemplateInfo Object
此对象包含一些当前模板的信息。下面是一些CodeTemplateInfo可用的属性。

DateCreated (DateTime)
返回一个date类型值,是模板创建的时间。

DateModified (DateTime)
返回模板最后一次被修改的时间。

Description (string)
返回模板声明时对模版的描述信息。

DirectoryName (string)
返回当前模板文件所在的路径。

FileName (string)
返回当前模版文件的文件名称。

FullPath (string)
返回当前模板的完整路径,路径名+文件名。

Language (string)
返回代码模版声明时使用的语言。

TargetLanguage (string)
返回代码模版声明时生成的目标语言。

 

Progress Object

这个属性用来报告当前模板的执行过程。下面是一些Progress可用的成员。

MaximumValue (Int32)
模版progress允许的最大值。

MinimumValue (Int32)
模版progress允许的最小值。

Step (Int32)
模版每执行一不progress的增长值。

Value (Int32)
Progress的当前值。

PerformStep() Method
按照指定好的progress的增加值执行一步。(原文:Perform a progress step incrementing the progress value by the amount specified in the Step property.

Increment(Int32 amount) Method
指定progress的增加值。(原文:Increment the progress value by the specified amount.

OnProgress (ProgressEventHandler) Event
这个事件用来报告模版的执行过程。(原文:This event can be used to be notified of template execution progress.

1this.Progress.OnProgress += new ProgressEventHandler(this.OnProgress);
2
3public void OnProgress(object sender, ProgressEventArgs e)
4{
5  Trace.WriteLine(e.Value);
6}