NVelocity extension method ASP.NET webform

942 views Asked by At

I was wondering if it's possible to use an extension method with asp.net webforms and nvelocity. I would like to set some defaults if the string value is null or empty.

Example of .vm file:

    Example of my email body...

    Billable Status: $billableStatus.Evaluate()

    rest of my email body...

Attempted extension method:

public static class Helper
{
    public static string Evaluate(this string value)
    {
        if (String.IsNullOrEmpty(value))
            return "Not Provided";
        else
            return value;
    }
}

Or is there an alternative to what I'm tryting to accomplish?

2

There are 2 answers

0
Mauricio Scheffer On BEST ANSWER

I don't think NVelocity can resolve extension methods with C#/VB.NET syntax sugar. What I do is register an instance of a helper in the velocity context:

var context = VelocityContext();
context.Put("helper", new Helper());
context.Put("billableStatus", "something");
...

and then in your template:

$helper.Evaluate($billableStatus)

You have to make your helper non-static for this to work, of course.

0
Mazhar Qayyum On

I came across something similar in past and I was looking for something more sophisticated and with more control. I found that NVelocity does provide a way to intercept the method and property calls but for that you will have to implement certain things. In order to make your custom interceptor you will need to implement NVelocity.IDuck. For example


    public class MyClass : NVelocity.IDuck
    {
        public object GetInvoke(string propName)
        {
            ....
        }

        public object Invoke(string method, params object[] args)
        {
            ....
        }

        public void SetInvoke(string propName, object value)
        {
            ....
        }
    }

Now any instance of MyClass will intercept and pass the method and property calls to our these three function implementation and give us a chance to resolve and return the output. You may notice from these three function signatures that in order to implement them we may need some reflection where we can locate respective methods on available extension types and execute them. If needed you can read following blog post for more details about going this way. NVelocity and extension methods