Ejemplo n.º 1
0
        private void Connect()
        {
            try
            {
                // initialize connection object
                Connection = new CtreeSqlConnection();
                Connection.ConnectionString = Envs.GetTypedEnvVariable <string>("DATABASE_CONNECTION_STRING",
                                                                                "UID=promax;PWD=itax#2021;Database=ctreeSQL_GEO_D2;Server=172.22.6.83;Service=6570;");

                // initialize command object
                Command             = new CtreeSqlCommand();
                Command.CommandType = System.Data.CommandType.Text;
                Command.Connection  = Connection;
                Command.Transaction = null;

                // connect to server
                Console.WriteLine("\tLogon to server...");
                Connection.Open();
            }
            catch (CtreeSqlException e)
            {
                HandleException(e);
            }
            catch (Exception e)
            {
                HandleException(e);
            }
        }
        public void CanSetEnvAndConfigInheritance2()
        {
            // 1. Setup current env using supplied environment names/types.
            //    and all the available environments.
            // 2. Also supply the refpaths( config paths in this case ).
            Envs.Set("ny.prod,qa,dev", "ny.prod:prod,london.prod:prod,uat,qa,dev", "ny.prod.config,qa.config,dev.config");

            Assert.AreEqual(Env.Name, "ny.prod");
            Assert.AreEqual(Env.EnvType, EnvType.Prod);
            Assert.AreEqual(Env.IsDev, false);
            Assert.AreEqual(Env.IsProd, true);
            Assert.AreEqual(Env.IsQa, false);
            Assert.AreEqual(Env.IsUat, false);
            Assert.AreEqual(Env.Available[0], "ny.prod");
            Assert.AreEqual(Env.Available[1], "london.prod");
            Assert.AreEqual(Env.Available[2], "uat");
            Assert.AreEqual(Env.Available[3], "qa");
            Assert.AreEqual(Env.Available[4], "dev");
            Assert.AreEqual(Env.Selected, Env.Get("ny.prod"));

            // Check that the refpaths ( config files) have been set on the respective envs)
            Assert.AreEqual(Env.Get("ny.prod").RefPath, "ny.prod.config");
            Assert.AreEqual(Env.Get("qa").RefPath, "qa.config");
            Assert.AreEqual(Env.Get("dev").RefPath, "dev.config");

            Assert.AreEqual(Env.Count, 5);
        }
        /// <summary>
        /// Run the application.
        /// </summary>
        public override BoolMessageItem Execute()
        {
            //// Setup notification on Environment changed.
            Env.OnChange += (sender, args) => Console.Write("New Env: " + Env.Name);

            // Use 1: Set to "prod"(PRODUCTION) with default available envs as "prod,uat,qa,dev".
            Envs.Set("prod");
            PrintEnvironment();

            // Use 2: Set to "qa"(QA) with default available envs as "prod,qa,dev".
            Envs.Set("qa", "prod,qa,dev");
            PrintEnvironment();

            // Use 3: Set to "dev"(DEVELOPMENT) with default available envs as "prod,uat,qa,dev".
            //        Also set the "dev" env RefPath to "dev.config".
            Envs.Set("dev", "prod,uat,qa,dev", "dev.config");
            PrintEnvironment();

            // Use 4: Env Set up & Configuration File Setup with Inheritance
            //        - Set env to "newyork.prod"(PRODUCTION) with default available envs as "newyork.prod,london.prod,qa,dev".
            //        - Also set the "newyork.prod" env RefPath to use 3 config files "ny.prod.config,prod.config,dev.config.
            //        - Config file sequence is an inheritance of files ny.prod.config (inherits) prod.config (inherits) dev.config
            Envs.Set("newyork.prod", "newyork.prod,london.prod,qa,dev", "newyork.prod.config,prod.config,dev.config");
            PrintEnvironment();

            // Use 5: Set up the environment using Built objects.
            Envs.Set("Dev2", GetSampleEvironments(), "");
            PrintEnvironment();


            // Use 6: Change the environment from the last one ("Dev2").
            Env.Change("Qa");
            PrintEnvironment();
            return(BoolMessageItem.True);
        }
