示例#1
0
        private async Task <IEventStoreConnection> GetConnectionAsync()
        {
            var settings = ConnectionSettings.Create()
                           //.UseConsoleLogger()
                           //.EnableVerboseLogging()
                           .KeepReconnecting();
            var connection = EventStoreConnection.Create(settings, new IPEndPoint(IPAddress.Loopback, 1113));
            await connection.ConnectAsync();

            return(connection);
        }
示例#2
0
        private static IEventStoreConnection BuildConnection(string name, Uri uri, bool openConnection = false)
        {
            var conn = EventStoreConnection.Create(
                EventStore.ClientAPI.ConnectionSettings.Create().KeepRetrying().KeepReconnecting(), uri, name);

            if (openConnection)
            {
                conn.ConnectAsync().Wait();
            }
            return(conn);
        }
示例#3
0
        public override void TestFixtureSetUp()
        {
            base.TestFixtureSetUp();
#if (!DEBUG)
            Assert.Ignore("These tests require DEBUG conditional");
#else
            QueueStatsCollector.InitializeIdleDetection();
            _nodeEndpoints[0] = new Endpoints(
                PortsHelper.GetAvailablePort(IPAddress.Loopback), PortsHelper.GetAvailablePort(IPAddress.Loopback),
                PortsHelper.GetAvailablePort(IPAddress.Loopback), PortsHelper.GetAvailablePort(IPAddress.Loopback),
                PortsHelper.GetAvailablePort(IPAddress.Loopback), PortsHelper.GetAvailablePort(IPAddress.Loopback));
            _nodeEndpoints[1] = new Endpoints(
                PortsHelper.GetAvailablePort(IPAddress.Loopback), PortsHelper.GetAvailablePort(IPAddress.Loopback),
                PortsHelper.GetAvailablePort(IPAddress.Loopback), PortsHelper.GetAvailablePort(IPAddress.Loopback),
                PortsHelper.GetAvailablePort(IPAddress.Loopback), PortsHelper.GetAvailablePort(IPAddress.Loopback));
            _nodeEndpoints[2] = new Endpoints(
                PortsHelper.GetAvailablePort(IPAddress.Loopback), PortsHelper.GetAvailablePort(IPAddress.Loopback),
                PortsHelper.GetAvailablePort(IPAddress.Loopback), PortsHelper.GetAvailablePort(IPAddress.Loopback),
                PortsHelper.GetAvailablePort(IPAddress.Loopback), PortsHelper.GetAvailablePort(IPAddress.Loopback));

            PortsHelper.GetAvailablePort(IPAddress.Loopback);

            _nodes[0] = CreateNode(0,
                                   _nodeEndpoints[0], new IPEndPoint[] { _nodeEndpoints[1].InternalHttp, _nodeEndpoints[2].InternalHttp });
            _nodes[1] = CreateNode(1,
                                   _nodeEndpoints[1], new IPEndPoint[] { _nodeEndpoints[0].InternalHttp, _nodeEndpoints[2].InternalHttp });

            _nodes[2] = CreateNode(2,
                                   _nodeEndpoints[2], new IPEndPoint[] { _nodeEndpoints[0].InternalHttp, _nodeEndpoints[1].InternalHttp });


            _nodes[0].Start();
            _nodes[1].Start();
            _nodes[2].Start();

            WaitHandle.WaitAll(new[] { _nodes[0].StartedEvent, _nodes[1].StartedEvent, _nodes[2].StartedEvent });
            QueueStatsCollector.WaitIdle(waitForNonEmptyTf: true);
            _conn = EventStoreConnection.Create(_nodes[0].ExternalTcpEndPoint);
            _conn.ConnectAsync().Wait();

            _manager = new ProjectionsManager(
                new ConsoleLogger(),
                _nodes[0].ExternalHttpEndPoint,
                TimeSpan.FromMilliseconds(10000));

            if (GivenStandardProjectionsRunning())
            {
                EnableStandardProjections();
            }
            QueueStatsCollector.WaitIdle();
            Given();
            When();
#endif
        }
