Пример #1
0
 public IDatabase GetAccessDB()
 {
     return(DatabaseConfiguration.Build()
            .UsingConnectionString(Program.GData.AccessSOURCE)
            .UsingProvider <MsAccessDbDatabaseProvider>()
            .Create());
 }
Пример #2
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddSingleton <IDatabaseBuildConfiguration>(DatabaseConfiguration
                                                                .Build()
                                                                .UsingConnectionString(Configuration.GetConnectionString("PostgreSQL"))
                                                                .UsingProviderName("Npgsql")
                                                                .UsingCommandTimeout(180)
                                                                .WithAutoSelect()
                                                                .WithNamedParams()
                                                                );

            services.AddOptions <Blob.Configuration>().ValidateDataAnnotations().Bind(Configuration.GetSection("Blob"));
            services.AddTransient <Blob.IStore, Blob.Store>();

            services.AddOptions <Face.Configuration>().ValidateDataAnnotations().Bind(Configuration.GetSection("Face"));
            services.AddSingleton <Face.IMapper, Face.Mapper>();
            services.AddTransient <IDbConnection>(sp => new NpgsqlConnection());
            services.AddTransient <IDatabase>(sp => sp.GetService <IDatabaseBuildConfiguration>().Create());
            services.AddTransient <Data.IStore, Data.Store>();

            services.AddCors(o => o.AddPolicy(
                                 "CorsPolicy",
                                 builder =>
            {
                builder.AllowAnyOrigin()
                .AllowAnyMethod()
                .AllowAnyHeader();
            })
                             );

            services.AddControllers();

            services.AddOpenApiDocument();
        }
Пример #3
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.Configure <CookiePolicyOptions>(options =>
            {
                // This lambda determines whether user consent for non-essential cookies is needed for a given request.
                options.CheckConsentNeeded    = context => true;
                options.MinimumSameSitePolicy = SameSiteMode.None;
            });


            services.AddPetaPocoConfiguration <MvcPetaPocoDBContext>(
                options =>
            {
                var connectionStrnig = Configuration["ConnectionStrings:MySQL:MvcMySQL"];
                var providerName     = Configuration["ConnectionStrings:MySQL:provider"];

                //options.ConnectionString = connectionStrnig;
                //options.ProviderName = providerName;
                options.Configuration = DatabaseConfiguration.Build().UsingConnectionString(connectionStrnig)
                                        .UsingProvider <MariaDbDatabaseProvider>();
                //.UsingProviderName(providerName);
            });

            services.AddScoped <IUserService, UserService>();

            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
        }
Пример #4
0
 public IDatabase GetAzureDB()
 {
     return(DatabaseConfiguration.Build()
            .UsingConnectionString(Program.GData.AzureSOURCE)
            .UsingProvider <SqlServerDatabaseProvider>()
            .Create());
 }
Пример #5
0
        static void StartServer()
        {
            var connectionString = ConfigurationManager.ConnectionStrings["postgres"].ConnectionString;

            //if (!File.Exists (@"database.sqlite")) {

            logger.Info("Updating the database");
            //SqliteConnection.CreateFile(@"database.sqlite");
            MigrateToLatest(connectionString);
            logger.Info("Database migrated");
            //}

            // var provider = new MonoSQLiteDatabaseProvider ();
            var provider = new PostgreSQLDatabaseProvider();

            var config = DatabaseConfiguration.Build()
                         .UsingConnectionString(connectionString)
                         .UsingProvider(provider)
                         .UsingDefaultMapper <ConventionMapper>();

            // connection.Open();

            //logger.Info (db.ExecuteScalar<int>("select count(*) from ambulances where ambulances.ambulanceId = 'A9';"));

            //var ambulanceRepository = new AmbulanceRepository(db);
            //var hospitalRepository = new HospitalRepository(db);
            //var incidentRepository = new IncidentRepository(db);

            var orchestrator = new Orchestrator(config);

            orchestrator.Start();
        }
Пример #6
0
        public VmsDB GetInstance()
        {
            var dbConfig = DatabaseConfiguration.Build()
                           .UsingConnectionString(connectionString)
                           .UsingProvider <SqlServerCEDatabaseProviders>();

            return(new VmsDB(dbConfig));
        }
Пример #7
0
 public DataProvider()
 {
     if (db == null)
     {
         db = DatabaseConfiguration.Build().UsingConnectionStringName("DbString").Create();
         //db = DatabaseConfiguration.Build().UsingProvider<MySqlDatabaseProvider>().UsingConnectionString(connectionString).Create();
     }
 }
