tags:

views:

76

answers:

1

I am using codeplex NVelocity library on .net and i want to catch an error when I execute Evalute method on VelocityEngine instance and one of the parameter in template text was not found.

How can I obtain this?

I find IInvalidReferenceEventHandler interface in NVelocity.App.Event namespace but I dont't find any information how to use it. Any help will be appreciated.

+1  A: 

I've found the solution.

I've made EventHandler class:

public class NVelocityEventHandler : IInvalidReferenceEventHandler, IMethodExceptionEventHandler
{
     #region IInvalidReferenceEventHandler Members

     public object InvalidGetMethod(NVelocity.Context.IContext context, string reference, object object_Renamed, string property, NVelocity.Util.Introspection.Info info)
     {
      return "InvalidGetMethod:" + reference;
     }

     public object InvalidMethod(NVelocity.Context.IContext context, string reference, object object_Renamed, string method, NVelocity.Util.Introspection.Info info)
     {
      return "InvalidMethod:" + reference;
     }

     public bool InvalidSetMethod(NVelocity.Context.IContext context, string leftreference, string rightreference, NVelocity.Util.Introspection.Info info)
     {
      return true;
     }

     #endregion

     #region IMethodExceptionEventHandler Members

     object IMethodExceptionEventHandler.MethodException(Type claz, string method, Exception e)
     {
      return "MethodException:" + method;
     }

     #endregion 
}

Then I use it in the code below:

StringWriter writer = new StringWriter();
NVelocity.App.VelocityEngine eng = new NVelocity.App.VelocityEngine();
try
{
    NVelocityEventHandler te = new NVelocityEventHandler();
    EventCartridge ec = new EventCartridge();
    ec.AddEventHandler(te);
    VelocityContext vc = new VelocityContext((IDictionary)parameters);
    ec.AttachToContext(vc);
    eng.Evaluate(vc, writer, "templatestring", template);
}
catch (ParseErrorException pe)
{
    return pe.Message;
}
catch (MethodInvocationException mi)
{
    return mi.Message;
}
Peter Starbek