Ejemplo n.º 4
0
        public FixtureLoader LoadJson(string filePath)
        {
            var fullFilePath = FixturePath(filePath);

            using (StreamReader r = new StreamReader(fullFilePath))
            {
                var json = r.ReadToEnd();
                envs = Deserialize <Envs>(json);
            }

            return(this);
        }
        public void CanSetProdConfig()
        {
            // 2. Non-Strict setup indicating current environment and config references.
            Envs.Set("prod", "prod,uat,qa,dev", "prod.config");

            // 3. Non-Strict setup indicating current environment and config inheritance 2 files.
            Envs.Set("dev", "prod,uat,qa,dev", "dev1.config,dev2.config");

            // 4. Non-Strict setup indicating current environment inheritance and config inheritance.
            Envs.Set("prod,qa,dev", "prod,uat,qa,dev", "prod.config,qa.config,dev.config");
            //EnvironmentCurrent.Change("qa");

            // 5. Strict setup indicating current environments selected from the possible environments.
            //Envs.Set(GetSampleEvironments(), "Prod");
        }
        public void CanChangeEnv()
        {
            // 1. Setup current env using supplied environment names/types.
            //    and all the available environments.
            // 2. Also supply the refpaths( config paths in this case ).
            Envs.Set("prod,qa,dev", "prod,uat,qa,dev", "prod.config,qa.config,dev.config");

            Assert.AreEqual(Env.Name, "prod");
            Assert.AreEqual(Env.EnvType, EnvType.Prod);
            Assert.AreEqual(Env.IsDev, false);
            Assert.AreEqual(Env.IsProd, true);
            Assert.AreEqual(Env.IsQa, false);
            Assert.AreEqual(Env.IsUat, false);
            Assert.AreEqual(Env.Available[0], "prod");
            Assert.AreEqual(Env.Available[1], "uat");
            Assert.AreEqual(Env.Available[2], "qa");
            Assert.AreEqual(Env.Available[3], "dev");
            Assert.AreEqual(Env.Selected, Env.Get("prod"));

            // Check that the refpaths ( config files) have been set on the respective envs)
            Assert.AreEqual(Env.Get("prod").RefPath, "prod.config");
            Assert.AreEqual(Env.Get("qa").RefPath, "qa.config");
            Assert.AreEqual(Env.Get("dev").RefPath, "dev.config");

            // Now change environment.
            Env.OnChange += ((sender, eventArgs) =>
            {
                Assert.AreEqual(Env.Name, "qa");
                Assert.AreEqual(Env.EnvType, EnvType.Qa);
                Assert.AreEqual(Env.IsDev, false);
                Assert.AreEqual(Env.IsProd, false);
                Assert.AreEqual(Env.IsQa, true);
                Assert.AreEqual(Env.IsUat, false);
                Assert.AreEqual(Env.Available[0], "prod");
                Assert.AreEqual(Env.Available[1], "uat");
                Assert.AreEqual(Env.Available[2], "qa");
                Assert.AreEqual(Env.Available[3], "dev");
                Assert.AreEqual(Env.Selected, Env.Get("qa"));

                // Check that the refpaths ( config files) have been set on the respective envs)
                Assert.AreEqual(Env.Get("prod").RefPath, "prod.config");
                Assert.AreEqual(Env.Get("qa").RefPath, "qa.config");
                Assert.AreEqual(Env.Get("dev").RefPath, "dev.config");
            });

            Env.Change("qa");
            Assert.AreEqual(Env.Count, 4);
        }
        /// <summary>
        /// Run the application.
        /// </summary>
        public override BoolMessageItem Execute()
        {
            //// Setup notification on Environment changed.
            Env.OnChange += (sender, args) => Console.Write("New Env: " + Env.Name);

            // Use 1: Set to "prod"(PRODUCTION) with default available envs as "prod,uat,qa,dev".
            Envs.Set("prod");
            PrintEnvironment();

            // Use 2: Set to "qa"(QA) with default available envs as "prod,qa,dev".
            Envs.Set("qa", "prod,qa,dev");
            PrintEnvironment();

            // Use 3: Set to "dev"(DEVELOPMENT) with default available envs as "prod,uat,qa,dev".
            //        Also set the "dev" env RefPath to "dev.config".
            Envs.Set("dev", "prod,uat,qa,dev", "dev.config");
            PrintEnvironment();

            // Use 4: Env Set up & Configuration File Setup WITH-OUT Inheritance
            //        - Set env to "ny.prod"(PRODUCTION) with default available envs as "ny.prod,london.prod,qa,dev".
            //        - The "ny.prod" environment name is set to environment type of "prod" via format "<envName>:<envType>" e.g. "myprod:prod"
            //        - Also set the "ny.prod" env RefPath to use 3 config files "ny.prod.config,london.prod.config,dev.config. ( For config file inheritance ).
            Envs.Set("ny.prod", "ny.prod:prod,london.prod:prod,qa,dev", "ny.prod.config,london.prod.config,qa.config,dev.config");
            PrintEnvironment();

            // Use 5: Env Set up & Configuration File Setup WITH-OUT Inheritance but WITH config file distribution.
            //        - Also set the "ny.prod" env RefPath to use 1 config files "ny.prod.config,london.prod.config,dev.config.
            Envs.Set("ny.prod", "ny.prod:prod,london.prod:prod,qa,dev", "ny.prod.config,london.prod.config,qa.config,dev.config", true, false);
            PrintEnvironment();

            // Use 5: Env Set up & Configuration File Setup WITH Inheritance
            //        - Also set the "ny.prod" env RefPath to use 1 config files "ny.prod.config,london.prod.config,dev.config.
            Envs.Set("ny.prod", "ny.prod:prod,london.prod:prod,qa,dev", "ny.prod.config,london.prod.config,qa.config,dev.config", true, true);
            PrintEnvironment();

            // Use 5: Set up the environment using Built objects.
            Envs.Set("Dev2", GetSampleEvironments());
            PrintEnvironment();


            // Use 6: Change the environment from the last one ("Dev2").
            Env.Change("Qa");
            PrintEnvironment();
            return(BoolMessageItem.True);
        }
        public void CanSetEnvViaNameOnly()
        {
            // 1. Setup current env using default environment names/types.
            Envs.Set("prod");

            Assert.AreEqual(Env.Name, "prod");
            Assert.AreEqual(Env.EnvType, EnvType.Prod);
            Assert.AreEqual(Env.IsDev, false);
            Assert.AreEqual(Env.IsProd, true);
            Assert.AreEqual(Env.IsQa, false);
            Assert.AreEqual(Env.IsUat, false);
            Assert.AreEqual(Env.Available[0], "prod");
            Assert.AreEqual(Env.Available[1], "uat");
            Assert.AreEqual(Env.Available[2], "qa");
            Assert.AreEqual(Env.Available[3], "dev");
            Assert.AreEqual(Env.Selected, Env.Get("prod"));
            Assert.AreEqual(Env.Count, 4);
        }