Пример #8
0
 /// <summary>
 /// 添加 PetaPoco 拓展
 /// </summary>
 /// <param name="services"></param>
 /// <param name="optionsAction"></param>
 /// <returns></returns>
 public static IServiceCollection AddPetaPoco(this IServiceCollection services, Action <IDatabaseBuildConfiguration> optionsAction)
 {
     services.AddTransient <IDatabase>(sp =>
     {
         var builder = DatabaseConfiguration.Build();
         optionsAction(builder);
         return(new Database(builder));
     });
     return(services);
 }
Пример #9
0
        protected virtual IDatabaseBuildConfiguration BuildFromConnectionName(string name)
        {
#if NETCOREAPP
            return(DatabaseConfiguration.Build()
                   .UsingConnectionString(AppSetting.Instance.ConnectionStringFor(name).ConnectionString)
                   .UsingProviderName(AppSetting.Instance.ConnectionStringFor(name).ProviderName));
#else
            return(DatabaseConfiguration.Build().UsingConnectionStringName(name));
#endif
        }
Пример #10
0
        public void Construct_GivenInvalidArguments_ShouldThrow()
        {
#if !NETCOREAPP
            Should.Throw <InvalidOperationException>(() => new Database());
#endif

            Should.Throw <ArgumentNullException>(() => new Database((IDbConnection)null));

            Should.Throw <ArgumentNullException>(() => new Database("some connection string", (IProvider)null));
            Should.Throw <ArgumentException>(() => new Database(null, _provider));

#if !NETCOREAPP
            Should.Throw <ArgumentException>(() => new Database((string)null));
            Should.Throw <InvalidOperationException>(() => new Database("connection string name"));
#endif
            Should.Throw <ArgumentException>(() => new Database("connection string", (string)null));
            Should.Throw <ArgumentException>(() => new Database("connection string", ""));
            Should.Throw <ArgumentException>(() => new Database(null, "provider name"));
            Should.Throw <ArgumentException>(() => new Database("", "provider name"));
            Should.Throw <ArgumentException>(() => new Database("connection string", "provider name"));

            Should.Throw <ArgumentException>(() => new Database(null, _dbProviderFactory));
            Should.Throw <ArgumentNullException>(() => new Database("some connection string", (DbProviderFactory)null));

            Should.Throw <ArgumentNullException>(() => new Database((IDatabaseBuildConfiguration)null));
            Should.Throw <InvalidOperationException>(() =>
            {
                try
                {
                    DatabaseConfiguration.Build().Create();
                }
                catch (Exception e)
                {
#if !NETCOREAPP
                    e.Message.ShouldContain("One or more connection strings");
#else
                    e.Message.ShouldContain("A connection string is required");
#endif
                    throw;
                }
            });
            Should.Throw <InvalidOperationException>(() =>
            {
                try
                {
                    DatabaseConfiguration.Build().UsingConnectionString("cs").Create();
                }
                catch (Exception e)
                {
                    e.Message.ShouldContain("Unable to locate a provider");
                    throw;
                }
            });
            Should.Throw <ArgumentException>(() => new Database <SqlServerDatabaseProvider>(null));
        }
Пример #11
0
        public RepositoryBase(IConfiguration configuration)
        {
            _connectionString = "Server=127.0.0.1;Uid=root;Pwd=;Database=petapoco;Port=3306"; //configuration.GetValue<string>("DBInfo:ConnectionString");

            _db = DatabaseConfiguration.Build()
                  .UsingConnectionString(_connectionString)
                  .UsingProvider <MySqlDatabaseProvider>()
                  .Create();

            //_db.Execute(LoadTextResource("mysql_init.sql"));
        }
Пример #12
0
 /// <summary>
 /// 增加 PetaPoco 数据库操作服务
 /// </summary>
 /// <param name="services"></param>
 /// <param name="optionsAction"></param>
 /// <returns></returns>
 public static IServiceCollection AddPetaPoco(this IServiceCollection services, Action <IDatabaseBuildConfiguration> optionsAction)
 {
     services.AddTransient <IDatabase>(sp =>
     {
         var builder = DatabaseConfiguration.Build();
         optionsAction(builder);
         return(new Database(builder));
     });
     services.TryAddSingleton(typeof(IDataService <>), typeof(DefaultDataService <>));
     return(services);
 }
