次の方法で共有


VS 拡張機能内でのテキスト変換の呼び出し

更新 : 2011 年 3 月

メニュー コマンドやドメイン固有言語などの Visual Studio 拡張機能を作成する場合は、テキスト テンプレート サービスを使用してテキスト テンプレートを変換できます。 STextTemplating サービスを取得し、ITextTemplating にキャストします。

テキスト テンプレート サービスの取得

using Microsoft.VisualStudio.TextTemplating;
using Microsoft.VisualStudio.TextTemplating.VSHost;
...
// Get a service provider – how you do this depends on the context:
IServiceProvider serviceProvider = dte; 

// Get the text template service:
ITextTemplating t4 = serviceProvider.GetService(typeof(STextTemplating)) as ITextTemplating;

// Process a text template:
string result = t4.ProcessTemplate(filePath, System.IO.File.ReadAllText(filePath));

テンプレートへのパラメーターの引き渡し

パラメーターをテンプレートに渡すことができます。 テンプレート内で、<#@parameter#> ディレクティブを使用してパラメーター値を取得できます。

パラメーターの型については、シリアル化またはマーシャリング可能な型を使用する必要があります。 つまり、SerializableAttribute を使用して型を宣言するか、MarshalByRefObject から型を派生する必要があります。 この制限が必要なのは、テキスト テンプレートは別の AppDomain で実行されるためです。 System.StringSystem.Int32 などの組み込み型はすべてシリアル化可能です。

パラメーター値を渡すために、呼び出し元のコードでは Session ディクショナリまたは CallContext に値を配置できます。

次の例では、両方の方法を使用して短いテスト テンプレートを変換しています。

using Microsoft.VisualStudio.TextTemplating;
using Microsoft.VisualStudio.TextTemplating.VSHost;
...
// Get a service provider – how you do this depends on the context:
IServiceProvider serviceProvider = dte; 

// Get the text template service:
ITextTemplating t4 = serviceProvider.GetService(typeof(STextTemplating)) as ITextTemplating;
ITextTemplatingSessionHost sessionHost = t4 as ITextTemplatingSessionHost;

// Create a Session in which to pass parameters:
sessionHost.Session = sessionHost.CreateSession();
sessionHost.Session["parameter1"] = "Hello";
sessionHost.Session["parameter2"] = DateTime.Now;

// Pass another value in CallContext:
System.Runtime.Remoting.Messaging.CallContext.LogicalSetData("parameter3", 42);

// Process a text template:
string result = t4.ProcessTemplate("",
   // This is the test template:
   "<#@parameter type=\"System.String\" name=\"parameter1\"#>"
 + "<#@parameter type=\"System.DateTime\" name=\"parameter2\"#>"
 + "<#@parameter type=\"System.Int32\" name=\"parameter3\"#>"
 + "Test: <#=parameter1#>    <#=parameter2#>    <#=parameter3#>");

// This test code yields a result similar to the following line:
//     Test: Hello    07/06/2010 12:37:45    42 

エラー報告と出力ディレクティブ

処理中にエラーが発生すると、Visual Studio のエラー ウィンドウに表示されます。 また、ITextTemplatingCallback を実装したコールバックを指定することにより、エラーの通知を受けることもできます。

結果の文字列をファイルに書き込む場合は、テンプレートの <#@output#> ディレクティブで指定されているファイル拡張子とエンコードを確認できます。 この情報は、コールバックにも渡されます。 詳細については、「T4 出力ディレクティブ」を参照してください。

void ProcessMyTemplate(string MyTemplateFile)
{
  string templateContent = File.ReadAllText(MyTemplateFile);
  T4Callback cb = new T4Callback();
  // Process a text template:
  string result = t4.ProcessTemplate(MyTemplateFile, templateContent, cb);
  // If there was an output directive in the MyTemplateFile,
  // then cb.SetFileExtension() will have been called.
  // Determine the output file name:
  string resultFileName = 
    Path.Combine(Path.GetDirectoryName(MyTemplateFile), 
        Path.GetFileNameWithoutExtension(MyTemplateFile)) 
      + cb.fileExtension;
  // Write the processed output to file:
  File.WriteAllText(resultFileName, result, cb.outputEncoding);
  // Append any error messages:
  if (cb.errorMessages.Count > 0)
  {
    File.AppendAllLines(resultFileName, cb.errorMessages);
  }
}

class T4Callback : ITextTemplatingCallback
{
  public List<string> errorMessages = new List<string>();
  public string fileExtension = ".txt";
  public Encoding outputEncoding = Encoding.UTF8;

  public void ErrorCallback(bool warning, string message, int line, int column)
  { errorMessages.Add(message); }

  public void SetFileExtension(string extension)
  { fileExtension = extension; }

  public void SetOutputEncoding(Encoding encoding, bool fromOutputDirective)
  { outputEncoding = encoding; }
}

次のようなテンプレート ファイルを使用してコードをテストできます。

<#@output extension=".htm" encoding="ASCII"#>
<# int unused;  // Compiler warning "unused variable"
#>
Sample text.

コンパイラの警告は、Visual Studio のエラー ウィンドウに表示されます。また、コンパイラの警告によって、ErrorCallback の呼び出しも生成されます。

参照パラメーター

MarshalByRefObject から派生したパラメーター クラスを使用して、テキスト テンプレートの外部に値を渡すことができます。

関連トピック

履歴の変更

日付

履歴

理由

2011 年 3 月

トピックが作成されました。

情報の拡充