EzDevInfo.com

jint

Javascript Interpreter for .NET

JNI: converting unsigned int to jint

How do I convert an unsigned int to jint? Do I have to convert it at all, or can I just return it without any special treatment? This is basically my code right now, but I can't test it, as I haven't setup JNI locally.

JNIEXPORT jint JNICALL
Java_test_test(JNIEnv* env, jobject obj, jlong ptr)
{
    MyObject* m = (MyObject*) ptr; 
    unsigned int i = m->get(); 
    return i; 
}

Source: (StackOverflow)

Load a DOM and Execute javascript, server side, with .Net

I would like to load a DOM using a document (in string form) or a URL, and then Execute javascript functions (including jquery selectors) against it. This would be totally server side, in process, no client/browser.

Basically I need to load the dom and then use jquery selectors and text() & type val() functions to extract strings from it. I don't really need to manipulate the dom.

I have looked at .Net javascript engines such as Jurassic and Jint, but neither support loading a DOM, and so therefore can't do what I need.

I would be willing to consider non .Net solutions (node.js, ruby, etc) if they exist, but would really prefer .Net.

edit The below is a good answer, but currently I'm trying a different route, I'm attempting to port envjs to jurassic. If I can get that working I think it will do what I want, stay tuned....


Source: (StackOverflow)

Advertisements

C# - Return a value asychronously

    private TaskCompletionSource<bool> response;
    private string _text = "";

    public void SetResult(bool result)
    {
        this.response.SetResult(result);
    }

    public async Task<bool> SendYesNo()
    {
        response = new TaskCompletionSource<bool>();

        MessageBox.Show(this._text, "", MessageBoxButtons.YesNo);

        this._text = "";

        return response.Task.Result;
    }

I'm using this code which is executed in a JavaScript script file so I can't call the await keyword.

I want to return a boolean after I set it using SetResult. If the response is not set, it will wait until it's set and will not return anything until it's set. It also has to be asychronous.

