Ejemplo n.º 1
0
        /// <summary>
        /// Invokes the engine and returns the result of the invocation.
        /// </summary>
        /// <param name="engine">The engine.</param>
        /// <param name="type">The type.</param>
        /// <param name="path">The path.</param>
        /// <param name="context">The context.</param>
        /// <returns></returns>
        /// <exception cref="System.Exception">Unknown view type.</exception>
        public Task <ViewInvokeResult> InvokeEngine(IJsEngine engine, ViewType type, string path, ViewContext context)
        {
            if (type == ViewType.Full)
            {
                if (string.Equals(path, "{auto}", StringComparison.InvariantCultureIgnoreCase))
                {
                    path = context.HttpContext.Request.Path;
                    if (context.HttpContext.Request.QueryString.HasValue)
                    {
                        path += context.HttpContext.Request.QueryString.Value;
                    }
                }

                var result = engine.CallFunction("RenderView", path, context.ViewData.Model, context.ViewBag);
                return(Task.FromResult(new ViewInvokeResult {
                    Html = result.html,
                    Status = result.status,
                    Redirect = result.redirect
                }));
            }
            if (type == ViewType.Partial)
            {
                return(Task.FromResult(new ViewInvokeResult
                {
                    Html = (string)engine.CallFunction("RenderPartialView", path, context.ViewData.Model, context.ViewBag)
                }));
            }
            throw new Exception("Unknown view type.");
        }
Ejemplo n.º 2
0
        public object Invoke(string jsv, params object[] pp)
        {
            try
            {
                return(engine.CallFunction(jsv, pp));
            }
            catch (JsEngineException e)
            {
                Log.Logs.Instance.PushError($"[Script-{Version.id}] An engine-error occurred while running the script.\r\n" + e.Message);
            }
            catch (JsCompilationException e)
            {
                Log.Logs.Instance.PushError($"[Script-{Version.id}] An compile-error occurred while running the script.\r\n" + e.Message);
            }
            catch (JsRuntimeException e)
            {
                Log.Logs.Instance.PushError($"[Script-{Version.id}] An runtime-error occurred while running the script.\r\n" + e.Message);
            }
            catch (Exception e)
            {
                Log.Logs.Instance.PushError($"[Script-{Version.id}] " + e);
            }

            return(null);
        }
Ejemplo n.º 3
0
        /// <summary>
        /// "Packs" a JS code by using Dean Edwards' Packer
        /// </summary>
        /// <param name="content">Text content of JS asset</param>
        /// <returns>Minified text content of JS asset</returns>
        public string Pack(string content)
        {
            Initialize();

            string newContent;

            try
            {
                newContent = _jsEngine.CallFunction <string>(PACKING_FUNCTION_NAME,
                                                             content, _options.Base62Encode, _options.ShrinkVariables);
            }
            catch (JsScriptException e)
            {
                string errorDetails = JsErrorHelpers.GenerateErrorDetails(e, true);

                var           stringBuilderPool   = StringBuilderPool.Shared;
                StringBuilder errorMessageBuilder = stringBuilderPool.Rent();
                errorMessageBuilder.AppendLine(e.Message);
                errorMessageBuilder.AppendLine();
                errorMessageBuilder.Append(errorDetails);

                string errorMessage = errorMessageBuilder.ToString();
                stringBuilderPool.Return(errorMessageBuilder);

                throw new JsPackingException(errorMessage);
            }

            return(newContent);
        }
