Basic Introduction about T4 Templates & How to customize them for ASP.NET MVC Project

In ASP.Net MVC 3 you can easily generate views from predefined scaffolding templates provided for Create, Edit, List, Delete and Details views out of the box which seems quite riveting. Actually, there are some *.tt template files (known as T4 templates) stored at following path C:\Program Files\Microsoft Visual Studio 10.0\Common7\IDE\ItemTemplates\CSharp\Web that contains the basic structure and page layout for these views and based on those templates it generates the Create, Edit, Delete, List, Details and Empty .cshtml or .aspx files depends on which project language you have chosen for ASP.Net MVC project.

In this post I will discuss about T4 templates and how we can customize by taking a simple example.

What is T4

T4 stands for Text Template Transformation Toolkit. T4 generates text based on Text based template files, Template is a combination of text and control logic that you can define using C# or VB.net. Transformation actually executes the code written in template and brings out a final output whereas the Toolkit contains some assemblies leverage to produce the desire output file.

Now, let’s quickly open the sample Create.tt file to see what it looks like and how we can customize. When you open the file you can see directives

<#@ template language=”C#” HostSpecific=”True” #>

<#@ output extension=”.cshtml” #>

language specifies which language we are using either C# or VB.net and HostSpecific =”True” used only with custom hosts. If you set the value of parameter to true, you can access a property called Host in your text template. The property is a reference to the object that hosts the engine. At last, the output extension tells the extension in which the new file this will be generated.

T4 contains 4 types of blocks

  • Expression block

    Used as <#= expression #>, we can write C# or VB.net code but don’t use semi-colon at the end of statement

  • Statement block

    Used as <# code…. #>, define any C# or VB.net code and initialize variables, define loops etc. Here we have to specify semi-colon at the end of the code statement just like as we program in a class file.

  • Class feature block

    Used as <#+ code… #>, define methods, classes, properties and constants and can we called from anywhere within the template file. For example, we can create a function that perform some calculation based on the parameters passed and return a Boolean through which we can handle the UI designing.

Below is the actual page content that dynamically generates the page based on the model attached to it.