Пример #13
0
        public void Construct_GivenInvalidArguments_ShouldThrow()
        {
#if !NETCOREAPP
            Should.Throw <InvalidOperationException>(() => new Database());
#endif

            Should.Throw <ArgumentNullException>(() => new Database((IDbConnection)null));

            Should.Throw <ArgumentNullException>(() => new Database("some connection string", (IProvider)null));
            Should.Throw <ArgumentException>(() => new Database(null, _provider));

#if !NETCOREAPP
            Should.Throw <ArgumentException>(() => new Database((string)null));
            Should.Throw <InvalidOperationException>(() => new Database("some connection string"));
#endif

            Should.Throw <ArgumentException>(() => new Database(null, _dbProviderFactory));
            Should.Throw <ArgumentNullException>(() => new Database("some connection string", (DbProviderFactory)null));

            Should.Throw <ArgumentNullException>(() => new Database((IDatabaseBuildConfiguration)null));
            Should.Throw <InvalidOperationException>(() =>
            {
                try
                {
                    DatabaseConfiguration.Build().Create();
                }
                catch (Exception e)
                {
#if !NETCOREAPP
                    e.Message.ShouldContain("One or more connection strings");
#else
                    e.Message.ShouldContain("A connection string is required");
#endif
                    throw;
                }
            });
            Should.Throw <InvalidOperationException>(() =>
            {
                try
                {
                    DatabaseConfiguration.Build().UsingConnectionString("cs").Create();
                }
                catch (Exception e)
                {
#if !NETCOREAPP
                    e.Message.ShouldContain("Both a connection string and provider are required");
#else
                    e.Message.ShouldContain("Either a provider name or provider must be registered");
#endif
                    throw;
                }
            });
        }
Пример #14
0
        protected virtual IDatabaseBuildConfiguration BuildFromConnectionName(string name)
        {
#if NETCOREAPP
            var appSettings = AppSetting.Load();

            return(DatabaseConfiguration.Build()
                   .UsingConnectionString(appSettings.ConnectionStrings.First(c => c.Name.Equals(name, StringComparison.OrdinalIgnoreCase)).ConnectionString)
                   .UsingProviderName(appSettings.ConnectionStrings.First(c => c.Name.Equals(name, StringComparison.OrdinalIgnoreCase)).ProviderName));
#else
            return(DatabaseConfiguration.Build().UsingConnectionStringName(name));
#endif
        }
Пример #15
0
        public static void InjectedServices(IConfiguration Configuration, IServiceCollection services)
        {
            services.AddScoped <IContestService, ContestService>();
            services.AddScoped <IActionService, ActionService>();

            services.AddSingleton <IDatabase>((a) =>
            {
                return(DatabaseConfiguration.Build()
                       .UsingConnectionString(Configuration["ConnectionString"])
                       .UsingProvider <SqlServerDatabaseProvider>()
                       .Create());
            });
        }
Пример #16
0
        public static IDatabaseBuildConfiguration GetConfig(string connectionString)
        {
            return(DatabaseConfiguration.Build()
                   .UsingConnectionString(connectionString)
                   .UsingProvider(new Providers.UnityDatabaseProvider())
                   .UsingDefaultMapper <ConventionMapper>(m =>
            {
                // Vehicle => vehicles
                m.InflectTableName = (inflector, tn) => inflector.Pluralise(UncapitaliseInvariant(tn));

                // TimeOfDay => timeOfDay
                m.InflectColumnName = (inflector, cn) => UncapitaliseInvariant(cn);
            }));
        }
Пример #17
0
        public static IDatabaseBuildConfiguration Default()
        {
            var conn = ConfigurationManager.ConnectionStrings["database"].ConnectionString;

            return(DatabaseConfiguration.Build()
                   .UsingProvider <SqlServerDatabaseProvider>()
                   .UsingConnectionString(conn)
                   .UsingIsolationLevel(IsolationLevel.ReadUncommitted)
                   .UsingDefaultMapper <ConventionMapper>(x =>
            {
                x.InflectTableName = (In, tableName) => String.Concat("core.", tableName, "s");
                x.InflectColumnName = (In, col) => col.ToLower();
            }));
        }
Пример #18
0
 public void ConfigureServices(IServiceCollection services)
 {
     services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
     services.AddSingleton(DatabaseConfiguration.Build()
                           .UsingProvider <SqlServerDatabaseProvider>()
                           .UsingConnectionString(Configuration.GetConnectionString("DefaultConnection"))
                           .Create());
     services.AddApiVersioning(o => {
         o.ReportApiVersions = true;
         o.AssumeDefaultVersionWhenUnspecified = true;
         o.DefaultApiVersion = new ApiVersion(1, 0);
     });
     services.AddRepositoryCollection();
 }
