C# 底下 的 javascript(JS) 直譯器 (interpreter) [CS_test_jint project]

C# 底下 的 javascript(JS) 直譯器 (interpreter) [CS_test_jint project]

C# 底下 的 javascript(JS)  直譯器 (interpreter) [CS_test_jint project]


資料來源:

https://github.com/sebastienros/jint
https://www.youtube.com/watch?v=yCs6UmogKEg&t=57s
https://docs.microsoft.com/zh-tw/shows/code-conversations/sebastien-ros-on-jint-javascript-interpreter-net

https://blog.no2don.com/2020/03/cnet-core-c-jint-javascript.html


GITHUB: https://github.com/jash-git/CS_test_jint-project


官方教學影片備份



Code

    01.JS

//https://blog.no2don.com/2020/03/cnet-core-c-jint-javascript.html
function JSCallJS(a, b) {
    return "" + (GetSum(a, b) + 10);
}
//-----------

function GetSum(a, b) {
    return a + b;
}


function Echo() {
    return str + " From Javascript";
}

function CallServerFunc(name) {
    return name + " From Javascript - CallServerFunc";
}

function CallServerFunc2(name) {
    return testapi.GetStringFromClassFunction(name) + " From Javascript - CallServerFunc";

}

function parseJson() {
    obj = JSON.parse(json_data);

    var data = '';
    for (var i = 0; i < obj.sites.length; i++) {
        data += obj.sites[i].name + " : " + obj.sites[i].url+"\n";
    }

    return data;
}

function obj2JsonString() {
    input = JSON.parse(json_data);

    var output = [];
    for (var i = 0; i < input.sites.length; i++) {
        var obj = {};
        obj.ShowName = input.sites[i].name;
        obj.Url = input.sites[i].url;
        output.push(obj);
    }

    data = '{"obj":'+JSON.stringify(output)+'}';
    return data;
}


    02.CS

// See https://aka.ms/new-console-template for more information
using Jint;

//出處/原始教學 網站
//https://github.com/sebastienros/jint
//https://www.youtube.com/watch?v=yCs6UmogKEg&t=57s
//https://docs.microsoft.com/zh-tw/shows/code-conversations/sebastien-ros-on-jint-javascript-interpreter-net

//延伸教學 網站
//https://blog.no2don.com/2020/03/cnet-core-c-jint-javascript.html
namespace CS_test_Jint
{
    public class TestClass
    {

        public string GetStringFromClassFunction(string str)
        {
            return str + ", 您好我來自於 TestClass-GetStringFromClassFunction。";
        }
    }

    class Program
    {
        static void pause()
        {
            Console.WriteLine("\nPress any key to terminate...");
            Console.ReadKey();
        }

        //---
        //fun,js
        static int Sum(int x = 19, int y = 46)
        {
            var engine = new Engine();

            engine.Execute(System.IO.File.ReadAllText(AppDomain.CurrentDomain.BaseDirectory + "Script" +
                Path.DirectorySeparatorChar + "func.js"));

            var result = engine.Execute("GetSum(" + x + "," + y + ")").GetCompletionValue();

            return Convert.ToInt32(result.AsNumber());
        }

        static string Echo(string str = "DONMA")
        {
            //在 javascript 中,Echo  function 裡面並沒有 str 的參數,這樣我直接透過 C# 端定義一個 str 的變數,呼叫後並且取得回傳值。
            var engine = new Engine();

            engine.Execute(System.IO.File.ReadAllText(AppDomain.CurrentDomain.BaseDirectory + "Script" +
                Path.DirectorySeparatorChar + "func.js"));

            engine.SetValue("str", str);

            var result = engine.Execute("Echo()").GetCompletionValue();

            return result.AsString();
        }