@using (Html.BeginForm()) {

@Html.ValidationSummary(true)

<fieldset>

<legend><#= mvcHost.ViewDataType.Name #></legend>

<#

foreach (ModelProperty property in GetModelProperties(mvcHost.ViewDataType)) {

if (!property.IsPrimaryKey && !property.IsReadOnly && property.Scaffold) {

#>

<div class=”editor-label”>

<#

if (property.IsForeignKey) {

#>

@Html.LabelFor(model => model.<#= property.Name #>, “<#= property.AssociationName #>”)

<#

} else {

#>

@Html.LabelFor(model => model.<#= property.Name #>)

<#

}

#>

</div>

<div class=”editor-field”>

<#

if (property.IsForeignKey) {

#>

@Html.DropDownList(“<#= property.Name #>”, String.Empty)

<#

} else {

#>

@Html.EditorFor(model => model.<#= property.Name #>)

<#

}

#>

@Html.ValidationMessageFor(model => model.<#= property.Name #>)

</div>

<#

}

}

#>

<p>

<input type=”submit” value=”Create” />

</p>

</fieldset>

}

<div>

@Html.ActionLink(“Back to List of Main Page”, “Index”)

</div>

In the above mentioned code there is if statement that checks whether the property is a foreign key or not and based on that it generates a drop down code otherwise an input control.

Let’s create a sample application in ASP.Net MVC 3 and check it out by customizing a Create T4 template.

  1. Create a sample project in ASP.Net MVC3 in Visual Studio.
  2. Create a model class for Person and Designation. Person record contains some basic information and Designation holds the list of designations. Below is the Code First model Approach using Entity Framework ver. 4.3.1.


    public
    class
    Person    

    {


    public
    long PersonId { set; get; }


    public
    String FirstName { set; get; }


    public
    String LastName { set; get; }


    public
    String EmailAddress { set; get; }


    public
    String Phone { set; get; }


    public
    long DesignationId { set; get; }


    public
    virtual
    Designation Designation { set; get; }

    }


    public
    class
    Designation

    {


    public
    long DesignationId { set; get; }


    public
    String DesignationName { set; get; }


    public
    virtual
    ICollection<Person> Persons { get; set; }

    }

  3. Create a DBContext class and define DBSet for these entities.

public
class
DBContext : System.Data.Entity.DbContext, IDisposable

{


public
DbSet<Person> Persons { get; set; }


public
DbSet<Designation> Designations { set; get; }

}

  1. Now create a Person controller selecting Controller with read/write actions and select Person as a Model class and DB Context as you Database Context class.

  1. Now if you open the Create.cshtml file you will see a drop down list for designation. As in the template file there was a foreign key check. If you run the application form will be shown as below.

  1. Now let’s change a drop down to list box in the Create.tt file.

    <div class=”editor-field”>

    <#

    if (property.IsForeignKey) {

    #>


    @Html.ListBox(“<#= property.Name #>”)

    <#

    } else {

    #>

    Is not a foreign key baba: <#= property.IsForeignKey #> : @Html.EditorFor(model => model.<#= property.Name #>)

    <#

    }

    #>

    @Html.ValidationMessageFor(model => model.<#= property.Name #>)

    </div>

  1. Delete the previous controller and generate it again. It will generate a ListBox as specified in a tt file.

This was the simple example showing how developers can modify existing templates based on their needs and reduce development time. Hope this helps!

Using Enterprise Library Validation Application Block in WCF

Validation plays an important role in any messaging communication between distributed systems and especially when you are designing a SOA where the service is consumed by many third party consumers.

In this post I will show how to leverage the Enterprise Library Validation Application Block to apply validation on WCF Service contracts that really makes the task very easy for the developers to apply validations.

Develop Service
I will create a simple project that shows how one can apply validation on Service contracts in WCF.

  1. First of all create a Simple WCF Service Application Project in Visual Studio
  2. Add a reference to Microsoft.Practices.EnterpriseLibrary.Validation.Integration.WCF assembly.

  3. Open the Service Interface (by default it generated IService) and apply the class level attribute “ValidationBehavior” on service’s interface. ValidationBehavior is Validation Application Block Service Behavior and is responsible to validate requests. Now you need to apply the FaultContract and specify the type of data that holds the information about the error.

            FaultContract is used to communicate error from service to client.
     [ServiceContract]

     [ValidationBehavior]
     public interface IService1

 {
   [OperationContract]

   [FaultContract(typeof(ValidationFault))]
   string Execute(Name value);
 }
In the above code you can see there is a Name class object passed as a parameter in Execute    function.

     4.  Now implement the Service Contract interface in HelloWorldService class.

    public class HelloWorldService :IService1{
      public string Execute(Name name){
        return string.Format(“your name is {0} {1}”, name.FirstName, name.LastName);
      }
    }

5. This Name class is the Service’s DataContract. Below is the code snippet for Name class

    [DataContract]
    public class Name {
      [StringLength(25, MinimumLength=1, ErrorMessage=“First Name length is not correct”)]
      [DataMember]
      public String FirstName{ set; get; }

      [StringLength(25, MinimumLength = 1, ErrorMessage = “Last Name length is not correct”)]
      [DataMember]
public string LastName { set; get; }

}
In the above code, I have specified two properties of String type and applied Data Annotations attribute for String length validation. You can apply as many validations as you want.

Consume Service

6. Create a sample console project in Visual Studio to test.

7. Add a service reference by clicking on the Service References in Visual Studio.

8. Initialize service instance

9. Call Execute function and pass invalid string values.

   static void Main(string[] args) {
      var name = new Name { FirstName = “”, LastName = “” };
      var client = new ConsoleApplication1.Services.Service1.Service1Client();
      try{ Console.WriteLine(client.SayHello(name)); }
catch (FaultException<ValidationFault> fault)
      {
         foreach (var detail in fault.Detail.Details)
{
               Console.WriteLine(“{0}:{1}”, detail.Key, detail.Message); }
      }
      client.Close();
      Console.ReadLine();
    }

10. In the above code I have passed Name object with empty string values to test whether the service is validating or not and here is the result.