Пример #19
0
        public ApiController()
        {
            var provider         = new PostgreSQLDatabaseProvider();
            var connectionString = ConfigurationManager.ConnectionStrings["postgres"].ConnectionString;
            var config           = DatabaseConfiguration.Build()
                                   .UsingConnectionString(connectionString)
                                   .UsingProvider(provider)
                                   .UsingDefaultMapper <ConventionMapper>();
            var db = new Database(config);

            ambulanceRepository  = new AmbulanceRepository(db);
            hospitalRepository   = new HospitalRepository(db);
            incidentRepository   = new IncidentRepository(db);
            allocationRepository = new AllocationRepository(db);
        }
Пример #20
0
        public HomeController()
        {
            // var provider = new MonoSQLiteDatabaseProvider();
            var provider         = new PostgreSQLDatabaseProvider();
            var connectionString = ConfigurationManager.ConnectionStrings["postgres"].ConnectionString;
            var config           = DatabaseConfiguration.Build()
                                   .UsingConnectionString(connectionString)
                                   .UsingProvider(provider)
                                   .UsingDefaultMapper <ConventionMapper>();
            var db = new Database(config);

            // connection.Open();

            //logger.Info (db.ExecuteScalar<int>("select count(*) from ambulances where ambulances.ambulanceId = 'A9';"));

            ambulanceRepository  = new AmbulanceRepository(db);
            hospitalRepository   = new HospitalRepository(db);
            incidentRepository   = new IncidentRepository(db);
            allocationRepository = new AllocationRepository(db);
        }
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddCors(options =>
            {
                options.AddPolicy(MyAllowSpecificOrigins,
                                  builder =>
                {
                    builder.WithOrigins("http://localhost:53135",
                                        "http://localhost:4200"
                                        )
                    .AllowAnyHeader()
                    .AllowAnyMethod();
                });
            });
            services.AddControllers();
            services.AddSingleton <Contracts.IEmployeeServices, Services.EmployeeServices>();
            services.AddAutoMapper(typeof(AutoMappingProfile));
            var connection = DatabaseConfiguration.Build()
                             .UsingConnectionString("Server=DESKTOP-1K0UIDG\\SQLEXPRESS; Database = EmployeeDB; Trusted_Connection=True;")
                             .UsingProviderName("System.Data.SqlClient")
                             .Create();

            services.AddSingleton(connection);
        }
Пример #22
0
 public DatabaseConfigurationTests()
 {
     config = DatabaseConfiguration.Build();
 }
 // private readonly string strGetUsersQuery = @"select first_name FirstName,last_name LastName,user_id UserId from security.user_account";
 #endregion
 public PostgresSqlRepository(IOptions <AppSettingsModel> Appstns)
 {
     this.appSettings = Appstns;
     db = DatabaseConfiguration.Build().UsingConnectionString(appSettings.Value.DefaultConnection).UsingProvider(new PostgreSQLDatabaseProvider()).Create();
     db.OpenSharedConnection();
 }
 public ProjectManagerDbHelper(ApplicationManager app)
     : base(app)
 {
     Db = DatabaseConfiguration.Build().UsingConnectionString(Parameters.Parameters.ProjectManagerDbConnectionString)
          .UsingProvider(new PostgreSQLDatabaseProvider()).Create();
 }
