Cannot compile template with Lookup helper - signature or security transparency is not compatible - handlebars.net

I'm trying to use the following template (TestTemplate) in a console application using .NET Core 2.1 and Handlebars.Net 1.9.5
<html>
<head>
<title>A title</title>
</head>
<body>
{{ > (lookup TemplateName)}}
</body>
</html>
So the line with {{ > (lookup TemplateName)}} is causing me problems.
The idea is to use a partial, where the partial name will be resolved later by passing the TemplateName variable.
However, when I try to compile the template by using
var foo = Resource1.TestTemplate;
Handlebars.Compile(Encoding.UTF8.GetString(foo));
I get the following exception :
System.ArgumentException: Cannot bind to the target method because its signature or security transparency is not compatible with that of the delegate type.
at System.Reflection.RuntimeMethodInfo.CreateDelegateInternal(Type delegateType, Object firstArgument, DelegateBindingFlags bindingFlags)
at HandlebarsDotNet.Compiler.SubExpressionVisitor.GetHelperDelegateFromMethodCallExpression(MethodCallExpression helperCall)
at HandlebarsDotNet.Compiler.SubExpressionVisitor.VisitSubExpression(SubExpressionExpression subex)
at System.Linq.Expressions.ExpressionVisitor.VisitUnary(UnaryExpression node)
at System.Linq.Expressions.UnaryExpression.Accept(ExpressionVisitor visitor)
at System.Dynamic.Utils.ExpressionVisitorUtils.VisitArguments(ExpressionVisitor visitor, IArgumentProvider nodes)
at System.Linq.Expressions.ExpressionVisitor.VisitMethodCall(MethodCallExpression node)
at System.Linq.Expressions.MethodCallExpression.Accept(ExpressionVisitor visitor)
at System.Linq.Expressions.ExpressionVisitor.VisitUnary(UnaryExpression node)
at System.Linq.Expressions.UnaryExpression.Accept(ExpressionVisitor visitor)
at System.Linq.Expressions.ExpressionVisitor.VisitConditional(ConditionalExpression node)
at System.Linq.Expressions.ConditionalExpression.Accept(ExpressionVisitor visitor)
at System.Dynamic.Utils.ExpressionVisitorUtils.VisitBlockExpressions(ExpressionVisitor visitor, BlockExpression block)
at System.Linq.Expressions.ExpressionVisitor.VisitBlock(BlockExpression node)
at System.Linq.Expressions.BlockExpression.Accept(ExpressionVisitor visitor)
at HandlebarsDotNet.Compiler.FunctionBuilder.Compile(IEnumerable1 expressions, Expression parentContext, String templatePath) --- End of inner exception stack trace --- at HandlebarsDotNet.Compiler.FunctionBuilder.Compile(IEnumerable1 expressions, Expression parentContext, String templatePath)
at HandlebarsDotNet.Compiler.FunctionBuilder.Compile(IEnumerable1 expressions, String templatePath) --- End of inner exception stack trace --- at HandlebarsDotNet.Compiler.FunctionBuilder.Compile(IEnumerable1 expressions, String templatePath)
at HandlebarsDotNet.Handlebars.HandlebarsEnvironment.Compile(String template)
I hope someone has an idea, because I've already been searching quite some time.

Ok I totally missed that I was looking at the HandleBars.js documentation.
In HandleBars.js the lookup helper is built-in, but so far, it isn't in the .net version.
So you have to declare the lookup helper yourself, which in my case goes something like this:
Handlebars.RegisterHelper("lookup", (output, context, arguments) => { output.WriteSafeString(arguments[0]); });
Hope it can help someone else.

Related

Micronaut - Thymeleaf - #request is null

