public StartTransactionOperation(TaskCompletionSource<EventStoreTransaction> source,
                                  Guid corrId,
                                  bool forward,
                                  string stream,
                                  int expectedVersion,
                                  EventStoreConnection parentConnection)
 {
     _source = source;
     _corrId = corrId;
     _forward = forward;
     _stream = stream;
     _expectedVersion = expectedVersion;
     _parentConnection = parentConnection;
 }
        public EventStoreClient(string connUri, Microsoft.Extensions.Logging.ILogger logger)
        {
            _logger = logger;
            var settings = ConnectionSettings.Create().UseCustomLogger(new EventStoreClientLogger(_logger)).FailOnNoServerResponse().Build();

            try
            {
                _client = EventStoreConnection.Create(settings, new Uri(connUri));
                _client.AuthenticationFailed += this.Handle_AuthenticationFailed;
                _client.Closed        += this.Handle_Closed;
                _client.Connected     += this.Handle_Connected;
                _client.Disconnected  += this.Handle_Disconnected;
                _client.ErrorOccurred += this.Handle_ErrorOccurred;
                _client.Reconnecting  += this.Handle_Reconnecting;
            }
            catch (Exception esException)
            {
                logger.LogError(esException, esException.Message);
                throw;
            }
        }
        public static async Task JsonFormat()
        {
            var conn = EventStoreConnection.Create(new Uri("tcp://*****:*****@localhost:1113"));
            await conn.ConnectAsync();

            var data     = Encoding.UTF8.GetBytes("{\"a\":\"2\"}");
            var metadata = Encoding.UTF8.GetBytes("{}");
            var evt      = new EventData(Guid.NewGuid(), "testEvent", true, data, metadata);

            await conn.AppendToStreamAsync("test-stream", ExpectedVersion.Any, evt);

            var streamEvents = await conn.ReadStreamEventsForwardAsync("test-stream", 0, 1, false);

            var returnedEvent = streamEvents.Events[0].Event;

            Console.WriteLine(
                "Read event with data: {0}, metadata: {1}",
                Encoding.UTF8.GetString(returnedEvent.Data),
                Encoding.UTF8.GetString(returnedEvent.Metadata)
                );
        }
        static async Task <IEventStoreConnection> ConfigureEventStore(string connectionString)
        {
            var gesConnection = EventStoreConnection.Create(
                connectionString,
                ConnectionSettings.Create()
                .EnableVerboseLogging()
                .KeepReconnecting()
                .KeepRetrying()
                .SetOperationTimeoutTo(FromSeconds(10))
                .SetTimeoutCheckPeriodTo(FromSeconds(2))
                .SetReconnectionDelayTo(FromSeconds(3))
                .SetHeartbeatTimeout(FromSeconds(6))
                .SetHeartbeatInterval(FromSeconds(3))
                .SetGossipTimeout(FromSeconds(2)),
                "DCore.Platform.Integration.EventStore.Tests"
                );

            await gesConnection.ConnectAsync();

            return(gesConnection);
        }
            protected override async Task Given()
            {
                var node = GetFollowers()[0];
                await Task.WhenAll(node.AdminUserCreated, node.Started);

                using var connection = EventStoreConnection.Create(ConnectionSettings.Create()
                                                                   .DisableServerCertificateValidation()
                                                                   .PreferFollowerNode(),
                                                                   node.ExternalTcpEndPoint);
                await connection.ConnectAsync();

                try {
                    await connection.AppendToStreamAsync(ProtectedStream, ExpectedVersion.NoStream,
                                                         new UserCredentials("admin", "changeit"),
                                                         new EventData(Guid.NewGuid(), "-", false, Array.Empty <byte>(), Array.Empty <byte>()));
                } catch (Exception ex) {
                    _caughtException = ex;
                }

                await base.Given();
            }
        public EventStoreSnapshotStore()
        {
            var serialization = Context.System.Serialization;

            _serializer = serialization.FindSerializerForType(typeof(SelectedSnapshot));

            _connection = new Lazy <Task <IEventStoreConnection> >(async() =>
            {
                var settings = ConnectionSettings.Create()
                               //.KeepReconnecting()
                               .UseConsoleLogger()
                               .SetDefaultUserCredentials(new UserCredentials("admin", "changeit"));

                var endPoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 1113);

                IEventStoreConnection connection = EventStoreConnection.Create(settings, endPoint, "akka.net-store");
                await connection.ConnectAsync();

                return(connection);
            });
        }
