Beispiel #1
0
        static async Task Main(string[] args)
        {
            Log.Logger = new LoggerConfiguration()
                         .Enrich.FromLogContext()
                         .WriteTo.Console()
                         .MinimumLevel.Verbose()
                         .CreateLogger();

            Log.Logger.Information("Starting Automatica.Core.CI database tool");

            var config = new ConfigurationBuilder()
                         .SetBasePath(new FileInfo(Assembly.GetEntryAssembly().Location).DirectoryName)
                         .AddJsonFile("appsettings.json", true)
                         .Build();

            var fi = new FileInfo(Assembly.GetEntryAssembly().Location);

            if (File.Exists(Path.Combine(fi.DirectoryName, DatabaseConstants.DatabaseInitName)))
            {
                File.Delete(Path.Combine(fi.DirectoryName, DatabaseConstants.DatabaseInitName));
            }

            var hostBuilder = new HostBuilder().ConfigureServices((hostContext, services) =>
            {
                var startup = new Startup(config);
                startup.ConfigureServices(services);
            }
                                                                  ).Build();


            string loadDirectory = "";

            if (args.Length > 0)
            {
                loadDirectory = args[0];
            }
            else
            {
                loadDirectory = fi.DirectoryName;
            }

            DatabaseInit.EnsureDatabaseCreated(hostBuilder.Services);

            var server = new CoreServer(hostBuilder.Services);
            await server.Load(loadDirectory, "*.dll");


            Console.WriteLine($"Done....");
            Environment.Exit(0);
        }
        public void TestDatabaseInit()
        {
            if (File.Exists("automatica.core-test.db"))
            {
                File.Delete("automatica.core-test.db");
            }

            var mockConfSection = new Mock <IConfigurationSection>();

            mockConfSection.SetupGet(m => m[It.Is <string>(s => s == "AutomaticaDatabaseType")]).Returns("sqlite");
            mockConfSection.SetupGet(m => m[It.Is <string>(s => s == "AutomaticaDatabaseSqlite")]).Returns("Data Source=automatica.core-test.db");

            var mockConfiguration = new Mock <IConfiguration>();

            mockConfiguration.Setup(a => a.GetSection(It.Is <string>(s => s == "ConnectionStrings"))).Returns(mockConfSection.Object);


            var serviceProviderMock = new Mock <IServiceProvider>();

            serviceProviderMock.Setup(a => a.GetService(It.Is <Type>(s => s == typeof(IConfiguration)))).Returns(mockConfiguration.Object);
            serviceProviderMock.Setup(a => a.GetService(It.Is <Type>(s => s == typeof(AutomaticaContext)))).Returns(new AutomaticaContext(mockConfiguration.Object, true));
            serviceProviderMock.Setup(a => a.GetService(It.Is <Type>(s => s == typeof(IVisualisationFactory)))).Returns(new VisuTempInit());

            try
            {
                DatabaseInit.EnsureDatabaseCreated(serviceProviderMock.Object);
                Assert.True(true);
            }
            catch (Exception e)
            {
                Assert.True(false);
                Console.Error.WriteLine($"{e}");
            }
            finally
            {
                if (File.Exists("automatica.core-test.db"))
                {
                    File.Delete("automatica.core-test.db");
                }
            }
        }
        public BaseControllerTest()
        {
            var tmpFolder = Path.Combine(Path.GetTempPath(), DatabaseFilePath);

            Directory.CreateDirectory(tmpFolder);

            var mockConfSection = new Mock <IConfigurationSection>();

            mockConfSection.SetupGet(m => m[It.Is <string>(s => s == "AutomaticaDatabaseType")]).Returns("sqlite");
            mockConfSection.SetupGet(m => m[It.Is <string>(s => s == "AutomaticaDatabaseSqlite")]).Returns($"Data Source={tmpFolder}/{DatabaseFilePath}.db");

            var mockConfiguration = new Mock <IConfiguration>();

            mockConfiguration.Setup(a => a.GetSection(It.Is <string>(s => s == "ConnectionStrings"))).Returns(mockConfSection.Object);

            var config = mockConfiguration.Object;

            Configuration = config;

            var services = new ServiceCollection();

            services.AddSingleton(config);
            services.AddAutomaticaCoreService(config, false);
            services.AddDbContext <AutomaticaContext>();
            services.AddSingleton <T>();

            services.AddAutomaticaPushServices(config, false);

            var hubClients  = new Mock <IHubClients>();
            var clientProxy = new Mock <IClientProxy>();

            hubClients.SetupGet(clients => clients.All).Returns(() => clientProxy.Object);
            hubClients.Setup(clients => clients.Group(It.IsAny <string>())).Returns(() => clientProxy.Object);

            var dataHubMoq = new Mock <IHubContext <DataHub> >();

            dataHubMoq.SetupGet(a => a.Clients).Returns(() => hubClients.Object);

            services.AddSingleton(dataHubMoq.Object);
            var telegramHubMoq = new Mock <IHubContext <TelegramHub> >();

            services.AddSingleton(telegramHubMoq.Object);

            services.AddSingleton <ILogger <NotifyDriverHandler> >(NullLogger <NotifyDriverHandler> .Instance);
            services.AddSingleton <ILogger <RuleEngineDispatcher> >(NullLogger <RuleEngineDispatcher> .Instance);
            services.AddSingleton <ILogger <LogicLoader> >(NullLogger <LogicLoader> .Instance);
            services.AddSingleton <ILogger <DriverLoader> >(NullLogger <DriverLoader> .Instance);
            services.AddSingleton <ILogger <PluginHandler> >(NullLogger <PluginHandler> .Instance);
            services.AddSingleton <ILogger <LearnMode> >(NullLogger <LearnMode> .Instance);
            services.AddSingleton <ILogger>(NullLogger.Instance);

            var mqttServerMock = new Mock <IMqttServer>();

            services.AddSingleton <IMqttServer>(mqttServerMock.Object);


            ServiceProvider = services.BuildServiceProvider();

            DatabaseInit.EnsureDatabaseCreated(ServiceProvider);

            Controller = ServiceProvider.GetRequiredService <T>();
        }
