Ejemplo n.º 1
0
        public bool include(string filename)
        {
            try
            {
                Handle pluginHandle = engine.LoadScriptCompiled(g_WorkingDirectory + filename, "V8.NET", true);
                if (!pluginHandle.IsError)
                {
                    Handle x = engine.Execute(pluginHandle, true);
                    if (!x.IsError)
                    {
                        V8Handles.Add(pluginHandle);
                        Logger.LogDebug("[V8] " + filename + " compiled success fully");

                        return(true);
                    }
                    x.Dispose();
                }
                pluginHandle.Dispose();
            }
            catch (Exception ex)
            {
                Logger.LogError("[V8] Failed to include (" + filename + "): " + ex.Message);
            }
            return(false);
        }
Ejemplo n.º 2
0
        /// <summary>
        /// 执行js V8方法
        /// </summary>
        /// <param name="reString">Js代码</param>
        /// <param name="para">参数字符串(使用逗号分隔)</param>
        /// <param name="MethodName">方法名称</param>
        public static string V8Method(string reString, string para, string MethodName)
        {
            V8Engine engine = V8Engine.Create();        //创建V8对象
            V8Script script = engine.Compile(reString); //编译

            try
            {
                engine.Execute(script);                                                              //将编译的脚本加载到V8引擎中
                string res = engine.Execute(string.Format("{0}({1})", MethodName, para)).ToString(); //执行结果
                return(res);
            }
            catch (Exception ex)
            {
                return(ex.Message);//异常信息
            }
        }
Ejemplo n.º 3
0
 private static string CompileCoffeeScript(string script)
 {
     using (var engine = new V8Engine())
     {
         engine.DynamicGlobalObject.script = script;
         return(engine.Execute(File.ReadAllText("js/coffee-script.js") + "CoffeeScript.compile(script)"));
     }
 }
Ejemplo n.º 4
0
        public string GetData(int value)
        {
            // V8Engine.ASPBINSubFolderName = "V8.NET"; // It is already "V8.NET" by default, so just delete this line if not needed.  Please see integration steps at the top for more details.
            var    engine = new V8Engine();
            Handle result = engine.Execute("'You entered: '+" + value, "V8.NET Web Service Test");

            return(result.AsString);
        }
Ejemplo n.º 5
0
        /// <summary>
        /// Executes Emmet command with the specified identifier on the specified editor view.
        /// </summary>
        /// <param name="cmdId">Identifier of the command to execute.</param>
        /// <param name="editor">Editor to execute command in.</param>
        /// <exception cref="ArgumentOutOfRangeException">
        /// Indicates that the specified command identifier was not found.
        /// </exception>
        public bool RunCommand(int cmdId, IEmmetEditor editor)
        {
            if (null == _engine)
            {
                InitializeEngine();
            }

            if (!_editor.Attach(editor))
            {
                return(false);
            }

            string script = string.Empty;

            switch (cmdId)
            {
            case PackageIds.CmdIDExpandAbbreviation:
                script = "window.emmet.run('expand_abbreviation', editor);";
                break;

            case PackageIds.CmdIDWrapWithAbbreviation:
                script = "window.emmet.run('wrap_with_abbreviation', editor);";
                break;

            case PackageIds.CmdIDToggleComment:
                script = "window.emmet.run('toggle_comment', editor);";
                break;

            case PackageIds.CmdIDMergeLines:
                script = "window.emmet.run('merge_lines', editor);";
                break;

            default:
                throw new ArgumentOutOfRangeException(nameof(cmdId),
                                                      cmdId,
                                                      "Specified command identifier not found.");
            }

            Handle retVal = _engine.Execute(script);

            _editor.Detach();

            if (retVal.IsError)
            {
                this.TraceError($"Emmet engine error: {retVal.AsString}");
                return(false);
            }
            else if (retVal.AsBoolean == false)
            {
                this.Trace($"Command {script} returned false.");
                return(false);
            }

            this.Trace($"Command {script} completed successfully.");
            return(true);
        }
        public InternalHandle setInterval(V8Engine engine,
                                          bool isConstructCall,
                                          InternalHandle _this,
                                          params InternalHandle[] args)
        {
            if (isConstructCall)
            {
                return(_this);
            }
            else
            {
                if (args != null && args.Length == 2)
                {
                    InternalHandle timerCallback = args[0];
                    InternalHandle milliseconds  = args[1];

                    if (milliseconds != null && milliseconds.IsInt32 && timerCallback != null && timerCallback.IsFunction)
                    {
                        int    ms             = milliseconds.AsInt32;
                        string sourceFragment = timerCallback.Value.ToString();

                        System.Timers.Timer tmr = new System.Timers.Timer();
                        tmr.Interval = milliseconds.AsInt32;

                        tmr.Elapsed += (object sender, System.Timers.ElapsedEventArgs e) =>
                        {
                            if (!engine.IsDisposed)
                            {
                                try
                                {
                                    engine.Execute("____$=" + sourceFragment + ";____$();", ScriptingEngine.SOURCE_NAME, false);
                                }
                                catch { }
                            }
                            else
                            {
                                tmr.Stop();
                            }
                        };

                        tmr.Start();

                        timers.Add(tmr);

                        Handle timerHandle = engine.CreateValue(timers.Count - 1);

                        return(timerHandle);
                    }
                }
            }

            return(InternalHandle.Empty);
        }