I started working on a Micronaut 2.57 application with Thymeleaf 3.0.12 and micronaut-views-thymeleaf 2.21 that can present some views. According to the Thymeleaf docs, I should have the #request object but I think I always get null.
The thymeleaf template looks like:
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<title>Home</title>
</head>
<body>
<h3>#request.contextPath</h3>
<span th:utext="${#request.contextPath}"></span>
<h3>#request.requestURI</h3>
<span th:utext="${#request.requestURI}"></span>
<h3>#request.requestURL</h3>
<span th:utext="${#request.requestURL}"></span>
</body>
</html>
The controller to present the view:
import io.micronaut.http.HttpResponse;
import io.micronaut.http.annotation.Controller;
import io.micronaut.http.annotation.Get;
import io.micronaut.views.View;
#Controller
public class HomeController {
#View("home2")
#Get("/")
public HttpResponse<Object> showHome() {
return HttpResponse.ok();
}
}
After starting the application and browsing to localhost:8080, I receive the following stacktrace which indicates that the #request does not exist
17:52:57.326 [main] INFO io.micronaut.runtime.Micronaut - Startup completed in 2231ms. Server Running: http://localhost:8080
17:53:06.644 [io-executor-thread-1] ERROR org.thymeleaf.TemplateEngine - [THYMELEAF][io-executor-thread-1] Exception processing template "home2": Exception evaluating OGNL expression: "#request.contextPath" (template: "home2" - line 8, col 7)
org.thymeleaf.exceptions.TemplateProcessingException: Exception evaluating OGNL expression: "#request.contextPath" (template: "home2" - line 8, col 7)
at org.thymeleaf.standard.expression.OGNLVariableExpressionEvaluator.evaluate(OGNLVariableExpressionEvaluator.java:191)
at org.thymeleaf.standard.expression.OGNLVariableExpressionEvaluator.evaluate(OGNLVariableExpressionEvaluator.java:95)
at org.thymeleaf.standard.expression.VariableExpression.executeVariableExpression(VariableExpression.java:166)
at org.thymeleaf.standard.expression.SimpleExpression.executeSimple(SimpleExpression.java:66)
at org.thymeleaf.standard.expression.Expression.execute(Expression.java:109)
at org.thymeleaf.standard.expression.Expression.execute(Expression.java:138)
at org.thymeleaf.standard.processor.StandardUtextTagProcessor.doProcess(StandardUtextTagProcessor.java:87)
at org.thymeleaf.processor.element.AbstractAttributeTagProcessor.doProcess(AbstractAttributeTagProcessor.java:74)
at org.thymeleaf.processor.element.AbstractElementTagProcessor.process(AbstractElementTagProcessor.java:95)
at org.thymeleaf.util.ProcessorConfigurationUtils$ElementTagProcessorWrapper.process(ProcessorConfigurationUtils.java:633)
at org.thymeleaf.engine.ProcessorTemplateHandler.handleOpenElement(ProcessorTemplateHandler.java:1314)
at org.thymeleaf.engine.OpenElementTag.beHandled(OpenElementTag.java:205)
at org.thymeleaf.engine.TemplateModel.process(TemplateModel.java:136)
at org.thymeleaf.engine.TemplateManager.parseAndProcess(TemplateManager.java:661)
at org.thymeleaf.TemplateEngine.process(TemplateEngine.java:1098)
at org.thymeleaf.TemplateEngine.process(TemplateEngine.java:1067)
at io.micronaut.views.thymeleaf.ThymeleafViewsRenderer.render(ThymeleafViewsRenderer.java:109)
at io.micronaut.views.thymeleaf.ThymeleafViewsRenderer.lambda$render$1(ThymeleafViewsRenderer.java:96)
at io.micronaut.core.io.Writable.writeTo(Writable.java:77)
at io.micronaut.http.server.netty.RoutingInBoundHandler.lambda$encodeHttpResponse$7(RoutingInBoundHandler.java:1683)
at io.micronaut.scheduling.instrument.InvocationInstrumenterWrappedRunnable.run(InvocationInstrumenterWrappedRunnable.java:47)
at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128)
at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628)
at java.base/java.lang.Thread.run(Thread.java:829)
Caused by: ognl.OgnlException: source is null for getProperty(null, "contextPath")
at ognl.OgnlRuntime.getProperty(OgnlRuntime.java:3229)
at ognl.ASTProperty.getValueBody(ASTProperty.java:114)
at ognl.SimpleNode.evaluateGetValueBody(SimpleNode.java:212)
at ognl.SimpleNode.getValue(SimpleNode.java:258)
at ognl.ASTChain.getValueBody(ASTChain.java:141)
at ognl.SimpleNode.evaluateGetValueBody(SimpleNode.java:212)
at ognl.SimpleNode.getValue(SimpleNode.java:258)
at ognl.Ognl.getValue(Ognl.java:537)
at ognl.Ognl.getValue(Ognl.java:501)
at org.thymeleaf.standard.expression.OGNLVariableExpressionEvaluator.executeExpression(OGNLVariableExpressionEvaluator.java:328)
at org.thymeleaf.standard.expression.OGNLVariableExpressionEvaluator.evaluate(OGNLVariableExpressionEvaluator.java:170)
... 23 common frames omitted
Does anyone know why this variable might not be passed to the template?
Other variables that I've tested:
#locale - works
#ctx - works
#request - always null
#response - always null
#session - always null
#servletContext - always null
The io.micronaut.views.thymeleaf.ThymeleafViewsRenderer passes a WebContext to the engine it's rendering, so I'm clueless why these objects are not accessible.
Any pointers are appreciated.
EDIT: I've debugged somewhat further and this is the list of keys that the contextVariableMap contains: [ctx, root, vars, object, locale, request, response, session, servletContext, conversions, uris, calendars, dates, bools, numbers, objects, strings, arrays, lists, sets, maps, aggregates, messages, ids, execInfo, httpServletRequest, httpSession] but the servletContext,httpServletRequest, request are all null.
Second edit: looking even deeper I stumbled across
if (REQUEST_EXPRESSION_OBJECT_NAME.equals(expressionObjectName)) {
if (context instanceof IWebContext) {
return ((IWebContext) context).getRequest();
}
return null;
}
in the org.thymeleaf.standard.expression.StandardExpressionObjectFactory. The passed context is of type WebEngineContext, which should implement IWebContext but the instanceof evaluation is false...
Diving even deeper now.
Looking into the creation of the WebEngineContext I stumble on this class: o.micronaut.views.thymeleaf.WebEngineContext which is defined as public class WebEngineContext extends EngineContext. This is different from the org.thymeleaf.context.WebEngineContext that implements the interface to resolve #request.
It turns out that there is a incompatibility with Micronaut and the Thymeleaf Servlet objects. I've reported the issue https://github.com/micronaut-projects/micronaut-views/issues/241 and we'll see from there.
At the moment you can use #ctx.getRequest() to get the instance of the io.micronaut.http.server.netty.NettyHttpRequest.
The other objects are still a mystery for me too.

