public async Task <bool> Connect() { _logger.LogInformation("Attempting connection to EventStore ..."); try { ConnectionSettings connectionSettings = ConnectionSettings .Create() .SetReconnectionDelayTo(TimeSpan.FromMilliseconds(1000)) .SetHeartbeatTimeout(TimeSpan.FromMilliseconds(500)) .SetDefaultUserCredentials(new UserCredentials("admin", "changeit")) .EnableVerboseLogging() .UseConsoleLogger() .Build(); IPEndPoint ipendpoint = new IPEndPoint(IPAddress.Parse(_configuration["EventStoreSettings:ServerIP"]), int.Parse(_configuration["EventStoreSettings:Port"])); connection = EventStoreConnection.Create(connectionSettings, ipendpoint, _stream); await connection.ConnectAsync(); return(true); } catch (Exception e) { _logger.LogError($"Error in connecting to EventStore ... {e.Message}"); Console.WriteLine($"Error in connecting to EventStore ... {e.Message}"); throw e; } }
public void should_throw_exception_when_trying_to_reopen_closed_connection() { var closed = new ManualResetEventSlim(); var settings = ConnectionSettings.Create() .EnableVerboseLogging() .LimitReconnectionsTo(0) .WithConnectionTimeoutOf(TimeSpan.FromSeconds(10)) .SetReconnectionDelayTo(TimeSpan.FromMilliseconds(0)) .FailOnNoServerResponse(); if (_tcpType == TcpType.Ssl) settings.UseSslConnection("ES", false); using (var connection = EventStoreConnection.Create(settings, TestNode.BlackHole.ToESTcpUri())) { connection.Closed += (s, e) => closed.Set(); connection.ConnectAsync().Wait(); if (!closed.Wait(TimeSpan.FromSeconds(120))) // TCP connection timeout might be even 60 seconds Assert.Fail("Connection timeout took too long."); Assert.That(() => connection.ConnectAsync().Wait(), Throws.Exception.InstanceOf<AggregateException>() .With.InnerException.InstanceOf<InvalidOperationException>()); } }
public MainForm() { InitializeComponent(); var settings = ConnectionSettings.Create(); settings.SetDefaultUserCredentials(userCredentials); connection = EventStoreConnection.Create(settings, new IPEndPoint(new IPAddress(new byte[] { 127, 0, 0, 1 }), 1113)); connection.Connect(); Thread.Sleep(3000); pm = new ProjectionsManager( new ConsoleLogger(), new IPEndPoint(new IPAddress(new byte[] { 127, 0, 0, 1 }), 2113)); pm.Enable("$by_category", userCredentials); pm.Enable("$by_event_type", userCredentials); pm.Enable("$stream_by_category", userCredentials); pm.Enable("$streams", userCredentials); ac = new AlarmClock(connection); ac.Start(); }
public void Connect(string connectionString, string user, string password, string certificateCommonName, bool useSsl = false, int reconnectAttempts = -1, int heartbeatInterval = 30, int heartbeatTimeout = 120) { var settings = ConnectionSettings .Create() .KeepReconnecting() .UseConsoleLogger(); _creds = new UserCredentials(user, password); settings.SetDefaultUserCredentials(new UserCredentials(user, password)); settings.SetHeartbeatInterval(TimeSpan.FromSeconds(heartbeatInterval)); settings.SetHeartbeatTimeout(TimeSpan.FromSeconds(heartbeatTimeout)); if (useSsl && !String.IsNullOrEmpty(certificateCommonName)) { settings.UseSslConnection(certificateCommonName, true); } if (reconnectAttempts > 0) { settings.LimitReconnectionsTo(reconnectAttempts); KeepReconnecting = false; } var connectUri = new Uri(connectionString); _eventStoreConnection = EventStoreConnection.Create(settings, connectUri); _eventStoreConnection.ConnectAsync().Wait(); }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { 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.AddMassTransit(x => { x.UsingRabbitMq((context, config) => { config.Host("masstransit"); }); }); services.AddMassTransitHostedService(); services.AddSingleton(eventStoreConnection); services.AddTransient <AggregateRepository>(); services.AddControllers(); services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new OpenApiInfo { Title = "HelloWebApi", Version = "v1" }); }); }
static void Main(string[] args) { var settings = ConnectionSettings.Create() .SetDefaultUserCredentials(new UserCredentials("admin", "changeit")) .Build(); var connection = EventStoreConnection.Create(settings, new IPEndPoint(IPAddress.Loopback, 1113)); connection.ConnectAsync().Wait(); connection.CreateObservable(StreamId) .DeserializeWithPosition <MyEvent>() .HandleEvent(e => Console.WriteLine("handled : " + e.Property)) .Subscribe(pos => Console.WriteLine("last position handled : " + pos)); var serializer = new EventSerializer(); while (true) { var key = Console.ReadKey().KeyChar; Console.Write("\b"); var @event = new MyEvent { Property = key.ToString() }; var eventData = new EventData(Guid.NewGuid(), nameof(MyEvent), true, serializer.Serialize(@event), null); connection.AppendToStreamAsync(StreamId, ExpectedVersion.Any, eventData).Wait(); } }
public void Run() { const int maxReconnections = 200; const int maxOperationRetries = 200; for (int i = 0; i < Connections; ++i) { _connections[i] = EventStoreConnection.Create( ConnectionSettings.Create() .UseCustomLogger(ApiLogger) .LimitConcurrentOperationsTo(MaxConcurrentRequests) .LimitRetriesForOperationTo(maxReconnections) .LimitReconnectionsTo(maxOperationRetries) .FailOnNoServerResponse(), new Uri(string.Format("tcp://*****:*****@{0}:{1}", _nodeConnection.IpAddress, _nodeConnection.TcpPort)), string.Format("ESConn-{0}", i)); _connections[i].Closed += (s, e) => Log.Debug("[SCENARIO] {connection} closed.", e.Connection.ConnectionName); _connections[i].Connected += (s, e) => Log.Debug("[SCENARIO] {connection} connected to [{remoteEndPoint}].", e.Connection.ConnectionName, e.RemoteEndPoint); _connections[i].Disconnected += (s, e) => Log.Debug("[SCENARIO] {connection} disconnected from [{remoteEndPoint}].", e.Connection.ConnectionName, e.RemoteEndPoint); _connections[i].Reconnecting += (s, e) => Log.Debug("[SCENARIO] {connection} reconnecting.", e.Connection.ConnectionName); _connections[i].ErrorOccurred += (s, e) => Log.Debug(e.Exception, "[SCENARIO] {connection} error occurred.", e.Connection.ConnectionName); _connections[i].ConnectAsync().Wait(); } RunInternal(); }
private static ConnectionSettingsBuilder Settings(TcpType tcpType, UserCredentials userCredentials) { var settings = ConnectionSettings.Create() .SetDefaultUserCredentials(userCredentials) .UseCustomLogger(ClientApiLoggerBridge.Default) .EnableVerboseLogging() .LimitReconnectionsTo(10) .LimitAttemptsForOperationTo(1) .SetTimeoutCheckPeriodTo(TimeSpan.FromMilliseconds(100)) .SetReconnectionDelayTo(TimeSpan.Zero) .FailOnNoServerResponse() //.SetOperationTimeoutTo(TimeSpan.FromDays(1)) ; if (tcpType == TcpType.Ssl) { settings.DisableServerCertificateValidation(); } else { settings.DisableTls(); } return(settings); }
static void Main(string[] args) { XmlConfigurator.Configure(); HostFactory.Run(x => { x.UseLog4Net(); x.Service <AssociateAccountEndPoint>(s => { var connSettings = ConnectionSettings.Create().SetDefaultUserCredentials(new UserCredentials("admin", "changeit")) .KeepReconnecting().KeepRetrying().Build(); var endpointConnection = EventStoreConnection.Create(connSettings, new IPEndPoint(IPAddress.Loopback, 1113), "ES-Subscriber"); var domainConnection = EventStoreConnection.Create(connSettings, new IPEndPoint(IPAddress.Loopback, 1113), "ES-Processor"); endpointConnection.ConnectAsync().Wait(); domainConnection.ConnectAsync().Wait(); s.ConstructUsing( name => new AssociateAccountEndPoint(new EventStoreDomainRepository("account", domainConnection), endpointConnection)); s.WhenStarted((tc, hostControl) => tc.Start()); s.WhenStopped(tc => tc.Stop()); }); x.RunAsLocalSystem(); x.UseAssemblyInfoForServiceInfo(); x.SetDescription("Sample application"); x.SetDisplayName("EventStore Example Host"); x.SetServiceName("EventStore.Tools.Example.Host"); }); }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { var esConnection = EventStoreConnection.Create( Configuration["eventStore:connectionString"], ConnectionSettings.Create().KeepReconnecting(), Environment.ApplicationName); var store = new EsAggregateStore(esConnection); services.AddSingleton(esConnection) .AddSingleton <IAggregateStore>(store) .AddSingleton <IApplicationService, DailyBudgetsCommandService>() .AddControllers(); var dailybudgetItems = new List <ReadModels.DailyBudgets>(); services.AddSingleton <IEnumerable <ReadModels.DailyBudgets> >(dailybudgetItems); var subscription = new EsSubscription(esConnection, dailybudgetItems); services.AddSingleton <IHostedService>(new EventStoreService(esConnection, subscription)); services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_3_0); services.AddOpenApiDocument(settings => { settings.Title = "Budgee"; settings.DocumentName = "v1"; settings.Version = "v1"; }); //services.AddSwaggerGen(c => // c.SwaggerDoc("v1", // new Microsoft.OpenApi.Models.OpenApiInfo { Title = "DailyBudgets", Version = "v1" })); }
static void Main(string[] args) { //uncommet to enable verbose logging in client. var settings = ConnectionSettings.Create();//.EnableVerboseLogging().UseConsoleLogger(); using (var conn = EventStoreConnection.Create(settings, new IPEndPoint(IPAddress.Loopback, DEFAULTPORT))) { conn.ConnectAsync().Wait(); //Normally the creating of the subscription group is not done in your general executable code. //Instead it is normally done as a step during an install or as an admin task when setting //things up. You should assume the subscription exists in your code. CreateSubscription(conn); conn.ConnectToPersistentSubscription(STREAM, GROUP, (_, x) => { var data = Encoding.ASCII.GetString(x.Event.Data); Console.WriteLine("Received: " + x.Event.EventStreamId + ":" + x.Event.EventNumber); Console.WriteLine(data); }); Console.WriteLine("waiting for events. press enter to exit"); Console.ReadLine(); } }
public virtual ConnectionSettings CreateConnectionSettings(AkkaLogger logger) { return(ConnectionSettings.Create() .KeepReconnecting() .UseCustomLogger(logger) .SetDefaultUserCredentials(new UserCredentials("admin", "changeit"))); }
public EventStoreJournal() { _serializerSettings = new JsonSerializerSettings { TypeNameHandling = TypeNameHandling.Objects, TypeNameAssemblyFormat = FormatterAssemblyStyle.Simple, Formatting = Formatting.Indented, Converters = { new ActorRefConverter(Context) } }; _connection = new Lazy <Task <IEventStoreConnection> >(async() => { var settings = ConnectionSettings.Create() .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-journal"); await connection.ConnectAsync(); return(connection); }); }
public void Run() { const int maxReconnections = 200; const int maxOperationRetries = 200; for (int i = 0; i < Connections; ++i) { _connections[i] = EventStoreConnection.Create( ConnectionSettings.Create() .DisableVerboseLogging() .UseCustomLogger(ApiLogger) .LimitConcurrentOperationsTo(MaxConcurrentRequests) .LimitRetriesForOperationTo(maxReconnections) .LimitReconnectionsTo(maxOperationRetries) .FailOnNoServerResponse() .OnClosed((c, s) => Log.Debug("[SCENARIO] {0} closed.", c.ConnectionName)) .OnConnected((c, ep) => Log.Debug("[SCENARIO] {0} connected to [{1}].", c.ConnectionName, ep)) .OnDisconnected((c, ep) => Log.Debug("[SCENARIO] {0} disconnected from [{1}].", c.ConnectionName, ep)) .OnErrorOccurred((c, e) => Log.DebugException(e, "[SCENARIO] {0} error occurred.", c.ConnectionName)) .OnReconnecting(c => Log.Debug("[SCENARIO] {0} reconnecting.", c.ConnectionName)), new IPEndPoint(_nodeConnection.IpAddress, _nodeConnection.TcpPort), string.Format("ESConn-{0}", i)); _connections[i].Connect(); } RunInternal(); }
public static IServiceCollection AddInfrastructure(this IServiceCollection services, IConfiguration configuration) { var eventStoreSettings = new EventStoreSettings(); configuration.GetSection(nameof(EventStoreSettings)).Bind(eventStoreSettings); services.Configure <EventStoreSettings>(configuration.GetSection(nameof(EventStoreSettings))); var eventStoreConnection = EventStoreConnection.Create( connectionString: eventStoreSettings.ConnectionString, builder: ConnectionSettings.Create().KeepReconnecting(), connectionName: eventStoreSettings.ConnectionName); eventStoreConnection.ConnectAsync().GetAwaiter().GetResult(); services.AddSingleton(eventStoreConnection); var couchbaseSettings = new CouchbaseSettings(); configuration.GetSection(nameof(CouchbaseSettings)).Bind(couchbaseSettings); services.Configure <CouchbaseSettings>(configuration.GetSection(nameof(CouchbaseSettings))); services.AddCouchbase((opt) => { opt.ConnectionString = couchbaseSettings.ConnectionStrings; opt.Username = couchbaseSettings.UserName; opt.Password = couchbaseSettings.Password; }); services.AddTransient(typeof(IGenericRepository <>), typeof(GenericRepository <>)); return(services); }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { var esConnection = EventStoreConnection.Create( Configuration["eventStore:connectionString"], ConnectionSettings.Create().KeepReconnecting(), Environment.ApplicationName); var store = new EsAggregateStore(esConnection); services.AddSingleton(esConnection); services.AddSingleton <IAggregateStore>(store); services.AddSingleton(new ClassifiedAdsApplicationService( store, new FixedCurrencyLookup())); services.AddSingleton <IHostedService, HostedService>(); services.AddMvc(); services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new Info { Title = "ClassifiedAds", Version = "v1" }); }); }
public async Task should_throw_exception_when_trying_to_reopen_closed_connection() { ClientApiLoggerBridge.Default.Info("Starting '{0}' test...", "should_throw_exception_when_trying_to_reopen_closed_connection"); var closed = new TaskCompletionSource <bool>(TaskCreationOptions.RunContinuationsAsynchronously); var settings = ConnectionSettings.Create() .EnableVerboseLogging() .UseCustomLogger(ClientApiLoggerBridge.Default) .LimitReconnectionsTo(0) .WithConnectionTimeoutOf(TimeSpan.FromSeconds(10)) .SetReconnectionDelayTo(TimeSpan.FromMilliseconds(0)) .FailOnNoServerResponse(); if (_tcpType == TcpType.Ssl) { settings.UseSslConnection("ES", false); } var ip = IPAddress.Loopback; int port = PortsHelper.GetAvailablePort(ip); using var connection = EventStoreConnection.Create(settings, new IPEndPoint(ip, port).ToESTcpUri()); connection.Closed += (s, e) => closed.TrySetResult(true); await connection.ConnectAsync(); await closed.Task.WithTimeout( TimeSpan.FromSeconds(120)); // TCP connection timeout might be even 60 seconds await AssertEx.ThrowsAsync <ObjectDisposedException>(() => connection.ConnectAsync().WithTimeout()); }
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."); } } }
public void can_create_room_type() { var eventNamespace = "Administration.EventModel.Events"; var eventAssembly = "Administration"; 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 repo = new SimpleRepo(conn, eventNamespace, eventAssembly); var roomSvc = new AdminSvc(repo); var roomTypeId = Guid.NewGuid(); roomSvc.Handle(new AddRoomType(roomTypeId, "King", "big bed room")); var room = repo.Load <RoomType>(roomTypeId); Assert.Equal(roomTypeId, ((IEventSource)room).Id); }
public static IEventStoreConnection Create(IEventStoreConfiguration configuration, ILogger customerLogger, string username, string password) { var connectionSettings = ConnectionSettings.Create() .FailOnNoServerResponse() .UseCustomLogger(customerLogger) .KeepReconnecting() .KeepRetrying() .SetMaxDiscoverAttempts(int.MaxValue) .SetDefaultUserCredentials(new UserCredentials(username, password)); if (configuration.UseSingleNode) { return(EventStoreConnection.Create(connectionSettings.Build(), new Uri(configuration.SingleNodeConnectionUri))); } var gossipEndpoints = BuildIpEndPoints(configuration.ClusterConfiguration.ClusterNodes).ToArray(); connectionSettings.SetGossipSeedEndPoints(gossipEndpoints); if (configuration.ClusterConfiguration.UseSsl) { // This host name does not need to exist. It's used only to enable server validation in terms of matching certificate and trust chain. connectionSettings.UseSslConnection("your-domain.com", validateServer: true); } return(EventStoreConnection.Create(connectionSettings.Build())); }
static void Main(string[] args) { const string STREAM = "a_test_stream"; const int DEFAULTPORT = 1113; //uncommet to enable verbose logging in client. var settings = ConnectionSettings.Create();//.EnableVerboseLogging().UseConsoleLogger(); using (var conn = EventStoreConnection.Create(settings, new IPEndPoint(IPAddress.Loopback, DEFAULTPORT))) { conn.ConnectAsync().Wait(); //Note the subscription is subscribing from the beginning every time. You could also save //your checkpoint of the last seen event and subscribe to that checkpoint at the beginning. //If stored atomically with the processing of the event this will also provide simulated //transactional messaging. var sub = conn.SubscribeToStreamFrom(STREAM, StreamPosition.Start, true, (_, x) => { var data = Encoding.ASCII.GetString(x.Event.Data); Console.WriteLine("Received: " + x.Event.EventStreamId + ":" + x.Event.EventNumber); Console.WriteLine(data); }); Console.WriteLine("waiting for events. press enter to exit"); Console.ReadLine(); } }
public EventStoreFixture() { _node = EmbeddedVNodeBuilder .AsSingleNode() .OnDefaultEndpoints() .RunInMemory() .DisableDnsDiscovery() .DisableHTTPCaching() //.DisableScavengeMerging() .DoNotVerifyDbHashes() .Build(); _node.StartAndWaitUntilReady().Wait(); var conns = ConnectionSettings.Create() .SetDefaultUserCredentials(new EventStore.ClientAPI.SystemData.UserCredentials("admin", "changeit")) .Build(); var eventStoreConnection = EmbeddedEventStoreConnection.Create(_node, conns); StreamStoreConnection = new EventStoreConnectionWrapper(eventStoreConnection); EventSerializer = new JsonMessageSerializer(); StreamNameBuilder = new PrefixedCamelCaseStreamNameBuilder("masterdata"); _repo = new StreamStoreRepository(StreamNameBuilder, StreamStoreConnection, EventSerializer); }
static void Main(string[] args) { ConfigureLogging(); var positionRepo = new PositionRepository($"position-test", "PositionUpdated", BuildEsConnection, new NLogLogger(LogManager.GetCurrentClassLogger())); positionRepo.Start().Wait(); Log.Info($"Initial position is {positionRepo.Get()}"); using (var connection = BuildEsConnection()) { connection.ConnectAsync().Wait(); var position = connection.AppendToStreamAsync("tests", ExpectedVersion.Any, new List <EventData> { new EventData(Guid.NewGuid(), "EventTested", true, Encoding.ASCII.GetBytes("abc"), null) }) .Result.LogPosition; positionRepo.Set(position); } Thread.Sleep(1500); Log.Info($"Event saved. Current position is {positionRepo.Get()}"); Log.Info("Press enter to exit the program"); Console.ReadLine(); IEventStoreConnection BuildEsConnection() { return(EventStoreConnection.Create( ConnectionSettings.Create().SetDefaultUserCredentials(new UserCredentials("admin", "changeit")), new Uri("tcp://localhost:1113"))); } }
public static IServiceCollection AddEventStore(this IServiceCollection services, IWebHostEnvironment env, IConfiguration configuration) { var eventStoreConnectStr = configuration["eventStore:connectionString"]; var connection = EventStoreConnection.Create( eventStoreConnectStr, ConnectionSettings.Create().KeepReconnecting(), env.ApplicationName); services.AddSingleton(connection); services.AddSingleton <IAggregateStore>(x => new AggregateStore(connection)); var classifiedAditems = new List <ClassifiedAdDetailsViewModel>(); services.AddSingleton <IEnumerable <ClassifiedAdDetailsViewModel> >(classifiedAditems); var userItems = new List <UserDetailsViewModel>(); services.AddSingleton <IEnumerable <UserDetailsViewModel> >(userItems); var subscription = new ProjectionManger(connection, new ClassifiedAdProjection(classifiedAditems, userid => userItems.FirstOrDefault(x => x.UserId == userid)?.DisplayName), new UserDetailsProjection(userItems), new ClassifiedAdUpcasters(connection, userId => userItems.FirstOrDefault( x => x.UserId == userId)?.PhotoUrl) ); services.AddSingleton <IHostedService>(new HostedService(connection, subscription)); return(services); }
public EventStoreFacade(string httpUrl, string tcpUrl, string user, string password) { if (httpUrl.StartsWith("http://")) { throw new InvalidOperationException("Ssl is required to work."); } var tcpUri = new Uri(tcpUrl); ConnectionSettings tcpSettings = ConnectionSettings.Create() .UseSslConnection(false) .KeepReconnecting() .KeepRetrying() .LimitReconnectionsTo(1000) .LimitRetriesForOperationTo(100) .WithConnectionTimeoutOf(TimeSpan.FromSeconds(5)) .SetDefaultUserCredentials(new ApiCredentials(user, password)) .Build(); this._tcp = EventStoreConnection.Create(tcpSettings, tcpUri); _tcp.ConnectAsync().GetAwaiter().GetResult(); Log.Debug("TCP: Connected."); var httpSettings = new EventStoreClientSettings(); httpSettings.ConnectivitySettings.Address = new Uri(httpUrl); DefaultCredentials = new UserCredentials(user, password); _httpClient = new HttpEventStoreChannel(new EventStoreClient(httpSettings)); _tcpClient = new TcpEventStoreChannel(_tcp); _client = _tcpClient; }
static async Task Main(string[] args) { Log.Info("Building services..."); var config = BuildConfig(); var links = config.GetSection("links").Get <IEnumerable <Link> >(); var services = new List <LinkerService>(); foreach (var link in links) { if (link.Filters == null || !link.Filters.Any()) { Log.Info("Setting 'include all' default filter"); var defaultFilter = new Filter(FilterType.Stream, "*", FilterOperation.Include); link.Filters = new List <Filter> { defaultFilter }; } var filters = link.Filters.Select(linkFilter => new Filter { FilterOperation = linkFilter.FilterOperation, FilterType = linkFilter.FilterType, Value = linkFilter.Value }).ToList(); var filterService = new FilterService(filters); var service = new LinkerService(new LinkerConnectionBuilder(new Uri(link.Origin.ConnectionString), ConnectionSettings.Create().SetDefaultUserCredentials(new UserCredentials(link.Origin.User, link.Origin.Pass)), link.Origin.ConnectionName), new LinkerConnectionBuilder(new Uri(link.Destination.ConnectionString), ConnectionSettings.Create().SetDefaultUserCredentials(new UserCredentials(link.Destination.User, link.Destination.Pass)), link.Destination.ConnectionName), filterService, Settings.Default(), new NLogger()); services.Add(service); } await StartServices(services); Log.Info("Press enter to exit the program"); Console.ReadLine(); }
public void should_close_connection_after_configured_amount_of_failed_reconnections() { var closed = new ManualResetEventSlim(); var settings = ConnectionSettings.Create() .EnableVerboseLogging() .LimitReconnectionsTo(1) .WithConnectionTimeoutOf(TimeSpan.FromSeconds(10)) .SetReconnectionDelayTo(TimeSpan.FromMilliseconds(0)) .FailOnNoServerResponse(); if (_tcpType == TcpType.Ssl) settings.UseSslConnection("ES", false); using (var connection = EventStoreConnection.Create(settings, TestNode.BlackHole.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(120))) // TCP connection timeout might be even 60 seconds Assert.Fail("Connection timeout took too long."); Assert.That(() => connection.AppendToStreamAsync("stream", ExpectedVersion.EmptyStream, TestEvent.NewTestEvent()).Wait(), Throws.Exception.InstanceOf<AggregateException>() .With.InnerException.InstanceOf<InvalidOperationException>()); } }
protected override IEventStoreConnection CreateConnection() { var settings = ConnectionSettings.Create() .PerformOnAnyNode(); return(EventStoreConnection.Create(settings, _nodes[2].ExternalTcpEndPoint)); }
public PersistentSubcription(ICardRepository cardRepository) { _cardRepository = cardRepository; try { ConnectionSettings connectionSettings = ConnectionSettings.Create() .SetDefaultUserCredentials(new UserCredentials("admin", "changeit")) //.EnableVerboseLogging() .UseConsoleLogger() .Build(); IPEndPoint ipendpoint = new IPEndPoint(IPAddress.Parse(EVENTSTORE_IP), EVENSTORE_PORT); _connection = EventStoreConnection.Create(connectionSettings, ipendpoint, STREAM); _connection.ConnectAsync().Wait(); } catch (Exception e) { Console.WriteLine($"Error in ReadFromEventStore() ctor: {e.Message}"); throw e; } }
public static IHostBuilder CreateHostBuilder(string[] args) => Host.CreateDefaultBuilder(args) .ConfigureServices((hostContext, services) => { services.Configure <EventStoreSettings>(hostContext.Configuration.GetSection("EventStoreSettings")); services.AddLogging(builder => { builder.SetMinimumLevel(LogLevel.Debug); builder.AddConsole(); }); services.AddSingleton <ILogger, SeriLogger>(); services.AddSingleton(provider => { var builder = ConnectionSettings.Create(); builder.FailOnNoServerResponse(); builder.KeepReconnecting(); builder.KeepRetrying(); var settings = builder.Build(); return(EventStoreConnection.Create(settings, new Uri(provider .GetService <IOptionsMonitor <EventStoreSettings> >() .CurrentValue.ConnectionString))); }); services.AddSingleton(provider => { var logger = provider.GetService <ILogger>(); return(new ProjectionsManager(logger, new DnsEndPoint("localhost", 2113), TimeSpan.FromSeconds(15))); }); services.AddHostedService <EventStoreHostedService>(); });