Esempio n. 7
0
        public void return_empty_slice_if_asked_to_read_from_end()
        {
            const string stream = "read_all_events_forward_should_return_empty_slice_if_asked_to_read_from_end";

            using (var store = EventStoreConnection.Create())
            {
                store.Connect(Node.TcpEndPoint);
                var create = store.CreateStreamAsync(stream, false, new byte[0]);
                Assert.DoesNotThrow(create.Wait);

                var testEvents = Enumerable.Range(0, 5).Select(x => new TestEvent((x + 1).ToString())).ToArray();

                var write5 = store.AppendToStreamAsync(stream, ExpectedVersion.EmptyStream, testEvents);
                Assert.DoesNotThrow(write5.Wait);

                var read = store.ReadAllEventsForwardAsync(Position.End, 1);
                Assert.DoesNotThrow(read.Wait);

                Assert.That(read.Result.Events.Length, Is.EqualTo(0));
            }
        }
        public void SetUp()
        {
            _logger = new ConsoleLogger();

            _eventStoreConnection = EventStoreConnection.Create(new IPEndPoint(IPAddress.Loopback, 1113));
            _eventStoreConnection.ConnectAsync().Wait();
            _eventStoreSession = new EventStoreSession(_eventStoreConnection, _logger);

            Resolver.Configure(
                type =>
            {
                if (type == typeof(ILogger))
                {
                    return(_logger);
                }

                throw new InvalidOperationException($"No type of {type} registered.");
            },
                type => null,
                o => { });
        }
Esempio n. 9
0
        public void be_able_to_subscribe_to_non_existing_stream_and_then_catch_created_event()
        {
            const string stream = "subscribe_should_be_able_to_subscribe_to_non_existing_stream_and_then_catch_created_event";

            using (var store = EventStoreConnection.Create())
            {
                store.Connect(MiniNode.Instance.TcpEndPoint);
                var appeared = new CountdownEvent(1);
                var dropped  = new CountdownEvent(1);

                Action <RecordedEvent, Position> eventAppeared = (x, p) => appeared.Signal();
                Action subscriptionDropped = () => dropped.Signal();

                store.SubscribeAsync(stream, eventAppeared, subscriptionDropped);

                var create = store.CreateStreamAsync(stream, false, new byte[0]);
                Assert.That(create.Wait(Timeout));

                Assert.That(appeared.Wait(Timeout));
            }
        }
Esempio n. 10
0
        public EventStoreJournal()
        {
            _log = Context.GetLogger();

            var serialization = Context.System.Serialization;

            _serializer = serialization.FindSerializerForType(typeof(IPersistentRepresentation));

            _connection = new Lazy <Task <IEventStoreConnection> >(async() =>
            {
                var settings = ConnectionSettings.Create()
                               .KeepReconnecting()
                               .SetDefaultUserCredentials(new UserCredentials("admin", "changeit"));

                var endPoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 4532);

                IEventStoreConnection connection = EventStoreConnection.Create(settings, endPoint, "akka.net");
                await connection.ConnectAsync();
                return(connection);
            });
        }
Esempio n. 11
0
        public void should_timeout_connection_after_configured_amount_time_on_conenct()
        {
            var closed   = new ManualResetEventSlim();
            var settings =
                ConnectionSettings.Create()
                .EnableVerboseLogging()
                .UseCustomLogger(ClientApiLoggerBridge.Default)
                .LimitReconnectionsTo(0)
                .SetReconnectionDelayTo(TimeSpan.FromMilliseconds(0))
                .FailOnNoServerResponse()
                .WithConnectionTimeoutOf(TimeSpan.FromMilliseconds(1000));

            if (_tcpType == TcpType.Ssl)
            {
                settings.UseSslConnection("ES", false);
            }

            var ip = new IPAddress(new byte[]
                                   { 8, 8, 8, 8 }); //NOTE: This relies on Google DNS server being configured to swallow nonsense traffic
            const int port = 4567;

            using (var connection = EventStoreConnection.Create(settings, new IPEndPoint(ip, port).ToESTcpUri())) {
                connection.Closed    += (s, e) => closed.Set();
                connection.Connected += (s, e) => Console.WriteLine("EventStoreConnection '{0}': connected to [{1}]...",
                                                                    e.Connection.ConnectionName, e.RemoteEndPoint);
                connection.Reconnecting += (s, e) =>
                                           Console.WriteLine("EventStoreConnection '{0}': reconnecting...", e.Connection.ConnectionName);
                connection.Disconnected += (s, e) =>
                                           Console.WriteLine("EventStoreConnection '{0}': disconnected from [{1}]...",
                                                             e.Connection.ConnectionName, e.RemoteEndPoint);
                connection.ErrorOccurred += (s, e) => Console.WriteLine("EventStoreConnection '{0}': error = {1}",
                                                                        e.Connection.ConnectionName, e.Exception);
                connection.ConnectAsync().Wait();

                if (!closed.Wait(TimeSpan.FromSeconds(15)))
                {
                    Assert.Fail("Connection timeout took too long.");
                }
            }
        }