示例#4
0
        protected override void PreStart()
        {
            base.PreStart();
            var connectionString = _settings.ConnectionString;
            var connectionName   = _settings.ConnectionName;

            _eventStoreConnection = EventStoreConnection.Create(connectionString, connectionName);

            _eventStoreConnection.ConnectAsync().Wait();
            _adapter = BuildDefaultJournalAdapter();
        }
示例#5
0
        public EventStoreClient(
            IServiceProvider serviceProvider,
            IOptionsMonitor <EventStoreOptions> eventStoreOptions)
        {
            this.serviceProvider   = serviceProvider;
            this.eventStoreOptions = eventStoreOptions;

            connection = EventStoreConnection.Create(
                uri: new Uri(this.eventStoreOptions.CurrentValue.ConnectionString),
                connectionName: this.eventStoreOptions.CurrentValue.ConnectionName);
        }
示例#6
0
        public IEventStoreConnection CreateConnection(
            Func <ConnectionSettingsBuilder, ConnectionSettingsBuilder> configureSettings = default,
            int?port = default, bool useDnsEndPoint = false)
        {
            var settings = (configureSettings ?? DefaultConfigureSettings)(DefaultBuilder).Build();

            return(EventStoreConnection.Create(
                       settings,
                       new IPEndPoint(IPAddress.Loopback, port ?? (settings.UseSslConnection
                                                                           ? ExternalSecurePort
                                                                           : ExternalPort))));
        }
        private static async Task <IEventStoreConnection> Connect()
        {
            var connectionSettings = ConnectionSettings.Create()
                                     .KeepReconnecting()
                                     .UseDebugLogger();
            var ipAddress = new IPAddress(new byte[] { 127, 0, 0, 1 });
            var endPoint  = new IPEndPoint(ipAddress, 1113);
            var conn      = EventStoreConnection.Create(connectionSettings, endPoint);
            await conn.ConnectAsync();

            return(conn);
        }
示例#8
0
        public void which_does_not_exist_should_fail()
        {
            const string stream = "which_does_not_exist_should_fail";

            using (var connection = EventStoreConnection.Create())
            {
                connection.Connect(MiniNode.Instance.TcpEndPoint);
                var delete = connection.DeleteStreamAsync(stream, ExpectedVersion.Any);
                Assert.Inconclusive();
                //Assert.That(() => delete.Wait(), Throws.Exception.TypeOf<AggregateException>().With.InnerException.TypeOf<WrongExpectedVersionException>());
            }
        }
示例#9
0
        static IEventStoreConnection GetConnection()
        {
            var credentials = new UserCredentials("admin", "changeit");
            var connection  =
                EventStoreConnection.Create(
                    ConnectionSettings.Create()
                    .UseConsoleLogger()
                    .SetDefaultUserCredentials(credentials),
                    new IPEndPoint(IPAddress.Loopback, 1113), "EventEmitter");

            return(connection);
        }
