Wednesday, 6 January 2016

T4 Templates to Generate classes from XML

Today I came across an issue in a UI Automation project where the Automation devleoper has to use some elements which were references to UI elements from an XML. Let’s see how the XML was looking like:
image_thumb[27]
Now this XML has tag <element> which has to be used in helper methods to find elements. it was something like below:
image_thumb[23]
The problem was that this type of lines were scattered across the project. I found this issue during the codereview and decided to find an approach how to get rid of such problem and then comes Ideas in my mind…

T4 Templates to rescue

I had this notion of T4 templates saw and did some fixes in EF generated TT templates but I have never create a template from scratch. To create a template from scratch its always handly to use tools like T4 editor and few more custom utilities which makes the life easy.
I knew about Tangible T4 template extension of Visual studio 2013. This extension have a free version which gives you more than you wanted features, but ofcourse there are many benefits to have pro licensed as well. But this was enough for me so what I got with Tengible T4 template.
The Editor for syntax highlighting :
image_thumb[4]
(Figure. 1)

This was the only feature I was looking for. But there was more A few VS File templates were also installed and couple of them were having sample code as well to get started which was great.

I used the Advanced T4 template to add new Template file which has generated a sample template like shown in Figure. 1
Now I had to change it to give a custom implementation so that I can get desired classes. Because the Editor gave a lot of help and everything was visible so it was easy to differentiate the local code and template code. So all I had to do was read my XML file iterate through it and genrate desired result as classes and constant fields.
Below is the complete code that I used:

image_thumb[11]
I have attached the screenshot and highlighted the code which would get generated. It’s really as simple as it seems. You can debug the code easily by placing a Debug breakpoint any where in the code and Right click on the Template and Select “Debug Template”
image_thumb[7]
With Tangible T4 template it allows to compile and run the T4 when you press Ctrl+S key(Save document). That’s it.
Here are the results that I generated using it:
image_thumb[16]
What we have achieved using it? Well see for yourself:
image_thumb[20]
For now everybody was happy. But this is not it, Next I’m gonna use T4 to generate Enums from values in Domain tables from database. Hope this would help someone looking for something like this.