Пример #1
0
        /// <summary>
        /// 静态
        /// </summary>
        static TranslationHelper()
        {
            var runtime = ChakraRuntime.Create();

            _baseUrl         = "http://translate.google.cn/translate_a/single";
            _cookieContainer = new CookieContainer();
            _chakraContext   = runtime.CreateContext(true);

            _googleTransBaseUrl = "https://translate.google.com/";
            _googleTkk          = "";

            var baseResultHtml = HttpHelper.GetRequest(_googleTransBaseUrl, _cookieContainer, null);

            int index      = baseResultHtml.IndexOf("tkk:");
            int startIndex = baseResultHtml.IndexOf("'", index);
            int endIndex   = baseResultHtml.IndexOf("'", startIndex + 1);

            _googleTkk = baseResultHtml.Substring(startIndex + 1, endIndex - startIndex);
            //Regex re = new Regex(@"(?<=tkk=')(.*?)(?=')");
            //Regex re = new Regex("(?<=(tkk:'))[.\\s\\S]*?(?=(';))");
            //_googleTkk = re.Match(baseResultHtml).ToString();

            var jsFileText = File.ReadAllText("../translateLib/gettk.js");

            _chakraContext.RunScript(jsFileText); //运行脚本
        }
Пример #2
0
 public HttpRequestor(string serverUrl, ChakraContext context)
 {
     _serverUrl          = serverUrl;
     _client             = new HttpClient();
     _client.BaseAddress = new Uri(_serverUrl);
     _client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
     _context = context;
 }
Пример #3
0
 public virtual void TestCleanup()
 {
     CleanupContext();
     context.Dispose();
     context = null;
     LogAndPop("Context released");
     runtime.Dispose();
     runtime = null;
     LogAndPop("Runtime released");
 }
Пример #4
0
 public virtual void TestInitialize()
 {
     runtime = ChakraRuntime.Create();
     LogAndPush("Runtime Created");
     context = runtime.CreateContext(true);
     LogAndPush("Context created");
     converter = context.ServiceNode.GetService <IJSValueConverterService>();
     SetupContext();
     Log("Context setup complete");
 }
Пример #5
0
        private void initJSRuntime()
        {
            runtime = ChakraRuntime.Create();
#if DEBUG
            context = runtime.CreateContext(true);
#else
            context = runtime.CreateContext(false);
#endif
            JSRequireLoader.EnableRequire(context, WorkPath);
            var s = Properties.Resources.boot;
            context.RunScript(Properties.Resources.boot);
        }
Пример #6
0
        public PluginManager(ChakraContext context, LoadPluginInstallerFunction loadPluginInstallerCallback)
        {
            context.GlobalObject.Binding.SetFunction <string, JavaScriptValue>("RequireNative", (name) =>
            {
                var plugin = loadPluginInstallerCallback(name);
                var stub   = createStubValue();
                plugin.Install(stub);
                return(stub.ReferenceValue);
            });
            var jsvalue = context.ServiceNode.GetService <IJSValueService>().CreateObject();

            apiContainer = new JSValue(context.GlobalObject.ServiceNode, jsvalue);
            context.GlobalObject.WriteProperty(API_OBJECT_NAME, apiContainer);
        }
Пример #7
0
 public void test1()
 {
     ChakraRuntime runtime = ChakraRuntime.Create();
     ChakraContext context = runtime.CreateContext(true);
     var           s       = context.RunScript("1+1");
     //context.GlobalObject.Binding.SetFunction<int, int>("add", Add);
     //context.RunScript("function test(callback){callback('hello world')})");
     //context.ServiceNode.GetService<IJSValueConverterService>().RegisterMethodConverter<string>();
     //context.GlobalObject.CallMethod<Action<string>>("test", echo);
     DebugEcho instance = new DebugEcho();
     //context.ServiceNode.GetService<IJSValueConverterService>().RegisterProxyConverter<DebugEcho>(
     //    (binding, instance, serviceNode) =>
     //    {
     //        binding.SetMethod<string>("echo",instance.Echo);
     //    });
     //DebugEcho obj = new DebugEcho();
     //context.GlobalObject.WriteProperty<DebugEcho>("debugEcho", obj);
 }