示例#10
0
        public override void TestFixtureSetUp()
        {
            base.TestFixtureSetUp();
#if (!DEBUG)
            Assert.Ignore("These tests require DEBUG conditional");
#else
            QueueStatsCollector.InitializeIdleDetection();
            CreateNode();
            try
            {
                _conn = EventStoreConnection.Create(_node.TcpEndPoint);
                _conn.ConnectAsync().Wait();

                _manager = new ProjectionsManager(
                    new ConsoleLogger(),
                    _node.ExtHttpEndPoint,
                    TimeSpan.FromMilliseconds(10000));
                WaitIdle();
                if (GivenStandardProjectionsRunning())
                {
                    EnableStandardProjections();
                }
                QueueStatsCollector.WaitIdle();
                Given();
                When();
            }
            catch
            {
                try
                {
                    if (_conn != null)
                    {
                        _conn.Close();
                    }
                }
                catch
                {
                }
                try
                {
                    if (_node != null)
                    {
                        _node.Shutdown();
                    }
                }
                catch
                {
                }

                throw;
            }
#endif
        }
        private static IEventStoreConnection Connect(string userName, string password)
        {
            ConnectionSettings settings =
                ConnectionSettings.Create()
                .UseConsoleLogger()
                .SetDefaultUserCredentials(new UserCredentials(userName, password));
            var endPoint   = new IPEndPoint(EventStoreIP, EventStorePort);
            var connection = EventStoreConnection.Create(settings, endPoint, null);

            connection.Connect();
            return(connection);
        }
        public EventStoreEventStore(IEventStoreConnection connection)
        {
            this.connection = connection;

            _connection = EventStoreConnection.Create(
                new IPEndPoint(
                    IPAddress.Parse("127.0.0.1"),
                    1113
                    )
                );
            _connection.ConnectAsync().Wait();
        }
        public EventStoreSnapshotStore()
        {
            settings = EventStorePersistence.Get(Context.System).SnapshotStoreSettings;
            log      = Context.GetLogger();

            var serialization = Context.System.Serialization;

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

            connection = EventStoreConnection.Create(settings.ConnectionString, settings.ConnectionName);
            connection.ConnectAsync().Wait();
        }
示例#14
0
        static async Task Main(string[] args)
        {
            var id = await CreatePlayer();

            using var conn = EventStoreConnection.Create(new Uri("tcp://*****:*****@localhost:1113"));
            await conn.ConnectAsync();

            var streamId = $"Player-{id}";
            var player   = await new AggregateRepository(conn).Fetch <PlayerAggregate>(streamId);

            Console.WriteLine(player.ToString());
        }
示例#15
0
        private static void InitConnection(ConnectionSettingsBuilder connectionSettings, IPAddress[] ipAddresses)
        {
            conn = EventStoreConnection.Create(
                connectionSettings,
                new IPEndPoint(IPAddress.Parse(ipAddresses.First().ToString()), 1113));

            conn.Connected     += ConnOnConnected;
            conn.Closed        += ConnOnClosed;
            conn.ErrorOccurred += ConnOnErrorOccurred;

            conn.ConnectAsync();
        }
示例#16
0
        public static void AddMyEventStoreServices(this IServiceCollection services, IConfiguration config)
        {
            config.ConfigureByOption("eventStore:type", new Options
            {
                ["MongoDb"] = () =>
                {
                    var mongoConfiguration = config.GetRequiredValue("eventStore:mongoDb:configuration");
                    var mongoDatabaseName  = config.GetRequiredValue("eventStore:mongoDb:database");

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

                        return(new MongoEventStore(mongDatabase, c.GetRequiredService <IEventNotifier>()));
                    })
                    .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.AddSingletonAs(connection)
                    .As <IEventStoreConnection>();

                    services.AddSingletonAs(c => new GetEventStore(connection, c.GetRequiredService <IJsonSerializer>(), eventStorePrefix, eventStoreProjectionHost))
                    .As <IEventStore>();

                    services.AddHealthChecks()
                    .AddCheck <GetEventStoreHealthCheck>("EventStore", tags: new[] { "node" });
                }
            });

            services.AddSingletonAs <OrleansEventNotifier>()
            .As <IEventNotifier>();

            services.AddSingletonAs <DefaultStreamNameResolver>()
            .As <IStreamNameResolver>();

            services.AddSingletonAs <DefaultEventDataFormatter>()
            .As <IEventDataFormatter>();

            services.AddSingletonAs(c =>
            {
                var allEventConsumers = c.GetServices <IEventConsumer>();

                return(new EventConsumerFactory(n => allEventConsumers.FirstOrDefault(x => x.Name == n)));
            });
        }