Ejemplo n.º 9
0
        /// <summary>
        /// Initialize with contextual data.
        /// </summary>
        /// <param name="context"></param>
        public virtual void Init(object context)
        {
            string env    = _argsParsed.Get("env", "dev");
            string log    = _argsParsed.Get("log", "%name%-%yyyy%-%MM%-%dd%-%env%-%user%.log");
            string config = _argsParsed.Get("config", string.Format(@"config\{0}.config", env));

            // 1. Initialize the environment. prod, prod.config
            Envs.Set(env, "prod,uat,qa,dev", config);

            // 2. Append the file based logger.
            Logger.Default.Append(new LogFile(this.GetType().Name, log, DateTime.Now, env));

            // 3. Initialize config inheritance from environment inheritance.
            Config.Init(Configs.LoadFiles(Env.RefPath));

            // 4. Set the config and logger, and emailer instances on the application.
            _config  = Config.Current;
            _log     = Logger.Default;
            _emailer = new EmailService(_config, "EmailServiceSettings");
        }
Ejemplo n.º 10
0
        /// <summary>
        /// Show how to set the environment and load the config files
        /// based on the environment.
        /// </summary>
        public void SetEnvironment()
        {
            // 1. Get environment passed from command line. -env:Prod
            // 2. Get all the environments supported.
            // 3. Create environment.
            // 4. Set current environment.
            IEnv env = new EnvDef(AppConfig.GetSampleEvironments(), _argsReciever.Environment);

            Envs.Set(env);

            // Show the environment selection API.
            Logger.Info("====================================================");
            Logger.Info("ENVIRONMENTS ");
            Logger.Info("Environment name: " + Env.Name);
            Logger.Info("Environment type: " + Env.EnvType);
            Logger.Info("Environment inherits: " + Env.Inherits);
            Logger.Info("Environment file: " + Env.RefPath);
            Logger.Info("Environment prod: " + Env.IsProd);
            Logger.Info(Environment.NewLine);
        }