java struts2 very strange behaviour while using iterator

public class UserAction{
private UserData user;
//getter, setter
public String Load() {
user = UserDao.getInstance().getItem(getUserContext().getId());
request.getSession().setAttribute("item", user);
return super.Load();
}
}
public class PropertyAction {
private List <PropertyData> propertyList;
//getter, setter
#Override
public String execute() throws Exception {
propertyList=PropertyDao.getInstance().getItems();
return "list";
}
}
jsp:
<s:iterator value="propertyList" var="item">
${item.name}
${item.thema}
${item.desc}
</s:iterator>
I want to show very strange behaviour of Struts2.
I click property link -> then run PropertyAction.execute() and it display above jsp.
I click user link -> then run UserAction.Load()
I click property link -> then run PropertyAction.execute() and error has been shown "UserData has no property thema".
I spy what happened and I notice that I set setAttribute with name "item". So if I use var="item" in my iterator in jsp, it doesn not use value from propertyList but from session !
My question is it is correct behaviour ?
This is defined behavior; whether or not it's "correct" is debatable.
Because you're using JSP EL, the Struts request wrapper is responsible for resolving JSP EL expressions. The normal application scopes are searched first (e.g., application, session, request). If nothing is found, only then will the value stack be queried for matching expressions.
If you accessed item via non-JSP EL means, e.g., the <s:property> tag, only the value stack would be queried, and you'd get the expected behavior.
When you mix ELs results are not always what you'd expect, so you must be aware how the frameworks in question relate to each other.

Proxem Stanford Parser asp MVC

