This project is read-only.

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 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 in <projectpath>\Models\, 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");

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Coffee;
using Coffee.DataModels;
 XmlDocument configurationData = new XmlDocument();
 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");
		foreach(XmlNode property in properties)
			string type = "", datatype = "";

				type = property.Attributes["type"].Value;

				datatype = property.Attributes["datatype"].Value;

			string propertytype = "string";

				case "TextBox":
				case "DropDownList":
				case "RadioButtonList":
					propertytype = 
						(datatype == "integer" ? "int?" :
						(datatype == "double" ? "double?" :
				case "YesNo":
					propertytype = "bool?";

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


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


No comments yet.