Monday, January 10, 2011

nVelocity to render templates

nVelocity is a .Net-based template engine. It permits anyone to use the simple yet powerful template language to reference objects defined in .Net code. I use this template engine for rendering the mail templates in my application. This is a wonderful framework, with a defined syntax to render field values inside the template. For those who do not know, project is a port of the Jakarta Velocity to Microsoft .Net (written in C#). This is a discontinued project, but the Castle project fork  enhanced it to support their monorail implementation. There are different versions available, I used one from Castle project website which has a lot of bug fixes and features incorporated than the original.

Below is the sample code to illustrate nVelocity to render mail template.

using System;
using System.Collections.Generic;
using System.IO;
using Commons.Collections;
using NVelocity;
using NVelocity.App;
using System.Collections;

namespace NVelocitySample
{
class Program
{
static VelocityEngine velocity;
static void Main(string[] args)
{
InitializeVelocity();

string output = GenerateOutput();
Console.WriteLine(output);
}

private static void InitializeVelocity()
{
ExtendedProperties properties = new ExtendedProperties();

velocity = new VelocityEngine(properties);
}


private static string GenerateOutput()
{
Message mail = new Message();


mail.From = "sender@company.com";
mail.To = "recipient@company.com";
mail.Subject = "This a mail render example";
mail.Body = "This is the body where replace a dictionary to show the versatility of nVelocity";


Dictionary<string, string> coll = new Dictionary<string, string>();
coll["key"] = "Hi,";



string stringData = "From: $mail.From \n";
stringData += "To: $mail.To \n\n";
stringData += "Subject: $mail.Subject \n\n";
stringData += "$coll.get_Item('key') $mail.Body";


Hashtable hashTable = new Hashtable();
hashTable.Add("mail", mail);
hashTable.Add("coll", coll);

VelocityContext context = new VelocityContext(hashTable);

StringWriter generated = new StringWriter();
StringReader reader = new StringReader(stringData);
velocity.Evaluate(context, generated, "nVelocityLog", reader);
return generated.GetStringBuilder().ToString();


}


class Message
{
private string from;
private string to;
private string subject;
private string body;

public string From
{
get { return from; }
set { from = value; }
}

public string To
{
get { return to; }
set { to = value; }
}

public string Subject
{
get { return subject; }
set { subject = value; }
}

public string Body
{
get { return body; }
set { body = value; }
}
}

class Coll
{
Dictionary<string, string> fields = new Dictionary<string, string>();

public Dictionary<string, string> Fields
{
get { return fields; }
set { fields = value; }
}
}
}
}




No comments:

Post a Comment