Hot File

Template merging with NVelocity and ASP.NET

View: 2907    Dowload: 0   Comment: 0   Post by: naruto  
Author: none   Category: Embedded Systems   Fields: Other

0 point/5 review File has been tested

Download   template-merging-with.rar (326.10 KB)

You need to Sign In to download the file template-merging-with.rar
If you do not have an account then Sign up for free here

Download error   Report copyright violation

If you have ever tried to implement a newsletter system or a service for communicating with website users, you have probably faced the requisite to send multiple email messages with a common template and some differences, like a personalized greeting in the message header, or an unsubscribe link with a personalized querystring. Maybe the first way to accomplish this is by writing the static parts of the message in plain text files - for example: emailheader.txt, emailfooter.txt - and reassemble them in the code, merging the varying parts, like recipient's name, surname, personalized querystring link, and so on.

Introduction

But what about having a template engine which, given a template - be it a file on the file system, an assembly embedded resource, or an in-memory object - and the information we want to merge in the template, does this all for us?

"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. The purpose of this project is to port the Jakarta Velocity[^] project to Microsoft .NET (written in C#)."

Going back to the newsletter example, using NVelocity, the developer just needs to:

  • create a template for email messages specifying the parts that will have to be merged using a simple language called VTL (Velocity Template Language).
  • supply the information to be merged.

NVelocity will do the rest.

Background

In order to write NVelocity templates, a basic knowledge of the language it uses would be helpful. Anyway, in email templates, it's rarely necessary to write loops, methods, or branch conditions; instead, more often, the need is to replace single variables with values provided programmatically.

In this article, I'm going to show a simple way of writing templates, but if you think that you need something more complex, my advice is to read the VTL Reference Guide[^].

The notation for variables, as taken from the VTL Reference guide, is the following:

Notation (variable name):

$ [ ! ][ { ][ a..z, A..Z ][ a..z, A..Z, 0..9, -, _ ][ } ]

Examples:

  • Normal notation: $mud-Slinger_9
  • Silent notation: $!mud-Slinger_9
  • Formal notation: ${mud-Slinger_9}

About the article

In this article, I am going to show how I implemented a wrapper for NVelocity functionalities, which simplifies merging templates coming from a file system, assembly resources, or in-memory objects, and will build a simple web project for demonstration. The source code zip file contains the wrapper project, while the sample project zip file contains a web project which shows how to use it to merge templates in ASP.NET.

As a note, keep in mind that the wrapper can be used in any other project type, from console applications to Windows Forms and WebServices as well. I have chosen to build the demo in ASP.NET because it is a good compromise between a nice user interface and ease of creation.

Using the code

The main access point is the class NVelocityEngineFactory, which exposes three static methods. Each of these methods return an object that implements the INVelocityEngine interface, which can respectively be used to retrieve templates from embedded resources, file system, or memory. The boolean parameter required by each of the methods is used to specify whether the result of the merge has to be cached or not.

The three correspondent engine types are NVelocityAssemblyEngine, NVelocityFileEngine, and NVelocityMemoryEngine.

All of them inherit from the NVelocityEngineBase base class, which defines a common constructor and a static protected method.

Since implementing the INVelocityEngine interface, the three engine classes expose a public method with an overload called Process, which take two or three parameters and return a string or void.

In the first case, the two input parameters are the IDictionary object containing the values to be merged in the template and the template itself, while the return value is the merged template put in a string object.

In the second case, the additional parameter is a TextWriter object which, after the processing, will contain the merged template.

The template

To use the three types of engines, we need to create a template to be merged. Using VTL syntax, we write a simple template which can be used to render a message containing a simple personalized greeting, along with the date when the merging was done.

To test all of the three engines, the demo project contains a template file placed on the file system, a template file embedded in the assembly as a resource, and an in-memory template (a string) created at runtime.

To write a template file, we just need to open a text editor and save the file with the .vm extension.

Hi $name $surname, this output has been generated from a $templateType template on $date.

This is a very simple template, but it's not difficult to imagine in its place an entire HTML email with nice formatting and some images.

