Esempio n. 1
0
        private void InitializeEventFlowDbStructure(IServiceProvider serviceProvider)
        {
            var msSqlDatabaseMigrator = serviceProvider.GetService <IMsSqlDatabaseMigrator>();

            EventFlowEventStoresMsSql.MigrateDatabase(msSqlDatabaseMigrator);
            EventFlowSnapshotStoresMsSql.MigrateDatabase(msSqlDatabaseMigrator);
        }
Esempio n. 2
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public IServiceProvider ConfigureServices(IServiceCollection services)
        {
            services.AddMvc();

            var containerBuilder = new ContainerBuilder();

            containerBuilder.Populate(services);

            var container = EventFlowOptions.New
                            .UseAutofacContainerBuilder(containerBuilder)
                            .AddAspNetCoreMetadataProviders()
                            .ConfigureMsSql(MsSqlConfiguration.New.SetConnectionString("Server=localhost;Database=RestAirline;User Id=sa;Password=RestAirline123"))
                            .UseMssqlEventStore()
                            .ConfigureBookingCommands()
                            .ConfigureBookingCommandHandlers()
                            .ConfigureInMemoryReadModel()
                            .ConfigureBookingQueryHandlers()
                            .ConfigureBookingDomain()
                            .ConfigureEntityFrameworkReadModel()
                            //EventFlow expect the read model to exist, and thus any maintenance of the database schema for the read models must be handled before EventFlow is initialized.
//                .ConfigureMsSqlReadModel()
                            .CreateContainer();

            var msSqlDatabaseMigrator = container.Resolve <IMsSqlDatabaseMigrator>();

            EventFlowEventStoresMsSql.MigrateDatabase(msSqlDatabaseMigrator);

            return(new AutofacServiceProvider(container));
        }
        static void Main(string[] args)
        {
            var logRepository = LogManager.GetRepository(Assembly.GetEntryAssembly());

            XmlConfigurator.Configure(logRepository, new FileInfo("log4net.config"));

            using (var resolver = EventFlowOptions.New
                                  .AddEvents(typeof(CompetitionRegisteredEvent), typeof(CompetitionCorrectedEvent), typeof(CompetitionDeletedEvent), typeof(EntryRecordedEvent), typeof(EntryTimeCorrectedEvent))
                                  .AddCommands(typeof(RegisterCompetitionCommand), typeof(CorrectCompetitionCommand), typeof(DeleteCompetitionCommand), typeof(RecordEntryCommand), typeof(CorrectEntryTimeCommand))
                                  .AddCommandHandlers(typeof(RegisterCompetitionHandler), typeof(CorrectCompetitionHandler), typeof(DeleteCompetitionHandler), typeof(RecordEntryHandler), typeof(CorrectEntryTimeHandler))
                                  .AddSnapshots(typeof(CompetitionSnapshot))
                                  .RegisterServices(sr => sr.Register(i => SnapshotEveryFewVersionsStrategy.Default))
                                  .RegisterServices(sr => sr.Register(c => ConfigurationManager.ConnectionStrings["EventStore"].ConnectionString))
                                  .UseMssqlEventStore()
                                  .UseMsSqlSnapshotStore()
                                  .AddMsSqlReadModel()
                                  .AddEntityFrameworkReadModel()
                                  .CreateResolver())
            {
                var msSqlDatabaseMigrator = resolver.Resolve <IMsSqlDatabaseMigrator>();
                EventFlowEventStoresMsSql.MigrateDatabase(msSqlDatabaseMigrator);
                // var sql = EventFlowEventStoresMsSql.GetSqlScripts().Select(s => s.Content).ToArray();

                // Create a new identity for our aggregate root
                var exampleId = CompetitionId.New;

                // Define some important value
                const string name  = "test-competition";
                const string name2 = "new-name";
                const string user  = "******";

                // Resolve the command bus and use it to publish a command
                var commandBus      = resolver.Resolve <ICommandBus>();
                var executionResult = commandBus.PublishAsync(new RegisterCompetitionCommand(exampleId, user, name), CancellationToken.None).Result;

                executionResult = commandBus.PublishAsync(new CorrectCompetitionCommand(exampleId, name2), CancellationToken.None).Result;

                ReadModel.MsSql.ReadModelConfiguration.Query(resolver, exampleId).Wait();
                ReadModel.EntityFramework.ReadModelConfiguration.Query(resolver, exampleId).Wait();

                var entry1Id = EntryId.New;
                var entry2Id = EntryId.New;

                commandBus.PublishAsync(new RecordEntryCommand(exampleId, entry1Id, "Discipline 1", "Name 1", 11111), CancellationToken.None).Wait();
                commandBus.PublishAsync(new RecordEntryCommand(exampleId, entry2Id, "Discipline 2", "Name 2", 22222), CancellationToken.None).Wait();
                commandBus.PublishAsync(new CorrectEntryTimeCommand(exampleId, entry1Id, 10000), CancellationToken.None).Wait();
                commandBus.PublishAsync(new CorrectEntryTimeCommand(exampleId, entry2Id, 20000), CancellationToken.None).Wait();

                for (int x = 1; x < 100; x++)
                {
                    commandBus.PublishAsync(new CorrectEntryTimeCommand(exampleId, entry2Id, 2000 + x), CancellationToken.None).Wait();
                }

                commandBus.PublishAsync(new DeleteCompetitionCommand(exampleId), CancellationToken.None).Wait();
            }
            //Console.ReadLine();
        }