Esempio n. 12
0
        public static void AddMyEventStoreServices(this IServiceCollection services, IConfiguration config)
        {
            var consumeEvents = config.GetOptionalValue("eventStore:consume", false);

            if (consumeEvents)
            {
                services.AddTransient <EventConsumerActor>();
            }

            config.ConfigureByOption("eventStore:type", new Options
            {
                ["MongoDb"] = () =>
                {
                    var mongoConfiguration = config.GetRequiredValue("eventStore:mongoDb:configuration");
                    var mongoDatabaseName  = config.GetRequiredValue("eventStore:mongoDb:database");

                    services.AddSingleton(c =>
                    {
                        var mongoClient  = Singletons <IMongoClient> .GetOrAdd(mongoConfiguration, s => new MongoClient(s));
                        var mongDatabase = mongoClient.GetDatabase(mongoDatabaseName);

                        return(new MongoEventStore(mongDatabase, c.GetRequiredService <IEventNotifier>()));
                    })
                    .As <IExternalSystem>()
                    .As <IEventStore>();
                },
                ["GetEventStore"] = () =>
                {
                    var eventStoreConfiguration  = config.GetRequiredValue("eventStore:getEventStore:configuration");
                    var eventStoreProjectionHost = config.GetRequiredValue("eventStore:getEventStore:projectionHost");
                    var eventStorePrefix         = config.GetValue <string>("eventStore:getEventStore:prefix");

                    var connection = EventStoreConnection.Create(eventStoreConfiguration);

                    services.AddSingleton(c => new GetEventStore(connection, eventStorePrefix, eventStoreProjectionHost))
                    .As <IExternalSystem>()
                    .As <IEventStore>();
                }
            });
        }
        private async Task BuildEventStore(IServiceCollection services)
        {
            //Create EventStore Connection
            var gesConnection = EventStoreConnection.Create(
                Configuration["EventStore:ConnectionString"],
                ConnectionSettings.Create()
                .KeepReconnecting()
                .EnableVerboseLogging()
                .SetHeartbeatInterval(TimeSpan.FromMilliseconds(5 * 1000))
                .UseDebugLogger(),
                Environment.ApplicationName
                );

            gesConnection.Connected += (sender, args)
                                       => Console.WriteLine($"Connection to {args.RemoteEndPoint} event store established.");

            gesConnection.ErrorOccurred += (sender, args)
                                           => Console.WriteLine($"Connection error : {args.Exception}");

            await gesConnection.ConnectAsync();


            var serializer = new JsonNetSerializer();

            var eventMapper = new EventTypeMapper()
                              .Map <Domain.Events.V1.ReviewCreated>("reviewCreated")
                              .Map <Domain.Events.V1.CaptionAndContentChanged>("reviewUpdated")
                              .Map <Domain.Events.V1.ReviewPublished>("reviewPublished")
                              .Map <Domain.Events.V1.ReviewApproved>("reviewApproved");


            var aggregateStore = new GesAggrigateStore(
                gesConnection,
                serializer,
                eventMapper,
                (type, id) => $"{type.Name}-{id}",
                null);

            services.AddSingleton(new ApplicationService(aggregateStore));
        }