Пример #25
0
        public static void Generate()
        {
            var config = new ConfigurationBuilder()
                         .AddJsonFile("appsettings.json", optional: false)
                         .Build();

            var settings = new Data.AppSettings();

            config.GetSection("AppSettings").Bind(settings);

            // Or the fluent configuration (PostgreSQL as an example)
            var db = DatabaseConfiguration.Build()
                     .UsingConnectionString(config.GetConnectionString("PocoConnection"))
                     .UsingProvider <MySqlDatabaseProvider>()
                     .UsingDefaultMapper <ConventionMapper>(m =>
            {
                m.InflectTableName  = (inflector, s) => inflector.Pluralise(inflector.Underscore(s));
                m.InflectColumnName = (inflector, s) => inflector.Underscore(s);
            }).Create();

            var factorData = new Faker <Factor>();

            factorData.RuleFor(factor => factor.Name, faker => "Faker: " + faker.Name.JobArea());
            factorData.RuleFor(factor => factor.Description, faker => faker.Lorem.Paragraph());

            var activityData = new Faker <Activity>();

            activityData.RuleFor(a => a.Name, faker => "Activity: " + faker.Name.JobType());
            activityData.RuleFor(a => a.Description, faker => faker.Name.JobTitle());

            var clientData = new Faker <Client>();

            clientData.RuleFor(c => c.Password, faker => SecurityHelper.HashPassword(faker.Internet.Password(), settings.Secret));
            clientData.RuleFor(c => c.Token, (faker, client) => "");

            var affectData = new Faker <Affect>();

            affectData.RuleFor(a => a.FactorId, faker =>
            {
                var f = db.Query <Factor>("SELECT * FROM factors ORDER BY RAND() LIMIT 1;").First();
                return(f.FactorId);
            });
            affectData.RuleFor(a => a.ActivityId, faker =>
            {
                var a = db.Query <Activity>("SELECT * FROM activities ORDER BY RAND() LIMIT 1;").First();
                return(a.ActivityId);
            });
            affectData.RuleFor(a => a.InfluenceName, faker =>
            {
                var inf = db.Query <Influence>("SELECT * FROM influences ORDER BY RAND() LIMIT 1;").First();
                return(inf.InfluenceName);
            });
            affectData.RuleFor(a => a.Source, faker => faker.Internet.Url());
            affectData.RuleFor(a => a.Description, faker => faker.Commerce.Product());

            var clienTaskData = new Faker <ClientTask>();

            clienTaskData.RuleFor(clientTask => clientTask.ActivityId, faker =>
            {
                var a = db.Query <Activity>("SELECT * FROM activities ORDER BY RAND() LIMIT 1;").First();
                return(a.ActivityId);
            });
            clienTaskData.RuleFor(clientTask => clientTask.ClientId, faker =>
            {
                var c = db.Query <Client>("SELECT * FROM clients ORDER BY RAND() LIMIT 1;").First();
                return(c.ClientId);
            });
            clienTaskData.RuleFor(clientTask => clientTask.Subject, faker => new Faker().Name.JobTitle());
            clienTaskData.RuleFor(clientTask => clientTask.At, faker => DateTime.Now);
            clienTaskData.RuleFor(clientTask => clientTask.Duration, faker => new Random().Next(1, 10));

            // Delete old data
            db.Delete <Affect>("");
            db.Delete <ClientTask>("");
            db.Delete <Activity>("");
            db.Delete <Factor>("");
            db.Delete <Influence>("");
            db.Delete <Client>("");

            // Start Generation
            if (db.Query <Influence>().Count() == 0)
            {
                for (int i = 0; i < 10; i++)
                {
                    db.Insert(clientData.Generate());
                }

                for (int i = 0; i < 30; i++)
                {
                    db.Insert(activityData.Generate());
                }

                for (int i = 0; i < 50; i++)
                {
                    db.Insert(factorData.Generate());
                }

                db.Insert(new Influence {
                    InfluenceDisplay = "Positive", InfluenceName = "positive"
                });
                db.Insert(new Influence {
                    InfluenceDisplay = "Negative", InfluenceName = "negative"
                });
                db.Insert(new Influence {
                    InfluenceDisplay = "Indifferent", InfluenceName = "indifferent"
                });
                db.Insert(new Influence {
                    InfluenceDisplay = "Unclear", InfluenceName = "unclear"
                });

                for (int i = 0; i < 100; i++)
                {
                    var a = affectData.Generate();
                    // Don't violate primary key constraint
                    var ex = db.Exists <Affect>("WHERE activity_id = @0 AND factor_id = @1 AND influence_name = @2", a.ActivityId, a.FactorId, a.InfluenceName);
                    if (!ex)
                    {
                        db.Insert(a);
                    }
                }

                for (int i = 0; i < 100; i++)
                {
                    db.Insert(clienTaskData.Generate());
                }
            }
        }
Пример #26
0
 public SaveToDatabase()
 {
     _db = DatabaseConfiguration.Build()
           .UsingConnectionStringName("mssql")
           .Create();
 }