Esempio n. 4
0
        public override IRootResolver CreateRootResolver(EventFlowOptions eventFlowOptions)
        {
            TestDatabase = MsSqlHelper.CreateDatabase("eventflow");

            var resolver = eventFlowOptions
                           .ConfigureMsSql(MsSqlConfiguration.New.SetConnectionString(TestDatabase.ConnectionString))
                           .UseEventStore <MsSqlEventStore>()
                           .CreateResolver();

            MsSqlConnection = resolver.Resolve <IMsSqlConnection>();
            EventFlowEventStoresMsSql.MigrateDatabase(resolver.Resolve <IMsSqlDatabaseMigrator>());

            return(resolver);
        }
Esempio n. 5
0
        private static void Main(string[] args)
        {
            TradingPersistenceService tradingPersistenceService = null;

            try
            {
                Console.WriteLine(@"
                                     █████╗ ██╗       ██████╗ ██████╗ ████████╗██╗ ██████╗ ███╗   ██╗
                                    ██╔══██╗██║      ██╔═══██╗██╔══██╗╚══██╔══╝██║██╔═══██╗████╗  ██║
                                    ███████║██║█████╗██║   ██║██████╔╝   ██║   ██║██║   ██║██╔██╗ ██║
                                    ██╔══██║██║╚════╝██║   ██║██╔═══╝    ██║   ██║██║   ██║██║╚██╗██║
                                    ██║  ██║██║      ╚██████╔╝██║        ██║   ██║╚██████╔╝██║ ╚████║
                                    ╚═╝  ╚═╝╚═╝       ╚═════╝ ╚═╝        ╚═╝   ╚═╝ ╚═════╝ ╚═╝  ╚═══╝");
                var services = new ServiceCollection();
                var startup  = new Startup();
                var provider = startup.ConfigureServices(services);


                //migrate
                Task.Run(() =>
                {
                    var sql = provider.GetService <IMsSqlDatabaseMigrator>();
                    EventFlowEventStoresMsSql.MigrateDatabase(sql);
                    EventFlowSnapshotStoresMsSql.MigrateDatabase(sql);
                });


                tradingPersistenceService = provider.GetService <TradingPersistenceService>();
                tradingPersistenceService.InitializeTradingsServiceAsync().Wait();


                while (true)
                {
                    var input = Console.ReadLine();
                    switch (input)
                    {
                    case "-l": {
                        tradingPersistenceService.GetListOfSubscribe();
                        break;
                    }
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                Console.ReadLine();
            }
        }
        protected override IRootResolver CreateRootResolver(IEventFlowOptions eventFlowOptions)
        {
            _testDatabase = MsSqlHelpz.CreateDatabase("eventflow");

            var resolver = eventFlowOptions
                           .ConfigureMsSql(MsSqlConfiguration.New.SetConnectionString(_testDatabase.ConnectionString.Value))
                           .UseEventStore <MsSqlEventPersistence>()
                           .CreateResolver();

            var databaseMigrator = resolver.Resolve <IMsSqlDatabaseMigrator>();

            EventFlowEventStoresMsSql.MigrateDatabase(databaseMigrator);
            databaseMigrator.MigrateDatabaseUsingEmbeddedScripts(GetType().Assembly);

            return(resolver);
        }
Esempio n. 7
0
        public async Task <bool> Handle(FlashCommand request, CancellationToken cancellationToken)
        {
            Consoler.TitleStart("flash database start");

            var connectionString =
                ConfigurationManager.ConnectionStrings["Vita"].ConnectionString;

            if (DatabaseUtil.CheckDatabaseExists(connectionString.Replace("Vita", "master"), "Vita"))
            {
                DatabaseUtil.DeleteAllTables(connectionString);
            }

            Consoler.TitleStart("Create Database if not exist ...");
            EnsureDatabase.For.SqlDatabase(connectionString);
            Consoler.TitleEnd("Completed");
            Consoler.Write("EventFlow Schema Created...");

            // EventFlow Schema
            EventFlowEventStoresMsSql.MigrateDatabase(IocContainer.Container.Resolve <IMsSqlDatabaseMigrator>());
            Consoler.Write("EventFlow Schema Created...");

            // Schema
            var result = DeployChanges.To
                         .SqlDatabase(connectionString)
                         .WithTransaction()
                         .WithScriptsEmbeddedInAssembly(Assembly.GetExecutingAssembly())
                         .LogToConsole()
                         .Build()
                         .PerformUpgrade();

            foreach (var script in result.Scripts)
            {
                Consoler.Write($"script: {script.Name}");
            }

            if (result.Error != null)
            {
                Consoler.ShowError(result.Error);
            }

            await Task.CompletedTask;

            Consoler.TitleEnd("flash database finished");
            return(result.Successful);
        }
Esempio n. 8
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(
            IApplicationBuilder app,
            IHostingEnvironment env,
            IApplicationLifetime appLifetime)
        {
            app.UseStaticFiles();

            var migrator = ApplicationContainer.Resolve <IMsSqlDatabaseMigrator>();

            EventFlowEventStoresMsSql.MigrateDatabase(migrator);

            app.UseSwagger();
            app.UseSwaggerUI(c =>
            {
                c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1");
            });

            app.UseMvc();

            appLifetime.ApplicationStopped.Register(() => this.ApplicationContainer.Dispose());
        }
Esempio n. 9
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseMiddleware <CommandPublishMiddleware>();
            app.UseMvc();

            app.UseSwagger();
            app.UseSwaggerUI(c =>
            {
                c.SwaggerEndpoint("/swagger/v1/swagger.json", "Event Sourcing api V1");
            });

            var msSqlDatabaseMigrator = app.ApplicationServices.GetService <IMsSqlDatabaseMigrator>();

            EventFlowEventStoresMsSql.MigrateDatabase(msSqlDatabaseMigrator);
            EventFlowSnapshotStoresMsSql.MigrateDatabase(msSqlDatabaseMigrator);
        }
Esempio n. 10
0
        public override IRootResolver CreateRootResolver(EventFlowOptions eventFlowOptions)
        {
            TestDatabase = MsSqlHelper.CreateDatabase("eventflow");

            var resolver = eventFlowOptions
                           .ConfigureMsSql(MsSqlConfiguration.New.SetConnectionString(TestDatabase.ConnectionString))
                           .UseEventStore <MsSqlEventStore>()
                           .UseMssqlReadModel <MsSqlTestAggregateReadModel>()
                           .CreateResolver();

            MsSqlConnection       = resolver.Resolve <IMsSqlConnection>();
            ReadModelSqlGenerator = resolver.Resolve <IReadModelSqlGenerator>();
            ReadModelPopulator    = resolver.Resolve <IReadModelPopulator>();

            var databaseMigrator = resolver.Resolve <IMsSqlDatabaseMigrator>();

            EventFlowEventStoresMsSql.MigrateDatabase(databaseMigrator);
            databaseMigrator.MigrateDatabaseUsingEmbeddedScripts(GetType().Assembly);

            return(resolver);
        }
Esempio n. 11
0
        protected override IRootResolver CreateRootResolver(IEventFlowOptions eventFlowOptions)
        {
            _testDatabase = MsSqlHelpz.CreateDatabase("eventflow");

            var resolver = eventFlowOptions
                           .RegisterServices(sr => sr.RegisterType(typeof(ThingyMessageLocator)))
                           .ConfigureMsSql(MsSqlConfiguration.New.SetConnectionString(_testDatabase.ConnectionString.Value))
                           .UseMssqlReadModel <MsSqlThingyReadModel>()
                           .UseMssqlReadModel <MsSqlThingyMessageReadModel, ThingyMessageLocator>()
                           .AddQueryHandlers(
                typeof(MsSqlThingyGetQueryHandler),
                typeof(MsSqlThingyGetVersionQueryHandler),
                typeof(MsSqlThingyGetMessagesQueryHandler))
                           .CreateResolver();

            var databaseMigrator = resolver.Resolve <IMsSqlDatabaseMigrator>();

            EventFlowEventStoresMsSql.MigrateDatabase(databaseMigrator);
            databaseMigrator.MigrateDatabaseUsingEmbeddedScripts(GetType().Assembly);

            return(resolver);
        }
        /// <summary>
        /// Initalises the eventflow database tables
        /// </summary>
        /// <see cref="https://eventflow.readthedocs.io/EventStore.html#mssql-event-store"/>
        /// <param name="args"></param>
        static void Main(string[] args)
        {
            var devEnvironmentVariable = Environment.GetEnvironmentVariable("NETCORE_ENVIRONMENT");
            var isDevelopment          = string.IsNullOrEmpty(devEnvironmentVariable) || devEnvironmentVariable.ToLower() == "development";
            //Determines the working environment as IHostingEnvironment is unavailable in a console app

            var builder = new ConfigurationBuilder()
                          .SetBasePath(Directory.GetCurrentDirectory());


            if (isDevelopment) //only add secrets in development
            {
                builder.AddUserSecrets("babaea2e-4e26-4c24-8243-7f166cdf3230");
            }

            Configuration = builder.Build();

            var connectionString = Configuration["EventStoreConnectionString"];

            //var services = new ServiceCollection()
            //    .Configure<Secrets>(Configuration.GetSection(nameof(Secrets)))
            //    .AddOptions()
            //    .BuildServiceProvider();

            //services.GetService<Secrets>();

            var rootResolver = EventFlowOptions.New
                               .AddAspNetCoreMetadataProviders()
                               .UseMssqlEventStore()
                               .ConfigureMsSql(MsSqlConfiguration.New.SetConnectionString(connectionString))
                               .CreateResolver();

            var msSqlDatabaseMigrator = rootResolver.Resolve <IMsSqlDatabaseMigrator>();

            EventFlowEventStoresMsSql.MigrateDatabase(msSqlDatabaseMigrator);
        }
        static async Task Main(string[] args)
        {
            /*
             * SETUP
             */
            var logRepository = LogManager.GetRepository(Assembly.GetEntryAssembly());

            XmlConfigurator.Configure(logRepository, new FileInfo("log4net.config"));

            using (var resolver = EventFlowOptions.New
                                  .AddEvents(Assembly.GetAssembly(typeof(CompetitionRegisteredEvent)))
                                  .AddCommands(Assembly.GetAssembly(typeof(RegisterCompetitionCommand)), t => true)
                                  .AddCommandHandlers(Assembly.GetAssembly(typeof(RegisterCompetitionHandler)))
                                  .AddSnapshots(Assembly.GetAssembly(typeof(CompetitionSnapshot)), t => true)
                                  .RegisterServices(sr => sr.Register(i => SnapshotEveryFewVersionsStrategy.Default))
                                  .UseMssqlEventStore()
                                  .UseMsSqlSnapshotStore()
                                  .AddMsSqlReadModel()
                                  .AddEntityFrameworkReadModel()
                                  .CreateResolver())
            {
                var msSqlDatabaseMigrator = resolver.Resolve <IMsSqlDatabaseMigrator>();
                EventFlowEventStoresMsSql.MigrateDatabase(msSqlDatabaseMigrator);
                // var sql = EventFlowEventStoresMsSql.GetSqlScripts().Select(s => s.Content).ToArray();

                /*
                 * USAGE
                 */

                // Create a new identity for our aggregate root
                var exampleId = CompetitionId.New;

                // Define some important value
                const string name  = "test-competition";
                const string name2 = "new-name";
                const string user  = "******";

                // Resolve the command bus and use it to publish a command
                var commandBus      = resolver.Resolve <ICommandBus>();
                var executionResult = commandBus.Publish(new RegisterCompetitionCommand(exampleId, user, name), CancellationToken.None);

                executionResult = commandBus.Publish(new CorrectCompetitionCommand(exampleId, name2), CancellationToken.None);

                ReadModel.MsSql.ReadModelConfiguration.Query(resolver, exampleId);
                ReadModel.EntityFramework.ReadModelConfiguration.Query(resolver, exampleId);

                using (var http = new HttpClient())
                {
                    var comp = exampleId.ToString();

                    var entry1Id = await RecordEntry(http, new { CompetitionId = comp, Discipline = "Discipline 1", Name = "Name 1", TimeInMillis = 11111 });

                    var entry2Id = await RecordEntry(http, new { CompetitionId = comp, Discipline = "Discipline 2", Name = "Name 2", TimeInMillis = 22222 });
                    await CorrectEntryTime(http, entry1Id, new { CompetitionId = comp, TimeInMillis = 10000 });
                    await CorrectEntryTime(http, entry2Id, new { CompetitionId = comp, TimeInMillis = 20000 });

                    for (int x = 1; x < 100; x++)
                    {
                        await CorrectEntryTime(http, entry2Id, new { CompetitionId = comp, TimeInMillis = 2000 + x });
                    }
                }
                executionResult = commandBus.Publish(new DeleteCompetitionCommand(exampleId), CancellationToken.None);
            }
        }