Esempio n. 14
0
        static async Task Main(string[] args)
        {
            var gesConnection = EventStoreConnection.Create(new Uri("tcp://*****:*****@localhost:1113"),
                                                              "InputFromFileConsoleApp");


            await gesConnection.ConnectAsync();

            var aggregateStore = new AggregateStore(gesConnection);



            var orderId = Guid.NewGuid();
            var order   = Order.Create(orderId, new CustomerId("alper"));

            order.AddItem(new ProductId("ekmek"), 1, 5);
            order.AddItem(new ProductId("yumurta"), 5, 2);
            order.AddItem(new ProductId("sucuk"), 5, 2);

            order.RemoveItem(new ProductId("sucuk"));
            order.Ship();


            await aggregateStore.Save(order);

            Console.WriteLine($"Saved Order=>{order.ToString()}");



            var orderRead = await aggregateStore.Load <Order>(orderId.ToString());

            orderRead.Complate();

            await aggregateStore.Save(orderRead);

            Console.WriteLine(orderRead);


            Console.ReadKey();
        }
Esempio n. 15
0
        public async Task HandleAsync(ICommand _command)
        {
            var cmd = _command as I本を延長するCommand;

            if (cmd == null)
            {
                throw new ArgumentException(nameof(_command), "I本を延長するCommand型ではありません。");
            }

            using (var c = EventStoreConnection.Create(
                       ConnectionSettings.Create().SetDefaultUserCredentials(Connection.UserCredentials())
                       , Connection.EventStoreUri()))
            {
                try
                {
                    await c.ConnectAsync();

                    await c.AppendToStreamAsync(
                        cmd.本のID.ID文字列,
                        ExpectedVersion.StreamExists,
                        new EventData(
                            Guid.NewGuid(),
                            Domain.RentalSubDomain.Events.Book.ExtendedBookVer100,
                            true,
                            JsonSerializer.Serialize(
                                Domain.RentalSubDomain.Events.Book.ExtendedBookDTOVer100.Create(
                                    cmd.本のID.ID文字列,
                                    cmd.貸出期間.貸出期間自DateTime,
                                    cmd.貸出期間.貸出期間至DateTime
                                    )
                                ),
                            new byte[] {}
                            ));
                }
                finally
                {
                    c.Close();
                }
            }
        }
Esempio n. 16
0
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddAuthorization(options =>
            {
                options.AddPolicy("SystemMessagingPolicy", policyAdmin =>
                {
                    policyAdmin.RequireClaim("scope", "gofish.messaging");
                });
            });

            services.AddMvc();

            services.Configure <ApplicationSettings>(_config.GetSection("ApplicationSettings"));

            services.AddDbContext <AdvertisingDbContext>();
            services.AddTransient <IMessageBroker <Advert>, AdvertMessageBroker>();
            services.AddTransient <AdvertRepository, AdvertRepository>();
            services.AddTransient <ICommandMediator, CommandMediator>();
            services.AddTransient <IAdvertFactory, AdvertFactory>();
            services.AddTransient <ILookupCacheProvider, LookupCacheProvider>();

            services.AddTransient <ICommandHandler <CreateAdvertCommand, Advert>, CreateAdvertCommandHandler>();
            services.AddTransient <ICommandHandler <UpdateAdvertCommand, Advert>, UpdateAdvertCommandHandler>();
            services.AddTransient <ICommandHandler <PostAdvertCommand, Advert>, PostAdvertCommandHandler>();
            services.AddTransient <ICommandHandler <PublishAdvertCommand, Advert>, PublishAdvertCommandHandler>();
            services.AddTransient <ICommandHandler <WithdrawAdvertCommand, Advert>, WithdrawAdvertCommandHandler>();
            services.AddTransient <ICommandHandler <StockUpdatedCommand, Advert>, StockUpdatedCommandHandler>();

            var config = new AutoMapper.MapperConfiguration(cfg =>
            {
                cfg.CreateMap <Advert, AdvertDto>();
                cfg.CreateMap <Advert, AddAdvertToStockDto>();
            });

            services.AddSingleton <AutoMapper.IMapper>(sp => config.CreateMapper());

            services.AddSingleton <IEventStoreConnection>(sp => EventStoreConnection.Create(new Uri(_config["ApplicationSettings:EventStoreUrl"])));

            services.AddScoped <ModelStateActionFilterAttribute>();
        }
