T4 Helper

johnsheehan edited this page Sep 15, 2010 · 6 revisions

For large APIs generating XML classes for deserializing can be tedious. RestSharp includes a T4 template to generate a .cs class file from an .rs schema file. .rs files are essentially XML, but can be customized to get the desired output.


Install T4Toolbox from http://t4toolbox.codeplex.com/

Using the helper

To use the helper, copy T4Helper.tt and T4Toolbox.tt into a folder. Create an file and name it filename.rs and paste some XML into it. Right click on T4Helper and select ‘Run Custom Tool’. A .cs file will be generated for each .rs file that matches the schema you’ve defined. The T4 helper tries to guess what the type is of the element data, so if it doesn’t guess correctly update your schema file to contain an easily-guessable value.

The T4 helper also handles nested classes, but be aware that if multiple .rs files contain nested classes with the same name, a class will be generated for each one, resulting in conflicts if you tried to build the project containing the .cs files. In general, the generated .cs files should not be used directly, but used as a starting point for your actual model.

If your generated classes require a namespace, open T4Helper.tt and edit the ‘var _namespace = "";’ line to contain the required namespace.