Beispiel #4
0
        static void Main(string[] args)
        {
            var config = new ConfigurationBuilder()
                         .SetBasePath(ServerInfo.GetConfigDirectory())
                         .AddJsonFile("appsettings.json", false)
                         .AddEnvironmentVariables()
                         .Build();

            var logBuild = LogConfiguration.ConfigureLogger();

            Log.Logger = logBuild.CreateLogger();

            foreach (DictionaryEntry env in Environment.GetEnvironmentVariables())
            {
                var envVar = $"{env.Key}={env.Value}";
                Log.Logger.Debug($"Using env variable: {envVar}");
            }

            var logger = SystemLogger.Instance;

            if (!File.Exists(Path.Combine(ServerInfo.GetConfigDirectory(), "appsettings.json")))
            {
                logger.LogError($"Could not find appsettings.json in {ServerInfo.GetConfigDirectory()}");
            }

            if (!String.IsNullOrEmpty(Environment.GetEnvironmentVariable("MQTT_LOG_VERBOSE")))
            {
                MqttNetGlobalLogger.LogMessagePublished += (s, e) =>
                {
                    var trace =
                        $"mqtt >> [{e.TraceMessage.ThreadId}] [{e.TraceMessage.Source}] [{e.TraceMessage.Level}]: {e.TraceMessage.Message}";
                    if (e.TraceMessage.Exception != null)
                    {
                        trace += Environment.NewLine + e.TraceMessage.Exception.ToString();
                    }

                    logger.LogDebug(trace);
                };
            }

            var webHost = BuildWebHost(config["server:port"]);

            if (args.Length > 0 && args[0] == "develop")
            {
                ServerInfo.PluginDirectory     = args[1];
                ServerInfo.PluginFilePattern   = args[2];
                ServerInfo.IsInDevelopmentMode = true;
            }
            else
            {
                var pluginDir = Environment.GetEnvironmentVariable("AUTOMATICA_PLUGIN_DIR");
                if (!String.IsNullOrEmpty(pluginDir))
                {
                    ServerInfo.PluginDirectory = pluginDir;
                }
                else
                {
                    ServerInfo.PluginDirectory = new FileInfo(Assembly.GetExecutingAssembly().Location).DirectoryName;
                }
            }

            logger.LogInformation($"Starting...Version {ServerInfo.GetServerVersion()}, Datetime {ServerInfo.StartupTime}. Running .NET Core Version {GetNetCoreVersion()}");

            var db = webHost.Services.GetRequiredService <AutomaticaContext>();

            DatabaseInit.EnsureDatabaseCreated(webHost.Services);



            var serverId = db.Settings.SingleOrDefault(a => a.ValueKey == "ServerUID");

            if (serverId == null)
            {
                var guid = Guid.NewGuid();
                db.Settings.Add(new Setting
                {
                    ValueKey  = "ServerUID",
                    Value     = guid,
                    Group     = "SERVER.SETTINGS",
                    IsVisible = false,
                    Type      = (long)PropertyTemplateType.Text
                });
                ServerInfo.ServerUid = guid;
                db.SaveChanges();
            }
            else
            {
                ServerInfo.ServerUid = new Guid(serverId.ValueText);
            }

            webHost.Services.GetService <DiscoveryService>();
            webHost.Run();

            logger.LogInformation("Stopped...");
        }