Esempio n. 17
0
        static void Main(string[] args)
        {
            var projector = new SqlProjector(
                Resolve.WhenEqualToHandlerMessageType(new OnHandInventoryViewProjection()),
                new TransactionalSqlCommandExecutor(
                    SqlClientFactory.Instance,
                    @"Data Source=localhost;Initial Catalog=InventoryPOC;Integrated Security=SSPI;",
                    IsolationLevel.ReadCommitted));

            projector.Project(new List <object> {
                new DropSchema(), new CreateSchema()
            });

            var credentials = new UserCredentials("admin", "changeit");

            var connectionSettings = ConnectionSettings.Create()
                                     .KeepReconnecting()
                                     .KeepRetrying()
                                     .FailOnNoServerResponse()
                                     .WithConnectionTimeoutOf(TimeSpan.FromSeconds(20))
                                     .SetOperationTimeoutTo(TimeSpan.FromSeconds(10))
                                     .SetHeartbeatInterval(TimeSpan.FromSeconds(10))
                                     .SetHeartbeatTimeout(TimeSpan.FromSeconds(20));

            using (var connection = EventStoreConnection.Create("ConnectTo=tcp://admin:[email protected]:1113; HeartBeatTimeout=5000", connectionSettings))
            {
                connection.ConnectAsync().GetAwaiter().GetResult();

                var subscription = connection.SubscribeToStreamFrom("$ce-ledgerEntry", StreamPosition.Start, CatchUpSubscriptionSettings.Default, (_, @event) =>
                {
                    projector.Project(
                        JsonConvert.DeserializeObject(
                            Encoding.UTF8.GetString(@event.Event.Data),
                            Assembly.GetAssembly(typeof(PortfolioRenamed)).GetType(@event.Event.EventType)));
                }, userCredentials: credentials);

                var a = subscription.LastProcessedEventNumber;
                Console.ReadKey();
            }
        }
Esempio n. 18
0
        public async Task <LivenessResult> IsHealthy(LivenessExecutionContext context, CancellationToken cancellationToken = default)
        {
            try
            {
                _logger?.LogInformation($"{nameof(EventStoreLiveness)} is checking the EventStore host.");

                var eventStoreUri = new Uri(_uri);

                ConnectionSettings connectionSettings;

                if (string.IsNullOrEmpty(_login) || string.IsNullOrEmpty(_password))
                {
                    connectionSettings = ConnectionSettings.Create()
                                         .KeepRetrying()
                                         .Build();
                }
                else
                {
                    connectionSettings = ConnectionSettings.Create()
                                         .KeepRetrying()
                                         .SetDefaultUserCredentials(new UserCredentials(_login, _password))
                                         .Build();
                }

                var connection = EventStoreConnection.Create(
                    connectionSettings,
                    new Uri(_uri),
                    "BeatPulse HealthCheck");

                await connection.ConnectAsync();

                return(LivenessResult.Healthy());
            }
            catch (Exception ex)
            {
                _logger?.LogWarning($"The {nameof(EventStoreLiveness)} check fail for Eventstore with the exception {ex.ToString()}.");

                return(LivenessResult.UnHealthy(ex));
            }
        }
        public static IServiceCollection AddClearance(this IServiceCollection services, IConfiguration configuration)
        {
            services.Configure <ClearanceDatabaseSettings>(configuration.GetSection("ClearanceDtosDatabaseSettings"));
            services.AddSingleton <IClearanceDatabaseSettings>(sp => sp.GetRequiredService <IOptions <ClearanceDatabaseSettings> >().Value);

            var esConnection = EventStoreConnection.Create(
                ConnectionSettings.Create().KeepReconnecting().DisableServerCertificateValidation().DisableTls(),
                new System.Uri(configuration["ClearanceEventStoreSettings:ConnectionString"]));

            esConnection.ConnectAsync().Wait();

            services.AddSingleton(esConnection);

            services.AddTransient <IRepository <ClearanceRoot>, Repository <ClearanceRoot> >();
            services.AddTransient <IClearanceDtoRepository, ClearanceDtoRepository>();
            services.AddTransient <IUserSettingsService, UserSettingsService>();
            services.AddTransient <IAccountDtoService, AccountDtoService>();

            services.AddMvcCore().AddApplicationPart(Assembly.GetExecutingAssembly()).AddControllersAsServices();

            return(services);
        }