        static string DoubleCall(string str = "當麻")
        {
            //先建立一個 TestClass ,並且讓 javascript 可以呼叫 TestClass 中 GetStringFromClassFunction 並且在回傳給 C# 端
            var engine = new Engine();

            engine.SetValue("testapi", new TestClass());

            engine.Execute(System.IO.File.ReadAllText(AppDomain.CurrentDomain.BaseDirectory + "Script" +
                Path.DirectorySeparatorChar + "func.js"));

            var result = engine.Execute("testapi.GetStringFromClassFunction('" + str + "')").GetCompletionValue();


            return result.AsString();
        }

        static String CallSum(int x = 19, int y = 46)
        {
            var engine = new Engine();

            engine.Execute(System.IO.File.ReadAllText(AppDomain.CurrentDomain.BaseDirectory + "Script" +
                Path.DirectorySeparatorChar + "func.js"));

            var result = engine.Execute("JSCallJS(" + x + "," + y + ")").GetCompletionValue();

            return result.AsString();
        }

        static String JS_ParseJson()
        {
            string text = "{ \"sites\" : [" +
                          "{ \"name\":\"Runoob\" , \"url\":\"www.runoob.com\" }," +
                          "{ \"name\":\"Google\" , \"url\":\"www.google.com\" }," +
                          "{ \"name\":\"Taobao\" , \"url\":\"www.taobao.com\" } ]}";

            var engine = new Engine();

            engine.Execute(System.IO.File.ReadAllText(AppDomain.CurrentDomain.BaseDirectory + "Script" +
                Path.DirectorySeparatorChar + "func.js"));

            engine.SetValue("json_data", text);

            var result = engine.Execute("parseJson()").GetCompletionValue();

            return result.AsString();
        }

        static String JS_CreateJsonString()
        {
            string text = "{ \"sites\" : [" +
                          "{ \"name\":\"Runoob\" , \"url\":\"www.runoob.com\" }," +
                          "{ \"name\":\"Google\" , \"url\":\"www.google.com\" }," +
                          "{ \"name\":\"Taobao\" , \"url\":\"www.taobao.com\" } ]}";

            var engine = new Engine();

            engine.Execute(System.IO.File.ReadAllText(AppDomain.CurrentDomain.BaseDirectory + "Script" +
                Path.DirectorySeparatorChar + "func.js"));

            engine.SetValue("json_data", text);

            var result = engine.Execute("obj2JsonString()").GetCompletionValue();

            return result.AsString();
        }
        //---fun,js

        static void Main(string[] args)
        {
            var engine = new Engine();

            /*
            //單行JS直譯測試,確定Jint Lib可用
            Console.WriteLine(engine.Execute("2+5*12").GetCompletionValue());
            */

            /*
            //透過C#無限迴圈,製作一個CMD的可輸入的JS直譯器
            // x=12
            // y=2
            // z=x+y
            //function add(x,y){return (x+y);}
            //add(10,20.5)
            //add(add (10,20),-20.5)
            while (true)
            {
                Console.Write("> ");
                var Command = Console.ReadLine();
                var Result = engine.Execute(Command).GetCompletionValue();
                Console.WriteLine(Result);
            }
            //*/

            //*
            //測試 https://blog.no2don.com/2020/03/cnet-core-c-jint-javascript.html 網站現成 JS檔 直譯呼叫使用
            Console.WriteLine(Sum());
            Console.WriteLine(Echo());
            Console.WriteLine(DoubleCall());
            Console.WriteLine(String.Format("19+46+10={0}", CallSum()));
            //*/

            //JSON基本測試
            Console.WriteLine(JS_ParseJson());
            Console.WriteLine(JS_CreateJsonString());

            pause();
        }
    }
}