Ejemplo n.º 7
0
 private static void Run(string script)
 {
     using (var engine = new V8Engine())
     {
         engine.RegisterType(typeof(Boolean), "Boolean", true, ScriptMemberSecurity.Permanent);
         engine.RegisterType(typeof(ScriptWidget), "ScriptUIItem", true, ScriptMemberSecurity.Permanent);
         var consoleType = engine.RegisterType(typeof(ScriptConsole), "ScriptConsole", true, ScriptMemberSecurity.Permanent);
         engine.DynamicGlobalObject.console = consoleType.CreateObject(new ScriptConsole());
         var desktopType = engine.RegisterType(typeof(ScriptWidgetDesktop), "ScriptUIDesktop", true, ScriptMemberSecurity.Permanent);
         engine.DynamicGlobalObject.desktop = desktopType.CreateObject(ScriptWidgetDesktop.Instance);
         engine.Execute(script);
     }
 }
Ejemplo n.º 8
0
        public void CompileAndExecute(string script)
        {
            if (isDisposing)
            {
                return;
            }

            const string ES_REF = "ecmascript:";
            const string JS_REF = "javascript:";

            script = script.TrimStart();

            string start = script.Substring(0, ES_REF.Length).ToLower();

            script = start.StartsWith(ES_REF) ? script.Remove(0, ES_REF.Length) : script;
            script = start.StartsWith(JS_REF) ? script.Remove(0, JS_REF.Length) : script;

            using (InternalHandle handle = v8.Compile(script, SOURCE_NAME, false).AsInternalHandle)
            {
                if (!handle.IsError)
                {
                    try
                    {
                        Handle result = v8.Execute(handle, true);
                        //handle.Dispose();
                    }
                    catch (Exception ex)
                    {
                        ConsoleColor tmp = Console.ForegroundColor;
                        Console.ForegroundColor = ConsoleColor.Red;

                        Console.WriteLine("(SCRIPT) {0}", ex.Message);

                        Console.ForegroundColor = tmp;
                    }
                }
            }
        }
Ejemplo n.º 9
0
        public void LoadExtensions_PointedToPreferencesFile_LoadsCustomSnippets()
        {
            // Arrange
            V8Engine       engine   = new V8Engine();
            EngineCompiler compiler = new EngineCompiler(engine);

            // Act
            compiler.CompileCore();
            compiler.LoadExtensions(TestContext.TestDeploymentDir);

            // Assert
            string script = "window.emmet.resources.fuzzyFindSnippet('css', 'section')";
            Handle result = engine.Execute(script);

            // preferences.json file contains "section" abbreviation for css. If we are able to find it then
            // our extension has been loaded correctly.
            result.IsObject.Should().BeTrue();
        }