Ejemplo n.º 11
0
        public async Task <JsonResult> Update(Envs model)
        {
            var result = new BaseResult();
            var list   = await _envService.GetList();

            var nameList = list.Where(s => s.Name == model.Name);
            var oldModel = list.Where(s => s.Id == model.Id).FirstOrDefault();

            if (nameList != null && nameList.Count() > 0 && nameList.FirstOrDefault().Id != model.Id)
            {
                result.IsSuccess = false;
                result.ErrorMsg  = "该环境名称已经存在";
            }
            else
            {
                await _permissionService.BatchUpdatePer(oldModel.Name, model.Name, PermissionType.Env);

                result.IsSuccess = await _envService.Update(model);
            }
            return(Json(result, JsonRequestBehavior.AllowGet));
        }
Ejemplo n.º 12
0
        // public override void ConfigureAppConfiguration(IFunctionsConfigurationBuilder builder)
        // {
        //     FunctionsHostBuilderContext context = builder.GetContext();

        //     Envs.Load();

        //     // KeyVault
        //     var secretClient = new SecretClient(new Uri(Env.GetString("AZURE_KEYVAULT_ENDPOINT")), Identity.GetCredentialChain());
        //     var storageConnectionString = secretClient.GetSecret(Env.GetString("AZURE_STORAGE_CONNECTION_STRING_SECRET_NAME"));
        //     var signalRConnectionString = secretClient.GetSecret(Env.GetString("AZURE_SIGNALR_CONNECTION_STRING_SECRET_NAME"));

        //     //Environment.SetEnvironmentVariable("Values:AzureWebJobsStorage", storageConnectionString.Value.Value);

        //     builder.ConfigurationBuilder
        //     .AddInMemoryCollection(new Dictionary<string, string> {
        //         { "ClientSyncQueueConnectionString", storageConnectionString.Value.Value },
        //         { "AzureSignalRConnectionString", signalRConnectionString.Value.Value }
        //     })
        //     .AddEnvironmentVariables();
        // }

        public override void Configure(IFunctionsHostBuilder builder)
        {
            //FunctionsHostBuilderContext context = builder.GetContext();

            Envs.Load();

            // KeyVault
            var secretClient            = new SecretClient(new Uri(Env.GetString("AZURE_KEYVAULT_ENDPOINT")), Identity.GetCredentialChain());
            var storageConnectionString = secretClient.GetSecret(Env.GetString("AZURE_STORAGE_CONNECTION_STRING_SECRET_NAME"));
            var signalRConnectionString = secretClient.GetSecret(Env.GetString("AZURE_SIGNALR_CONNECTION_STRING_SECRET_NAME"));

            //Environment.SetEnvironmentVariable("Values:AzureWebJobsStorage", storageConnectionString.Value.Value);
            var config = new ConfigurationBuilder()
                         .AddInMemoryCollection(new Dictionary <string, string> {
                { "ClientSyncQueueConnectionString", storageConnectionString.Value.Value },
                { "AzureSignalRConnectionString", signalRConnectionString.Value.Value }
            })
                         .AddEnvironmentVariables().Build();

            builder.Services.AddSingleton <IConfiguration>(config);
        }
Ejemplo n.º 13
0
        public async Task <JsonResult> Insert(Envs model)
        {
            var result = new BaseResult();
            var list   = await _envService.GetList();

            var nameList = list.Where(s => string.Equals(s.Name.Trim(), model.Name, StringComparison.OrdinalIgnoreCase));

            if (nameList != null && nameList.Count() > 0)
            {
                result.IsSuccess = false;
                result.ErrorMsg  = "该环境名称已经存在";
            }
            else
            {
                await _envService.Insert(model);

                result.IsSuccess = await _permissionService.BatchInsertByAfterEnv(model.Name);
            }

            return(Json(result, JsonRequestBehavior.AllowGet));
        }
        public void CanSetEnvViaNameAndType()
        {
            // 1. Setup current env using supplied environment names/types.
            // Not that <envName>:<envType> is the format
            // where <envType> = prod | uat | qa | dev
            Envs.Set("ny.prod", "ny.prod:prod,london.prod:prod,uat,qa,dev");

            Assert.AreEqual(Env.Name, "ny.prod");
            Assert.AreEqual(Env.EnvType, EnvType.Prod);
            Assert.AreEqual(Env.IsDev, false);
            Assert.AreEqual(Env.IsProd, true);
            Assert.AreEqual(Env.IsQa, false);
            Assert.AreEqual(Env.IsUat, false);
            Assert.AreEqual(Env.Available[0], "ny.prod");
            Assert.AreEqual(Env.Available[1], "london.prod");
            Assert.AreEqual(Env.Available[2], "uat");
            Assert.AreEqual(Env.Available[3], "qa");
            Assert.AreEqual(Env.Available[4], "dev");
            Assert.AreEqual(Env.Selected, Env.Get("ny.prod"));
            Assert.AreEqual(Env.Count, 5);
        }