Esempio n. 20
0
        public static IServiceCollection AddInfrastructure(this IServiceCollection services, IConfiguration configuration)
        {
            if (configuration.GetValue <bool>("UseInMemoryDatabase")) //s.n install for getvalue  Install-Package Microsoft.Extensions.Configuration.Binder -Version 5.0.0
            {
                services.AddDbContext <ApplicationContext>(options =>
                                                           options.UseInMemoryDatabase("GSNew")); //s.n Install-Package Microsoft.EntityFrameworkCore.InMemory
            }
            else
            {
                /*S.N for registration ef*/
                services.AddDbContext <ApplicationContext>(options =>
                                                           options.UseSqlServer(
                                                               configuration.GetConnectionString("DefaultConnection"),
                                                               b => b.MigrationsAssembly(typeof(ApplicationContext).Assembly.FullName)));
            }

            //services.AddScoped<IApplicationContext>(provider => provider.GetService<ApplicationContext>());
            //return services;

            services.AddScoped <Func <ApplicationContext> >((provider) => () => provider.GetService <ApplicationContext>());
            services.AddScoped <DbFactory>();
            services.AddScoped <IUnitOfWork, UnitOfWork>();

            /*S.n conifig event store*/

            /*S.N Install-Package EventStore.Client -Version 5.0.9*/
            var eventStoreConnection = EventStoreConnection.Create(
                connectionString: configuration.GetValue <string>("EventStore:ConnectionString"),
                builder: ConnectionSettings.Create().KeepReconnecting(),
                connectionName: configuration.GetValue <string>("EventStore:ConnectionName"));

            eventStoreConnection.ConnectAsync().GetAwaiter().GetResult();

            services.AddSingleton(eventStoreConnection);
            services.AddScoped(typeof(IEventRepository), typeof(EventRepository));
            /**/

            return(services);
        }
        static async Task Main(string[] args)
        {
            var gesConnection = EventStoreConnection.Create(new Uri("tcp://*****:*****@localhost:1113"),
                                                              "InputFromFileConsoleApp");


            await gesConnection.ConnectAsync();

            var streamName = "abc";


            var msg = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(new User()
            {
                Name    = "Alper",
                Surname = "Hankendi"
            }));

            var g = Guid.NewGuid();
            //streamName += "_" + g.ToString();



            await gesConnection.AppendToStreamAsync(streamName, -1, new List <EventData>()
            {
                new EventData(g, "addUser", true, msg, null)
            });

            await gesConnection.AppendToStreamAsync(streamName, 0, new List <EventData>()
            {
                new EventData(g, "testUSER", true, msg, null)
            });

            await gesConnection.AppendToStreamAsync(streamName, 1, new List <EventData>()
            {
                new EventData(g, "deleteUSER", true, msg, null)
            });

            Console.ReadKey();
        }
