Пример #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 virtual void TestCleanup()
 {
     CleanupContext();
     context.Dispose();
     context = null;
     LogAndPop("Context released");
     runtime.Dispose();
     runtime = null;
     LogAndPop("Runtime released");
 }
Пример #3
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");
 }
Пример #4
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);
        }
Пример #5
0
        private static void ChakraCoreTestForWeb3()
        {
            var runtime = ChakraRuntime.Create();
            var context = runtime.CreateContext(true);

            context.GlobalObject.Binding.SetFunction <string, int>("print", Print); //js: function add(v){[native code]}
            context.RunScript(File.ReadAllText("/Users/peng/Downloads/bignumber.js"));
            context.RunScript(File.ReadAllText("/Users/peng/Downloads/web3.min.js"));
            context.RunScript("var console = {}; console.log = function(message, t){print(message)};console.error = function(message, t){print(message)};");
            context.RunScript("console.log('test');");
            context.RunScript("var Web3 = require('web3');var web3 = new Web3(); console.log(web3.toWei(20, 'ether'));");
            // Console.WriteLine(x);
        }
Пример #6
0
        private static void ChakraCoreTest()
        {
            var runtime = ChakraRuntime.Create();
            var context = runtime.CreateContext(true);

            context.GlobalObject.Binding.SetFunction <string, int>("print", Print); //js: function add(v){[native code]}
            context.RunScript(File.ReadAllText("/Users/peng/Downloads/test.js"));
            context.RunScript("var console = {};console.log = function(message, t){print(message)};console.error = function(message, t){print(message)};");
            context.RunScript("console.log('test');");
            var x = context.GlobalObject.CallFunction <int, int>("test", 4);

            Console.WriteLine(x);
        }
Пример #7
0
 public static void Inject(ChakraRuntime runtime)
 {
     runtime.ServiceNode.GetService <IJSValueConverterService>().RegisterProxyConverter <TestProxy>((binding, value, node) =>
     {
         var converter = node.GetService <IJSValueConverterService>();
         binding.SetFunction <string, string>("echo", value.Echo);
         binding.SetFunction <string>("GetName", value.GetName);
         converter.RegisterTask <int>();
         binding.SetFunction <Task <int> >("asyncFunction", value.AsyncCallAsync);
         converter.RegisterMethodConverter <string>();
         binding.SetMethod <Action <string> >("callBackToJs", value.CallBackToJS);
     });
 }
Пример #8
0
        private static void ChakraCoreTestForAElf()
        {
            var runtime = ChakraRuntime.Create();
            var context = runtime.CreateContext(true);

            context.GlobalObject.Binding.SetFunction <string, int>("print", Print); //js: function add(v){[native code]}
            context.RunScript(File.ReadAllText("/Users/peng/Downloads/aelf.js"));
            // context.RunScript(File.ReadAllText("/Users/peng/Downloads/test.js"));
            // context.RunScript("function test(a){console.log('received ' + a); return a+a;}");
            context.RunScript("var console = {}; console.log = function(message, t){print(message)}; console.error = function(message, t){print(message)};");
            context.RunScript("var Aelf = require('aelf'); var aelf = new Aelf(new Aelf.providers.HttpProvider('http://localhost:8000/chain')); aelf.chain.connectChain(); console.log(aelf.isConnected());");
            // var x = context.GlobalObject.CallFunction<string, string>("salt", "xxx");
            // Console.WriteLine(x);
        }
Пример #9
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);
 }
Пример #10
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));
        }
Пример #11
0
        private static void Main()
        {
            try
            {
                var js = "(() => { return 'Hello, World!'; })()";

                var sourceContext = JsSourceContext.FromIntPtr(IntPtr.Zero);
                using (var runtime = new ChakraRuntime())
                {
                    ChakraCore.JsRun(JsValueRef.FromString(js), sourceContext++, JsValueRef.FromString(""), JsParseScriptAttributes.StrictMode, out var result);

                    Console.WriteLine(result.ToString());
                    Console.WriteLine(runtime.IsExecutionDisabled);
                    Console.WriteLine(runtime.MemoryLimit);
                    Console.WriteLine(runtime.MemoryUsage);

                    Console.ReadLine();
                }
            }
            catch (Exception e)
            {
                Debug.WriteLine(e);
            }
        }
Пример #12
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();
        }
Пример #13
0
 protected virtual ChakraContext createContext(ChakraRuntime runtime)
 {
     return(runtime.CreateContext(false));
 }
Пример #14
0
 protected virtual ChakraRuntime createRuntime()
 {
     return(ChakraRuntime.Create());
 }
Пример #15
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();
        }
Пример #16
0
 protected override ChakraRuntime createRuntime()
 {
     return(ChakraRuntime.Create(JavaScriptRuntimeAttributes.AllowScriptInterrupt));
 }