Ejemplo n.º 15
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            Envs.Load();

            services.AddSingleton(typeof(Clients));
            services.AddHostedService <DataHostedService>();
            services.AddSignalR();
            services.AddControllers();
            services.AddCors(options =>
            {
                options.AddPolicy(CorsOrigins,
                                  builder => builder.AllowAnyOrigin()
                                  .AllowAnyMethod()
                                  .AllowAnyHeader());
            });

            services.AddResponseCompression(opts =>
            {
                opts.MimeTypes = ResponseCompressionDefaults.MimeTypes.Concat(
                    new[] { "application/octet-stream" });
            });
        }
Ejemplo n.º 16
0
        /// <summary>
        /// INHERITANCE
        /// 1. -env:Prod -date:${today}   -config:prod.config,dev.config -log:{env}.log -source:Bloomberg 10
        /// 2. -env:Prod -date:${today-1} -config:prod.config,dev.config -log:{env}.log -source:Reuters 10
        /// </summary>
        public override void Init()
        {
            // base.Init(). Does everything, this is just to show how to setup everything.
            //base.Init();

            string env    = _argsParsed.Get("env", "dev");
            string log    = _argsParsed.Get("log", "%name%-%yyyy%-%MM%-%dd%-%env%-%user%.log");
            string config = _argsParsed.Get("config", string.Format(@"config\{0}.config", env));

            // 1. Initialize the environment
            Envs.Set(env, "prod,uat,qa,dev", config);

            // 2. Append the file logger.
            Logger.Default.Append(new LogFile(this.GetType().Name, log, DateTime.Now, env));

            // 3. Initialize config inheritance.
            Config.Init(Configs.LoadFiles(Env.RefPath));

            // 4. Set the config, logger, emailer instances on the application.
            _config  = Config.Current;
            _log     = Logger.Default;
            _emailer = new EmailService(_config, "EmailServiceSettings");
        }
        public void CanSetEnvViaBuildEnvs()
        {
            // 1. Setup current env using supplied environment names/types.
            // Not that <envName>:<envType> is the format
            // where <envType> = prod | uat | qa | dev
            List <EnvItem> available = GetSampleEvironments();

            Envs.Set("Dev2", available, "");

            Assert.AreEqual(Env.Name, "Dev2");
            Assert.AreEqual(Env.EnvType, EnvType.Dev);
            Assert.AreEqual(Env.IsDev, true);
            Assert.AreEqual(Env.IsProd, false);
            Assert.AreEqual(Env.IsQa, false);
            Assert.AreEqual(Env.IsUat, false);
            Assert.AreEqual(Env.Available[0], "Dev");
            Assert.AreEqual(Env.Available[1], "Dev2");
            Assert.AreEqual(Env.Available[2], "Qa");
            Assert.AreEqual(Env.Available[3], "Prod");
            Assert.AreEqual(Env.Available[4], "MyProd");
            Assert.AreEqual(Env.Selected, Env.Get("Dev2"));
            Assert.AreEqual(Env.Count, 5);
        }
Ejemplo n.º 18
0
 public async Task <bool> Update(Envs model)
 {
     return(await _envRepository.Update(model));
 }
Ejemplo n.º 19
0
 public async Task <bool> Insert(Envs model)
 {
     return(await _envRepository.Insert(model));
 }