Esempio n. 22
0
        protected override async Task Given()
        {
            _conn = EventStoreConnection.Create(_node.TcpEndPoint);
            await _conn.ConnectAsync();

            await _conn.CreatePersistentSubscriptionAsync(_streamName, _groupName, _settings,
                                                          DefaultData.AdminCredentials);

            _sub1 = _conn.ConnectToPersistentSubscription(_streamName, _groupName,
                                                          (subscription, @event) => {
                Console.WriteLine();
                return(Task.CompletedTask);
            },
                                                          (subscription, reason, arg3) => Console.WriteLine(), DefaultData.AdminCredentials);
            _sub2 = _conn.ConnectToPersistentSubscription(_streamName, _groupName,
                                                          (subscription, @event) => {
                Console.WriteLine();
                return(Task.CompletedTask);
            },
                                                          (subscription, reason, arg3) => Console.WriteLine(),
                                                          DefaultData.AdminCredentials);
        }
        public async Task <IEnumerable <Event> > GetEvents(long firstEventSequenceNumber, long lastEventSequenceNumber)
        {
            using var connection = EventStoreConnection.Create(
                      ConnectionSettings.Create().DisableTls().Build(),
                      new Uri(ConnectionString));
            await connection.ConnectAsync();

            var result = await connection.ReadStreamEventsForwardAsync(
                "ShoppingCart",
                start : firstEventSequenceNumber,
                count : (int)(lastEventSequenceNumber - firstEventSequenceNumber),
                resolveLinkTos : false);

            return(result.Events
                   .Select(e =>
                           new
            {
                Content = Encoding.UTF8.GetString(e.Event.Data),
                Metadata = JsonSerializer.Deserialize <EventMetadata>(Encoding.UTF8.GetString(e.Event.Metadata), new JsonSerializerOptions {
                    PropertyNameCaseInsensitive = true
                }) !
            })
Esempio n. 24
0
        public void should_fail_to_commit_if_started_with_correct_ver_but_on_commit_stream_was_deleted()
        {
            const string stream = "should_fail_to_commit_if_started_with_correct_ver_but_on_commit_stream_was_deleted";

            using (var store = new EventStoreConnection(MiniNode.Instance.TcpEndPoint))
                store.CreateStream(stream, new byte[0]);

            using (var store = new EventStoreConnection(MiniNode.Instance.TcpEndPoint))
            {
                var start = store.StartTransactionAsync(stream, ExpectedVersion.EmptyStream);
                Assert.DoesNotThrow(start.Wait);

                var write = store.TransactionalWriteAsync(start.Result.TransactionId, start.Result.Stream, new[] { new TestEvent() });
                Assert.DoesNotThrow(write.Wait);

                var delete = store.DeleteStreamAsync(stream, ExpectedVersion.EmptyStream);
                Assert.DoesNotThrow(delete.Wait);

                var commit = store.CommitTransactionAsync(start.Result.TransactionId, start.Result.Stream);
                Assert.That(() => commit.Wait(), Throws.Exception.TypeOf <AggregateException>().With.InnerException.TypeOf <StreamDeletedException>());
            }
        }
Esempio n. 25
0
        public void should_not_fail_to_commit_if_started_with_wrong_ver_but_committing_with_correct_ver()
        {
            const string stream = "should_not_fail_to_commit_if_started_with_wrong_ver_but_committing_with_correct_ver";

            using (var store = new EventStoreConnection(MiniNode.Instance.TcpEndPoint))
                store.CreateStream(stream, new byte[0]);

            using (var store = new EventStoreConnection(MiniNode.Instance.TcpEndPoint))
            {
                var start = store.StartTransactionAsync(stream, 1);
                Assert.DoesNotThrow(start.Wait);

                var append = store.AppendToStreamAsync(stream, ExpectedVersion.EmptyStream, new[] { new TestEvent() });
                Assert.DoesNotThrow(append.Wait);

                var write = store.TransactionalWriteAsync(start.Result.TransactionId, start.Result.Stream, new[] { new TestEvent() });
                Assert.DoesNotThrow(write.Wait);

                var commit = store.CommitTransactionAsync(start.Result.TransactionId, start.Result.Stream);
                Assert.DoesNotThrow(commit.Wait);
            }
        }
Esempio n. 26
0
        static void Main(string[] args)
        {
            //Bootstrap
            var settings = ConnectionSettings.Create()
                           .SetDefaultUserCredentials(new UserCredentials("admin", "changeit"))
                           .KeepReconnecting()
                           .KeepRetrying()
                           //.UseConsoleLogger()
                           .Build();
            var conn = EventStoreConnection.Create(settings, new IPEndPoint(IPAddress.Parse("127.0.0.1"), 1113));

            conn.ConnectAsync().Wait();

            var eventNamespace = "Administration.EventModel.Events";
            var eventAssembly  = "Administration";

            var repo = new SimpleRepo(conn, eventNamespace, eventAssembly);

            var roomTypeRm = new RoomTypeReader(() => conn, repo.Deserialize);

            var mainBus = new SimpleBus();

            var adminSvc = new AdminSvc(repo);

            mainBus.Subscribe <AddRoomType>(adminSvc);
            mainBus.Subscribe <AddRoom>(adminSvc);

            var view       = new ConsoleView();
            var controller = new Controller(view, mainBus);

            roomTypeRm.Subscribe(model => view.RoomSummaries = model);

            view.Redraw();
            roomTypeRm.Start();
            controller.StartCommandLoop();

            Console.WriteLine("press enter to exit");
            Console.ReadLine();
        }
Esempio n. 27
0
        static void Main()
        {
            StreamEventsSlice streamEvents;

            using (var connection = EventStoreConnection.Create(new IPEndPoint(IPAddress.Loopback, 1113)))
            {
                connection.ConnectAsync().Wait();

                streamEvents = connection.ReadStreamEventsForwardAsync(
                    "test-stream", StreamPosition.Start, 2500, true).Result;
            }

            var returnedEvents = streamEvents.Events;

            var streamLength = returnedEvents.Length;

            var eventDataDictionary = new Dictionary <long, string>();

            var eventCount = 0;

            foreach (ResolvedEvent eve in returnedEvents)
            {
                var number = eve.Event.EventNumber;
                var data   = Encoding.UTF8.GetString(eve.Event.Data);

                eventDataDictionary.Add(number, data);

                eventCount++;

                //For testing:
                //Console.WriteLine($"Caught up on {eventCount}/{streamLength}: {data}");

                if (eventCount == 0 || eventCount % 50 == 0)
                {
                    Console.WriteLine($"Caught up on {eventCount}/{streamLength} events in stream");
                }
            }
            Console.WriteLine("All caught up");
        }
        public static void AddEventStore(this IServiceCollection services, IConfiguration configuration)
        {
            var eventStoreConfig = configuration.GetSection("EventStore").Get <EventStoreConfig>();

            var userCrendetials = new global::EventStore.ClientAPI.SystemData.UserCredentials(eventStoreConfig.Username, eventStoreConfig.Password);

            var connectionSettings = ConnectionSettings.Create();

            connectionSettings.SetDefaultUserCredentials(userCrendetials);
            connectionSettings.KeepReconnecting();

            var eventStoreConnection = EventStoreConnection.Create(
                connectionSettings: connectionSettings,
                uri: eventStoreConfig.Host,
                connectionName: "Meeting.Topics.API");

            eventStoreConnection.ConnectAsync().GetAwaiter().GetResult();

            services.AddSingleton(eventStoreConnection);

            services.AddTransient <IEventStore, EventStore>();
        }
Esempio n. 29
0
        protected override void Load(ContainerBuilder builder)
        {
            builder
            .Register(x =>
            {
                var settings = ConnectionSettings
                               .Create()
                               .KeepReconnecting()
                               .KeepRetrying()
                               .FailOnNoServerResponse();

                var connection = EventStoreConnection.Create(ConnectionString, settings);
                connection.ConnectAsync().Wait();
                return(connection);
            })
            .As <IEventStoreConnection>()
            .InstancePerLifetimeScope();

            builder.RegisterGeneric(typeof(EventStoreRepository <,>))
            .AsImplementedInterfaces();

            builder
            .Register(
                x => BullOak.Repositories.Configuration
                .Begin()
                .WithDefaultCollection()
                .WithDefaultStateFactory()
                .AlwaysUseThreadSafe()
                .WithEventPublisher(new EventPublisher(x.Resolve <IPublishEndpoint>()))
                .WithAnyAppliersFrom(AppliersAssembly).AndNoMoreAppliers()
                .WithNoUpconverters()
                .Build())
            .As <IHoldAllConfiguration>();

            builder.RegisterType <EventCleaner>()
            .AsSelf();

            base.Load(builder);
        }
Esempio n. 30
0
        private static void Main(string[] args)
        {
            var runtime = Runtime.StartNewAsync().Result;

            var connection = EventStoreConnection
                             .Create(ConnectionSettings.Create().Build(), new IPEndPoint(IPAddress.Loopback, 1113));

            connection.ConnectAsync().Wait();

            Console.WriteLine(@"Type ""q"" to quit");
            Console.WriteLine(@"Type ""a"" to append an event");

            string input;

            do
            {
                input = Console.ReadLine();

                if (input != "a")
                {
                    continue;
                }

                var @event   = new ItemPurchased(GuidEncoder.Encode(Guid.NewGuid()));
                var metadata = new Dictionary <string, string>
                {
                    { "tenantId", "Warehouse A" },
                    { "$correlationId", GuidEncoder.Encode(Guid.NewGuid()) }
                };
                var eventData = EventSerializer.Serialize(Guid.NewGuid(), @event, metadata);

                connection.AppendToStreamAsync("ingress", ExpectedVersion.Any, eventData).Wait();

                Console.WriteLine("Appended event");
            } while (!string.Equals(input, "q"));

            runtime.Stop();
            Console.WriteLine("Stopping...");
        }
Esempio n. 31
0
        public async Task SetupFixture()
        {
            _embeddedEventStore = new EmbeddedEventStoreFixture();
            await _embeddedEventStore.Initialize();

            await Task.Delay(5000);

            var userCredentials    = new UserCredentials("admin", "changeit");
            var connectionSettings = ConnectionSettings.Create().WithConnectionTimeoutOf(TimeSpan.FromSeconds(10)).SetDefaultUserCredentials(userCredentials);

            _connection = EventStoreConnection.Create(connectionSettings, new Uri(EventStoreRepositoryConfiguration.Default.ConnectionString));

            await _connection.ConnectAsync();

            await Task.Delay(200);

            await CreateSubscription(_connection, euroDolStream, euroDolStream);

            await Task.Delay(200);

            await CreateSubscription(_connection, euroJpyStream, euroJpyStream);
        }