htmlentities in ASP.NET + MonoRail + NVelocity October 23, 2009

Recycle BinLet’s imagine you started an ASP.NET project while Microsoft’s MVC framework (cheekily named “MVC”) was not yet “production-ready”, or if you do not consider it production-ready yet. Let’s say that you eschewed the ridiculously last-century (if ever) WebForms, in favour of something a little more modern. Your choice of framework would be limited to, well, Castle Project’s MonoRail.

MonoRail makes the best of a bad situation. I commend Castle Project on the work that has gone into it. And it seems to embrace the C# idiom.

For a template engine, I chose NVelocity. It seemed a sensible choice. And it has nice “foreach” loops.

Imagine my surprise when it turned out that it has no quick way to escape strings.

Huh? Surely not?

Let’s recap.

PHP:

	<?php print htmlentities($plaintext); ?>

Django pre-1.0:

	{{ plaintext|escape }}

Django post-1.0:

	{{ plaintext }}

C# ASP.NET + MonoRail + NVelocity:

MyProject/Helpers/HttpUtilityHelper.cs:

	using System;
	using System.Web;

	namespace MyProject.Helpers
	{
		public class HttpUtilityHelper
		{
			public string HtmlEncode(string plaintext)
			{
				return HttpUtility.HtmlEncode(plaintext);
			}

			public string UrlEncode(string plaintext)
			{
				return HttpUtility.UrlEncode(plaintext);
			}

		}
	}

MyProject/Controllers/SomeOrOtherController.cs:

	...
	using MyProject.Helpers;
	...
	namespace MyProject.Controllers
	{
		[Helper(typeof(HttpUtilityHelper))]
		public class  SomeOrOtherController : BaseController
		{
			...
		}
	}

MyProject/Views/SomeOrOther/index.vm:

	$HttpUtilityHelper.HtmlEncode($plaintext)

On the other hand, you could save yourself a lot of hassle, and explore other platform options. Don’t be afraid of learning a new language. It might save you a lot of time in the log run.

Leave a Reply