Ejemplo n.º 10
0
 static void Main(string[] args)
 {
     try
     {
         //var engine = new V8Engine();
         var engine  = new V8Engine(false);
         var context = engine.CreateContext();
         engine.SetContext(context);
         using (var result = engine.Execute("'Hello World!'"))
         {
             Console.WriteLine(result.AsString);
         }
     }
     catch (Exception ex)
     {
         Console.WriteLine(ex.GetFullErrorMessage());
     }
     Console.ReadKey(true);
 }
Ejemplo n.º 11
0
        static void Main(string[] args)
        {
            V8Engine v8Engine = new V8Engine();

            var result = v8Engine.Execute(
                @"var gs = (function () {  // NOTE: 'result' WILL ALWAYS BE 'undefined' BECAUSE OF 'var' before 'gs'.
                    var myClassObject = function() {};
                    myClassObject.prototype.getCompanyInfo = function (a, b, c) {
                        var staff = [
                            {
                                'name': 'John',
                                'address': '1 Walk Way',
                                'dob': 'July '+a+', 1970'
                            },
                            {
                                'name': 'Peter',
                                'address': '241 Otoforwan Rd',
                                'dob': 'January '+b+', 1953'
                            },
                            {
                                'name': 'Marry',
                                'address': '1 Contrary Lane',
                                'dob': 'August '+c+', 1984'
                            }
                        ];
                        var result = {
                            'isEnabled': true,
                            'staff': staff
                        };
                        return result;
                    };
                    return new myClassObject();
                })();"
                );

            //create parameter
            Handle day1 = v8Engine.CreateValue("1");
            Handle day2 = v8Engine.CreateValue("2");
            Handle day3 = v8Engine.CreateValue("3");

            var     gs           = v8Engine.GlobalObject.GetProperty("gs");
            var     resultHandle = gs.Call("getCompanyInfo", null, day1, day2, day3); // NOTE: The object context is already known, so pass 'null' for '_this'.
            Company completion   = v8Engine.GetObject <Company>(resultHandle);

            //examine result
            var    test0              = resultHandle.GetProperty("isEnable");
            Handle test1              = resultHandle.GetProperty("staff"); // NOTE: "ObjectHandle" is a special handle for objects (which also obviously includes arrays, etc.).
            var    arrayLength        = test1._.ArrayLength;
            Handle arrayItem1         = test1._.GetProperty(0);
            var    arrayItem1_name    = arrayItem1._.GetProperty("name");
            var    arrayItem1_address = arrayItem1._.GetProperty("address");
            var    arrayItem1_dob     = (~arrayItem1).GetProperty("dob");
            Handle arrayItem2         = test1._.GetProperty(1); // (arrays are treated same as objects here)
            Handle arrayItem3         = test1._.GetProperty(2); // (arrays are treated same as objects here)

            //  ==================================================================== OR  ====================================================================

            v8Engine.RegisterType <Company2>(null, true, ScriptMemberSecurity.Locked); // (this line is NOT required, but allows more control over the settings)
            v8Engine.GlobalObject.SetProperty(typeof(Company2));                       // <= THIS IS IMPORTANT! It sets the type on the global object (though you can put this anywhere like any property)

            var gs2 = v8Engine.Execute(
                @"(function () {
                    var myClassObject = function() {};
                    myClassObject.prototype.getCompanyInfo = function (a, b, c) {
                        return new Company2(a, b, c);
                    };
                    return new myClassObject();
                })();"
                );

            var resultHandle2             = gs2.Call("getCompanyInfo", null, day1, day2, day3); // NOTE: The object context is already known, so pass 'null' for '_this'.
            var objectBindingModeIfNeeded = resultHandle2.BindingMode;
            var ci2 = (Company2)resultHandle2.BoundObject;                                      // (when a CLR class is bound, it is tracked by the handle in a special way)

            //  =============================================================================================================================================
            // Take your pick. ;)

            System.Console.WriteLine("Script executions completed. Press any key to exit.");
            System.Console.ReadKey(true);
        }
