Friday, March 16, 2012

ASP.Net MVC 3 : T4 Text templates for generating dynamic mail body

Actually there is no relation between ASP.Net MVC 3 and T4 Text templates. I added MVC in title as I learned template feature while working on registration module of an ASP.Net MVC 3 project. You can even have T4 Templates in console application.

The problem

As part of Azure ACS service our client wants to have our own custom identity provider which should stand with google and facebook. The specialty of our identity provider is, it can provide role details through claims as it uses simple ASP.Net membership. We selected thinktecture's IdentityServer and hosted in Azure. Initially we were hard coding the users and after successful implementation we started to think about registration. The target product is a mobile application and initial thought was to have a registration page in the website of the mobile app. But there are chances that a user may need to register from the mobile app when he finds it interesting . It is little difficult for him to go to the website and come back with his credentials. So decided to extend identity server to have registration.

As it is in agile model we started to write the module where we were able to complete registration with in hours. But when we talk to people we came to remember the normal registration process followed in other sites. ie a confirmation mail with code should be send and once confirmed a welcome mail.

How that confirmation code is generated is another story which I can tell in a future post. But that was one day job to complete and got it tested in Azure quickly. The system just sends a mail with confirmation link .When we opened the mail it never looked that much stylish like a production app. What is wrong with that ? Oh the contents. It's my English which sometime even I cannot understand .

Yes.Its not a developer's task to write stylish English and format the communication with colors and other stuff. Client has no ready made format for the mail at that point. But I needed to complete the module and switch to another important one. So how to give a customizable solution to this mailing problem where the developer will be free from changes in the mail content and style?


The proposals


There are so many solutions available to have customizable template based mailing solution such as
The solution - T4 Templates

The first 2 options needs one more nuget package into our application which we don't wan't as it is already flooded with nuget packages. They offer really sophisticated features in sending mails but we decided to go with the T4 templates method which don't want any new library to be added / installed.

Implementing T4 Templates for dynamic mails

It involves mainly 2 steps. Creating T4 template and render to get the actual text to be sent.

Creating T4 templates

It is easy as adding a .cs file. Right click on the project in solution explorer and select Add => New Item. In the dialog select C# => General => Preprocessed Text Template .The extension of the file will be '.tt'. It also generate a .cs along with that like a xaml or aspx file. You can have some thing as follows inside the template.


<#@ output extension=".txt" #>
<#@ template language="C#" #>
 
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
 <head>
  <title>Welcome to your site!</title>
 </head>
 <body>
  <strong>Welcome to your site !!</strong><br/>
  <br />
  Your confirmation code is : <i><#= this.ConfirmationCode #> </i>.
  <br /><br />
  You may use the above code in the confirmation screen or click on the below link to confirm your registration.
  <br/><br />
  Your confirmation link : <a href="<#= this.ConfirmLink + this.ConfirmationCode #>"><#= this.ConfirmLink + this.ConfirmationCode #></a> 
 </body>
</html>


You can see some inline code in the template what are they ? They are nothing but properties of the ConfirmMail class.Is there a class generated? How to add properties to the class > Is it by editing the design   er generated cs file? No.

Adding partial class for template & properties

If you want to add properties or methods to the T4 template you need to first add a partial class as new cs file. The challenge here is to have 2 files with same name. That is any way not possible.So have the naming convention as ConfirmMail.partial.cs. Add those properties there.

Code - ConfirmMail.partial.cs

    public partial class ConfirmMail
    {
        public string ConfirmationCode { getprivate set; }
        public string ConfirmLink { getprivate set; }
        public ConfirmMail(string confirmationCode, string confirmLink)
        {
            this.ConfirmationCode = confirmationCode;
            this.ConfirmLink = confirmLink;
        }
    }


NB: Don't add the properties in the generated file because each time the editor refresh those properties will be deleted

Rendering template

Now you have the template and the place holders to replace to values. The remaining task is to render the template with actual values. Its simple as creating an object of the class and calling the TransformText() method.


            var template = new ConfirmMail(confirmCode, confirmLink);
            return template.TransformText();

The method TransformText is not coming from any base class.Its just a virtual method in the generated ConfirmMail class.

IntelliSense support in editing T4 Templates

By default Visual studio don't have support for editing T4 templates. But you can install VSTS 2010 extensions such as VisualT4 to edit the templates with intelli sense support.

Please don't think that the application of T4 templates are only in sending mail. You can even generate dynamic code, views and so many other things. Hope you had a spike in your brain which initiated thoughts on application of T4 Templates


The code support doesn't stop with some property substitutions . You can have loops inside the T4 template like MVC RAZOR views. More details can be obtained from below links


Links
http://msdn.microsoft.com/en-us/library/ee844259.aspx

No comments: