Text Templating in Visual Studio

Visual Studio allows you to create code generator templates easily using the T4 Text Templating engine, this is in fact used by the ADO.NET EntityObject Generator template to generate entities from the database for Entity Framework.

If you are working exclusively with a physical XML survey, you might find the following tool useful.

Create a new text file and name it CoffeViewModel.tt in Visual Studio and copy the following code into it, make sure to replace PATH TO XML with the relative path to your XML file from the location of the template.

So if you create your XML in <projectpath>\Surveys\MySurvey.xml and place your CoffeViewModel.tt in <projectpath>\Models\CoffeViewModel.tt, then your PATH TO XML would be ..\Surveys\MySurvey.xml

This template should (re)generate your ViewModel classes from your XML for you whenever you do a build.

This makes it really easy to do rapid prototyping of Survey pages.

<#@ template language="C#" debug="false" hostspecific="true"#>
<#@ assembly name="System.Xml.dll" #>
<#@ import namespace="System.Xml" #>
<#@ output extension=".cs"#><#

string inputFile = this.Host.ResolvePath(@"PATH TO XML");
System.Diagnostics.Debug.WriteLine(inputFile);


#>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Coffee;
using Coffee.DataModels;
<#
 XmlDocument configurationData = new XmlDocument();
 configurationData.Load(inputFile); 
 XmlNodeList controls = configurationData.SelectNodes("//control");

 foreach(XmlNode control in controls)
 {
	XmlNode mapper = control.SelectSingleNode("datamapper");
	string className = mapper.Attributes["name"].Value;
#>
/// <summary>
/// Summary description for <#=className#>ViewModel
/// </summary>
public class <#=className#>ViewModel : DataModel
{
<#
	XmlNodeList properties = control.SelectNodes("configuration/question");
	if(properties!=null)
	{
		foreach(XmlNode property in properties)
		{
			string type = "", datatype = "";

			if(property.Attributes["type"]!=null)
				type = property.Attributes["type"].Value;

			if(property.Attributes["datatype"]!=null)
				datatype = property.Attributes["datatype"].Value;

			string propertytype = "string";

			switch(type)
			{
				case "TextBox":
				case "DropDownList":
				case "RadioButtonList":
					propertytype = 
						(datatype == "integer" ? "int?" :
						(datatype == "double" ? "double?" :
						"string"));
						break;
				case "YesNo":
					propertytype = "bool?";
					break;
			}

			string id = property.Attributes["id"].Value;
#>
    public <#=propertytype#> <#=id#> { get; set; }
<#
		}
	}
#>
}

<#
 }
#>

Last edited Jul 6, 2012 at 3:45 PM by RupertAvery, version 3

Comments

No comments yet.