Пример #27
0
        public static void Main(string[] args)
        {
            //DeployAmbulanceAtStationAllocator();
            //Thread.Sleep(TimeSpan.FromSeconds(10));

            Console.WriteLine("Hello World!");
            var monitoringDelay = TimeSpan.FromSeconds(1);

            logger.Info("Connecting to database");
            var provider         = new PostgreSQLDatabaseProvider();
            var connectionString = ConfigurationManager.ConnectionStrings["postgres"].ConnectionString;

            var config = DatabaseConfiguration.Build()
                         .UsingConnectionString(connectionString)
                         .UsingProvider(provider)
                         .UsingDefaultMapper <ConventionMapper>();

            db = new Database(config);
            incidentRepository      = new IncidentRepository(db);
            ambulanceRepository     = new AmbulanceRepository(db);
            allocationRepository    = new AllocationRepository(db);
            hospitalRepository      = new HospitalRepository(db);
            configurationRepository = new ConfigurationRepository(db);
            logger.Info("Connected to database");

            logger.Info("Building KAOS model.");
            var filename = "./Models/simple.kaos";
            var parser   = new KAOSTools.Parsing.ModelBuilder();

            model = parser.Parse(File.ReadAllText(filename), filename);
            var model2 = parser.Parse(File.ReadAllText(filename), filename);

            ActiveResolutions = Enumerable.Empty <Resolution>();

            var declarations = parser.Declarations;

            logger.Info("(done)");

            logger.Info("Configuring monitors.");
            // Configure all the monitors (for all obstacles and domain properties).
            KAOSMetaModelElement[] goals     = model.Goals().ToArray();
            KAOSMetaModelElement[] obstacles = model.LeafObstacles().ToArray();
            var projection = new HashSet <string>(GetAllPredicates(goals));

            monitor = new GoalMonitor(model, goals.Union(obstacles), projection, HandleFunc,
                                      // new TimedStateInformationStorage(TimeSpan.FromMinutes(60), TimeSpan.FromMinutes(120)),
                                      monitoringDelay);
            logger.Info("(done)");

            foreach (var p in model.Predicates())
            {
                Console.WriteLine(p.FriendlyName);
            }

            // What goals and obstacles should appear in LOG
            cpsGoals     = model.Goals(x => x.CustomData.ContainsKey("log_cps"));
            cpsObstacles = model.Obstacles(x => x.CustomData.ContainsKey("log_cps"));

            // Initialize obstruction sets
            obstructionLock = new object();
            ComputeObstructionSets();

            Console.WriteLine("Waiting ...");
            Console.ReadKey();

            logger.Info("Launching monitors");
            monitor.Run(false);

            var goalMonitorProcessor = new GoalMonitorProcessor(monitor);

            csvExport = new CSVGoalExportProcessor("experiment-goal.csv", "experiment-obstacle.csv");
            // goalMonitorProcessor.AddProcessor(csvExport, monitoringDelay);

            new Timer((state) => UpdateCPS(), null, monitoringDelay, monitoringDelay);
            new Timer((state) => MonitorStep(), null, monitoringDelay, monitoringDelay);
            Thread.Sleep(TimeSpan.FromSeconds(5));
            logger.Info("Launching processors");
            //new Timer((state) => LogStatistic(), null, monitoringDelay, monitoringDelay);
            new Timer((state) => LogCSV(), null, monitoringDelay, monitoringDelay);

            // Configure optimization process.
            optimizer = new Optimizer(monitor, model2);
            new Timer((state) => Optimize(), null, TimeSpan.FromSeconds(30), TimeSpan.FromSeconds(60));

            while (true)
            {
                ;
            }
        }