Ejemplo n.º 12
0
 public void Test()
 {
     _v8.Execute("function foo(s) { /* Some JavaScript Code Here */ return s; }", "My V8.NET Console");
     var result  = _v8.DynamicGlobalObject.foo("bar!");
     var result2 = (string)result;
 }
Ejemplo n.º 13
0
        private void InitEntityContext(Entity entity)
        {
            // Remove previous context if any.
            entityContexts.Remove(entity.Guid);

            logger.Debug("Entered initEntityContext with entity [{0}]", entity.Guid);

            string serverScript = (string)entity["scripting"]["serverScript"];

            if (serverScript == null)
            {
                return;
            }

            logger.Debug("Creating the context. Server script is {0}", serverScript);

            V8Engine engine;

            try
            {
                engine = new V8Engine();
            }
            catch (Exception e)
            {
                logger.ErrorException("Exception during context creation", e);
                return;
            }

            logger.Debug("Adding context to the list");

            entityContexts.Add(entity.Guid, engine);

            logger.Debug("Creating context wrapper");

            // This object should be used to assign event handlers, e.g. script.onNewObject = function (newObject) {...}
            var context = new V8NetContext(engine);

            logger.Debug("Creating script object");

            context.Execute("script = {}");

            logger.Debug("About to enter context scope");

            engine.WithContextScope = () =>
            {
                logger.Debug("Configuring the context");

                // Register global objects.
                // FIXME: Potential security issue. Users can access .Type in script which allows to create any object and
                // thus run arbitrary code on the server.
                foreach (var entry in registeredGlobalObjects)
                {
                    engine.GlobalObject.SetProperty(entry.Key, entry.Value, null, true, V8PropertyAttributes.Locked);
                }

                logger.Debug("Calling context callbacks");

                // Invoke new context handlers.
                newContextHandlers.ForEach(handler => handler(context));

                logger.Debug("Executing serverScript");

                // Execute server script.
                engine.Execute(serverScript);
            };
        }
        protected override async Task OnLoadAsync()
        {
            var scriptsDir = Path.Combine(m_Runtime.WorkingDirectory, "scripts");
            var nativeDir  = Path.Combine(m_Runtime.WorkingDirectory, "native");

            if (!s_Initialized)
            {
                if (!Directory.Exists(nativeDir))
                {
                    Directory.CreateDirectory(nativeDir);
                }

                var latestPackageId = await m_NuGetPackageManager.GetLatestPackageIdentityAsync("V8.NET");

                var nupkgFile     = m_NuGetPackageManager.GetNugetPackageFile(latestPackageId);
                var packageReader = new PackageArchiveReader(nupkgFile);
                foreach (var file in packageReader.GetFiles("contentFiles"))
                {
                    if (!file.Contains("netstandard2.0"))
                    {
                        continue;
                    }

                    var fileName = Path.GetFileName(file);
                    var entry    = packageReader.GetEntry(file);
                    using var stream = entry.Open();
                    var ms = new FileStream(Path.Combine(nativeDir, fileName), FileMode.Create);
                    await stream.CopyToAsync(ms);

                    ms.Close();
                    stream.Close();
                }

                Loader.AlternateRootSubPath = nativeDir;
                s_Initialized = true;
            }

            if (!Directory.Exists(scriptsDir))
            {
                Directory.CreateDirectory(scriptsDir);
            }
            else
            {
                foreach (var directory in Directory.GetDirectories(scriptsDir))
                {
                    m_Logger.LogInformation($"[loading] Script: {directory}");

                    var filePath = Path.Combine(directory, "startup.js");
                    if (!File.Exists(filePath))
                    {
                        continue;
                    }

                    var scriptId = new DirectoryInfo(directory).Name;

                    m_Engine = new V8Engine(true);
                    var globalContext = m_Engine.GetContext();
                    var v8Context     = m_Engine.CreateContext();

                    var scriptLifeTime = m_LifetimeScope.BeginLifetimeScope(builder =>
                    {
                        builder.Register(ctx => m_Engine)
                        .As <V8Engine>()
                        .SingleInstance()
                        .OwnedByLifetimeScope();

                        builder.Register(ctx => v8Context)
                        .As <Context>()
                        .SingleInstance()
                        .OwnedByLifetimeScope();
                    });

                    try
                    {
                        var serviceProvider = scriptLifeTime.Resolve <IServiceProvider>();
                        m_Engine.SetContext(v8Context);
                        m_Engine.GlobalObject.SetProperty("logger", ActivatorUtilities.CreateInstance <ScriptLogger>(serviceProvider, scriptId), memberSecurity: ScriptMemberSecurity.Locked);
                        m_Engine.GlobalObject.SetProperty("openmod", ActivatorUtilities.CreateInstance <OpenModFunctions>(serviceProvider), memberSecurity: ScriptMemberSecurity.Locked);
                        var script = m_Engine.LoadScript(filePath, throwExceptionOnError: true);
                        m_Engine.Execute(script, throwExceptionOnError: true, trackReturn: false);
                        m_Engine.SetContext(globalContext);
                        GC.KeepAlive(script);
                    }
                    catch (Exception ex)
                    {
                        m_Logger.LogError(ex.GetBaseException(), $"Script error in script \"{scriptId}\"");
                    }
                }
            }
        }
