T4 templates

To fully integrate the generation process into Visual Studio, you can create a T4 template which automatically downloads the JSDL and generates the C# classes (or other code). Every time the web service has changed, the T4 template can be reevaluated and the web service client class is immediately updated.

To use the T4 template, copy all files from the "- Bin" directory to the directory "Jsdl" in the solution directory and create the following T4 template (the output class name and namespace is inferred from the template's name and location).

<#@ template debug="false" hostspecific="true" language="C#" #>
<#@ assembly name="System.Core" #>
<#@ assembly name="$(SolutionDir)\Jsdl\Jsdl.Library.dll" #>
<#@ assembly name="$(SolutionDir)\Jsdl\Newtonsoft.Json.dll" #>
<#@ import namespace="Jsdl" #>
<#@ import namespace="Jsdl.Generators" #>
<#@ import namespace="System.IO" #>
<#@ import namespace="Microsoft.CSharp" #>
<#@ output extension=".cs" #>
<#
	// CONFIGURATION
	var jsdlFile = @"SampleService.json"; // relative to the T4 template's location
	var gen = (CsharpCodeGenerator)CodeGenerator.Create("Csharp");
	// -------------

	var provider = new CSharpCodeProvider();
	var clientClassName = provider.CreateEscapedIdentifier(
		Path.GetFileNameWithoutExtension(Host.TemplateFile));
	var clientClassNamespace = Host.ResolveParameterValue(
		"directiveId", "namespaceDirectiveProcessor", "namespaceHint");

	jsdlFile = Host.ResolvePath(jsdlFile);
	var code = generator.Generate(
		File.ReadAllText(jsdlFile), clientClassName, clientClassNamespace);
#>
<#= code #>

The sample above loads the web service definition from a file relative to the template's location. To load the definition from an URL you can use the code below:

<#@ template debug="false" hostspecific="true" language="C#" #>
<#@ assembly name="System.Core" #>
<#@ assembly name="$(SolutionDir)\Jsdl\Jsdl.Library.dll" #>
<#@ assembly name="$(SolutionDir)\Jsdl\Newtonsoft.Json.dll" #>
<#@ import namespace="Jsdl" #>
<#@ import namespace="Jsdl.Generators" #>
<#@ import namespace="System.IO" #>
<#@ import namespace="Microsoft.CSharp" #>
<#@ output extension=".cs" #>
<#
	// CONFIGURATION
	var jsdlUrl = @"http://rsuter.com/Services/Jsdl/SampleService.php?operation=jsdl";
	var gen = CodeGenerator.Create(...);
	// -------------

	var provider = new CSharpCodeProvider();
	var clientClassName = provider.CreateEscapedIdentifier(
		Path.GetFileNameWithoutExtension(Host.TemplateFile));
	var clientClassNamespace = Host.ResolveParameterValue(
		"directiveId", "namespaceDirectiveProcessor", "namespaceHint");

	var code = generator.GenerateFromUrl(
		jsdlUrl, clientClassName, clientClassNamespace);
#>
<#= code #>

More samples: https://jsdl.svn.codeplex.com/svn/-%20T4%20templates/


Last edited May 22, 2013 at 11:09 AM by rsuter, version 9

Comments

No comments yet.