Beispiel #1
0
        private async Task Initialize()
        {
            if (!_instance.IsRunning)
            {
                _manager.Start();
            }

            using (var connection = _instance.CreateConnection())
            {
                await connection.OpenAsync();

                var tempPath       = Environment.GetEnvironmentVariable("Temp");
                var createDatabase = $"CREATE DATABASE [{_databaseName}] on (name='{_databaseName}', "
                                     + $"filename='{tempPath}\\{_databaseName}.mdf')";
                using (var command = new SqlCommand(createDatabase, connection))
                {
                    await command.ExecuteNonQueryAsync();
                }
            }

            var sqlConnectionStringBuilder = _instance.CreateConnectionStringBuilder();

            sqlConnectionStringBuilder.InitialCatalog = _databaseName;
            ConnectionString = sqlConnectionStringBuilder.ToString();
            var settings = new MsSqlStreamStoreV3Settings(ConnectionString);

            _msSqlStreamStoreV3 = new MsSqlStreamStoreV3(settings);
            await _msSqlStreamStoreV3.CreateSchemaIfNotExists();
        }
        public MsSqlStreamStoreV3Fixture()
        {
            var config = new TestConfiguration();

            _dbFixture = new DbFixture(config);

            MsqlStreamStore = new MsSqlStreamStoreV3(new MsSqlStreamStoreV3Settings(_dbFixture.ConnectionString));
            MsqlStreamStore.CreateSchemaIfNotExists().Wait();
        }
        public async Task InitializeAndWarmUp()
        {
            var eventStore = new MsSqlStreamStoreV3(new MsSqlStreamStoreV3Settings(ConnectionString));
            await eventStore.CreateSchemaIfNotExists();

            _outbox = new SqlStreamStoreOutbox(eventStore, TimeSpan.Zero);
            var db = new TestDbContextWithOutbox(ConnectionString, _outbox);

            db.Database.CreateIfNotExists();
            await WarmUp();
        }
        private async Task <IStreamStore> GetStreamStore(string schema)
        {
            var settings = new MsSqlStreamStoreV3Settings(ConnectionString)
            {
                Schema = schema,
                DisableDeletionTracking = _disableDeletionTracking
            };
            var store = new MsSqlStreamStoreV3(settings);
            await store.CreateSchemaIfNotExists();

            return(store);
        }
Beispiel #5
0
        public static async Task WithSqlStreamStore()
        {
            var connectionString = "Server=(local);Database=SqlStreamStoreDemo;Trusted_Connection=True;MultipleActiveResultSets=true";
            var settings         = new MsSqlStreamStoreV3Settings(connectionString);
            var streamStore      = new MsSqlStreamStoreV3(settings);
            await streamStore.CreateSchemaIfNotExists();

            repository = new SqlStreamStoreRepository <Counter>(streamStore);

            var counterId = Guid.Parse("fbb0f16b-646a-45d3-a1ee-596217897b62");

            await CreateAndSaveCounter(counterId);
            await LoadAndUpdateCounter(counterId);
        }
Beispiel #6
0
        private void ConfigureMssql2019()
        {
            CreateMsSqlDatabaseUnlessExists();
            var connectionString = "Server=localhost;Database=memstate;User Id=sa;Password=abc123ABC;";

            _connection = new SqlConnection(connectionString);
            var settings = new MsSqlStreamStoreV3Settings(connectionString);

            settings.Schema = "memstate";
            var store = new MsSqlStreamStoreV3(settings);

            store.CreateSchemaIfNotExists().GetAwaiter().GetResult();
            _streamStore = store;
        }
Beispiel #7
0
        private async Task <IStreamStore> GetMsSqlStore(bool dropAll)
        {
            var store = new MsSqlStreamStoreV3(new MsSqlStreamStoreV3Settings(Configuration.MsSqlConnectionString));

            if (dropAll)
            {
                await store.DropAll();
            }
            if (dropAll || !(await store.CheckSchema()).IsMatch())
            {
                store.CreateSchemaIfNotExists().Wait();
            }

            return(store);
        }
        public async Task EnsureSchemaInitialized()
        {
            // `receptionDelay` should include transaction timeout + clock drift. Otherwise, it may skip events during reception.
            var receptionDelay = TimeSpan.FromMilliseconds(3000);
            var eventStore     = new MsSqlStreamStoreV3(new MsSqlStreamStoreV3Settings(ConnectionString));
            await eventStore.DropAll();

            await eventStore.CreateSchemaIfNotExists();

            _eventStore = eventStore;
            Outbox      = new SqlStreamStoreOutbox(eventStore, receptionDelay);
            var db = new TestDbContextWithOutbox(ConnectionString, Outbox);

            db.Database.CreateIfNotExists();
        }
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc();

            services.AddTransient <IConnectionFactory>(sp => new ConnectionFactory(_connectionString));

            var streamStore = new MsSqlStreamStoreV3(new MsSqlStreamStoreV3Settings(_connectionString));

            streamStore.CreateSchemaIfNotExists();

            services.AddSingleton <IStreamStore>(streamStore);

            services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new OpenApiInfo {
                    Title = "TEST", Version = "V1"
                }); });
        }