Пример #28
0
        public static void Main(string[] args)
        {
            logger.Info("Starting simulator");
            var connectionString = ConfigurationManager.ConnectionStrings["postgres"].ConnectionString;
            var provider         = new PostgreSQLDatabaseProvider();

            var config = DatabaseConfiguration.Build()
                         .UsingConnectionString(connectionString)
                         .UsingProvider(provider)
                         .UsingDefaultMapper <ConventionMapper>();

            var incSimulator = new IncidentSimulator(new Database(config));

            var mapService = new MapService();
            var hospitals  = new Dictionary <string, Coordinate>();

            hospitals.Add("HOP1", new Coordinate(50.834957f, 4.348430f));
            hospitals.Add("HOP2", new Coordinate(50.814250f, 4.357530f));
            hospitals.Add("HOP3", new Coordinate(50.853853f, 4.360663f));
            hospitals.Add("HOP4", new Coordinate(50.852575f, 4.452851f));
            hospitals.Add("HOP5", new Coordinate(50.845607f, 4.317075f));
            hospitals.Add("HOP6", new Coordinate(50.804648f, 4.367769f));
            hospitals.Add("HOP7", new Coordinate(50.825022f, 4.379507f));
            hospitals.Add("HOP8", new Coordinate(50.813997f, 4.259632f));
            //hospitals.Add ("HOP8",  new Coordinate(50.8128775f, 4.2649523f));
            hospitals.Add("HOP9", new Coordinate(50.905819f, 4.390159f));
            hospitals.Add("HOP10", new Coordinate(50.8885403f, 4.3288842f));
            hospitals.Add("HOP11", new Coordinate(50.833261f, 4.347095f));
            hospitals.Add("HOP12", new Coordinate(50.8872628f, 4.3089256f));
            hospitals.Add("HOP13", new Coordinate(50.842471f, 4.399073f));

            var pasiDelta      = new SimulatedStation("pasiDelta", "PASI Delta", new Coordinate(50.818754f, 4.402740f), "pasiDelta_printer");
            var hopIxelles     = new SimulatedStation("hopIxelles", "Hopital d'Ixelles", new Coordinate(50.824938f, 4.379172f), "hopIxelles_printer");
            var pasiAnderlecht = new SimulatedStation("pasiAnderlecht", "PASI Anderlecht", new Coordinate(50.832740f, 4.311812f), "pasiAnderlecht_printer");
            var pasiEvere      = new SimulatedStation("pasiEvere", "PASI Evere", new Coordinate(50.870964f, 4.417631f), "pasiEvere_printer");
            var pasiVUB        = new SimulatedStation("pasiVUB", "PASI VUB", new Coordinate(50.890831f, 4.308449f), "pasiVUB_printer");
            var pasiChenaie    = new SimulatedStation("pasiChenaie", "PASI Chenaie", new Coordinate(50.783341f, 4.356218f), "pasiChenaie_printer");
            var pasiCite       = new SimulatedStation("pasiCite", "PASI Cité", new Coordinate(50.849709f, 4.361116f), "pasiCite_printer");
            var pasiUCL        = new SimulatedStation("pasiUCL", "PASI UCL", new Coordinate(50.851937f, 4.460279f), "pasiUCL_printer");
            var heliport       = new SimulatedStation("heliport", "Caserne de l'Héliport", new Coordinate(50.859485f, 4.351848f), "heliport_printer");
            var moliere        = new SimulatedStation("moliere", "Hopital Molière", new Coordinate(50.815206f, 4.342141f), "moliere_printer");
            var saintpierre    = new SimulatedStation("saintpierre", "Hopital Saint-Pierre", new Coordinate(50.835228f, 4.348342f), "saintpierre_printer");

            logger.Info("Adding ambulances");

            var a01 = new SimulatedAmbulance("A1", mapService, hospitals, pasiAnderlecht);
            var a02 = new SimulatedAmbulance("A2", mapService, hospitals, pasiDelta);
            var a03 = new SimulatedAmbulance("A3", mapService, hospitals, pasiVUB);
            var a04 = new SimulatedAmbulance("A4", mapService, hospitals, pasiCite);
            var a05 = new SimulatedAmbulance("A5", mapService, hospitals, pasiVUB);
            var a06 = new SimulatedAmbulance("A6", mapService, hospitals, heliport);
            var a07 = new SimulatedAmbulance("A7", mapService, hospitals, heliport);
            var a08 = new SimulatedAmbulance("A8", mapService, hospitals, heliport);
            var a09 = new SimulatedAmbulance("A9", mapService, hospitals, hopIxelles);
            var a10 = new SimulatedAmbulance("A10", mapService, hospitals, pasiUCL);
            var a11 = new SimulatedAmbulance("A11", mapService, hospitals, pasiUCL);
            var a12 = new SimulatedAmbulance("A12", mapService, hospitals, pasiCite);
            var a13 = new SimulatedAmbulance("A13", mapService, hospitals, moliere);
            var a14 = new SimulatedAmbulance("A14", mapService, hospitals, pasiVUB);
            var a15 = new SimulatedAmbulance("A15", mapService, hospitals, pasiDelta);

            //var a16 = new SimulatedAmbulance("A16", mapService, hospitals, saintpierre);
            //var a17 = new SimulatedAmbulance("A17", mapService, hospitals, heliport);
            //var a18 = new SimulatedAmbulance("A18", mapService, hospitals, pasiChenaie);
            //var a19 = new SimulatedAmbulance("A19", mapService, hospitals, pasiChenaie);
            //var a20 = new SimulatedAmbulance("A20", mapService, hospitals, saintpierre);
            //var a21 = new SimulatedAmbulance("A21", mapService, hospitals, saintpierre);
            //var a22 = new SimulatedAmbulance("A22", mapService, hospitals, pasiEvere);
            //var a23 = new SimulatedAmbulance("A23", mapService, hospitals, pasiEvere);
            //var a24 = new SimulatedAmbulance("A24", mapService, hospitals, pasiEvere);
            //var a25 = new SimulatedAmbulance("A25", mapService, hospitals, pasiCite);
            //var a26 = new SimulatedAmbulance("A26", mapService, hospitals, pasiCite);

            logger.Info("Ambulances added");

            Thread.Sleep(TimeSpan.FromSeconds(5));
            incSimulator.Start();
        }