Using the wrapper along with the templates

Now, all we need to do is:

  • Create new instances of the template engines, supplying the information about the template. In order to process a file template, the directory of the template is needed, while processing an embedded resource template will require the assembly name. Finally, to process an in-memory object, no specific parameter is needed, the template will be supplied when the Process method of the engine is called.
  • Add some contents to an object implementing the IDictionary interface and pass it to the engine Process method.

File template

Supposing we have placed the template file in a subdirectory called Templates in the root folder of our web project and named it SimpleTemplate.vm:

string templateDir = HttpContext.Current.Server.MapPath("Templates");
string templateName = "SimpleTemplate.vm";

INVelocityEngine fileEngine = 
    NVelocityEngineFactory.CreateNVelocityFileEngine(templateDir, true);

IDictionary context = new Hashtable();

context.Add("name", TextBox1.Text);
context.Add("surname", TextBox2.Text);
context.Add("templateType", "file");
context.Add("date", DateTime.Now.ToString("D"));

LabelMergedFile.Text = fileEngine.Process(context, templateName);

The LabelMergedFile Text attribute will contain the text of the template and, in place of the variables, the values supplied in the code.

Embedded resource template

Supposing we have placed the template file in a subdirectory called EmbeddedResources in the root folder of our web project, named it SimpleTemplate.vm, and marked it as an embedded resource (under Visual Studio, this can be accomplished by right clicking the file, choosing Properties, and then setting the "Build Action" property to "Embedded Resource"):

string assemblyName = Assembly.GetExecutingAssembly().GetName().Name;

INVelocityEngine embeddedEngine = 
    NVelocityEngineFactory.CreateNVelocityAssemblyEngine(assemblyName, true);

IDictionary context = new Hashtable();

context.Add("name", TextBox1.Text);
context.Add("surname", TextBox2.Text);
context.Add("templateType", "embedded");
context.Add("date", DateTime.Now.ToString("D"));

LabelMergedEmbedded.Text = 
    embeddedEngine.Process(context, "EmbeddedResources.SimpleTemplate.vm"); 

Note that when calling the Process method, you need to specify the path of the resource, like in file system paths, but with dots in place of slashes.

In-memory template

Differently from the previous cases, now the template must reside in memory, so we create a string object that contains the template:

string template = "Hi $name $surname, this output has been " + 
                  "generated from a $templateType template on $date.";

INVelocityEngine memoryEngine =
    NVelocityEngineFactory.CreateNVelocityMemoryEngine(true);

IDictionary context = new Hashtable();

context.Add("name", TextBox1.Text);
context.Add("surname", TextBox2.Text);
context.Add("templateType", "memory");
context.Add("date", DateTime.Now.ToString("D"));

LabelMergedMemory.Text = memoryEngine.Process(context, template);

Note that the keys of the objects you place in the IDictionary object must correspond to the variable's names specified in the template if you want NVelocity to merge them. In case you forget to supply a key whose corresponding variable is contained in the template, NVelocity just forgets about it and will give in output $variablename.

Points of interest

I wrote this brief tutorial because I myself have been looking for something like this while I was implementing a newsletter service and after getting crazy at trying to merge the templates by hand.

NVelocity can do much more than this anyway, and if you want to find a place where NVelocity is truly "milked", you should take a look at CastleProject[^], where they use it as a view engine in their MonoRail[^] project.

The sad thing about NVelocity is that the project is almost dead; the latest release, 0.4.2, is dated October 27, 2003.

The positive thing is that CastleProject developers have made a fork of the project, fixed some bugs, and killed a tedious assembly dependence on an old Log4Net distribution, which NVelocity used as the internal logger engine.

Actually, this NVelocity fork has reached version 0.5, which is the one I have included in the sample project, and whose source can be found in CastleProject's SVN repository.

Template merging with NVelocity and ASP.NET