I'm using Proxem wrapper for Stanford Parser and I'm facing problem with Parsing in ASP.NET MVC 3 and 4 application. It throws
System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---> System.NullReferenceException: Object reference not set to an instance of an object.
at Proxem.Antelope.Parsing.Sentence.a(List`1 A_0)
at Proxem.Antelope.Parsing.Sentence..ctor(SerializationInfo info, StreamingContext ctxt)
--- End of inner exception stack trace ---
In WPF and console application it works fine.
I fixed it. Constructor Parser(string path) is invoking constructor Parser(string path, int poolsize) with poolsize value = 1. Using constructor Parser(string path, int poolsize) with values -> Parser(yourPath, 0) make it work with MVC and WCF.

InvalidOperationsException during XML-Serialization in XNA

I have a question concerning an Error I experience while trying to read an XML-File through the XNA 4.0 Content Pipeline in order to build Objects. First I reused old XNA 3.1 Code of mine which worked back in the day but now throws the an Error Message:
Building content threw InvalidOperationException: Instanzen von abstrakten Klassen können nicht erstellt werden. (Unable to build Instances of abstract Classes - roughly translated)
at ReflectionEmitUtils()
...and goes on forever, I can post it, if it's needed, but for better readability of my initial request..
Then I used this Method but it throws the same error.
These are the relevant pieces of source code:
I've written a class to define the content/structure of the XML-File:
public class Command
{
public List<bool> mButtons;
public List<Keys> keys;
public Enum iD;
}
And this is my XML File, with which I want to build Command-Objects
<?xml version="1.0" encoding="utf-8" ?>
<XnaContent>
<Asset Type="KinectRTS_Input.Command">
<mButtons>true/mButtons>
<keys>
<Item>LeftControl/Item>
</keys>
<iD>SMulti/iD>
</Asset>
</XnaContent>
(In my code, the Brackets are all correct, though since this Form processes XML-Tags...;))
I used a Test-Application in order to find out, which Format the XNA-Serializer uses to output List-Items and enums, so I'm reasonably sure, that there's not the error.
It looks like either your XML is invalid or your Model is. For the mButtons field, you have defined it as a List<bool> but in the XML it's a bool not a List<bool>. I would either edit the XML to have the <mButtons> element contain a single <Item> element or change the declaration of mButtons in the Model to be a bool not List<bool>.
Too easy...the problem wasn't with the Lists, in fact the Test-Application mentioned in my request actually returned XML-Tags with Item-Tags for the keys-List and without Item-Tags for the bool-list. Wrapping the bool into Item-Tags resulted in an " at not expected"-Error. I have no idea, why the Serializer handles List and List differently, though.
The problem was the Enum 'iD', which is an abstract class and thus throws the Error mentiones above. It seems that I was overwhelmed by the sheer size of the error-message and just disregarded the crucial bit of info - that the Serializer tries to build an abstract class.
But thanks anyway. – Kuroni Kaimei

MyBatis mapper to call a PROC with multiple IN parameters

I'm trying to design a small CRUD tool, and so far every facet (the Rich Faces UI and Managed Beans,
validation, the mySQL database, etc.) is going fine, but not the myBatis piece.
I'm relatively new to myBatis and am keeping the users guide and API close at hand, but there
are still some things that just won't come together for me, and one is any call to a procedure
involving multiple IN parameters. Here is an example:
This from the DB set up scripts:
create procedure MY_FOO_PROC (IN valA VARCHAR(15), IN valB CHAR(1))
begin
select blah from blah where blah = valA and blah = valB etc.;
end
This from MyMapper.java:
public interface MyMapper {
List<MyFooClass> getProgress (
#Param("valA") String valueA, #Param("valB") String valueB);
}
This from MyMapper.xml:
<select id="getProgress" parameterType="map"
resultMap="MyFooMap" statementType="CALLABLE">
{ call MY_FOO_PROC (
#{valA, mode=IN, jdbcType=VARCHAR}
#{valB, mode=IN, jdbcType=CHAR}
)}
</select>
And finally this from my DAO class:
public static List<MyFooClass>
doGetProgress (String valueA, String valueB) {
SqlSession session = MyBatisConnectionFactory.getInstance().getSqlSessionFactory().openSession();
EsparMapper mapper = session.getMapper(MyMapper.class);
List<MyFooClass> listFoo = mapper.getProgress(valueA, valueB); // line which originates exception below
session.close();
return listFoo;
}
The result:
### Error querying database. Cause: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Incorrect number of arguments for PROCEDURE dbname.MY_FOO_PROC; expected 2, got 1
### The error may involve my.package.names.getProgress-Inline
### The error occurred while setting parameters
I will note that I have also tried:
creating a POJO with variables valA and valB and getters/setters for
each,
making parameterType="PojoClass" in the XML,
skipping the session.getMapper() and creating an instance of PojoClass,
and calling session.selectList("getProgress", pojoInstance);
with the nearly identical result (i.e. wrong number of arguments).
Very little help on net search, most telling me to do what I think I have already done.
I think you're missing a comma in the procedure call.
<select id="getProgress" parameterType="map"
resultMap="MyFooMap" statementType="CALLABLE">
{ call MY_FOO_PROC (
#{valA, mode=IN, jdbcType=VARCHAR} , --<--- this
#{valB, mode=IN, jdbcType=CHAR}
)}
</select>

Resources