Ejemplo n.º 20
0
        public void Execute(Bytecode bytecode, Environment rootEnv, Heap heap)
        {
            this.Heap = heap;
            SP        = 0;
            FP        = 0;
            Span <Value> _stack = stackalloc Value[1000]; //allocate our local stack

            Envs.Add(0, rootEnv);                         //global environment, still no modules supported
            while (SP < bytecode.Bytecodes.Length)
            {
                Thread.Sleep(100);
                var opCode = (OpCode)bytecode.Bytecodes[SP].i32; //grabs the current bytecode operation
                Console.ForegroundColor = ConsoleColor.DarkGray;
                Console.Write($"{SP.ToString("X8")} ");
                Console.ForegroundColor = ConsoleColor.Green;
                if (bytecode.IsDebugging && bytecode.DebugInfo != null && bytecode.DebugInfo.ContainsKey(SP))
                {
                    Console.WriteLine(bytecode.DebugInfo[SP]);
                }
                else
                {
                    Console.WriteLine($"OPCODE: {opCode.ToString()}");
                }
                Console.ForegroundColor = ConsoleColor.White;
                SP++;
                switch (opCode)
                {
                case OpCode.PUSH:
                    Push(_stack, bytecode.Bytecodes[SP++]);
                    break;

                case OpCode.NIL:
                    Push(_stack, Value.Nil);
                    break;

                case OpCode.FALSE:
                    Push(_stack, Value.False);
                    break;

                case OpCode.TRUE:
                    Push(_stack, Value.True);
                    break;

                case OpCode.POP:
                    Pop(_stack);
                    break;

                case OpCode.DUP:
                {
                    var value = Peek(_stack);
                    Push(_stack, value);
                    break;
                }

                case OpCode.PRINT:
                {
                    var value = Pop(_stack);
                    if (value.type == ValueType.INT || value.type == ValueType.NUMBER || value.type == ValueType.BOOL)
                    {
                        Console.WriteLine($"{value}");
                    }
                    else if (value.type == ValueType.SYMBOL)
                    {
                        Console.WriteLine($"{bytecode.Symbols[value.i32]}");
                    }
                    break;
                }

                case OpCode.DEBUG:
                    Envs[CurrentEnv].Print();
                    Print();
                    break;

                case OpCode.STORE:
                {
                    string storeLiteral = bytecode.Symbols[bytecode.Bytecodes[SP++].i32];
                    var    value        = Pop(_stack);
                    Env.Add(storeLiteral, value);
                    break;
                }

                case OpCode.LOOKUP_LOCAL:
                {
                    var lookupLiteral = bytecode.Symbols[bytecode.Bytecodes[SP++].i32];
                    var value         = Env.Lookup(lookupLiteral);
                    Push(_stack, value);
                    break;
                }

                case OpCode.LOAD_REFERENCE:     //dereference
                {
                    var reference = Pop(_stack);
                    if (reference.type == ValueType.REFERENCE)
                    {
                        var value = Heap[reference.i32];
                        Push(_stack, value);
                    }
                    //TODO: add type error
                    break;
                }

                case OpCode.STORE_REFERENCE:     //reference
                {
                    var value     = Pop(_stack);
                    var reference = Heap.Add(value);
                    Push(_stack, new Value(ValueType.REFERENCE, reference));
                    break;
                }

                case OpCode.ADD:
                {
                    var value1 = Pop(_stack);
                    var value2 = Pop(_stack);
                    if (value1.type == ValueType.INT && value2.type == ValueType.INT)
                    {
                        Push(_stack, value1.i32 + value2.i32);
                    }
                    else if (value1.type == ValueType.NUMBER && value2.type == ValueType.NUMBER)
                    {
                        Push(_stack, value1.fl + value2.fl);
                    }
                    else
                    {
                        throw new Exception("Invalid types for OP_ADD");
                    }
                    break;
                }

                case OpCode.ADD1:
                {
                    var value1 = Pop(_stack);
                    if (value1.type == ValueType.INT)
                    {
                        Push(_stack, value1.i32 + 1);
                    }
                    else if (value1.type == ValueType.NUMBER)
                    {
                        Push(_stack, value1.fl + 1f);
                    }
                    else
                    {
                        throw new Exception("Invalid types for OP_ADD");
                    }
                    break;
                }

                case OpCode.SUB:
                {
                    var value1 = Pop(_stack);
                    var value2 = Pop(_stack);
                    if (value1.type == ValueType.INT && value2.type == ValueType.INT)
                    {
                        Push(_stack, value2.i32 - value1.i32);
                    }
                    else if (value1.type == ValueType.NUMBER && value2.type == ValueType.NUMBER)
                    {
                        Push(_stack, value2.fl - value1.fl);
                    }
                    else
                    {
                        throw new Exception("Invalid types for SUB");
                    };
                    break;
                }

                case OpCode.SUB1:
                {
                    var value = Pop(_stack);
                    if (value.type == ValueType.INT)
                    {
                        Push(_stack, value.i32 - 1);
                    }
                    else if (value.type == ValueType.NUMBER)
                    {
                        Push(_stack, value.fl - 1.0f);
                    }
                    else
                    {
                        throw new Exception("Invalid types for SUB1");
                    }
                    break;
                }

                //always jump to next value
                case OpCode.JMP:
                    SP = bytecode.Bytecodes[SP].i32;
                    break;

                //conditional jump, jumps to next address if the top of the stack is true
                case OpCode.JMPCMP:
                {
                    var _newPC = bytecode.Bytecodes[SP++].i32;
                    var value  = Pop(_stack);
                    if ((value.type == ValueType.BOOL && value.b) ||
                        (value.type == ValueType.INT && value.i32 == 0))
                    {
                        SP = _newPC;
                    }
                    break;
                }

                //conditional jump, jumps to next address if the top of the stack is false
                case OpCode.JNE:
                {
                    var _newPC = bytecode.Bytecodes[SP++].i32;
                    var value  = Pop(_stack);
                    if (value.b)
                    {
                        SP = _newPC;
                    }
                    break;
                }

                case OpCode.CLOSURE:
                {
                    /*
                     *  A Closure has to capture variables from the current Environment creating a copy at the time the Closure was created.
                     *  this means that every captured variable will be a new reference in the Store.
                     *
                     *  The new Environment needs to to point to the new Store references, maybe an OpCode could be used to hint
                     *  the interpreter to only capture the variables it needs because capturing everything will be expensive
                     *  on huge environments.
                     *
                     |-------------+--------------+---|
                     | Env E1      |              |   |
                     | var a = 10; |              |   |
                     |             | ------------ |   |
                     |             | Env E1       |   |
                     |             | var c = 30;  |   |
                     |             | var b = 20;  |   |
                     +-------------+--------------+---+
                     |
                     |  Symbol Table:
                     | Loc | Symbol |
                     |
                     | Env | Symbol | Ref |
                     |-----+--------+-----|
                     | E1  | a      |   7 |
                     | E2  | a      |   8 |
                     | E2  | b      |   9 |
                     | E3  | c      |  10 |
                     +-----+--------+-----+
                     |  OPCODE:
                     | Loc | Type     | Val |                             |
                     |-----+----------+-----+-----------------------------|
                     |   0 | CLOSURE  |  80 | closure points to PC        |
                     |   1 | NUMBER   |   3 | Closure captured references |
                     |   2 | UPVALUE  |   5 | Env Reference a             |
                     |   3 | UPVALUE  |   9 | Env Reference b             |
                     |   4 | UPVALUE  |  16 | Env Reference c             |
                     |  .. | ..       |  .. |                             |
                     |  .. | ..       |  .. |                             |
                     |   7 | INT      |  10 | Previous Environment a = 10 |
                     |   8 | INT      |  10 | New Environment a = 10      |
                     |   9 | INT      |  20 | b = 20                      |
                     |  10 | INT      |  30 | c = 30                      |
                     |  .. | ..       |  .. |                             |
                     |  80 | FUNCTION |  .. | Function Location           |
                     +-----+----------+-----+-----------------------------+
                     * */
                    var closure = new Value(ValueType.CLOSURE, bytecode.Bytecodes[SP++].i32);         //get the closure
                    Push(_stack, closure);
                    //create new environment with upvalues
                    var closeUpValues = bytecode.Bytecodes[SP++];
                    //ReadOnlySpan<Value> arguments = stackalloc Value[closeUpValues.i32]; //get the number of upvalues
                    var upvalues = new string[closeUpValues.i32];
                    for (int i = 0; i < closeUpValues.i32; i++)
                    {
                        upvalues[i] = bytecode.Symbols[bytecode.Bytecodes[SP++].i32];
                    }
                    //clone the environment here
                    Envs.Add(closure.i32, rootEnv.ClosureEnvironment(upvalues));

                    break;
                }

                //the function itself should be retrieved from the stack
                //the closure contains all the necessary information to execute
                //what we need after the application is the number of arguments to POP
                case OpCode.APP:
                {
                    //number of arguments to get
                    int argumentCount = bytecode.Bytecodes[SP].i32;
                    //where to we store the arguments?
                    //using the stack would be inefficient

                    //closure
                    var closure = Pop(_stack);
                    if (closure.type != ValueType.CLOSURE)
                    {
                        throw new Exception($"Expected a Closure, got a {closure.type} instead");
                    }


                    Push(_stack, SP + 1);     //push return address at the top of the stack
                    Push(_stack, FP);         //push frame pointer
                    Push(_stack, CurrentEnv); //push current environment


                    //store return address after frame pointer
                    //Push(new Value() { type = ValueType.INT, i32 = PC + 1 });
                    //point frame pointer to top of the stack
                    FP = Top;

                    //here we have to switch the environment

                    //move to procedure location
                    SP = closure.i32;
                    //move to closure env
                    CurrentEnv = SP;
                    break;
                }

                //function return, functions should always return something
                case OpCode.RET:
                {
                    //return value
                    var returnValue = Pop(_stack);

                    while (Top > FP)
                    {
                        Pop(_stack);
                    }
                    CurrentEnv = Pop(_stack).i32; //previous environment
                    SP         = Pop(_stack).i32; //return address
                    Push(_stack, returnValue);
                    break;
                }

                case OpCode.QUIT:
                    return;
                }
            }
        }