Ejemplo n.º 4
0
 public PDDApi()
 {
     jsEngine.ExecuteFile(@"../../jm.js");
     _nano_fp = (string)jsEngine.CallFunction("create_nano_fp");
     Session.WithHeader("Accept", "application/json, text/plain, */*");
     Session.WithHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/85.0.4183.121 Safari/537.36 Edg/85.0.564.68");
     Session.Cookies.Add(
         "ua",
         new Cookie("ua",
                    @"Mozilla%2F5.0%20(Windows%20NT%2010.0%3B%20
                         Win64%3B%20x64)%20AppleWebKit%2F537.36%20(KH
                         TML%2C%20like%20Gecko)%20Chrome%2F85.0.4183.1
                         21%20Safari%2F537.36%20Edg%2F85.0.564.68"));
     Session.Cookies.Add(
         "_nano_fp",
         new Cookie("_nano_fp", _nano_fp));
 }
Ejemplo n.º 5
0
        private static string EncodeData(string data, string key, int keyId, out string Ctkey)
        {
            IJsEngineSwitcher engineSwitcher = JsEngineSwitcher.Current;

            engineSwitcher.EngineFactories.Add(new JurassicJsEngineFactory());
            engineSwitcher.DefaultEngineName = JurassicJsEngine.EngineName;
            using (IJsEngine engine = JsEngineSwitcher.Current.CreateDefaultEngine())
            {
                engine.Execute(DedeDataJsCode);
                if (keyId == 1)
                {
                    engine.Execute("var this_UrlKey1 = 'db0FaVXtwixFUGGQ1Iq9dN7yMrJ9DFHQ';var this_UrlKey2 = 'R8nD2B0DRcT0IoFrA5UqHeHLeFsbrOBvXIVhKmgcXXcDLDrQemyyQLdDpAom9N'");
                }
                var publickey = engine.CallFunction("getCtKey", key);
                Ctkey = publickey.ToString();
                string PostjsonStr = engine.CallFunction("encode", data, publickey).ToString();
                return(PostjsonStr);
            }
        }
Ejemplo n.º 6
0
        public string Transform(string markdown)
        {
            _jsEngine.Evaluate(@"marked.setOptions({
  highlight: function (code) {
    return hljs.highlightAuto(code).value;
  }
});"
                               );

            return(_jsEngine.CallFunction <string>("marked", markdown));
        }
Ejemplo n.º 7
0
        /// <summary>
        /// Ensures that React has been correctly loaded into the specified engine.
        /// </summary>
        /// <param name="engine">Engine to check</param>
        private static void EnsureReactLoaded(IJsEngine engine)
        {
            var result = engine.CallFunction <bool>("ReactNET_initReact");

            if (!result)
            {
                throw new ReactNotInitialisedException(
                          "React has not been loaded correctly. Please expose your version of React as global " +
                          "variables named 'React', 'ReactDOM', and 'ReactDOMServer', or enable the " +
                          "'LoadReact' configuration option to use the built-in version of React."
                          );
            }
        }
        /// <summary>
        /// Ensures that React has been correctly loaded into the specified engine.
        /// </summary>
        /// <param name="engine">Engine to check</param>
        private static void EnsureReactLoaded(IJsEngine engine)
        {
            var result = engine.CallFunction <string[]>("ReactNET_initReact");

            if (result.Length != 0)
            {
                throw new ReactNotInitialisedException(
                          $"React has not been loaded correctly: missing ({string.Join(", ", result)})." +
                          "Please expose your version of React as global variables named " +
                          "'React', 'ReactDOM', and 'ReactDOMServer', or enable the 'LoadReact'" +
                          "configuration option to use the built-in version of React."
                          );
            }
        }
Ejemplo n.º 9
0
        private static JObject DecodeData(string data, string key, out int keyId)
        {
            keyId = 0;
            IJsEngineSwitcher engineSwitcher = JsEngineSwitcher.Current;

            engineSwitcher.EngineFactories.Add(new JurassicJsEngineFactory());
            engineSwitcher.DefaultEngineName = JurassicJsEngine.EngineName;
            using (IJsEngine engine = JsEngineSwitcher.Current.CreateDefaultEngine())
            {
                engine.Execute(DedeDataJsCode);
                var     publickey   = engine.CallFunction("getCtKey", key);
                string  PostjsonStr = engine.CallFunction("decode", data, publickey).ToString();
                JObject jo;
                if (PostjsonStr.StartsWith("{"))
                {
                    jo = JsonStringToJsonObj(PostjsonStr);
                    if (jo != null)
                    {
                        return(jo);
                    }
                }
                keyId = 1;
                engine.Execute("var this_UrlKey1 = 'db0FaVXtwixFUGGQ1Iq9dN7yMrJ9DFHQ';var this_UrlKey2 = 'R8nD2B0DRcT0IoFrA5UqHeHLeFsbrOBvXIVhKmgcXXcDLDrQemyyQLdDpAom9N'");
                publickey   = engine.CallFunction("getCtKey", key);
                PostjsonStr = engine.CallFunction("decode", data, publickey).ToString();
                if (PostjsonStr.StartsWith("{"))
                {
                    jo = JsonStringToJsonObj(PostjsonStr);
                    if (jo != null)
                    {
                        return(jo);
                    }
                }
                return(null);
            }
        }