Beispiel #10
0
        public static IServiceCollection AddMsSqlEventStore(this IServiceCollection services,
                                                            Action <MsSqlEventSourcingOptions>?optionsAccessor = null, params Assembly[] eventAssemblies)
        {
            var msSqlOptions = new MsSqlEventSourcingOptions();

            optionsAccessor?.Invoke(msSqlOptions);
            // ReSharper disable once RedundantAssignment
            services.AddEventStore(eventSourcingOptions => eventSourcingOptions = msSqlOptions, eventAssemblies)
            .Configure(optionsAccessor)
            .AddSingleton <MsSqlCheckpointManager>();

            var serviceProvider = services.BuildServiceProvider();

            if (!(serviceProvider.GetService <IStreamStore>() is MsSqlStreamStoreV3))
            {
                services.AddSingleton <IStreamStore>(sp =>
                {
                    var streamStore = new MsSqlStreamStoreV3(
                        new MsSqlStreamStoreV3Settings(msSqlOptions.ConnectionString)
                    {
                        Schema = msSqlOptions.Schema
                    });

                    if (!msSqlOptions.CreateSchemaIfNotExists)
                    {
                        return(streamStore);
                    }

                    streamStore.CreateSchemaIfNotExists().Wait();
                    sp.GetRequiredService <MsSqlCheckpointManager>().CreateSchemaIfNotExists().Wait();

                    return(streamStore);
                });
            }

            services.TryAddSingleton <GetGlobalCheckpoint>(sp =>
                                                           sp.GetRequiredService <MsSqlCheckpointManager>().GetGlobalCheckpoint);

            services.TryAddSingleton <SetGlobalCheckpoint>(sp =>
                                                           sp.GetRequiredService <MsSqlCheckpointManager>().SetGlobalCheckpoint);

            return(services);
        }
Beispiel #11
0
        private MsSqlStreamStoreV3 GetStore()
        {
            var configurationBuilder = new ConfigurationBuilder()
                                       .SetBasePath(Directory.GetCurrentDirectory())
                                       .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true);

            var environment   = Environment.GetEnvironmentVariable("NETCORE_ENVIRONMENT");
            var isDevelopment = string.Equals(environment, "development", StringComparison.OrdinalIgnoreCase);

            if (isDevelopment)
            {
                configurationBuilder.AddUserSecrets(Assembly.GetCallingAssembly());
            }

            var configuration    = configurationBuilder.Build();
            var connectionString = configuration["EventStore:SqlStreamStore:ConnectionString"];
            var settings         = new MsSqlStreamStoreV3Settings(connectionString);
            var store            = new MsSqlStreamStoreV3(settings);

            return(store);
        }
        private static async Task <IStreamStore> CreateMssqlStreamStore(
            string connectionString,
            string schema,
            CancellationToken cancellationToken)
        {
            var connectionStringBuilder = new SqlConnectionStringBuilder(connectionString);

            using (var connection = new SqlConnection(new SqlConnectionStringBuilder(connectionString)
            {
                InitialCatalog = "master"
            }.ConnectionString))
            {
                await connection.OpenAsync(cancellationToken).ConfigureAwait(false);

                using (var command = new SqlCommand(
                           $@"
IF  NOT EXISTS (SELECT name FROM sys.databases WHERE name = N'{connectionStringBuilder.InitialCatalog}')
BEGIN
    CREATE DATABASE [{connectionStringBuilder.InitialCatalog}]
END;
",
                           connection))
                {
                    await command.ExecuteNonQueryAsync(cancellationToken).ConfigureAwait(false);
                }
            }

            var settings = new MsSqlStreamStoreV3Settings(connectionString);

            if (schema != null)
            {
                settings.Schema = schema;
            }

            var streamStore = new MsSqlStreamStoreV3(settings);

            await streamStore.CreateSchemaIfNotExists(cancellationToken);

            return(streamStore);
        }
Beispiel #13
0
        public static void UseEventServeMsSqlStreamStore(this IApplicationBuilder applicationBuilder)
        {
            using (var scope = applicationBuilder.ApplicationServices.CreateScope())
            {
                var context = scope.ServiceProvider.GetRequiredService <SqlStreamStoreContext>();
                context.Database.Migrate();
            }

            using (var scope = applicationBuilder.ApplicationServices.CreateScope())
            {
                var settingsProvider = scope.ServiceProvider.GetRequiredService <IMsSqlStreamStoreSettingsProvider>();

                var settings = settingsProvider.GetSettings();
                Task.WaitAll(settings);

                var store = new MsSqlStreamStoreV3(settings.Result);
                store.CreateSchemaIfNotExists().Wait();
                var checkResult = store.CheckSchema();
                Task.WaitAll(checkResult);
            }


            applicationBuilder.RegisterEventServeSubscriptions();
        }
