Example #1
0
        public void Init()
        {
            var hostBuilder = new CoreHostBuilder();
            var host        = hostBuilder.Build();

            serviceProvider = host.Services;
        }
Example #2
0
        //НЕОБХОДИМ ЗАПУЩЕННЫЙ OPERATOR!
        public async Task MyService()
        {
            var timeoutPoint = Task.Delay(60000).ContinueWith(res => { Trace.TraceWarning("test timeout (1 min)"); return(new bool[] { false }); });

            var successPoints = Task.WhenAll(
                receiveHandlerSet1.Task,
                receiveHandlerSet2.Task,
                querySet1.Task,
                querySet2.Task,
                responseHandlerSet.Task,
                callbackSet.Task
                ).ContinueWith(reslt => { Trace.TraceInformation("successPoints done"); return(reslt.Result); });

            var host = new CoreHostBuilder()
                       .ConfigureServices(sc =>
            {
                sc.AddScoped <IPlatformService, MyTestService>();

                sc.AddScoped <IMessageHandler, MyQueryHanlder>();
                sc.AddScoped <IMessageHandler, MyResponseHanlder>();
            }).Build();

            await host.StartAsync();

            var resTask = await Task.WhenAny(successPoints, timeoutPoint);

            resultTest = resTask.Result.All(x => x);
            Assert.IsTrue(resultTest);
        }
Example #3
0
        public async Task HealthcheckTesting1()
        {
            var hostBuilder = new CoreHostBuilder();
            var host        = hostBuilder.Build();

            var hs = host.Services.GetService <IHealthcheck>();

#pragma warning disable CS4014 // Так как этот вызов не ожидается, выполнение существующего метода продолжается до завершения вызова
            hs.StartAsync();
#pragma warning restore CS4014 // Так как этот вызов не ожидается, выполнение существующего метода продолжается до завершения вызова
            var configService = host.Services.GetService <IPrepareConfigService>();

            string healthcheckUrl = $"Http://localhost:{configService.MQ.healthcheckPort}/healthcheck";

            Thread.Sleep(1000);

            Assert.AreEqual(await CheckAnwer(healthcheckUrl), true);

            hs.AddCheck(() => true);
            Assert.AreEqual(await CheckAnwer(healthcheckUrl), true);

            hs.AddCheck(() => false);
            Assert.AreEqual(await CheckAnwer(healthcheckUrl), false);

            hs.AddCheck(() => true);
            Assert.AreEqual(await CheckAnwer(healthcheckUrl), false);

            hs.Stop();
        }
Example #4
0
        private static void Main(string[] args)
        {
            Stream myFile = File.Create("TestPlatformServiceLog.txt");

            TextWriterTraceListener myTextListener = new
                                                     CustomTrace(myFile);

            Trace.Listeners.Add(myTextListener);

            Trace.AutoFlush = true;

            var host = new CoreHostBuilder()
#if DEBUG
                       .ConfigureHostConfiguration(conBuilder =>
            {
                conBuilder.AddInMemoryCollection(new[] { new KeyValuePair <string, string>(HostDefaults.EnvironmentKey, "Development") });
            })
#endif
                       .ConfigureAppConfiguration((context, builder) =>
            {
                builder.AddJsonFile("config.json");
                Trace.TraceInformation($"Load config file: config.json");
            })
                       .ConfigureServices(sc =>
            {
                //  sc.AddScoped<IPlatformService, MyService1>();

                sc.AddScoped <IMessageHandler, MyQueryHanlder>();
                sc.AddScoped <IMessageHandler, MyResponseHanlder>();
            })
                       .Build();

            host.RunAsync().GetAwaiter().GetResult();
        }
Example #5
0
        public void GetPrepareConfigTest()
        {
            var host          = new CoreHostBuilder().Build();
            var configuration = host.Services.GetService <IPrepareConfigService>();

            Assert.IsNotNull(configuration?.MQ);
            Assert.IsNotNull(configuration?.Starter);
        }
Example #6
0
        public void RunInstance4()
        {
            var hostBuilder = new CoreHostBuilder();

            var host = hostBuilder.ConfigureServices((builderContext, services) => services.AddScoped <IPlatformService, Service1>())
                       .Build();

            host.Services.GetService <IPlatformService>().StartAsync(default(CancellationToken));
        }