Пример #8
0
        string ParseValues(StateSubmissionField field, JObject source, ChakraRuntime runtime)
        {
            string output = string.Empty;

            foreach (string value in field.Values)
            {
                if (value.StartsWith("literal:"))
                {
                    output += value.Replace("literal:", string.Empty);
                }
                else
                {
                    try
                    {
                        var token       = source.SelectToken(value);
                        var tokenString = (string)token;
                        tokenString = tokenString == null ? string.Empty : tokenString;


                        if (!string.IsNullOrEmpty(field.OnGetValueJavascript) && !string.IsNullOrEmpty(tokenString))
                        {
                            ChakraContext context = runtime.CreateContext(true);
                            context.GlobalObject.WriteProperty <string>("token", tokenString);
                            context.RunScript(field.OnGetValueJavascript);
                            tokenString = context.GlobalObject.CallFunction <string>("onGetValue");
                        }

                        output += tokenString;
                    }
                    catch (Exception e1)
                    {
                        int x = 1;
                    }
                }
            }

            return(Format(field.MaxLength, field.Format, output));
        }
Пример #9
0
        public JSEngine(IConsole console, BaseOption option, IRandomGenerator randomGenerator, IDebugAdapter debugAdapter)
        {
            DefaultScriptsPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Scripts");
            _console           = console;
            var config = new JavaScriptHostingConfig();

            _context = JavaScriptHosting.Default.CreateContext(config);
            _context.RegisterEvalService();
            _prettyPrint      = new PrettyPrint(this);
            _timerCallsHelper = new TimerCallsHelper(this);
            _option           = option;
            _randomGenerator  = randomGenerator;
            ExposeConsoleToContext();
            ExposeCryptoHelpers();
            ExposeAElfOption();
            LoadCryptoJS();
            LoadEncodingJS();
            LoadAelfJs();
            LoadHelpersJs();
            ExposeHttpRequestorToContext();
            ExposeTimerCallsHelper();
            ExposeAccountSaver();
        }
Пример #10
0
        static void Main(string[] args)
        {
            var runtime = ChakraRuntime.Create();

            context = runtime.CreateContext(false);
            context.ServiceNode.GetService <IJSValueConverterService>().RegisterProxyConverter <ModuleLoader>(
                (value, obj, node) =>
            {
                value.SetFunction <string, ChakraCore.NET.API.JavaScriptValue>("Import", obj.LoadModule);
                value.SetMethod <string>("Echo", obj.Echo);
            }

                );

            context.GlobalObject.WriteProperty <ModuleLoader>("__Sys", loader);
            string script = System.IO.File.ReadAllText("ModuleShell.js");

            //context.ServiceNode.GetService<IContextSwitchService>().With(() =>
            //{
            //    loader.InitModuleCallback();
            //});

            //context.RunScript(script);
            //context.GlobalObject.CallFunction<string>("RunModule");

            //context.ServiceNode.GetService<IContextSwitchService>().With(
            //    () => { loader.LoadModule("Module1.js"); }
            //    );
            //context.GlobalObject.CallMethod<string>("Main","call from c# ok");
            projectModuleClass("_output", "Module1.js", "abc");
            JSValue x = context.GlobalObject.ReadProperty <JSValue>("_output");

            x.CallMethod <string>("main", "call from projected ok");
            Console.Write("Press Enter to exit");
            Console.ReadLine();
        }
Пример #11
0
 protected virtual void initContext(ChakraContext context, JavaScriptHostingConfig config)
 {
     PluginManager pluginManager = new PluginManager(context, config.LoadPlugin);
 }
