Code Generator for Resource

  • 3914
  • 0

Code Generator for Resource

 

問題描述

 

當使用Resource檔來獲取資源(圖片、文字)時,如下列所示,會導致一些問題。

string msg = MessageHelper.GetMessage(DCMSConfigurationType.DataModelQueryDesigner, “Wrn_005”);
  • Wrn_005 為 string,可能會手誤打錯
  • 當Resx檔移除Wrn_005,使用到Wrn_005的Client端仍然不會發生任何的錯誤或警告訊息

 

解決方案描述

 

自製一個Code Generator 小工具使用 T4 Template技術,可以根據resx檔 產生對應的類別包含字串

產生的類別如下所示:

using System;
namespace Digiwin.Designer.Utilities.Resources 
{
	// Note: Attributes, access modifiers, inheritance and template parameter constraints
	//       can be added in another partial type definition.

		public static partial class DataModelQueryDesignerResourcesConst
		{
			public const string DMQG_ROOT_NODE = "DMQG_root_node";
			public const string DMQ_COLUMNS_NODE = "DMQ_columns_node";
			...
		}

}

使用後,Client使用方式可改成

MessageHelper.GetMessage(DCMSConfigurationType.DataModelQueryDesigner, DataModelQueryDesignerResourcesConst.WRN_005);

Resource字串(如Wrn_005) 可以獲得靜態程式碼檢查,並且避免手誤

 

解決方案

 

  • 加入一個附檔名.tt的檔案(EX: Template.tt)
  • 貼上下列的內容,修改 inputFile 及 NameSpace
<#

//相對於此tt檔的相對路徑 <= resource 檔名

var inputFile = "DataModelQueryDesignerResources.resx";

//欲產生的NameSpace

var nameSpace = "Digiwin.Designer.Utilities.Resources";

#>

<#

string templateDirectory = Path.GetDirectoryName(Host.TemplateFile);

var test = RexGenerator.Class(Path.Combine(templateDirectory, inputFile), nameSpace) ;

#>

<#= test #>

<#@ include file="Rex.ttinclude"#>
  • 存檔後,會生成對應檔案

image

範例可參考下載檔案

 

使用方式及注意事項

 

  • 勿修改自動產生出來的檔案,若需要修改,可使用Partial Class 的方式改之
  • 可使用轉換範本方式,重新產生檔案內容
  • 若在別的專案使用,請確保include檔案存在相對的資料夾下

 

使用Code Generator優點

  • 快速從Model => Code
  • 當撰寫新程式碼以及更新模型的結構描述時,協助建立遵守結構描述的程式碼(Coding Style)。
  • 產生的程式碼可從編譯器得到靜態程式碼檢查
  • 將單一的簡單範本檔加入至專案即可提供這些優點。
  • 可以快速地以累加方式開發和測試文字範本。
  • 通過變更範本(改變include檔案)及轉換範本的方式一次變更全部的程式碼。

image

 

Code 轉換示意圖

image

 

 

結語

 

利用T4 Template的方式,有著快速的好處,但若能改成Editor or 專案範本形式,使用上會比較直覺與方便,有較好的使用者體驗。

 

參考文件

 

http://msdn.microsoft.com/en-us/library/bb126445.aspx

 

http://www.hanselman.com/blog/T4TextTemplateTransformationToolkitCodeGenerationBestKeptVisualStudioSecret.aspx

 

下載 Download

 

Code Generator.rar

分享