Ejemplo n.º 10
0
        /// <summary>
        /// Calls a JavaScript function using the specified engine. If <typeparamref name="T"/> is
        /// not a scalar type, the function is assumed to return a string of JSON that can be
        /// parsed as that type.
        /// </summary>
        /// <typeparam name="T">Type returned by function</typeparam>
        /// <param name="engine">Engine to execute function with</param>
        /// <param name="function">Name of the function to execute</param>
        /// <param name="args">Arguments to pass to function</param>
        /// <returns>Value returned by function</returns>
        public static T CallFunctionReturningJson <T>(this IJsEngine engine, string function, params object[] args)
        {
            if (ValidationHelpers.IsSupportedType(typeof(T)))
            {
                // Type is supported directly (ie. a scalar type like string/int/bool)
                // Just execute the function directly.
                return(engine.CallFunction <T>(function, args));
            }
            // The type is not a scalar type. Assume the function will return its result as
            // JSON.
            var resultJson = engine.CallFunction <string>(function, args);

            try
            {
                return(JsonConvert.DeserializeObject <T>(resultJson));
            }
            catch (JsonReaderException ex)
            {
                throw new ReactException(string.Format(
                                             "{0} did not return valid JSON: {1}.\n\n{2}",
                                             function, ex.Message, resultJson
                                             ));
            }
        }
Ejemplo n.º 11
0
 public void CallFunction(string functionName, params object[] args)
 {
     new Thread(() =>
     {
         try
         {
             setMessage("执行开始");
             jsEngine.CallFunction(functionName, args);
             setMessage("执行结束");
         }
         catch (Exception ex)
         {
             setMessage(ex.ToString());
         }
     }).Start();
 }
        /// <summary>
        /// Ensures that React has been correctly loaded into the specified engine.
        /// </summary>
        /// <param name="engine">Engine to check</param>
        private void EnsureReactLoaded(IJsEngine engine)
        {
            var globalsString = engine.CallFunction <string>("ReactNET_initReact");

            string[] globals = globalsString.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries);

            if (globals.Length != 0)
            {
                _scriptLoadException = new ReactNotInitialisedException(
                    $"React has not been loaded correctly: missing ({string.Join(", ", globals)})." +
                    "Please expose your version of React as global variables named " +
                    "'React', 'ReactDOM', and 'ReactDOMServer', or enable the 'LoadReact'" +
                    "configuration option to use the built-in version of React."
                    );
            }
        }
Ejemplo n.º 13
0
        /// <summary>
        /// "Packs" a JS code by using Dean Edwards' Packer
        /// </summary>
        /// <param name="content">Text content of JS asset</param>
        /// <returns>Minified text content of JS asset</returns>
        public string Pack(string content)
        {
            Initialize();

            string newContent;

            try
            {
                newContent = _jsEngine.CallFunction <string>(PACKING_FUNCTION_NAME,
                                                             content, _options.Base62Encode, _options.ShrinkVariables);
            }
            catch (JsRuntimeException e)
            {
                throw new JsPackingException(JsErrorHelpers.Format(e));
            }

            return(newContent);
        }
Ejemplo n.º 14
0
        public string ProcessEvent(string serializedEvent)
        {
            /*
             * Avoid high memory usage as described in exploration 2020-02-02:
             * Use specialized implementation based on `CallFunction` instead of `Evaluate`.
             *
             * var eventExpression = AsJavascriptExpression(serializedEvent);
             *
             * var expressionJavascript = ProcessFromElm019Code.processEventSyncronousJsFunctionName + "(" + eventExpression + ")";
             *
             * return EvaluateInJsEngineAndReturnResultAsString(expressionJavascript);
             */

            var evalResult = javascriptEngine.CallFunction(
                ProcessFromElm019Code.processEventSyncronousJsFunctionName, serializedEvent);

            return(evalResult?.ToString());
        }
Ejemplo n.º 15
0
 private T CallJSFunction <T>(string functionName, params object[] args)
 {
     try
     {
         return(engine.CallFunction <T>(functionName, args));
     }
     catch (JsCompilationException e)
     {
         Global.Error("行" + e.LineNumber + "列" + e.ColumnNumber + "编译错误:" + e.Description);
         throw e;
     }
     catch (JsRuntimeException e)
     {
         Global.Error("行" + e.LineNumber + "列" + e.ColumnNumber + "运行时错误:" + e.Description);
         throw e;
     }
     catch (Exception e)
     {
         Global.Error(e.Message);
         throw e;
     }
 }