Example #7
0
        private void RunService <T>(string cfg) where T : class, IPlatformService
        {
            var hostBuilder = new CoreHostBuilder();

            var host = hostBuilder.ConfigureAppConfiguration((builderContext, configurationBuilder) => configurationBuilder.AddJsonFile(cfg, true, true))
                       .ConfigureServices((builderContext, services) => services.AddScoped <IPlatformService, T>())
                       .Build();

            host.Services.GetService <IPlatformService>().StartAsync(default(CancellationToken));
        }
Example #8
0
        public void DefaultConfigFile_Test()
        {
            var hostBuilder = new CoreHostBuilder();
            var host        = hostBuilder.Build();
            var factory     = host.Services.GetService <IConfiguration>();

            var testValue = factory.GetStrValue("ru:spinosa:defaultConfigKey");

            Assert.AreEqual("test value", testValue);
        }
Example #9
0
        public void ValidateSectionTest()
        {
            CfgStarterSection cfg_starter = new CfgStarterSection();
            var hostBuilder   = new CoreHostBuilder();
            var host          = hostBuilder.Build();
            var configuration = host.Services.GetService <IConfiguration>();

            configuration.GetSection("ru:spinosa:starter").Bind(cfg_starter, options => options.BindNonPublicProperties = true);
            Assert.IsTrue(cfg_starter.Validate());
        }
Example #10
0
        public void GetPrepareMultiConfigTest()
        {
            var host = new CoreHostBuilder()
                       .ConfigureAppConfiguration((context, builder) => {
                builder.AddJsonFile("config.json");
            }).Build();
            var configuration = host.Services.GetService <IPrepareConfigService>();

            Assert.IsNotNull(configuration?.MQ);
            Assert.IsNotNull(configuration?.Starter);
        }
Example #11
0
        public void GetSectionTest()
        {
            CfgStarterSection cfg_starter = new CfgStarterSection();
            var hostBuilder   = new CoreHostBuilder();
            var host          = hostBuilder.Build();
            var configuration = host.Services.GetService <IConfiguration>();

            configuration.GetSection("ru:spinosa:starter").Bind(cfg_starter, options => options.BindNonPublicProperties = true);

            Assert.IsNotNull(cfg_starter?._this?.servicename);
        }
Example #12
0
        public void DI_Test()
        {
            var hostBuilder = new CoreHostBuilder();

            var host = hostBuilder
                       .ConfigureServices((builderContext, services) => services.AddScoped <ITestService, TestService>())
                       .Build();

            var test = host.Services.GetService <ITestService>();

            Assert.IsNotNull(test);
        }
Example #13
0
        public void DI_Transient_Test()
        {
            var hostBuilder = new CoreHostBuilder();

            var host = hostBuilder
                       .ConfigureServices((builderContext, services) => services.AddTransient <ITestService, TestService>())
                       .Build();
            var test1 = host.Services.GetService <ITestService>();
            var test2 = host.Services.GetService <ITestService>();

            Assert.AreNotSame(test1, test2);
            Assert.AreNotEqual(test1.TID, test2.TID);
        }
Example #14
0
        public void EnvironmentConfig_Test()
        {
            //Set variables
            var testEnvriomentName  = "TEST_ENV_NAME";
            var testEnvriomentValue = "TEST_ENV_NAME VALUE";

            Environment.SetEnvironmentVariable(ConfigurationFactory.ENVRIOMENT_CONFIG_APP_PREFIX + testEnvriomentName, testEnvriomentValue);

            var hostBuilder = new CoreHostBuilder();
            var host        = hostBuilder.Build();
            var factory     = host.Services.GetService <IConfiguration>();

            Assert.AreEqual(factory[testEnvriomentName], testEnvriomentValue);
        }
Example #15
0
        private void RunService <T>(string cfg, string[] args) where T : class, IMyService
        {
            var hostBuilder = new CoreHostBuilder();

            var host = hostBuilder.ConfigureAppConfiguration((builderContext, configurationBuilder) => configurationBuilder.AddJsonFile(cfg, true, true))
                       .ConfigureServices((builderContext, services) =>
            {
                services.AddScoped <IMyService, T>();
            }
                                          )
                       .Build();

            host.Services.GetService <IMyService>().Run(args);
        }
Example #16
0
        public void ValidateSectionTest2()
        {
            CfgStarterSection cfg_starter = new CfgStarterSection();
            var hostBuilder   = new CoreHostBuilder();
            var host          = hostBuilder.Build();
            var configuration = host.Services.GetService <IConfiguration>();

            configuration.GetSection("ru:spinosa:starter").Bind(cfg_starter, options => options.BindNonPublicProperties = true);
            Assert.IsTrue(cfg_starter.Validate());

            cfg_starter._this.servicename = null;
            Assert.IsFalse(cfg_starter.Validate());

            Assert.ThrowsException <CoreException>(() => { cfg_starter.ValidateAndTrace("starter"); });
        }
