Exemplo n.º 1
0
        public static void EnsureSqlStreamStoreSchema <T>(MsSqlStreamStore streamStore, ILoggerFactory loggerFactory)
        {
            var logger = loggerFactory.CreateLogger <T>();

            // TODO: Need to revisit this with a Consul lock
            Policy
            .Handle <SqlException>()
            .WaitAndRetry(
                5,
                retryAttempt =>
            {
                var value       = Math.Pow(2, retryAttempt) / 4;
                var randomValue = new Random().Next((int)value * 3, (int)value * 5);
                logger.LogInformation("Retrying after {Seconds} seconds...", randomValue);
                return(TimeSpan.FromSeconds(randomValue));
            })
            .Execute(() =>
            {
                logger.LogInformation("Ensuring the sql stream store schema.");

                var checkSchemaResult = streamStore.CheckSchema().GetAwaiter().GetResult();
                if (!checkSchemaResult.IsMatch())
                {
                    streamStore.CreateSchema().GetAwaiter().GetResult();
                }
            });
        }
Exemplo n.º 2
0
        static async Task Main(string[] args)
        {
            var tpyeResovler     = new FullyQualifiedTypeNameTypeResolver("EventSourced.Example.Aggregate.Events.{0}, EventSourced.Example");
            var connectionString = "Server=(local);Database=SqlStreamStoreDemo;Trusted_Connection=True;MultipleActiveResultSets=true";
            var settings         = new MsSqlStreamStoreSettings(connectionString);
            var streamStore      = new MsSqlStreamStore(settings);

            streamStore.CreateSchema().GetAwaiter().GetResult();

            var eventStore = new SqlStreamStoreEventStore(streamStore, tpyeResovler);
            var system     = new EventSourcingSystem(eventStore);

            var counterCurrentValuesReadModel = new CounterCurrentValuesReadModel(system);
            var allPersistenceIdsReadModel    = new AllPersistenceIdsReadModel(system);

            var counterId = Guid.Parse("8c936406-720a-45d4-b1e0-a95bd595943f");
            var counter   = await system.Get(() => new Counter(counterId));

            if (!counter.IsInitialized())
            {
                counter.Initialize(0);
            }

            counter.Increment(5);
            counter.Decrement(2);

            Thread.Sleep(5000);
        }
Exemplo n.º 3
0
        public static async Task <IStreamStore> InitializeMsSqlStreamStore(string connectionString)
        {
            var streamStore = new MsSqlStreamStore(new MsSqlStreamStoreSettings(connectionString));

            await streamStore.CreateSchema();

            return(streamStore);
        }
Exemplo n.º 4
0
//        private static BalanceProjection _balanceProjection;

        static async Task Main()
        {
            var streamId = new StreamId("Account:93aad7b7-f6d2-438f-911b-8eaba5695d48");
            var store    = new MsSqlStreamStore(new MsSqlStreamStoreSettings("Server=localhost;Database=eqx;User Id=sa;Password=p@ssw0rd;"));

            store.CreateSchema().Wait();
            _streamStore = store;
            _account     = new Account(_streamStore, streamId);
//            _balanceProjection = new BalanceProjection(_streamStore, streamId);

            var key = string.Empty;

            while (key != "X")
            {
                Console.WriteLine("D: Deposit");
                Console.WriteLine("W: Withdrawal");
                Console.WriteLine("B: Balance");
                Console.WriteLine("T: Transactions");
                Console.WriteLine("X: Exit");
                Console.Write("> ");
                key = Console.ReadLine()?.ToUpperInvariant();
                Console.WriteLine();

                switch (key)
                {
                case "D":
                    var depositAmount = GetAmount();
                    if (depositAmount.IsValid)
                    {
                        var depositTrx = await _account.Deposit(depositAmount.Amount);

                        Console.WriteLine($"Deposited: {depositAmount.Amount:C} ({depositTrx})");
                    }
                    break;

                case "W":
                    var withdrawalAmount = GetAmount();
                    if (withdrawalAmount.IsValid)
                    {
                        var withdrawalTrx = await _account.Withdrawal(withdrawalAmount.Amount);

                        Console.WriteLine($"Withdrawn: {withdrawalAmount.Amount:C} ({withdrawalTrx})");
                    }
                    break;

                case "B":
                    Balance();
                    break;

                case "T":
                    await _account.Transactions();

                    break;
                }

                Console.WriteLine();
            }
        }
        public async Task <IStreamStore> GetStreamStore(string schema)
        {
            var settings = new MsSqlStreamStoreSettings(ConnectionString)
            {
                Schema = schema,
            };
            var store = new MsSqlStreamStore(settings);
            await store.CreateSchema();

            return(store);
        }
Exemplo n.º 6
0
        private void SetupStreamStore(IServiceCollection services)
        {
            var streamStore = new MsSqlStreamStore(_msSqlStreamStoreSettings);

            services.AddSingleton <IStreamStore>(x => streamStore);
            var schema = streamStore.CheckSchema().GetAwaiter().GetResult();

            if (!schema.IsMatch())
            {
                streamStore.CreateSchema();
            }
        }
        public async Task <MsSqlStreamStore> GetMsSqlStreamStore()
        {
            await CreateDatabase();

            var settings = new MsSqlStreamStoreSettings(ConnectionString)
            {
                Schema    = _schema,
                GetUtcNow = () => GetUtcNow()
            };

            var store = new MsSqlStreamStore(settings);
            await store.CreateSchema();

            return(store);
        }
        private static async Task CreateDatabase(string connectionString, CancellationToken ct)
        {
            // There is a while true loop here, because sometimes after creating the db, the db is not available always.
            // There are much better ways of handling this, but I couldn't be bothered right now;)
            while (true)
            {
                try
                {
                    await Task.Delay(1000);

                    Console.WriteLine("Creating database schema");
                    await Task.Delay(3000);

                    var mgr = new DatabaseManager(connectionString);
                    mgr.EnsureDatabaseExists(10, 10);

                    await Task.Delay(2000, ct);

                    var msSqlStreamStoreSettings = new MsSqlStreamStoreSettings(connectionString);

                    var store = new MsSqlStreamStore(msSqlStreamStoreSettings);
                    if (!(await store.CheckSchema(ct)).IsMatch())
                    {
                        await store.CreateSchema(ct);
                    }

                    var repo = new StreamStoreConfigRepository(store);

                    Console.WriteLine("Now generating 20 changes:");

                    for (int i = 0; i < 20; i++)
                    {
                        await Task.Delay(1000, ct);

                        await repo.Modify(ct, ("setting1", "new value, written at: " + DateTime.Now.ToLongTimeString()));
                    }

                    // Delay for a while, so the latest version can be printed.
                    await Task.Delay(1000, ct);

                    var history = await repo.GetSettingsHistory(ct);

                    Console.WriteLine($"There have historically been:{history.Count} versions: ");
                    foreach (var setting in history)
                    {
                        Console.WriteLine($"\t- Version: {setting.Version}, setting1 = '{setting["setting1"]}', ModifiedKeys: [{string.Join(',', setting.ModifiedKeys)}]");
                    }

                    Console.WriteLine($"Now reverting back to the first version's data: {history.First().Version}");

                    // Now revert back to the first version (this actually creates a new version, with the old data in it)
                    await repo.RevertToVersion(history.First(), ct);


                    // Completed succesfully. End the function
                    return;
                }
                catch (Exception ex)
                {
                    Console.WriteLine("error while creating database: " + ex.Message + " (will retry)");
                }
            }
        }