Пример #12
0
        public override void Execute(Action onSuccess, Action <Exception> onFailure)
        {
            try
            {
                string filename = string.Format("{0}_{1}_{2}_{3}_{4}_{5}_{6}_{7}.txt",
                                                Configuration.State,
                                                StartDate.Month,
                                                StartDate.Day,
                                                StartDate.Year,
                                                EndDate.Month,
                                                EndDate.Day,
                                                EndDate.Year,
                                                DateTime.Now.Ticks);

                MongoClient    client   = new MongoClient(System.Environment.GetEnvironmentVariable("ScreeningCosmosDb", EnvironmentVariableTarget.Process));
                IMongoDatabase database = client.GetDatabase("Screening");
                IMongoCollection <BsonDocument> collection = database.GetCollection <BsonDocument>("Screening");

                OutputText = string.Empty;
                ChakraRuntime runtime = ChakraRuntime.Create();

                JObject headerObject = new JObject();
                headerObject.Add("StartMonth", StartDate.Month.ToString());
                headerObject.Add("StartDay", StartDate.Day.ToString());
                headerObject.Add("StartYear", StartDate.Year.ToString());
                headerObject.Add("EndMonth", EndDate.Month.ToString());
                headerObject.Add("EndDay", EndDate.Day.ToString());
                headerObject.Add("EndYear", EndDate.Year.ToString());
                headerObject.Add("Ticks", DateTime.Now.Ticks.ToString());
                headerObject.Add("RecordCount", Screenings.Count);

                List <string> headerValues = new List <string>();
                if (Configuration.HeaderConfiguration != null)
                {
                    foreach (StateSubmissionField field in Configuration.HeaderConfiguration)
                    {
                        headerValues.Add(ParseValues(field, headerObject, runtime));
                    }

                    if (Configuration.HeaderConfiguration.Count > 0)
                    {
                        OutputText += ((Configuration.EncloseFieldsInQuotes ? "\"" : string.Empty) + string.Join(Configuration.DefaultDelimiter, headerValues) + (Configuration.EncloseFieldsInQuotes ? "\"" : string.Empty)) + "\n";
                    }
                }

                if (Screenings != null)
                {
                    List <Screening> screeningsToPrint = new List <Screening>();
                    foreach (var screening in Screenings)
                    {
                        var jsonObject = JObject.FromObject(screening);

                        if (!string.IsNullOrEmpty(Configuration.OnExecuteJavascript))
                        {
                            var           jsonObjectString = jsonObject.ToString();
                            ChakraContext context          = runtime.CreateContext(true);
                            context.GlobalObject.WriteProperty <string>("screeningString", jsonObjectString);
                            context.RunScript(Configuration.OnExecuteJavascript);
                            context.RunScript("var screening=JSON.parse(screeningString);");
                            jsonObjectString = context.GlobalObject.CallFunction <string>("onExecute");
                            jsonObject       = JObject.Parse(jsonObjectString);
                        }

                        JToken forcePrint = null;
                        if (jsonObject.TryGetValue("ForcePrint", out forcePrint))
                        {
                            if (forcePrint.Value <bool>() == true)
                            {
                                screeningsToPrint.Add(screening);
                                continue;
                            }
                        }

                        jsonObject.Add("Type", "StateSubmissionRecord");
                        jsonObject.Add("State", Configuration.State);
                        jsonObject.Add("DatePrepared", DateTime.Now.ToString());
                        jsonObject.Add("FileProduced", string.Empty);
                        jsonObject.Add("DateSent", string.Empty);
                        jsonObject.Add("DateValidated", string.Empty);
                        jsonObject.Add("OutputFile", filename);

                        collection.InsertOne(
                            MongoDB.Bson.Serialization.BsonSerializer.Deserialize <BsonDocument>(jsonObject.ToString()));

                        List <string> screeningValues = new List <string>();

                        if (Configuration.RecordConfiguration != null)
                        {
                            foreach (StateSubmissionField field in Configuration.RecordConfiguration)
                            {
                                screeningValues.Add(ParseValues(field, jsonObject, runtime));
                            }
                        }

                        OutputText += ((Configuration.EncloseFieldsInQuotes ? "\"" : string.Empty) +
                                       string.Join(Configuration.DefaultDelimiter, screeningValues) +
                                       (Configuration.EncloseFieldsInQuotes ? "\"" : string.Empty)) + "\n";
                    }

                    if (screeningsToPrint.Count > 0)
                    {
                        var unitOfWork = new GeneratePhysicalStatePacket();
                        unitOfWork.State      = Configuration.State;
                        unitOfWork.StartDate  = StartDate;
                        unitOfWork.EndDate    = EndDate;
                        unitOfWork.Screenings = screeningsToPrint;
                        unitOfWork.Execute(() => {
                        }, (f) => { });
                    }
                }

                //Microsoft.Azure.KeyVault.KeyVaultKeyResolver cloudResolver = new Microsoft.Azure.KeyVault.KeyVaultKeyResolver(GetToken);
                //var rsa = cloudResolver.ResolveKeyAsync(@"https://neonprod01vault.vault.azure.net/keys/FileStorage",
                //    CancellationToken.None).Result;
                //BlobEncryptionPolicy policy = new BlobEncryptionPolicy(rsa, cloudResolver);
                //BlobRequestOptions options = new BlobRequestOptions() { EncryptionPolicy = policy };

                StorageCredentials  storageCredentials = new StorageCredentials(System.Environment.GetEnvironmentVariable("StorageAccountName", EnvironmentVariableTarget.Process), System.Environment.GetEnvironmentVariable("StorageKeyVault", EnvironmentVariableTarget.Process));
                CloudStorageAccount account            = new CloudStorageAccount(storageCredentials, useHttps: true);
                CloudBlobClient     storageClient      = account.CreateCloudBlobClient();
                CloudBlobContainer  storageContainer   = storageClient.GetContainerReference("statepackages");
                storageContainer.CreateIfNotExists(BlobContainerPublicAccessType.Off);

                CloudBlockBlob blob = storageContainer.GetBlockBlobReference(filename);

                using (var stream = new MemoryStream(Encoding.UTF8.GetBytes(OutputText ?? "")))
                {
                    if (stream.Length == 0)
                    {
                        return;
                    }
                    blob.UploadFromStream(stream, stream.Length, null, null, null);
                }

                string filter = string.Format("{{ Type: 'StateSubmissionRecord', OutputFile : '{0}'}}", filename);
                var    update = Builders <BsonDocument> .Update.Set("FileProduced", DateTime.Now.ToString());

                collection.UpdateMany(filter, update);
            }
            catch (Exception e)
            {
                onFailure(e);
            }

            onSuccess();
        }