Example #17
0
        public void RunInstance3()
        {
            Stream myFile = File.Create("TestFile1.txt");

            /* Create a new text writer using the output stream, and add it to
             * the trace listeners. */


            var hostBuilder = new CoreHostBuilder();
            var host        = hostBuilder.ConfigureAppConfiguration((builderContext, configurationBuilder) => configurationBuilder.AddJsonFile("config1.json", true, true))
                              .ConfigureServices((builderContext, services) => services.AddScoped <IPlatformService, Service1>())
                              .Build();

            host.Services.GetService <IPlatformService>().StartAsync(default(CancellationToken));
            Trace.Flush();
        }
Example #18
0
        public void EnvironmentRewriteConfig_Test()
        {
            var testJSONAndEnvriomentKey = "envCustomTest";
            var testEnvriomentValue      = "envCustomTest ENV VALUE";
            //var testJSONValue = "EnvCustomTest JSON Value";

            //Set cfg
            var files = Directory.GetFiles(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, @"..\..\..\TestConfig"));

            Environment.SetEnvironmentVariable(ConfigurationFactory.ENVRIOMENT_CONFIG_FILE_NAMES, string.Join(",", files));

            //Set variables
            Environment.SetEnvironmentVariable(ConfigurationFactory.ENVRIOMENT_CONFIG_APP_PREFIX + testJSONAndEnvriomentKey, testEnvriomentValue);

            var hostBuilder = new CoreHostBuilder();
            var host        = hostBuilder.Build();
            var factory     = host.Services.GetService <IConfiguration>();

            //rewrite
            Assert.AreEqual(factory[testJSONAndEnvriomentKey], testEnvriomentValue);
        }
Example #19
0
        public void ChacheTest1()
        {
            var host         = new CoreHostBuilder().Build();
            var cacheService = host.Services.GetService <IMemoryCache>();

            var value1 = "value";
            var value2 = new { t = 1, msg = "hello" };
            var value3 = 13;
            var value4 = 0.5m;

            cacheService.Set("key1", value1);
            cacheService.Set("key2", value2);

            Assert.AreEqual(cacheService.Get <string>("key1"), value1);

            Assert.AreEqual(cacheService.Get <object>("key2"), value2);

            cacheService.Set("key3", value3, new MemoryCacheEntryOptions()
            {
                AbsoluteExpirationRelativeToNow = TimeSpan.FromSeconds(1)
            });
            Assert.AreEqual(cacheService.Get <object>("key3"), value3);
            Thread.Sleep(1200);
            Assert.IsNull(cacheService.Get <object>("key3"));


            cacheService.Set("key4", value4, new MemoryCacheEntryOptions()
            {
                SlidingExpiration = TimeSpan.FromSeconds(2),
            });
            Assert.AreEqual(cacheService.Get <object>("key4"), value4);
            Thread.Sleep(1000);
            Assert.AreEqual(cacheService.Get <object>("key4"), value4);
            Thread.Sleep(1000);
            Assert.AreEqual(cacheService.Get <object>("key4"), value4);
            Thread.Sleep(1000);
            Assert.AreEqual(cacheService.Get <object>("key4"), value4);
            Thread.Sleep(2100);
            Assert.IsNull(cacheService.Get <object>("key4"));
        }
Example #20
0
        public void DI_TestBaseRunning()
        {
            var hostBuilder = new CoreHostBuilder();

            var host = hostBuilder
                       .ConfigureServices((builderContext, services) => services.AddTransient <IPlatformService, TestService2>())
                       .Build();

            var resolver = host.Services;
            var service  = resolver.GetService <IPlatformService>();

            IConfiguration configuration = resolver.GetService <IConfiguration>();
            var            res           = resolver.GetService <IAppId>();

            var filename = configuration.GetStrValue(AppId.CONFIG_KEY_UUID_FILE_NAME);

            if (string.IsNullOrEmpty(filename))
            {
                filename = AppId.DEFAULT_UUID_FILE_NAME;
            }

            //check id
            if (File.Exists(filename))
            {
                var fileContent = File.ReadAllText(filename);
                Assert.AreEqual(res.CurrentUID, fileContent);
            }
            else
            {
                Assert.Fail("UUID_FILE not found!");
            }

            service.StartAsync(default(CancellationToken));

            Assert.IsTrue(true);
        }