Ejemplo n.º 21
0
        static async Task Main(string[] args)
        {
            Envs.Load();

            //using var listener = AzureEventSourceListener.CreateConsoleLogger();

            var clients = new Clients();
            await clients.InitializeAsync();

            while (true)
            {
                Console.WriteLine("Receiving Messages...");

                // Get Messages
                var messages = await clients.QueueClient.ReceiveMessagesAsync(maxMessages : Env.GetInt("AZURE_STORAGE_QUEUE_MSG_COUNT", 10));

                foreach (var message in messages.Value)
                {
                    try
                    {
                        Console.WriteLine(message.MessageText);

                        // Deserialize Message
                        var image = clients.DataProvider.DeserializeImage(message.MessageText);

                        // Extract Text from Image
                        try
                        {
                            var recognizeContentOperation = await clients.FormRecognizerClient.StartRecognizeContentFromUriAsync(new Uri(image.BlobUri));

                            var recognizeContentCompletion = await recognizeContentOperation.WaitForCompletionAsync();

                            var content = recognizeContentCompletion.Value;
                            var text    = content.SelectMany(page => page.Lines).Aggregate(new StringBuilder(), (a, b) =>
                            {
                                a.Append($"{b.Text} ");
                                return(a);
                            });

                            image.Text = text.ToString();
                        }
                        catch (Exception ex)
                        {
                            image.Error = ex.Message.ToString();
                            Console.WriteLine(ex.ToString());
                        }


                        if (!string.IsNullOrEmpty(image.Text))
                        {
                            try
                            {
                                Console.WriteLine($"Image Text: {image.Text}");

                                // Analyize Text Sentiment
                                var documentSentiment = await clients.TextAnalyticsClient.AnalyzeSentimentAsync(image.Text);

                                image.Sentiment = documentSentiment.Value.Sentiment.ToString();

                                Console.WriteLine($"Image Sentiment: {image.Sentiment}");
                            }
                            catch (Exception ex)
                            {
                                image.Error = ex.Message.ToString();
                                Console.WriteLine(ex.ToString());
                            }
                        }
                        else
                        {
                            image.Text = "No Text Extracted from Image.";
                            Console.WriteLine(image.Text);
                        }

                        image.Status = "Completed";

                        // Save Document
                        image = await clients.DataProvider.UpsertImageAsync(image);

                        Console.WriteLine($"Document Saved: {image.Id}");

                        // Delete Queue Message
                        var deleteResponse = await clients.QueueClient.DeleteMessageAsync(message.MessageId, message.PopReceipt);

                        Console.WriteLine($"Queue Message Deleted: {message.MessageId}");

                        // Enqueue message to Client Sync Queue
                        var sendReceipt = await clients.ClientSyncQueueClient.SendMessageAsync(
                            Convert.ToBase64String(Encoding.UTF8.GetBytes(JsonSerializer.Serialize <IImage>(image,
                                                                                                            new JsonSerializerOptions {
                            PropertyNamingPolicy = JsonNamingPolicy.CamelCase
                        })
                                                                          )));

                        Console.WriteLine($"Added to Client Sync Queue: {sendReceipt.Value.MessageId}");
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine(ex.ToString());
                    }
                }
                await Task.Delay(TimeSpan.FromSeconds(Env.GetInt("AZURE_STORAGE_QUEUE_RECEIVE_SLEEP", 1)));
            }
        }