Пример #13
0
 public static JavaScriptValue Eval(this ChakraContext context, string script)
 {
     return(context.ServiceNode.GetService <IHelperService>().Eval(script));
 }
Пример #14
0
        public static void RegisterEvalService(this ChakraContext context)
        {
            var svc = new ContextServiceWithHelper((ContextService)context.ServiceNode.GetService <IContextService>());

            context.ServiceNode.PushService <IHelperService>(svc);
        }
Пример #15
0
        public static byte[] RunScript(string file, HttpRequestHeader req, HttpRespondHeader res)
        {
            using (ChakraContext context = Runtime.CreateContext(true)) {
                //HttpRequestHeader
                if (!registered)
                {
                    context.ServiceNode.GetService <IJSValueConverterService>().RegisterProxyConverter <HttpRequestHeader>( //register the object converter
                        (binding, instance, serviceNode) => {
                        binding.SetFunction("getServer", new Func <HttpServers.BaseServer>(() => instance.Server));
                        binding.SetFunction("getHeaderKeys", new Func <Dictionary <string, string> >(() => instance.HeaderKeys));
                        binding.SetFunction("getParameters", new Func <System.Collections.Specialized.NameValueCollection>(() => instance.Parameters));
                        binding.SetFunction("getParametersJSON", new Func <string>(() => instance.Parameters.Serialize()));
                        binding.SetFunction("getAbsoluteFilePath", new Func <string>(() => instance.AbsoluteFilePath));
                    });
                    // HttpRespondHeader
                    context.ServiceNode.GetService <IJSValueConverterService>().RegisterProxyConverter <HttpRespondHeader>( //register the object converter
                        (binding, instance, serviceNode) =>
                    {
                        binding.SetMethod <string, string>("setState", (http, state) => instance.SetState(http.Equals("HTTP/1.0") ? HttpVersion.HTTP1_0 : http.Equals("HTTP/1.1") ? HttpVersion.HTTP2_0 : HttpVersion.UNKNOWN, state));
                        binding.SetMethod <string, string>("addHeader", (key, value) => instance.AddHeader(key, value));
                        binding.SetMethod <string>("setBody", (body) => instance.SetBody(body));
                        binding.SetMethod <System.Net.Sockets.TcpClient>("send", c => {
                            byte[] b = instance.Build();
                            c.GetStream().Write(b, 0, b.Length);
                            c.GetStream().Flush();
                        });
                        binding.SetMethod("markAsResponded", instance.Responded);
                    });
                    // TcpClient stuff
                    context.ServiceNode.GetService <IJSValueConverterService>().RegisterProxyConverter <System.Net.Sockets.TcpClient>( //register the object converter
                        (binding, instance, serviceNode) =>
                    {
                        binding.SetMethod <string>("sendText", (s) => {
                            byte[] b = Encoding.UTF8.GetBytes(s);
                            instance.GetStream().Write(b, 0, b.Length);
                            instance.GetStream().Flush();
                        });
                        binding.SetMethod <HttpRespondHeader>("send", (s) => {
                            byte[] b = s.Build();
                            instance.GetStream().Write(b, 0, b.Length);
                            instance.GetStream().Flush();
                        });
                        binding.SetFunction <string>("getIP", () => ((System.Net.IPEndPoint)instance.Client.RemoteEndPoint).Address.ToString());
                        binding.SetFunction <int>("getPort", () => ((System.Net.IPEndPoint)instance.Client.RemoteEndPoint).Port);
                        binding.SetMethod("close", instance.Close);
                        binding.SetFunction <string>("readString", () => {
                            byte[] b = new byte[instance.Available];
                            instance.GetStream().Read(b, 0, b.Length);
                            return(Encoding.UTF8.GetString(b));
                        });
                        binding.SetMethod <string, bool>("sendFile", (file, isBigFile) => { instance.Client.SendFile(file, null, null, isBigFile ? System.Net.Sockets.TransmitFileOptions.UseSystemThread : System.Net.Sockets.TransmitFileOptions.UseDefaultWorkerThread); });
                    });

                    registered = true;
                }


                context.GlobalObject.WriteProperty("RequestResult", "");
                context.GlobalObject.WriteProperty("RequestHandler", req);
                context.GlobalObject.WriteProperty("RespondHandler", res);
                context.GlobalObject.WriteProperty("Client", req.Client);
                context.GlobalObject.WriteProperty("AutoFlush", true);
                context.GlobalObject.Binding.SetMethod <string>("log", (s) => Console.WriteLine(s));
                context.GlobalObject.Binding.SetMethod <string>("send", (s) => {
                    req.Client.GetStream().Write(Encoding.UTF32.GetBytes(s), 0, s.Length);
                    if (context.GlobalObject.ReadProperty <bool>("AutoFlush"))
                    {
                        req.Client.GetStream().Flush();
                    }
                });
                context.GlobalObject.Binding.SetMethod("flush", () => req.Client.GetStream().Flush());
                context.GlobalObject.Binding.SetMethod("closeStream", () => req.Client.GetStream().Dispose());
                context.GlobalObject.Binding.SetMethod("closeConnection", () => req.Client.Close());

                try
                {
                    context.RunScript(System.IO.File.ReadAllText(file));
                }
                catch (Exception exp)
                {
                    ErrorLogger.WithTrace(req.Server.Settings, string.Format("[Warning][Backend error => RunScript()] : exception-message : {0}.\nstacktrace : {1}\n", exp.Message, exp.StackTrace), typeof(ChakraCoreObject));
                }

                if (res.DidRespond())
                {
                    Runtime.CollectGarbage();
                    return(HttpRequestHeader.ContentSplitter);
                }

                else
                {
                    byte[] b = Encoding.UTF8.GetBytes(context.GlobalObject.ReadProperty <string>("RequestResult"));
                    Runtime.CollectGarbage();
                    return(b);
                }
            }


            //context.Dispose();
        }