3 thoughts on “C# 底下 的 javascript(JS) 直譯器 (interpreter) [CS_test_jint project]

  1. 恭喜老爺 賀喜夫人

    我上星期 要開發『阿薩布魯 直譯器(interpreter)』的計畫 已經正式終止

    正所謂: 實力不夠, GOOGLE(GITHUB)來湊

    我今早 GITHUB找到 jint 專案,相關資料網址如下
    https://github.com/sebastienros/jint

    所以我上星期可以算是上班純吹冷氣打混摸魚

    我今早 將我找到的新方向報告老闆,還得到稱讚 哈哈

    有需要外掛直譯器的人,建議可以到GITHUB搜尋 interpreter 看看是否有適合自己 合用的

  2. Jint 從 2.11.58 -> 3.0.1


    public static bool ESCPOS_Work(String StrInput, out PT_CommandOutput PT_CommandOutputs)//工作單
    {
    bool blnResult = false;
    String StrTemplateVar = "";//範本外部參數
    PT_CommandOutputs = null;
    var engine = new Engine();

    if ((SQLDataTableModel.m_printer_templateDataTable != null) && (SQLDataTableModel.m_printer_valueList != null) && (SQLDataTableModel.m_printer_valueList.Count > 0) && (SQLDataTableModel.m_printer_templateDataTable.Rows.Count > 0))//判斷列印範本資料表有資料
    {
    //m_printer_templateDataTable --印表範本資料表全部資料
    //m_printer_valueList --存放所有UI印表機設定值

    //---
    //從DB載入對應範本到engine中
    String Strprint_templateSID = "-1";//預設值確保DB查不到
    for (int i = 0; i 0)
    {
    if (foundRows01[0]["include_command"].ToString() == "Y")//有引用共用函數
    {
    String expression02 = $"template_type = 'ESC_COMMAND'";
    DataRow[] foundRows02 = SQLDataTableModel.m_printer_templateDataTable.Select(expression02);
    if (foundRows02.Length > 0)
    {
    engine.Execute(foundRows02[0]["template_value"].ToString());//共用範本載入
    }
    }
    engine.Execute(foundRows01[0]["template_value"].ToString());//WORK_TICKET(工作單)範本載入
    }
    else
    {
    String StrLog = String.Format("{0}: {1};{2}", "ESCPOS_Work", StrInput, "printer_templateDataTable.foundRows.Count=0");
    LogFile.Write("JintErrot ; " + StrLog);
    return blnResult;
    }
    //---從DB載入對應範本到engine中
    }
    else
    {
    String StrLog = String.Format("{0}: {1};{2}", "ESCPOS_Work", StrInput, "printer_templateDataTable.Rows.Count=0");
    LogFile.Write("JintErrot ; " + StrLog);
    return blnResult;
    }

    try
    {
    engine.SetValue("input", StrInput);//設定輸入值
    engine.SetValue("TemplateVar", StrTemplateVar);//設定範本外部參數

    String StrFunName = "Main";//"Main()";
    //var StrJsonResult = engine.Execute(StrFunName).GetCompletionValue();//執行範本運算 2.11.58 版本
    var MainFunction = engine.GetValue("Main").AsFunctionInstance();
    var StrJsonResult = MainFunction.Call();//執行範本運算 3.0.1

    PT_CommandOutputs = new PT_CommandOutput();
    PT_CommandOutputs = JsonSerializer.Deserialize(StrJsonResult.AsString());//取回運算結果
    }
    catch (Exception ex)
    {
    PT_CommandOutputs = null;
    if (true)
    {
    String StrLog = String.Format("{0}: {1};{2}", "ESCPOS_Work", StrInput, ex.ToString());
    LogFile.Write("JintErrot ; " + StrLog);
    }
    }

    if ((PT_CommandOutputs != null) && (PT_CommandOutputs.state_code == 0))
    {
    for (int i = 0; i < PT_CommandOutputs.value.Count; i++)
    {
    PT_CommandOutputs.value[i] = UnescapeUnicode(PT_CommandOutputs.value[i]);
    }

    blnResult = true;
    }

    return blnResult;
    }

發表迴響

你的電子郵件位址並不會被公開。 必要欄位標記為 *