Wednesday, February 14, 2018

TDS code generation in Sitecore with Glass Mapper

Team Development for Sitecore is a great tool for reducing deployment time by making it nice and easy to move Sitecore items between environments. Likewise Glass Mapper provides ORM functionality from those same Sitecore items into your code (it gives you models of Sitecore item and provides decouples the Sitecore API for item access).

A great feature available with TDS is code generation. What this means is that any template that you serialize into a TDS template can automatically generate a model ready for use. This saves a lot of development time along with minimizing the chance for error. Gone are the days where a slight misspelling on the hand written model would cause problems, as would someone changing the template and forgetting to update the model.

Setting up code generation for TDS

The first step is to download the Text Template Transformation Toolkit (T4) templates for TDS. These are used to generate the C# models. The download is available on Github, and it's the files ending in .tt that we are after. I will often add these to a folder in the solution where they can be referenced by all TDS projects.

T4 templates for TDS

In the project where the output of code generation will go we need the following:
  • In the root of the project you need a class where the models will be output, I generally call mine Master.cs.
  • A reference to the Glass.Mapper.Sc nuget package.
  • A reference to the Sitecore.Kernel.dll for the version of Sitecore your instance is developed on. I use the Sitecore public nuget feed for this.
In the TDS project the following needs to be setup:
  • On the code generation tab, check the box to Enable Code Generation.
  • This will cause a Code Generation Templates item to appear under the TDS project in visual studio. On this node right add the T4 templates (add existing items).
  •  
    A tip for this is to select Add as link, which allows all TDS projects to share the same T4 templates rather than creating a copy per project.
  • On the code generation tab for the TDS project:
    • Select the target project where the code will be output
    • Select the file which will contain the models (this needs to be in the root of the project).
    • Select the base namespace for the file.
    • Reference the header transform file - GlassV3Header.tt
    • Reference the base project transform file - GlassV3Item.tt
  • Check the target file (master.cs), the models should have auto-generated.
It is also possible to have all code regenerate for a TDS project by right clicking it and selecting Re-Generate Code for All Items.

My solution for this example, looked as follows:

Example solution for TDS code generation

No comments:

Post a Comment