Template merging with NVelocity and ASP.NET Posted on 14-05-2014  If you have ever tried to implement a newsletter system or a service for communicating with website users, you have probably faced the requisite to send multiple email messages with a common template and some differences, like a personalized greeting in the message header, or an unsubscribe link with a personalized querystring. Maybe the first way to accomplish this is by writing the static parts of the message in plain text files - for example: emailheader.txt, emailfooter.txt - and reassemble them in the code, merging the varying parts, like recipient's name, surname, personalized querystring link, and so on. 5/10 2907

Comment:

To comment you must be logged in members.

Files with category

  • OpenTheme : An open source graphic user interface (GUI) toolkit

    View: 4197    Download: 2   Comment: 0   Author: none  

    OpenTheme : An open source graphic user interface (GUI) toolkit

    Category: Embedded Systems
    Fields: Other

    0.29591836734694/49 review
    OpenTheme is an XML based GUI toolkit with a set of foundation class and WYSIWYG editor. Although it's originally designed for full screen GUI, it is also good for Windowed user interface, with full localization support and arbitary...

  • Design State Machine Engine for embedded system development

    View: 3364    Download: 2   Comment: 0   Author: none  

    Design State Machine Engine for embedded system development

    Category: Embedded Systems
    Fields: none

    0/5 review
    Embedded systems are some special purpose computers that are used inside of devices. Embedded systems generally use micro controllers that contain many functions of a computer on a single device. Embedded systems have to tightly work together with...

  • The StateWizard VC++ Add-in and Engine with Source Code

    View: 3859    Download: 0   Comment: 0   Author: none  

    The StateWizard VC++ Add-in and Engine with Source Code

    Category: Embedded Systems
    Fields: none

    0/7 review
    In an environment where software systems are more and more complex, concurrent, and real-time oriented, the choice of modeling languages and tools becomes the success key for many projects. This article introduces a cross-platform state-oriented...

  • Template merging with NVelocity and ASP.NET

    View: 2907    Download: 0   Comment: 0   Author: none  

    Template merging with NVelocity and ASP.NET

    Category: Embedded Systems
    Fields: Other

    0/5 review
    If you have ever tried to implement a newsletter system or a service for communicating with website users, you have probably faced the requisite to send multiple email messages with a common template and some differences, like a personalized greeting...

  • Use PowerShell to Manage your Intel AMT Data

    View: 1894    Download: 0   Comment: 0   Author: none  

    Use PowerShell to Manage your Intel AMT Data

    Category: Embedded Systems
    Fields: Other

    0.45/10 review
    This article is in the Product Showcase section for our sponsors at CodeProject. These reviews are intended to provide you with information on products and services that we consider useful and of value to developers.

  • A C++ Embedded Web Server

    View: 3063    Download: 1   Comment: 0   Author: none  

    A C++ Embedded Web Server

    Category: Embedded Systems
    Fields: Other

    0.75/6 review
    Do you have a web page or two? Nothing fancy, perhaps, but a neat demonstration of what can be achieved with a handful of HTML tags? Do you have a sophisticated C++ Windows desktop application which now needs to be controlled and monitored remotely?...

  • Java/.NET Integration as Simple as Possible

    View: 1487    Download: 2   Comment: 0   Author: none  

    Java/.NET Integration as Simple as Possible

    Category: Embedded Systems
    Fields: Other

    0/3 review
    For a number of years, I have been developing software for integrating applications written in different platforms. And in my business, I face with interoperability issues: Java and C++, Java and COM, Java and .NET. To solve them, I have developed a...

  • Writing a 16-bit dummy kernel in C/C++

    View: 2666    Download: 3   Comment: 0   Author: none  

    Writing a 16-bit dummy kernel in C/C++

    Category: Embedded Systems
    Fields: Other

    0/11 review
    In my previous articles I was only briefing about on how to write a boot loader. That was fun and challenging. I enjoyed it a lot. But after learning how to write a boot-loader I wanted to write much better stuff like embedding more functionality...

 
Newsletter Email

File suggestion for you

File top downloads

logo codetitle
Codetitle.com - library source code to share, download the file to the community
Copyright © 2015. All rights reserved. codetitle.com Develope by Vinagon .Ltd