Beispiel #14
0
        public static async Task Main(string[] args)
        {
            // Configuration section
            const int NumberOfProducers           = 200;
            const int NumberOfConsumers           = 10;
            const ProducerAppendBehavior Behavior = ProducerAppendBehavior.Batched;
            const bool UseSnapshotIsolation       = true;

            var container = new SqlServerContainer();

            try
            {
                Console.WriteLine("Creating sql server container ...");
                await container.InitializeAsync().ConfigureAwait(false);

                Console.WriteLine("Created.");
                var db = await container.CreateDatabaseAsync(UseSnapshotIsolation).ConfigureAwait(false);

                Console.WriteLine("ConnectionString={0}", db.ConnectionString);
                using (var store = new MsSqlStreamStoreV3(new MsSqlStreamStoreV3Settings(db.ConnectionString)
                {
                    Schema = "dbo"
                }))
                {
                    Console.WriteLine("Creating sql stream store schema ...");
                    await store.CreateSchemaIfNotExists().ConfigureAwait(false);

                    Console.WriteLine("Created.");
                    using (var scheduler = new Scheduler(SystemClock.Instance))
                    {
                        var producers = Enumerable
                                        .Range(1, NumberOfProducers)
                                        .Select(id => new Producer(id, Behavior, store, scheduler))
                                        .ToArray();

                        var consumers = Enumerable
                                        .Range(1, NumberOfConsumers)
                                        .Select(id => new Consumer(id, store, scheduler))
                                        .ToArray();

                        Console.WriteLine("Starting {0} producers ...", NumberOfProducers);
                        Array.ForEach(producers, producer => producer.Start());
                        Console.WriteLine("Started.");

                        Console.WriteLine("Starting {0} consumers ...", NumberOfConsumers);
                        Array.ForEach(consumers, consumer => consumer.Start());
                        Console.WriteLine("Started.");

                        Console.WriteLine("Press enter to exit");
                        Console.ReadLine();

                        Console.WriteLine("Stopping {0} producers ...", NumberOfProducers);
                        Array.ForEach(producers, producer => producer.Stop());
                        Console.WriteLine("Stopped.");

                        Console.WriteLine("Stopping {0} consumers ...", NumberOfConsumers);
                        Array.ForEach(consumers, consumer => consumer.Stop());
                        Console.WriteLine("Stopped.");
                    }
                }
            }
            finally
            {
                Console.WriteLine("Removing sql server container ...");
                await container.DisposeAsync().ConfigureAwait(false);

                Console.WriteLine("Removed.");
            }
        }
Beispiel #15
0
        public async Task InitializeAsync()
        {
            var images = await _dockerClient.Images.ListImagesAsync(new ImagesListParameters { MatchName = MsSqlServerImage });

            if (images.Count == 0)
            {
                // No image found. Pulling latest ..
                Console.WriteLine("[Docker] Image not found - pulling latest");
                await _dockerClient.Images.CreateImageAsync(new ImagesCreateParameters { FromImage = MsSqlServerImage, Tag = "2019-latest" }, null, IgnoreProgress.Forever);
            }


            Console.WriteLine("[Docker] Creating container " + _containerName);
            //Create container ...
            await _dockerClient.Containers.CreateContainerAsync(
                new CreateContainerParameters
            {
                Image      = MsSqlServerImage,
                Name       = _containerName,
                Tty        = true,
                HostConfig = new HostConfig
                {
                    PortBindings = new Dictionary <string, IList <PortBinding> >
                    {
                        {
                            "1433/tcp",
                            new List <PortBinding> {
                                new PortBinding {
                                    HostPort = _port.ToString()
                                }
                            }
                        }
                    },
                },
                Env = new List <string>
                {
                    $"SA_PASSWORD={_saPass}",
                    "ACCEPT_EULA=Y"
                }
            });

            // Starting the container ...
            Console.WriteLine("[Docker] Starting container " + _containerName);

            await _dockerClient.Containers.StartContainerAsync(
                _containerName,
                new ContainerStartParameters { });


            var options = new DbContextOptionsBuilder <SqlStreamStoreContext>()
                          .UseSqlServer(ConnectionString, options =>
            {
                options.MigrationsAssembly(typeof(MsSqlStreamStoreOptions).Assembly.FullName);
                options.EnableRetryOnFailure(5, TimeSpan.FromSeconds(10), null);
            })
                          .Options;

            var context = new SqlStreamStoreContext(options);

            context.Database.Migrate();

            //Migrate the SSS context
            using var store = new MsSqlStreamStoreV3(new MsSqlStreamStoreV3Settings(ConnectionString)
            {
                Schema = "TestSchema"
            });
            await store.CreateSchemaIfNotExists();

            await store.CheckSchema();
        }