Ejemplo n.º 15
0
        protected override bool Execute(string name, CefV8Value obj, CefV8Value[] arguments, out CefV8Value returnValue, out string exception)
        {
            returnValue = CefV8Value.CreateNull();
            exception   = null;

            try
            {
                var context = CefV8Context.GetCurrentContext();
                var browser = context.GetBrowser();
                var frame   = browser.GetMainFrame();

                if (name == "compile" || name == "loadScript" || name == "loadScriptCompiled")
                {
                    if (arguments.Length >= 3)
                    {
                        var script                = arguments[0].GetStringValue();
                        var sourceName            = arguments[1].GetStringValue();
                        var throwExceptionOnError = arguments[2].GetBoolValue();
                        var callback              = (arguments.Length == 4 ? arguments[3] : null);

                        if (!string.IsNullOrEmpty(script) && !string.IsNullOrEmpty(sourceName))
                        {
                            if (callback != null && callback.IsFunction)
                            {
                                var runner = CefTaskRunner.GetForCurrentThread();
                                new Task(() =>
                                {
                                    context.Enter();
                                    if (name == "compile")
                                    {
                                        engine.Compile(script, sourceName, throwExceptionOnError);
                                    }
                                    else if (name == "loadScript")
                                    {
                                        engine.LoadScript(script, sourceName, throwExceptionOnError);
                                    }
                                    else if (name == "loadScriptCompiled")
                                    {
                                        engine.LoadScriptCompiled(script, sourceName, throwExceptionOnError);
                                    }
                                    runner.PostTask(new CallbackTask(context, callback, JsonMapper.ToJson(new StatusHelper("OK", name))));
                                    context.Exit();
                                }).Start();
                            }
                            else
                            {
                                if (name == "compile")
                                {
                                    engine.Compile(script, sourceName, throwExceptionOnError);
                                }
                                else if (name == "loadScript")
                                {
                                    engine.LoadScript(script, sourceName, throwExceptionOnError);
                                }
                                else if (name == "loadScriptCompiled")
                                {
                                    engine.LoadScriptCompiled(script, sourceName, throwExceptionOnError);
                                }
                                returnValue = CefV8Value.CreateString(JsonMapper.ToJson(new StatusHelper("OK", name)));
                            }
                        }
                        else
                        {
                            returnValue = DontMeetRequirements(context, callback);
                        }
                    }
                    else
                    {
                        returnValue = DontMeetRequirements(context, null);
                    }
                }
                else if (name == "consoleExecute" || name == "execute" || name == "verboseConsoleExecute")
                {
                    if (arguments.Length >= 4)
                    {
                        var script                = arguments[0].GetStringValue();
                        var sourceName            = arguments[1].GetStringValue();
                        var throwExceptionOnError = arguments[2].GetBoolValue();
                        var timeOut               = arguments[3].GetIntValue();
                        var callback              = (arguments.Length == 5 ? arguments[4] : null);

                        if (!string.IsNullOrEmpty(script) && !string.IsNullOrEmpty(sourceName))
                        {
                            if (callback != null && callback.IsFunction)
                            {
                                var runner = CefTaskRunner.GetForCurrentThread();
                                new Task(() =>
                                {
                                    context.Enter();
                                    if (name == "consoleExecute")
                                    {
                                        engine.ConsoleExecute(script, sourceName, throwExceptionOnError, timeOut);
                                    }
                                    else if (name == "execute")
                                    {
                                        engine.Execute(script, sourceName, throwExceptionOnError, timeOut);
                                    }
                                    else if (name == "verboseConsoleExecute")
                                    {
                                        engine.VerboseConsoleExecute(script, sourceName, throwExceptionOnError, timeOut);
                                    }
                                    runner.PostTask(new CallbackTask(context, callback, JsonMapper.ToJson(new StatusHelper("OK", name))));
                                    context.Exit();
                                }).Start();
                            }
                            else
                            {
                                if (name == "consoleExecute")
                                {
                                    engine.ConsoleExecute(script, sourceName, throwExceptionOnError, timeOut);
                                }
                                else if (name == "execute")
                                {
                                    engine.Execute(script, sourceName, throwExceptionOnError, timeOut);
                                }
                                else if (name == "verboseConsoleExecute")
                                {
                                    engine.VerboseConsoleExecute(script, sourceName, throwExceptionOnError, timeOut);
                                }
                                returnValue = CefV8Value.CreateString(JsonMapper.ToJson(new StatusHelper("OK", name)));
                            }
                        }
                        else
                        {
                            returnValue = DontMeetRequirements(context, callback);
                        }
                    }
                    else
                    {
                        returnValue = DontMeetRequirements(context, null);
                    }
                }
                else if (name == "terminateExecution")
                {
                    if (arguments.Length >= 0)
                    {
                        var callback = (arguments.Length == 1 ? arguments[0] : null);

                        if (callback != null && callback.IsFunction)
                        {
                            var runner = CefTaskRunner.GetForCurrentThread();
                            new Task(() =>
                            {
                                context.Enter();
                                engine.TerminateExecution();
                                runner.PostTask(new CallbackTask(context, callback, JsonMapper.ToJson(new StatusHelper("OK", "TerminateExecution"))));
                                context.Exit();
                            }).Start();
                        }
                        else
                        {
                            engine.TerminateExecution();
                            returnValue = CefV8Value.CreateString(JsonMapper.ToJson(new StatusHelper("OK", "TerminateExecution")));
                        }
                    }
                    else
                    {
                        returnValue = DontMeetRequirements(context, null);
                    };
                }
                else if (name == "runStartupFile")
                {
                    if (arguments.Length >= 0)
                    {
                        var callback = (arguments.Length == 1 ? arguments[0] : null);

                        if (callback != null && callback.IsFunction)
                        {
                            var runner = CefTaskRunner.GetForCurrentThread();
                            new Task(() =>
                            {
                                context.Enter();

                                var message = "V8 Script Engine : Started";
                                Log.Trace(message, configuration.Verbose);
                                runner.PostTask(new CallbackTask(context, callback, JsonMapper.ToJson(new StatusHelper("OK", message))));

                                context.Exit();
                            }).Start();
                        }
                        else
                        {
                            var message = "V8 Script Engine : Started";
                            Log.Trace(message, configuration.Verbose);
                            returnValue = CefV8Value.CreateString(JsonMapper.ToJson(new StatusHelper("OK", message)));
                        }
                    }
                    else
                    {
                        returnValue = DontMeetRequirements(context, null);
                    };
                }
                return(true);
            }
            catch (Exception ex)
            {
                returnValue = CefV8Value.CreateNull();
                exception   = ex.Message;
                return(true);
            }
        }
Ejemplo n.º 16
0
 public ScriptEngine(object n)
 {
     using (var stream = Assembly.GetExecutingAssembly().GetManifestResourceStream("H3ml.Script.Portable.init.js"))
         using (var reader = new StreamReader(stream))
             _v8.Execute(reader.ReadToEnd());
 }