Ejemplo n.º 16
0
        public string Transform(string text, bool sanitize = true)
        {
            if (text == null)
            {
                throw new ArgumentNullException("text");
            }

            string result;

            lock (_compilationSynchronizer)
            {
                Initialize();

                _jsEngine.Evaluate(@"
marked.setOptions({
    gfm: true,
    tables: true,
    breaks: true,
    pedantic: false,
    sanitize: false,
    smartLists: true,
    silent: false,
    highlight: function (code) {
        return hljs.highlightAuto(code).value;
    },
    langPrefix: '',
    smartypants: false,
    headerPrefix: '',
    renderer: new marked.Renderer(),
    xhtml: false
});");

                result = _jsEngine.CallFunction <string>("marked", text);
            }

            return((sanitize) ? HtmlUtility.SanitizeHtml(result) : result);
        }
 public string Transform(string code, BabelConfig config, string fileName = "unknown")
 {
     return(_engine.CallFunction <string>("babelTransform", code, config.Serialize(), fileName));
 }
Ejemplo n.º 18
0
        public Model.TestTaskForm TemplateTestTaskToForm(string template)
        {
            CheckTemplateTestTask(template);
            Model.TestTaskForm result = new Model.TestTaskForm();
            var jsonForm = _engine.CallFunction <string>("translateTemplateTestTaskToForm", new object[1] {
                template
            });
            dynamic form = Newtonsoft.Json.JsonConvert.DeserializeObject <ExpandoObject>(jsonForm);

            result.Header = form.header;

            Int64 type = form.type;

            switch (type)
            {
            case 0:
                result.Type = "Short Answer";
                break;

            case 1:
                result.Type = "Single Choose";
                break;

            case 2:
                result.Type = "Multiply Choose";
                break;

            default:
                Console.WriteLine("wtf " + (form.type == 0));
                break;
            }
            result.Grammar        = form.grammar;
            result.TaskText       = form.testText;
            result.FeedbackScript = form.feedbackScript;

            return(result);
        }
Ejemplo n.º 19
0
		/// <summary>
		/// Ensures that React has been correctly loaded into the specified engine.
		/// </summary>
		/// <param name="engine">Engine to check</param>
		private static void EnsureReactLoaded(IJsEngine engine)
		{
			var result = engine.CallFunction<bool>("ReactNET_initReact");
			if (!result)
			{
				throw new ReactNotInitialisedException(
					"React has not been loaded correctly. Please expose your version of React as a global " +
					"variable named 'React', or enable the 'LoadReact' configuration option to " +
					"use the built-in version of React."
				);
			}
		}
Ejemplo n.º 20
0
        public void CallingOfFunctionWithoutParametersIsCorrect()
        {
            // Arrange
            const string functionCode = @"function hooray() {
	return 'Hooray!';
}";
            const string targetOutput = "Hooray!";

            // Act
            _jsEngine.Execute(functionCode);
            var output = (string)_jsEngine.CallFunction("hooray");

            // Assert
            Assert.AreEqual(targetOutput, output);
        }
Ejemplo n.º 21
0
 public object CallFunction(string functionName, params object[] args)
 {
     CheckDisposed();
     return(_engine.CallFunction(functionName, args));
 }
		/// <summary>
		/// Ensures that React has been correctly loaded into the specified engine.
		/// </summary>
		/// <param name="engine">Engine to check</param>
		private static void EnsureReactLoaded(IJsEngine engine)
		{
			var result = engine.CallFunction<bool>("ReactNET_initReact");
			if (!result)
			{
				throw new ReactNotInitialisedException(
					"React has not been loaded correctly. Please expose your version of React as global " +
					"variables named 'React', 'ReactDOM' and 'ReactDOMServer', or enable the " +
					"'LoadReact' configuration option to use the built-in version of React. See " +
					"http://reactjs.net/guides/byo-react.html for more information."
				);
			}
		}
Ejemplo n.º 23
0
 public string Transform(string markdown)
 {
     return(_jsEngine.CallFunction <string>("marked", markdown));
 }