コード例 #1
0
    public async ValueTask <ParsedScript> ReadAsync(Stream stream, CancellationToken ct = default)
    {
        var script = await ReadRawAsync(stream, ct);

        if (script == null)
        {
            return(ParsedScript.Empty);
        }

        Plan.Change <string, string>[] changes;
        if (script.Changes == null)
        {
            changes = Array.Empty <Plan.Change <string, string> >();
        }
        else
        {
            changes = script.Changes.Select(c => Plan.Change.Create(AbsPath(c.Document), AbsPath(c.Update))).ToArray();
        }
        EnC.EditAndContinueCapabilities?caps     = null;
        IEnumerable <string>            unknowns = Array.Empty <string>();

        if (script.Capabilities != null)
        {
            IEnumerable <EnC.EditAndContinueCapabilities> goodCaps;
            (goodCaps, unknowns) = EditAndContinueCapabilitiesParser.Parse(script.Capabilities);
            var totalCaps = EnC.EditAndContinueCapabilities.None;
            foreach (var cap in goodCaps)
            {
                totalCaps |= cap;
            }
            caps = totalCaps;
        }
        return(ParsedScript.Make(changes, caps, unknowns));
    }
コード例 #2
0
    public static dynamic Evaluate(string key, string script, IDictionary <string, object> parameterValuePair = null)
    {
        try
        {
            using (ScriptEngine engine = new ScriptEngine(ScriptEngine.VBScriptLanguage))
            {
                List <object> parameters = new List <object>()
                {
                    "ADMIN"
                };
                string extraParameters = string.Empty;
                if (parameterValuePair != null && parameterValuePair.Count > 0)
                {
                    extraParameters = "," + string.Join(",", parameterValuePair.Select(e => e.Key));
                    foreach (var para in parameterValuePair)
                    {
                        parameters.Add(para.Value);
                    }
                }
                string       parsedScript = string.Format(@"Function {0}(NecUserProfile {2})
	{1}
	End Function"    , key, script, extraParameters);
                ParsedScript parsed       = engine.Parse(parsedScript);
                dynamic      value        = parsed.CallMethod(key, parameters.ToArray());
                return((value != null) ? value.ToString() : string.Empty);
            }
        }
        catch (Exception ex)
        {
            throw;
        }
    }
コード例 #3
0
        /// <summary>
        /// Get a payload list for the mutation
        /// </summary>
        /// <param name="rawRequest"></param>
        /// <param name="mutationRule"></param>
        /// <param name="hasFuzz">Whether the request contains <fuzz></param>
        /// <param name="entityId">The entitiy id</param>
        /// <returns></returns>
        public List <string> GeneratePayloadListFromMutation(string rawRequest, TestJob testJob, bool hasFuzz, string entityId)
        {
            List <string> payloadList = new List <string>();

            string mutationRule  = testJob.TestDef.Mutation;
            string payloadString = "";

            if (mutationRule.StartsWith(JAVASCRIPT_FUNCTION_TAG))
            {
                //extract JS function from rule
                string jsCode = mutationRule.Substring(JAVASCRIPT_FUNCTION_TAG.Length);
                //function should match the signature Callback(<string>,<string>,

                using (ScriptEngine engine = new ScriptEngine(ScriptEngine.JavaScriptLanguage))
                {
                    ParsedScript parsed = engine.Parse(jsCode);
                    payloadString = parsed.CallMethod(CALLBACK_NAME,
                                                      rawRequest, testJob.ParameterName, testJob.ParameterValue, testJob.RequestLocation.ToString()) as string;
                }
            }
            else
            {
                payloadString = mutationRule;
            }

            if (hasFuzz)
            {
                payloadString = payloadString.Replace("$original", String.Empty);
            }
            else
            {
                payloadString = payloadString.Replace("$original", testJob.ParameterValue);
            }
            payloadString = payloadString.Replace("$entity_id", entityId);

            if (!String.IsNullOrWhiteSpace(payloadString))
            {
                payloadString = payloadString.Replace(@"\,", "__comma__");
                var list = payloadString.Split(',');
                foreach (string payload in list)
                {
                    string finalPayload = payload.Replace("__comma__", ",");
                    payloadList.Add(finalPayload);
                    if (_testFile.GenerateAllEncodings) //also add encoding variants for the payload
                    {
                        payloadList.Add(Utils.UrlEncode(finalPayload));
                        payloadList.Add(Utils.UrlEncode(Utils.UrlEncode(finalPayload)));
                        payloadList.Add(Utils.UrlEncodeAll(finalPayload));
                        payloadList.Add(Utils.JSONEncode(finalPayload));
                        payloadList.Add(Utils.HtmlEncode(finalPayload));
                        payloadList.Add(Utils.Base64Encode(finalPayload));
                    }
                }
            }

            return(payloadList);
        }
コード例 #4
0
        public void CustomTester_TestScriptingEngine()
        {
            using (ScriptEngine engine = new ScriptEngine(ScriptEngine.JavaScriptLanguage))
            {
                ParsedScript parsed = engine.Parse(
                    "function Callback(x){return '1,2,'+x;}");

                var val = parsed.CallMethod("Callback", 3) as string;

                Assert.IsNotNull(val);
                Assert.AreEqual("1,2,3", val);
            }
        }
コード例 #5
0
        /// <summary>
        /// Run Javascript validation
        /// </summary>
        /// <param name="validation"></param>
        /// <param name="testResponseList"></param>
        /// <returns></returns>
        private bool RunJavaScriptValidation(string validation, List <string> testResponseList)
        {
            //extract JS function from rule
            string jsCode = validation.Substring(JAVASCRIPT_FUNCTION_TAG.Length);
            //function should match the signature boolean Callback(response1,...,responseN)
            bool found = false;

            using (ScriptEngine engine = new ScriptEngine(ScriptEngine.JavaScriptLanguage))
            {
                ParsedScript parsed = engine.Parse(jsCode);
                found = (bool)parsed.CallMethod(CALLBACK_NAME, testResponseList.ToArray());
            }
            return(found);
        }
コード例 #6
0
ファイル: GoogleTranslator.cs プロジェクト: radtek/Ocr
        private static string LazyGenerateToken(string text)
        {
            if (jsEngine == null)
            {
                jsEngine = new ScriptEngine("jscript");
            }

            // https://github.com/hujingshuang/MTrans/blob/master/tk/Google.js
            ParsedScript parsed = jsEngine.Parse(@"function token(a) {
    var k = """";
    var b = 406644;
    var b1 = 3293161072;

    var jd = ""."";
    var sb = ""+-a^+6"";
    var Zb = ""+-3^+b+-f"";

    for (var e = [], f = 0, g = 0; g < a.length; g++) {
        var m = a.charCodeAt(g);
        128 > m ? e[f++] = m: (2048 > m ? e[f++] = m >> 6 | 192 : (55296 == (m & 64512) && g + 1 < a.length && 56320 == (a.charCodeAt(g + 1) & 64512) ? (m = 65536 + ((m & 1023) << 10) + (a.charCodeAt(++g) & 1023), e[f++] = m >> 18 | 240, e[f++] = m >> 12 & 63 | 128) : e[f++] = m >> 12 | 224, e[f++] = m >> 6 & 63 | 128), e[f++] = m & 63 | 128)
    }
    a = b;
    for (f = 0; f < e.length; f++) a += e[f],
    a = RL(a, sb);
    a = RL(a, Zb);
    a ^= b1 || 0;
    0 > a && (a = (a & 2147483647) + 2147483648);
    a %= 1E6;
    return a.toString() + jd + (a ^ b)
};

function RL(a, b) {
    var t = ""a"";
    var Yb = ""+"";
    for (var c = 0; c < b.length - 2; c += 3) {
        var d = b.charAt(c + 2),
        d = d >= t ? d.charCodeAt(0) - 87 : Number(d),
        d = b.charAt(c + 1) == Yb ? a >>> d: a << d;
        a = b.charAt(c) == Yb ? a + d & 4294967295 : a ^ d
    }
    return a
}");

            return(parsed.CallMethod("token", text).ToString());
        }
コード例 #7
0
        public Extension(String path)
        {
            _extensionPath = path;
            _engine        = new ScriptEngine();
            _watcher       = new FileSystemWatcher(path)
            {
                EnableRaisingEvents = true
            };
            _watcher.Changed += _watcher_Changed;

            String entryPoint = Path.Combine(path, "extension.js");

            if (!File.Exists(entryPoint))
            {
                throw new Exception("Extension must contain an extension.js file.");
            }

            var files = Directory.GetFiles(path, "*.*", SearchOption.AllDirectories).ToList();

            foreach (var filePath in files)
            {
                var file = new FileInfo(filePath);
                _watchedFiles.Add(filePath, file.LastWriteTimeUtc);
            }

            _engine.SetNamedItem("lumen", new LumenScript(this));

            try {
                LoadScript(Path.Combine(path, @"..\common.js"));

                _parsed = LoadScript(entryPoint);

                __extension = new ParsedScript(_engine, _engine.Eval(_extensionIdent));

                ExtensionManager.Current.Add(this);
            }
            catch (ScriptException ex) {
                var s = _scripts.FromLineNumber(ex.Line);
                ex.Line = s.TranslateLineNumber(ex.Line);
                System.Windows.MessageBox.Show(ex.ErrorType + ": " + ex.Description + "\t\t\t" + s.Name + ":" + ex.Line);
            }
        }
コード例 #8
0
ファイル: BaiduTranslator.cs プロジェクト: radtek/Ocr
        private string GetSign(string text, string gtk)
        {
            if (jsEngine == null)
            {
                jsEngine = new ScriptEngine("jscript");
            }

            // https://github.com/hujingshuang/MTrans/blob/master/tk/Baidu.js
            ParsedScript parsed = jsEngine.Parse(@"function a(r, o) {
    for (var t = 0; t < o.length - 2; t += 3) {
        var a = o.charAt(t + 2);
        a = a >= ""a"" ? a.charCodeAt(0) - 87 : Number(a),
        a = ""+"" === o.charAt(t + 1) ? r >>> a: r << a,
        r = ""+"" === o.charAt(t) ? r + a & 4294967295 : r ^ a
    }
    return r
}
var C = null;
var token = function(r, _gtk) {
    var o = r.length;
    o > 30 && (r = """" + r.substr(0, 10) + r.substr(Math.floor(o / 2) - 5, 10) + r.substring(r.length, r.length - 10));
    var t = void 0,
    t = null !== C ? C: (C = _gtk || """") || """";
    for (var e = t.split("".""), h = Number(e[0]) || 0, i = Number(e[1]) || 0, d = [], f = 0, g = 0; g < r.length; g++) {
        var m = r.charCodeAt(g);
        128 > m ? d[f++] = m: (2048 > m ? d[f++] = m >> 6 | 192 : (55296 === (64512 & m) && g + 1 < r.length && 56320 === (64512 & r.charCodeAt(g + 1)) ? (m = 65536 + ((1023 & m) << 10) + (1023 & r.charCodeAt(++g)), d[f++] = m >> 18 | 240, d[f++] = m >> 12 & 63 | 128) : d[f++] = m >> 12 | 224, d[f++] = m >> 6 & 63 | 128), d[f++] = 63 & m | 128)
    }
    for (var S = h,
    u = ""+-a^+6"",
    l = ""+-3^+b+-f"",
    s = 0; s < d.length; s++) S += d[s],
    S = a(S, u);

    return S = a(S, l),
    S ^= i,
    0 > S && (S = (2147483647 & S) + 2147483648),
    S %= 1e6,
    S.toString() + ""."" + (S ^ h)
}");

            return(parsed.CallMethod("token", text, gtk).ToString());
        }
コード例 #9
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="script"></param>
        public RedjsConfig(string script)
        {
            this.Script = script;

            //执行js 脚本,获取版本号 和 发布时间
            using (ScriptEngine engine = new ScriptEngine("jscript"))
            {
                var          _c        = engine.Eval(script);
                ParsedScript _v_parsed = engine.Parse("function getVersion(){var _c = new Config(); return  _c.version ;}");

                var _v = _v_parsed.CallMethod("getVersion");

                ParsedScript _t_parsed = engine.Parse("function getTime(){var _c = new Config(); return  _c.releaseTime ;}");

                var _t = _t_parsed.CallMethod("getTime");

                this.Version = _v.ToString();

                this.ReleaseTime = _t.ToString().ConvertTo <DateTime>();;
            }
        }
コード例 #10
0
        private ParsedScript LoadScript(String scriptPath)
        {
            ParsedScript result        = null;
            String       script        = String.Empty;
            var          file          = new FileInfo(scriptPath);
            var          last          = _scripts.Count > 0 ? _scripts.Last() : new ExtensionScript();
            int          startPosition = last.StartPosition + last.Length;

            using (var sr = new StreamReader(scriptPath)) {
                script = sr.ReadToEnd();
            }
            try {
                result = _engine.Parse(script);
            }
            catch (ScriptException ex) {
                System.Windows.MessageBox.Show(ex.ErrorType + ": " + ex.Description + "\t\t\t" + file.Name + ":" + ex.Line);
            }

            _scripts.Add(new ExtensionScript {
                Name = file.Name, StartPosition = startPosition, Length = script.Length
            });

            return(result);
        }
コード例 #11
0
    private object Parse(string text, bool expression)
    {
        const string varName = "x___";

        System.Runtime.InteropServices.ComTypes.EXCEPINFO exceptionInfo;
        object result;

        _engine.SetScriptState(ScriptState.Connected);

        ScriptText flags = ScriptText.None;

        if (expression)
        {
            flags |= ScriptText.IsExpression;
        }

        try
        {
            // immediate expression computation seems to work only for 64-bit
            // so hack something for 32-bit...
            if (_parse32 != null)
            {
                if (expression)
                {
                    // should work for jscript & vbscript at least...
                    text = varName + "=" + text;
                }
                _parse32.ParseScriptText(text, null, null, null, IntPtr.Zero, 0, flags, out result, out exceptionInfo);
            }
            else
            {
                _parse64.ParseScriptText(text, null, null, null, IntPtr.Zero, 0, flags, out result, out exceptionInfo);
            }
        }
        catch
        {
            if (_site._lastException != null)
            {
                throw _site._lastException;
            }

            throw;
        }

        IntPtr dispatch;

        if (expression)
        {
            // continue  out 32-bit hack...
            if (_parse32 != null)
            {
                _engine.GetScriptDispatch(null, out dispatch);
                object dp = Marshal.GetObjectForIUnknown(dispatch);
                try
                {
                    return(dp.GetType().InvokeMember(varName, BindingFlags.GetProperty, null, dp, null));
                }
                catch
                {
                    if (_site._lastException != null)
                    {
                        throw _site._lastException;
                    }

                    throw;
                }
            }
            return(result);
        }

        _engine.GetScriptDispatch(null, out dispatch);
        ParsedScript parsed = new ParsedScript(this, dispatch);

        return(parsed);
    }