示例#17
0
        private async Task BuildEventStore(IServiceCollection services)
        {
            //Create EventStore Connection
            var eventStoreConnection = EventStoreConnection.Create(
                Configuration["EventStore:ConnectionString"],
                ConnectionSettings.Create()
                .KeepReconnecting()
                .EnableVerboseLogging()
                .SetHeartbeatInterval(TimeSpan.FromMilliseconds(5 * 1000))
                .UseDebugLogger(),
                Environment.ApplicationName
                );

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

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

            await eventStoreConnection.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(
                eventStoreConnection,
                serializer,
                eventMapper,
                (type, id) => $"{type.Name}-{id}",
                null);

            services.AddSingleton(new ApplicationService(aggregateStore));

            IAsyncDocumentSession GetSession() => BuildRevenDb().OpenAsyncSession();


            await ProjectionManager.With
            .Connection(eventStoreConnection)
            .CheckpointStore(new RavenDbChecklpointStore(GetSession))
            .Serializer(serializer)
            .TypeMapper(eventMapper)
            //TODO: GetSession function needs to inject projections...
            .AddProjection(new ActiveReviews())
            .AddProjection(new ReviewsByOwner())
            .StartAll();
        }
示例#18
0
        public EventStoreService(
            InMemoryCache cache,
            IOptions <EventStoreConfig> config,
            ILogger <EventStoreService> logger)
        {
            _logger     = logger;
            _streamName = config.Value.Stream;

            var settings = ConnectionSettings.Create()
                           .EnableVerboseLogging()
                           .Build();

            // Validate config
            if (string.IsNullOrWhiteSpace(config.Value.Host))
            {
                throw new ArgumentException($"Invalid configuration: Missing value for '{nameof(config.Value.Host)}'");
            }

            if (string.IsNullOrWhiteSpace(config.Value.Stream))
            {
                throw new ArgumentException($"Invalid configuration: Missing value for '{nameof(config.Value.Stream)}'");
            }

            // Prevent accidentally working with a production database
            if (Debugger.IsAttached)
            {
                Debug.Assert(config.Value.Host.Contains("localhost"),
                             "It looks like you are trying to connect to a production Event Store database. Are you sure you wish to continue?");
            }

            // Establish connection to Event Store
            var uri        = new Uri(config.Value.Host);
            var connection = EventStoreConnection.Create(settings, uri);

            connection.ConnectAsync().Wait();

            _store = new EventStore(connection);

            logger.LogInformation($"Connected to Event Store on '{uri.Host}', using stream '{_streamName}'");

            // Update stream to the latest version
            var mainAssembly    = Assembly.GetEntryAssembly();
            var migrationResult = StreamMigrator.MigrateAsync(_store, _streamName, mainAssembly).Result;

            if (migrationResult.fromVersion != migrationResult.toVersion)
            {
                logger.LogInformation($"Migrated stream '{_streamName}' from version '{migrationResult.fromVersion}' to version '{migrationResult.toVersion}'");
            }

            // Setup IDomainIndex-indices
            _cache = cache;
            PopulateIndicesAsync().Wait();
        }
示例#19
0
        static IEventStoreConnection GetEventStoreConnection()
        {
            ConnectionSettings settings = ConnectionSettings.Create()
                                          .SetDefaultUserCredentials(new UserCredentials("admin", "changeit"));

            var eventStoreConnection = EventStoreConnection.Create(
                settings,
                new IPEndPoint(IPAddress.Loopback, 1113));

            eventStoreConnection.ConnectAsync().Wait();
            return(eventStoreConnection);
        }
示例#20
0
        public static async Task AppendOneEvent()
        {
            var conn = EventStoreConnection.Create(new Uri("tcp://*****:*****@localhost:1113"));
            await conn.ConnectAsync();

            var sampleObject = new { a = 2 };
            var data         = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(sampleObject));
            var metadata     = Encoding.UTF8.GetBytes("{}");
            var evt          = new EventData(Guid.NewGuid(), "event-type", true, data, metadata);

            await conn.AppendToStreamAsync("newstream", ExpectedVersion.Any, evt);
        }
        private static async Task <IEventStoreConnection> GetConnection()
        {
            var connection = EventStoreConnection.Create(
                new IPEndPoint(IPAddress.Loopback, 1113)
                );

            await connection
            .ConnectAsync()
            .ConfigureAwait(false);

            return(connection);
        }
 public EventStoreClient()
 {
     _conn = EventStoreConnection.Create(new IPEndPoint(
                                             IPAddress.Parse("10.0.0.4"),
                                             1113
                                             ));
     _conn.Connected     += EventStore_Connected;
     _conn.Closed        += EventStore_Closed;
     _conn.Disconnected  += EventStore_Disconnected;
     _conn.Reconnecting  += EventStore_Reconnecting;
     _conn.ErrorOccurred += EventStore_ErrorOccured;
 }