How to achieve this without Tasks (as I can't use the await keyword in JavaScript)?


Source: (StackOverflow)

jni code throwing UnSatisfiedLinkError when passing int

I am getting java.lang.UnsatisfiedLinkError when I pass a integer to the method call. If I don't pass any parameter , the function works like a charm. What am I possibly doing wrong ?

Exception in thread "main" java.lang.UnsatisfiedLinkError: JniTimer.jniWait(I)V at JniTimer.main(JniTimer.java:15)

Java Code:

public class JniTimer {
    static {
        System.loadLibrary("JniTimer.dll");
    }

    public native void jniWait(int msec);

    public static void main(String[] args) {
        JniTimer myTimer = new JniTimer();
        int a = 100;
        myTimer.jniWait(a);

    }
}

JNI header:

   /* DO NOT EDIT THIS FILE - it is machine generated */
   #include <jni.h>
   /* Header for class JniTimer */

   #ifndef _Included_JniTimer
   #define _Included_JniTimer
   #ifdef __cplusplus
   extern "C" {
      #endif
    /*
   * Class:     JniTimer
    * Method:    jniWait
    * Signature: (I)V
       */
      JNIEXPORT void JNICALL Java_JniTimer_jniWait (JNIEnv *, jobject, jint);

    #ifdef __cplusplus
  }
   #endif
   #endif

JNI implementation:

    #include "stdafx.h"
    #include<jni.h>
    #include<windows.h>
    #include "JniTimer.h"
    #include <stdio.h>

    JNIEXPORT void JNICALL Java_JniTimer_jniWait(JNIEnv *env, jobject obj , jint ji ) {
    printf("Entered C methos") ;    //////JUST PRINTING FOR DEBUG     
        HANDLE hWaitEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
        if (hWaitEvent) {
            printf ("Inside wait");
            WaitForSingleObject(hWaitEvent,ji);
            CloseHandle (hWaitEvent);
        }
    }

Source: (StackOverflow)

Jint + XNA (C#)

Is it possible to use jint to manipulate a 3D environment created with XNA (C#), and to add functionality to this environment (again using jint)?


Source: (StackOverflow)

Jint with monotouch

I just wanted to know if Jint (Javascript Interpreter for .NET) works on MonoTouch. I have a project on MonoDevelop where I use the Jint library and I just wanted to figure out if I can use it with MonoTouch. Is there any tutorial that I can look into on how to use it?


Source: (StackOverflow)

How to handle parse error from js file inside of the jint?

I try to handle call js file inside of the C# application by using Jint. But it returns an error :

An unhandled exception of type 'Jint.Parser.ParserException' occurred in Jint.dll Additional information: Line 3: Unexpected token ILLEGAL

how to get ride of the error? i think my js code is correct :(

My C# code:

static void Main(string[] args) {


        var script1 = System.IO.File.ReadAllText("script1.js");


        var obj1 = new JavaScriptSerializer().Deserialize<object>("{\"a\" : \"1\", \"b\" : \"2\" }");
        var obj2 = new JavaScriptSerializer().Deserialize<object>("{Response : false}");
        var source = "function run(c,res) { try {  var x = f.a; return a; CreateNotify(c.a,c.b); res.Response =true; } catch(err) { res.Response =err.message; }  return res;}";
        var engine = new Jint.Engine().Execute(script1).Execute(source).SetValue("CreateNotify",new Action<object,object>(CreateNotify));
        JsValue val = engine.Invoke("run",new object[] { obj1,obj2 });
        object result = val.ToObject();
    }

    public static void CreateNotify(object arg1,object arg2) {

    }

script1.js Code :


    function X() {
}
X.prototype = {
    constructor: X,
    foo:function ()  {
        return true;
    }
}
f = new X();

Source: (StackOverflow)

Returning and populating jintArray from jni

I'm trying to return a jintArray from C++ to Java but no matter what I do the call keeps hanging and the code just stops. Even with something simple like this

JNIEXPORT jintArray JNICALL Java_main_getIntArray(JNIEnv *env, jclass c) {
        jintArray intArray = env->NewIntArray(5);
        jint values[5] = {69, 69, 69, 69, 69};

        env->SetIntArrayRegion(intArray, 0, 5, values);
        env->ReleaseIntArrayElements(intArray, values, NULL);
        return intArray;
    }

In java I'm doing

System.out.println("Start getting array");
System.out.println("Array: " + Arrays.toString(getIntArray()));
System.out.println("Done getting array");

but the only output I get is

Start getting array

Is there something I'm doing wrong?

  • I tried creating a pointer from values[] and using that one in the SetIntArrayRegion

  • I tried populating the array myself by looping over it

  • I tried removing the ReleaseIntArrayElements


Source: (StackOverflow)

Exposing specific namespaces to Jint

I would like to allow scripts running in Jint to access a pre-existing API I have set up as a namespace. By that I mean I have a single namespace that contains the API, including other namespaces. I do not want to allow the scripts access to the rest of the code - including the .Net framework.

I have already posted this on the Jint forum here: http://jint.codeplex.com/discussions/310772 However, no disrespect to them but the forum does not appear to be very active and I would like to be able to answer this ASAP so I am posting here as well.

A while ago, ThomasMaierhofer achieved something similar to this that I could probably modify to work this out here: http://jint.codeplex.com/discussions/211291

To my inexperienced brain this seems like a really neat way of exposing an API to the engine, but I have never seen it done like this before.

So my questions are: Would this work? And if so, why has it not been done like this before? And is there any way I could achieve this without modifying the Jint source so I can easily update the Jint .dll as new versions become available?

EDIT: The current API I have consists of multiple classes each with multiple functions. I can expose specific instances of these classes absolutely fine using SetParameter. Jint also has an AllowClr property that allows the script to access the CLR by fully qualifying namespaces. This is the example code they give demonstrating what happens if you set this to false. Source: http://jint.codeplex.com/wikipage?title=Using%20.NET%20classes%20from%20scripts

string stringBuilder = @"
    var sb = new System.Text.StringBuilder();
    return sb.ToString();
    ";
var engine = new JintEngine();
engine.AllowClr = false;
engine.Run(stringBuilder); // throws a SecurityException

I would like to allow this, but only for a specific namespace, not everything else. I hope that makes the question clearer.

Thanks for your help,

Sam.

P.S. I am working in VB.Net but answers involving C# are fine.


Source: (StackOverflow)

Ldfld problems under Mac OS X / Mono, probably Mono bug

I'm using 3rd party library JInt (the JavaScript interpriter) which was working fine until I've switched to Mac OS X, after that I keep on getting ArgumentNullExceptions, after some investigation I've found out that JInt uses dynamic code generation for making some sort of Js-Clr bridge. This method has the following instructions in the end:

code.Emit(OpCodes.Ldnull);
FieldInfo fieldInfo = typeof(JsUndefined).GetField("Instance");
code.Emit(OpCodes.Ldfld, fieldInfo);

Here's how these lines are executed (Full size screenshot here)

enter image description here

It is clearly seen that fieldInfo argument is not null, though when it comes to executing these lines, notice that LDFLD has no argument! (Full size screenshot here):

enter image description here

My current statement that will get executed is Ldnull, I performing "Step In"(Over Ldnull) and BANG exception occurs over Ldfld (Full size screenshot here)::

enter image description here

Any suggestions?


Source: (StackOverflow)

JINT - Can External Javascript be Included in parsing?

I am wanting to implement JINT in my website, with Ace text editor for the management to write some scripting situations in javascript. So far this looks to be fine, but I am having a hard time finding some specific information.

Essentially, I need to create some certain javascript "objects" with some functions attached to them. In normal javascript this is no problem, but I am curious if JINT can handle this scenario and allow me to load these objects from a *.js file when it is getting ready to run the scripts? I have dug around on this topic and not found a lot of answers; Primarily the only semi-conclusion I discovered was here; Stackoverflow Question

Any help is appreciated, as I am new to this entire concept of JINT and find it an interesting approach.. but with a lot of confusion. If there are other engines similar to JINT but better suited to this, recommendation would also be appreciated.


Source: (StackOverflow)

Run javascript from C# with Jint/Trap console.log calls

I'm using JINT to load a javascript file into a small C# app and call a number of methods with some parameters from C#. I want to get the return values of those methods. This is what I'm doing:

        JintEngine engine = new JintEngine();
        string file = File.ReadAllText(@"C:\thejavascript.js");
        engine.Run(file);            
        Console.WriteLine(engine.CallFunction("themethod")); 

The javascript method is as follows:

        function themethod() {   
            console.log("Hello!");
                return "Finished";
        }

I can see 'Finished' in the VisualStudio console when I run the code above, but the call to send 'Hello!' to the AS3 console is nowhere to be seen. It's not in the flashlog.txt file even. In fact, I think JINT throws an error, as the may not be a 'console' object in existance since there's no browser.

How can I trap what's sent to the console from javascript that's run in JINT? There is an example on the JINT download site that had SystemConsole' or something (not System.Console), but I have not been successfu in getting this to work. I want to be able to add debugging code to the javascript and see it in the console in VisualStudio.

Any ideas? This is making debugging what I'm doing very difficult. . .

Thanks in advance.


Source: (StackOverflow)

Interpret/parse Javascript Variables in c# with JInt or similar

I'm attempting to build an application that uses an API that was made for JavaScript. Rather than sending down JSON or XML it sends a Script tag with a JavaScript object within it like so:

<script>
var apiresult = {
    success: true,
    data: {
        userName: "xxxxx",
        jsonData: { 
            "id" : "8342859",
            "price" : "83.94"
            }
        }
    };
</script>

I'm trying to get out just the "jsonData" property. In browser land you can go:

apiresult.data.jsonData;

Obviously I can't do this in C#. I've tried using Jint and HtmlAgilityPack like so:

HtmlDocument = await client.GetHTMLAsync(url);

string scriptTag = htmlResult.DocumentNode.SelectNodes("//script").InnerHtml;

scriptTag += " return apiresult.data.jsonData;

JintEngine engine = new JintEngine();

Jint.Native.JsObject r = (Jint.Native.JsObject)engine.Run(scriptTag);

And if I expand "r.Results" in the watch window it shows the variables values, but how do I then get just the raw JSON back out so that I can parse it into my object?


Source: (StackOverflow)

Random values when retrieving jint value using JNI

I am passing a java object of type 'Properties' to c++ using JNI.

I retrieve an int value that is inserted into the Properties object using the following statements.

int intVal = 1;
Properties propObj = new Properties();
propObj.put("KEY_FOR_INT", intVal);

When i try to retrieve the value in c++ using JNI with the following statement, i get random values.

jint intValueFromJava = env->CallIntMethod(propObj, propGetID, env->NewStringUTF("KEY_FOR_INT"));

If i try to retrieve a string value or ArrayList, i am able to get it correctly.


Source: (StackOverflow)

How to get JSON value from Javascript using JINT library

I have this JavaScript file:

var input = {
  "CONTRATE": 0,
  "SALINC": 0,
  "RETAGE": 55.34,
  "MARSTATUS": "single",
  "SPOUSEDOB": "1970-01-01",
  "VIEWOPTION": "pension"
};

var inputValidation = "input.CONTRATE > 50 && input.SALINC < 50 && input.RETAGE > 50";

eval(inputValidation);

How to get JSON value of "input" variable using JINT as JSON object string?


Source: (StackOverflow)