Пример #29
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.Configure <CookiePolicyOptions>(options =>
            {
                // This lambda determines whether user consent for non-essential cookies is needed for a given request.
                options.CheckConsentNeeded    = context => true;
                options.MinimumSameSitePolicy = SameSiteMode.None;
            });


            services.AddDbContext <EfCoreDBContext>(
                options =>
            {
                var connectionString = Configuration["ConnectionStrings:MySQL:MvcMySQL"];
                options.UseMySql(connectionString,
                                 myopttion => { myopttion.ServerVersion(new Version(10, 2), ServerType.MariaDb); });
            });

            //services.AddScoped<IDatabase>(
            //    x =>
            //        {
            //            var connectionStrnig = Configuration["ConnectionStrings:MySQL:MvcMySQL"];

            //            var configuration = DatabaseConfiguration.Build().UsingConnectionString(connectionStrnig)
            //                .UsingProvider<MariaDbDatabaseProvider>();
            //            return new PetaPocoMvcDBContext(configuration);
            //        });

            services.AddScoped <IDatabase, PetaPocoMvcDBContext>(
                (x) =>
            {
                var connectionStrnig = Configuration["ConnectionStrings:MySQL:MvcMySQL"];

                var configuration = DatabaseConfiguration.Build().UsingConnectionString(connectionStrnig)
                                    .UsingProvider <MariaDbDatabaseProvider>();
                return(new PetaPocoMvcDBContext(configuration));
            });

            services.AddScoped <IUserService, UserService>();
            services.AddScoped <ISampleCustomerRepository, SampleCustomerRepository>();


            //Mqtt
            //services.AddHostedMqttServer(o=>{}).AddMqttConnectionHandler().AddConnections().AddMqttTcpServerAdapter();
            services.AddHostedMqttServerWithServices(
                builder =>
            {
                //builder.WithDefaultEndpoint();

                builder.WithDefaultEndpointPort(1883);
                builder.WithConnectionValidator(
                    c =>
                {
                    //从IServiceCollection中构建     ServiceProvider, 用以使用注入访问数据库的服务
                    var serprovider = services.BuildServiceProvider();
                    var us          = serprovider.GetService(typeof(IUserService)) as IUserService;
                    _logger.LogInformation($" ClientId:{c.ClientId} Endpoint:{c.Endpoint} Username:{c.Username} Password:{c.Password} WillMessage:{c.WillMessage}");
                    var x = us.GetAll();
                    if (c.ClientId.Length < 5)
                    {
                        c.ReturnCode = MqttConnectReturnCode.ConnectionRefusedIdentifierRejected;
                        return;
                    }

                    if (c.Username != "admin")
                    {
                        c.ReturnCode = MqttConnectReturnCode.ConnectionRefusedBadUsernameOrPassword;
                        return;
                    }

                    if (c.Password != "public")
                    {
                        c.ReturnCode = MqttConnectReturnCode.ConnectionRefusedBadUsernameOrPassword;
                        return;
                    }

                    c.ReturnCode = MqttConnectReturnCode.ConnectionAccepted;
                });
            });        //.AddMqttConnectionHandler().AddConnections().AddMqttTcpServerAdapter();
            //this adds tcp server support based on System.Net.Socket
            services.AddMqttTcpServerAdapter();

            //this adds websocket support
            services.AddMqttWebSocketServerAdapter();

            //添加内存缓存Memory
            services.AddMemoryCache();

            //添加分布式缓存RedisCache使用
            services.AddDistributedRedisCache(
                options =>
            {
                options.Configuration = "localhost";
            });
            //
            var ass = Assembly.GetEntryAssembly().GetReferencedAssemblies().Select(Assembly.Load).SelectMany(y => y.DefinedTypes)
                      .Where(type => typeof(IProfile).GetTypeInfo().IsAssignableFrom(type.AsType()));

            services.AddAutoMapper(cfg => { }, new List <Assembly>()
            {
                Assembly.GetEntryAssembly()
            });

            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
        }