示例#23
0
        private static IEventStoreConnection Connect()
        {
            ConnectionSettings settings =
                ConnectionSettings.Create()
                .UseConsoleLogger()
                .SetDefaultUserCredentials(new UserCredentials("admin", "changeit"));
            var endPoint   = new IPEndPoint(EventStoreIP, EventStorePort);
            var connection = EventStoreConnection.Create(settings, endPoint, null);

            connection.Connect();
            return(connection);
        }
        public EventStoreClient(ILogger <EventStoreClient> logger, IConfiguration configuration)
        {
            _logger = logger;

            var eventStoreConnectionString = configuration.GetValue <string>("EventStore:Url");

            _logger.LogDebug($"EventStore connection string is {eventStoreConnectionString}");

            _conn = EventStoreConnection.Create(new Uri(eventStoreConnectionString));
            _conn.ConnectAsync().Wait();
            _logger.LogInformation("Created connection to EventStore");
        }
示例#25
0
        public void Start()
        {
            //uncommet to enable verbose logging in client.
            var settings = ConnectionSettings.Create(); //.EnableVerboseLogging().UseConsoleLogger();

            settings.SetHeartbeatTimeout(new TimeSpan(0, 0, 1));

            _conn = EventStoreConnection.Create(settings, new IPEndPoint(IPAddress.Loopback, DEFAULTPORT));
            CreateSubscription();
            _conn.ConnectAsync().Wait();
            ConnectToSubscription();
        }
示例#26
0
 public static IEventStoreConnection GetConnection()
 {
     lock (_syncRoot)
     {
         if (_connection == null)
         {
             _connection = EventStoreConnection.Create(new Uri(GetEventStoreUrl()), "DomainEventHandler");
             _connection.ConnectAsync().Wait();
         }
     }
     return(_connection);
 }
示例#27
0
    public static void AddEventSourcingLayer(this IServiceCollection services, IConfiguration configuration)
    {
        var eventStoreConnection = EventStoreConnection.Create(
            connectionString: configuration["EventStore:ConnectionString"],
            builder: ConnectionSettings.Create().KeepReconnecting(),
            connectionName: configuration["EventStore:ConnectionName"]);

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

        services.AddSingleton(eventStoreConnection);
        //services.AddTransient<AggregateRepository>();
    }
示例#28
0
        static void Main(string[] args)
        {
            var connection = EventStoreConnection.Create(new IPEndPoint(IPAddress.Loopback, 1113));

            connection.ConnectAsync().Wait();
            var credential = new UserCredentials("admin", "changeit");

            connection.SubscribeToAllAsync(true, EventAppeared, SubscriptionDropped, credential).Wait();

            Console.WriteLine("Subscription started");
            Console.ReadLine();
        }
示例#29
0
        private async Task <IEventStoreConnection> CreateConnection()
        {
            if (_connection == null)
            {
                var connString = _config.ConnectionString;
                _connection = EventStoreConnection.Create(GetConnectionString());

                await _connection.ConnectAsync();
            }

            return(_connection);
        }
示例#30
0
        public IEventStoreConnection CreateConnection(string providedName)
        {
            var conn = clusterSettings != null
                ? EventStoreConnection.Create(connectionSettings, clusterSettings)
                : EventStoreConnection.Create(connectionSettings, singleNodeAddress);

            conn.Connected += (sender, args) =>
            {
                Console.WriteLine(">> Connection {0}: {1}", args.Connection.ConnectionName, providedName);
            };
            return(conn);
        }