Ejemplo n.º 1
0
        public async Task Raise(string eventName, object content)
        {
            await connection.ConnectAsync().ConfigureAwait(false);

            var contentJson  = JsonConvert.SerializeObject(content);
            var metaDataJson =
                JsonConvert.SerializeObject(new EventMetadata
            {
                OccurredAt = DateTimeOffset.Now,
                EventName  = eventName
            });

            var eventData = new EventData(
                Guid.NewGuid(),
                "ShoppingCartEvent",
                isJson: true,
                data: Encoding.UTF8.GetBytes(contentJson),
                metadata: Encoding.UTF8.GetBytes(metaDataJson)
                );

            await
            connection.AppendToStreamAsync(
                "ShoppingCart",
                ExpectedVersion.Any,
                eventData);
        }
Ejemplo n.º 2
0
        private Task EnsureConnected()
        {
            if (_connection != null)
            {
                return(Task.CompletedTask);
            }

            _connection = EventStoreConnection.Create(new Uri(_settings.ConnectionString));
            _connection.Disconnected += delegate { _connection.ConnectAsync().GetAwaiter().GetResult(); };
            return(_connection.ConnectAsync());
        }
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, IEventStoreConnection connection)
        {
            #region Dev
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                #region Swagger
                // Enable middleware to serve generated Swagger as a JSON endpoint.
                app.UseSwagger(c => { });
                // Enable middleware to serve swagger-ui (HTML, JS, CSS etc.), specifying the Swagger JSON endpoint.
                app.UseSwaggerUI(c =>
                {
                    c.SwaggerEndpoint("/swagger/v1/swagger.json", "Counter API V1");
                });

                #endregion
            }

            #endregion

            #region Core2.1
            app.UseMvc();
            app.UseStatusCodePages();
            #endregion

            #region Event sourcing
            // wait to complete the connection
            connection.ConnectAsync().Wait();
            #endregion
        }
        protected override void PreStart()
        {
            base.PreStart();

            _serializerSettings = new JsonSerializerSettings
            {
                TypeNameHandling       = TypeNameHandling.Objects,
                TypeNameAssemblyFormat = FormatterAssemblyStyle.Simple,
                Formatting             = Formatting.Indented,
                Converters             =
                {
                    new ActorRefConverter(Context)
                }
            };

            _connection = new Lazy <Task <IEventStoreConnection> >(async() =>
            {
                try
                {
                    IEventStoreConnection connection = EventStoreConnection.Create(_extension.EventStoreJournalSettings.ConnectionString, _extension.EventStoreJournalSettings.ConnectionName);
                    await connection.ConnectAsync();
                    return(connection);
                }
                catch (Exception exc)
                {
                    _log.Error(exc.ToString());
                    return(null);
                }
            });
        }
Ejemplo n.º 5
0
        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;
        }
Ejemplo n.º 6
0
        public async Task StartAsync(CancellationToken cancellationToken)
        {
            _supervisor.Initialize();
            await _esConnection.ConnectAsync();

            _pid = RootContext.Empty.Spawn(_subscriptionManager);
        }
Ejemplo n.º 7
0
        static void Main(string[] args)
        {
            Nodes.ForEach(n => n.Start());

            _connection = EventStoreConnection.Create(ConnectionSettings.Default,
                ClusterSettings.Create()
                    .DiscoverClusterViaGossipSeeds()
                    .SetGossipSeedEndPoints(new[]
                    {
                        new IPEndPoint(IPAddress.Loopback, 10004), new IPEndPoint(IPAddress.Loopback, 20004),
                        new IPEndPoint(IPAddress.Loopback, 30004)
                    }));

            _connection.ConnectAsync().Wait();

            Console.WriteLine("Waiting for nodes to start");
            Console.WriteLine("CBA to write code for this - Go sort out projections then press enter to begin");
            Console.ReadLine();

            Node master = GetMaster();

            while (!AreProjectionsFuckedYet())
            {
                master = GetMaster();
                master.FuckOff();
                Thread.Sleep(15000);
            }

            Console.WriteLine("Projections f****d!!! (Master is {0}, previously {1})", GetMaster().Name, master.Name);
            Console.ReadLine();
            Nodes.ForEach(n => n.FuckOff());
        }
Ejemplo n.º 8
0
 public async Task Start()
 {
     _conn.Reconnecting += _conn_Reconnecting;
     _conn.Disconnected += _conn_Disconnected;
     _conn.Connected    += _conn_Connected;
     await _conn.ConnectAsync();
 }
        public override async Task TestFixtureSetUp()
        {
            try {
                await base.TestFixtureSetUp();
            } catch (Exception ex) {
                throw new Exception("TestFixtureSetUp Failed", ex);
            }

            try {
                _node = new MiniNode <TLogFormat, TStreamId>(PathName);
                await _node.Start();

                _conn = BuildConnection(_node);
                await _conn.ConnectAsync();
            } catch (Exception ex) {
                throw new Exception("MiniNodeSetUp Failed", ex);
            }

            try {
                await Given().WithTimeout(Timeout);
            } catch (Exception ex) {
                throw new Exception("Given Failed", ex);
            }

            try {
                await When().WithTimeout(Timeout);
            } catch (Exception ex) {
                throw new Exception("When Failed", ex);
            }
        }
        public void Connect()
        {
            connection = EventStoreConnection.Create(new IPEndPoint(IPAddress.Loopback, 1113));
            connection.ConnectAsync().GetAwaiter().GetResult();

            persister = new SagaPersister();
        }
Ejemplo n.º 11
0
        public void Establish()
        {
            s_eventStoreNodeStarted     = false;
            s_eventStoreClientConnected = false;

            var noneIp = new IPEndPoint(IPAddress.None, 0);

            s_eventStoreNode = EmbeddedVNodeBuilder
                               .AsSingleNode()
                               .RunInMemory()
                               .WithExternalTcpOn(noneIp)
                               .WithInternalTcpOn(noneIp)
                               .WithExternalHttpOn(noneIp)
                               .WithInternalHttpOn(noneIp)
                               .Build();
            s_eventStoreNode.NodeStatusChanged +=
                (sender, e) => { if (e.NewVNodeState == VNodeState.Master)
                                 {
                                     s_eventStoreNodeStarted = true;
                                 }
            };
            s_eventStoreNode.Start();

            s_eventStore            = EmbeddedEventStoreConnection.Create(s_eventStoreNode);
            s_eventStore.Connected += (sender, e) => { s_eventStoreClientConnected = true; };
            s_eventStore.ConnectAsync().Wait();

            s_eventStoreMessageStore = new EventStoreMessageStore(s_eventStore);

            EnsureEventStoreNodeHasStartedAndTheClientHasConnected();
        }
Ejemplo n.º 12
0
        public EventStoreProxy(IComponentContext container)
        {
            _container = container;

            //Ensure we only set up the connection once
            lock (CreateConnectionLock)
            {
                if (_eventStoreConn == null)
                {
                    var connSettings = ConnectionSettings.Create()
                        .KeepReconnecting()
                        .KeepRetrying();

                    //TODO: get config value for address, port and user account
                    _eventStoreConn = EventStoreConnection.Create(connSettings, new IPEndPoint(IPAddress.Loopback, 1113));
                    _eventStoreConn.Disconnected += EventStoreConnDisconnected;
                    _eventStoreConn.ErrorOccurred += EventStoreConnErrorOccurred;
                    _eventStoreConn.Reconnecting += EventStoreConnReconnecting;
                    _eventStoreConn.Connected += EventStoreConnConnected;
                    _eventStoreConn.ConnectAsync().Wait();

                    SubscribeToStreamComment();
                    SubscribeToStreamTodo();
                }
            }
        }
Ejemplo n.º 13
0
        public async Task StartAsync(CancellationToken cancellationToken)
        {
            await _connection.ConnectAsync();

            _subscription = new EventStoreSubscription(_connection, _projections);
            _subscription.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();
        }
Ejemplo n.º 15
0
        public EventRepository()
        {
            var connectionString = "ConnectTo=tcp://user:password@localhost:1113; HeartBeatTimeout=500";

            Connection = EventStoreConnection.Create(connectionString);
            Connection.ConnectAsync().GetAwaiter().GetResult();
        }
Ejemplo n.º 16
0
        public EventStore(ILogger <EventStore> logger, IEventPublisher publisher, IOptions <EventStoreOptions> options)
        {
            _publisher = publisher;

            var assemblyNameFilter = options.Value.EventAssembliesPrefix ?? DefaultEventAssembliesPrefix;

            _eventSerializer = new EventSerializer(
                new DependencyContextFinder(assemblyNameFilter)); // Preferred since it doesn't require a path but will be incompatible with .NET Standard 2.0
            //new RuntimeLoaderFinder(new System.IO.DirectoryInfo(@".\bin\Debug\netcoreapp1.0"), assemblyNameFilter));

            try
            {
                Connection = EventStoreConnection.Create(Settings, new Uri(options.Value.ServerUri ?? DefaultServerUri));

                Connection.Disconnected += (s, e) =>
                                           logger.LogError("EventStore Disconnected");

                Connection.Reconnecting += (s, e) =>
                                           logger.LogError("EventStore Reconnecting");

                Connection.ErrorOccurred += (s, e) =>
                                            logger.LogError("EventStore ErrorOccurred");

                Connection.ConnectAsync().Wait();
            }
            catch (Exception ex)
            {
                logger.LogError(0, ex, "EventStore Exception");
            }
        }
Ejemplo n.º 17
0
        public override async Task TestFixtureSetUp()
        {
            await base.TestFixtureSetUp();

            _node = CreateMiniNode();
            await _node.Start();

            _connection = TestConnection.Create(_node.TcpEndPoint);
            await _connection.ConnectAsync();

            _lastResponse      = null;
            _lastResponseBody  = null;
            _lastResponseBytes = null;
            _lastJsonException = null;
            try {
                await Given().WithTimeout();
            } catch (Exception ex) {
                throw new Exception("Given Failed", ex);
            }

            try {
                await When().WithTimeout();
            } catch (Exception ex) {
                throw new Exception("When Failed", ex);
            }
        }
Ejemplo n.º 18
0
        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;
            }
        }
Ejemplo n.º 19
0
        public static void SetupEventStore()
        {
            var tcp  = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 1113);
            var http = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 2113);

            Connection = EventStoreConnection.Create(tcp);
            Connection.ConnectAsync().Wait();
            var  pManager = new ProjectionsManager(new NullLogger(), http, TimeSpan.FromSeconds(5));
            var  creds    = new UserCredentials("admin", "changeit");
            bool ready    = false;
            int  retry    = 0;

            while (!ready)
            {
                try
                {
                    pManager.EnableAsync("$streams", creds).Wait();
                    pManager.EnableAsync("$by_event_type", creds).Wait();
                    pManager.EnableAsync("$by_category", creds).Wait();
                    pManager.EnableAsync("$stream_by_category", creds).Wait();
                    ready = true;
                }
                catch
                {
                    retry++;
                    if (retry > 8)
                    {
                        throw new Exception("EventStore Projection Start Error.");
                    }
                    System.Threading.Thread.Sleep(250);
                }
            }
        }
Ejemplo n.º 20
0
        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;
            }
        }
Ejemplo n.º 21
0
        static void Main(string[] args)
        {
            using (_conn = EventStoreConnection.Create(new IPEndPoint(IPAddress.Loopback, 1113)))
            {
                _conn.ConnectAsync().Wait();


                var config = ConfigurationFactory.ParseString(@"akka {  
                        actor {
                            provider = ""Akka.Remote.RemoteActorRefProvider, Akka.Remote""
                        }
                            remote {
                            helios.tcp {
                                port = 50000 #bound to a static port
                                hostname = localhost
                        }
                    }
                }");
                var system = ActorSystem.Create("atBatWriter", config); //akka.tcp://localhost:50000@atBatWriter/user

                var supervisor = system.ActorOf(AtBatSupervisor.Create(), "supervisor");

                Console.ReadLine();
            }
        }
        /// <summary>
        /// Mains the specified arguments.
        /// </summary>
        /// <param name="args">The arguments.</param>
        private static async Task Main(String[] args)
        {
            // This example assumes you have an event store running locally on the default ports with the default username and password
            // If your event store connection information is different then update this connection string variable to point to your event store
            String connectionString = $"ConnectTo=tcp://admin:changeit@{Program.IpAddress}:1113;VerboseLogging=true;";

            // The subscription service requires an open connection to operate so create and open the connection here
            IEventStoreConnection eventStoreConnection = EventStoreConnection.Create(connectionString);

            await eventStoreConnection.ConnectAsync();

            await Program.AddEvents(eventStoreConnection, "Stream1-1", 1000);

            await Program.AddEvents(eventStoreConnection, "Stream2-1", 1000);

            await Program.StartProjection("TestProjection1");

            //await TruncateStreamTcp(eventStoreConnection, "$ce-Stream1", 100);                     //works
            //await TruncateStreamTcp(eventStoreConnection, "$ce-Stream1", 101);                     //works
            // await Program.TruncateStreamTcp(eventStoreConnection, "$ce-Stream1", 110);            //works

            //Both tcp and http truncate fails from 111

            await Program.TruncateStreamTcp(eventStoreConnection, "$ce-Stream1", 111); //fails

            // await TruncateStreamHttp("$ce-Stream1", 111);      //http truncate also fails

            //This projection no longer works (all stream position at -1)
            await Program.ResetProjection("TestProjection1");

            //This new projection does not work (all stream position at -1)
            await Program.StartProjection("TestProjection2");

            Console.ReadKey();
        }
Ejemplo n.º 23
0
        static void Main(string[] args)
        {
            var system = ActorSystem.Create("playerComposition");

            var searcher = system.ActorOf(PlayerSearchSupervisor.Create(), "supervisor");

            //  akka://playerCOmposition/user/supervisor

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

                Console.WriteLine("Player ID: ");
                var playerId = Console.ReadLine();

                for (int balls = 0; balls < 4; balls++)
                {
                    for (int strikes = 0; strikes < 3; strikes++)
                    {
                        var count = $"{balls}{strikes}";
                        searcher.Tell(new FindPlayerAndCount(playerId, count));
                    }
                }

                Console.ReadLine();
            }
        }
Ejemplo n.º 24
0
        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 EventStoreService(IConfiguration configuration)
        {
            _connection = EventStoreConnection.Create(
                configuration.GetConnectionString("EventStoreConnection"));

            _connection.ConnectAsync();
        }
 public void OneTimeSetUp()
 {
     _conn = BuildConnection();
     _conn.ConnectAsync().Wait();
     Given();
     When();
 }
        public override async Task SetUp()
        {
            await base.SetUp();

            _node = new MiniNode <TLogFormat, TStreamId>(PathName);
            await _node.Start();

            _conn = BuildConnection(_node);
            await _conn.ConnectAsync();

            await _conn.SetStreamMetadataAsync("$all", -1,
                                               StreamMetadata.Build().SetReadRole(SystemRoles.All),
                                               new UserCredentials(SystemUsers.Admin, SystemUsers.DefaultAdminPassword));

            _testEvents = Enumerable
                          .Range(0, 5)
                          .Select(x => TestEvent.NewTestEvent(x.ToString(), eventName: "AEvent"))
                          .ToList();

            _testEvents.AddRange(
                Enumerable
                .Range(0, 5)
                .Select(x => TestEvent.NewTestEvent(x.ToString(), eventName: "BEvent")).ToList());

            _fakeSystemEvents = Enumerable
                                .Range(0, 5)
                                .Select(x => TestEvent.NewTestEvent(x.ToString(), eventName: "$systemEvent"))
                                .ToList();
        }
Ejemplo n.º 28
0
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env, IHostApplicationLifetime appLifeTime, IEventStoreConnection connection)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            connection.ConnectAsync().Wait();
            connection.Disconnected += (sender, args) => appLifeTime.StopApplication();

            app.UseRouting();

            app.UseSwagger();

            app.UseSwaggerUI(c =>      //Swagger UI should be served from static container not service
            {
                c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1");
            });

            //app.UseAuthorization();            // maybe done by gateway

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });
        }
Ejemplo n.º 29
0
        public override async Task TestFixtureSetUp()
        {
            await base.TestFixtureSetUp();

            _credentials = new UserCredentials(SystemUsers.Admin, SystemUsers.DefaultAdminPassword);
            _timeout     = TimeSpan.FromSeconds(20);
            // Check if a node is running in ProjectionsManagerTestSuiteMarkerBase
            _tag = "_1";

            _node = CreateNode();
            await _node.Start().WithTimeout(_timeout);

            await _systemProjectionsCreated.WithTimeout(_timeout);

            _connection = TestConnection.Create(_node.TcpEndPoint);
            await _connection.ConnectAsync();

            _projManager = new ProjectionsManager(new ConsoleLogger(), _node.ExtHttpEndPoint, _timeout, _node.HttpMessageHandler);
            try {
                await Given().WithTimeout(_timeout);
            } catch (Exception ex) {
                throw new Exception("Given Failed", ex);
            }

            try {
                await When().WithTimeout(_timeout);
            } catch (Exception ex) {
                throw new Exception("When Failed", ex);
            }
        }
Ejemplo n.º 30
0
        static async Task Main(string[] args)
        {
            _stateDbContext = new StateDbContext();
            await _stateDbContext.Database.EnsureCreatedAsync();

            _subscriptionConnection = EventStoreConnectionFactory.Create(
                new EventStoreSingleNodeConfiguration(),
                new ConsoleLogger(),
                "admin", "changeit");
            _writeConnection = EventStoreConnectionFactory.Create(
                new EventStoreSingleNodeConfiguration(),
                new ConsoleLogger(),
                "admin", "changeit");

            await _subscriptionConnection.ConnectAsync();

            await _writeConnection.ConnectAsync();

            _eventStore = new Bank.Persistence.EventStore.EventStore(_writeConnection, new List <IEventSchema>
            {
                new InvoiceSchema()
            });
            _repository = new InvoiceRepository(_eventStore);

            //await StartMultipleSubscriptions();
            await StartCategoryGeneration();

            Console.ReadLine();
        }
Ejemplo n.º 31
0
        public async Task TheExampleCanRun()
        {
            await _eventStoreConnection.ConnectAsync();

            await WriteBytesToStream("test-stream", "testEvent", "some data");

            var streamEvents = await
                               _eventStoreConnection.ReadStreamEventsBackwardAsync("test-stream", StreamPosition.End, 1, false);

            var returnedEvent    = streamEvents.Events[0].Event;
            var returnedData     = Encoding.UTF8.GetString(returnedEvent.Data);
            var returnedMetaData = Encoding.UTF8.GetString(returnedEvent.Metadata);

            Assert.Equal("some data", returnedData);
            Assert.Equal("some metadata", returnedMetaData);
        }
Ejemplo n.º 32
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env,
                              IEventStoreConnection conn, IRepository <Product> productRepository,
                              IRepository <Customer> customerRepository, MongoClient mongoClient)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                app.UseBrowserLink();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
            }

            app.UseStaticFiles();

            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Carts}/{action=IndexAsync}/{id?}");
            });

            conn.ConnectAsync().Wait();

            if (!productRepository.FindAllAsync(x => true).Result.Any() &&
                !customerRepository.FindAllAsync(x => true).Result.Any())
            {
                SeedReadModel(productRepository, customerRepository);
            }
        }
        public override void TestFixtureSetUp()
        {
            base.TestFixtureSetUp();
            _node = new MiniNode(PathName);
            _node.Start();

            _connection = TestConnection.Create(_node.TcpEndPoint);
            _connection.ConnectAsync().Wait();
        }
Ejemplo n.º 34
0
 public override void TestFixtureSetUp()
 {
     base.TestFixtureSetUp();
     _node = new MiniNode(PathName, skipInitializeStandardUsersCheck: false);
     _node.Start();
     _conn = TestConnection.Create(_node.TcpEndPoint);
     _conn.ConnectAsync().Wait();
     When();
 }
        public override void TestFixtureSetUp()
        {
            base.TestFixtureSetUp();
            _node = new MiniNode(PathName);
            _node.Start();

            _connection = BuildConnection(_node);
            _connection.ConnectAsync().Wait();
        }
Ejemplo n.º 36
0
 public DispatcherBase(IMongoRepository mongoRepository, IGESConnection gesConnection, List<IHandler> eventHandlers)
 {
     _mongoRepository = mongoRepository;
     _gesConnection = gesConnection.BuildConnection();
     _gesConnection.ConnectAsync();
     _eventHandlers = eventHandlers;
     // add all handlers to the broadcast block so they receive news of events
     RegisterHandlers();
     // gets last event processed to avoid re processing events after a shut down.
     GetLastEventProcessedForHandlers();
 }
Ejemplo n.º 37
0
    public async Task<IEventStoreConnection> GetConnectionAsync() {
      if (Connection != null) return Connection;

      lock (BlockAllOtherThreads) {
        Connection = Factory.ConstructConnection();
      }
      Connection.Closed += OnClosed;
      await Connection.ConnectAsync().ConfigureAwait(false);

      return Connection;
    }
 public override void TestFixtureSetUp()
 {
     base.TestFixtureSetUp();
     _node = new MiniNode(PathName, skipInitializeStandardUsersCheck: false);
     _node.Start();
     _HttpEndPoint = _node.HttpEndPoint;
     _conn = BuildConnection(_node);
     _conn.ConnectAsync().Wait();
     Given();
     When();
 }
        public void SetUp()
        {
            var typeName = GetType().Name.Length > 30 ? GetType().Name.Substring(0, 30) : GetType().Name;
            PathName = Path.Combine(Path.GetTempPath(), string.Format("{0}-{1}", Guid.NewGuid(), typeName));
            Directory.CreateDirectory(PathName);

            Counter = 0;
            CreateNode();

            Connection = TestConnection.Create(Node.TcpEndPoint);
            Connection.ConnectAsync().Wait();
        }
        public override void TestFixtureSetUp()
        {
            base.TestFixtureSetUp();
            _credentials = new UserCredentials(SystemUsers.Admin, SystemUsers.DefaultAdminPassword);
            var createdMiniNode = false;
            _timeout = TimeSpan.FromSeconds(10);
            // Check if a node is running in ProjectionsManagerTestSuiteMarkerBase
            if (SetUpFixture.Connection != null && SetUpFixture.Node != null)
            {
                _tag = "_" + (++SetUpFixture.Counter);
                _node = SetUpFixture.Node;
                _connection = SetUpFixture.Connection;
            }
            else
            {
                createdMiniNode = true;
                _tag = "_1";

                _node = CreateNode();
                _node.Start();

                _connection = TestConnection.Create(_node.TcpEndPoint);
                _connection.ConnectAsync().Wait();
            }

            try
            {
                _projManager = new ProjectionsManager(new ConsoleLogger(), _node.ExtHttpEndPoint, _timeout);
                Given();
                When();
            }
            catch
            {
                if (createdMiniNode)
                {
                    if (_connection != null)
                    {
                        try {
                            _connection.Close();
                        } catch { 
                        }
                    }
                    if (_node != null)
                    {
                        try { 
                        	_node.Shutdown();
                        } catch {
                        }
                    }
                }
                throw;
            }
        }
Ejemplo n.º 41
0
        public void SetUp()
        {
            WebRequest.DefaultWebProxy = new WebProxy();
            _counter = 0;
            _directory = new SpecificationWithDirectoryPerTestFixture();
            _directory.TestFixtureSetUp();
            _node = new MiniNode(_directory.PathName, skipInitializeStandardUsersCheck: false, enableTrustedAuth: true);
            _node.Start();

            _connection = TestConnection.Create(_node.TcpEndPoint);
            _connection.ConnectAsync().Wait();
        }
 private void Connect()
 {
     var settings = ConnectionSettings.Create();
     var ip = new IPEndPoint(_ipAddress, _port);
     Log("Connecting to {0}:{1}...", _ipAddress, _port);
     _connection = EventStoreConnection.Create(settings, ip);
     _connection.ConnectAsync();
     _connection.AppendToStreamAsync("hello", ExpectedVersion.Any, new EventData(Guid.NewGuid(), "Hello", false, new byte[0], new byte[0]));
     Log("Connected.");
     Log("Username to be used is: {0}", _userName);
     _credentials = new UserCredentials(_userName, _password);
 }
        public override void SetUp()
        {
            base.SetUp();
            _node = new MiniNode(PathName, skipInitializeStandardUsersCheck: false);
            _node.Start();

            _conn = TestConnection.Create(_node.TcpEndPoint);
            _conn.ConnectAsync().Wait();
            _conn.SetStreamMetadataAsync("$all", -1,
                                    StreamMetadata.Build().SetReadRole(SystemRoles.All),
                                    new UserCredentials(SystemUsers.Admin, SystemUsers.DefaultAdminPassword)).Wait();
        }
Ejemplo n.º 44
0
        public void Start()
        {
            HasLoaded = false;
            _connection = EventStore.ClientAPI.EventStoreConnection.Create(_endpoint);
            var ct = _connection.ConnectAsync();
            ct.Wait();
            _checkPoint = Position.Start;
            if (string.IsNullOrEmpty(_streamName))
                _subscription = _connection.SubscribeToAllFrom(_checkPoint, false, EventAppeared, Live, SubscriptionDropped, _credentials);
            else
                _subscription = _connection.SubscribeToStreamFrom(_streamName, _lastEventNumber, true, EventAppeared, Live, SubscriptionDropped, _credentials);

        }
        public override void TestFixtureSetUp()
        {
            base.TestFixtureSetUp();
            #if (!DEBUG)
            throw new NotSupportedException("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
        }
        public override void SetUp()
        {
            base.SetUp();
            _node = new MiniNode(PathName);
            _node.Start();

            _connection = TestConnection.Create(_node.TcpEndPoint);
            _connection.ConnectAsync().Wait();

            _connection.SetStreamMetadataAsync(Stream, ExpectedVersion.EmptyStream, StreamMetadata.Build().SetMaxCount(3)).Wait();

            _testEvents = Enumerable.Range(0, 5).Select(x => TestEvent.NewTestEvent(data: x.ToString())).ToArray();
            _connection.AppendToStreamAsync(Stream, ExpectedVersion.EmptyStream, _testEvents).Wait();
        }
        public static Task ConnectAsync(string ip, int port, string user, string password)
        {
            credentials = new UserCredentials(user, password);
            connection = EventStoreConnection.Create(
                ConnectionSettings.Create()
                    .SetDefaultUserCredentials(credentials)
                    .UseConsoleLogger()
                    .UseDebugLogger()
                    .KeepReconnecting()
                    .FailOnNoServerResponse()
                    .KeepRetrying(),
                new IPEndPoint(IPAddress.Loopback, 1113));

            return connection.ConnectAsync();
        }
 protected override void Given()
 {
     _serverEndPoint = new IPEndPoint(IPAddress.Loopback, PortsHelper.GetAvailablePort(IPAddress.Loopback));
     _url = _HttpEndPoint.ToHttpUrl("/stats/tcp");
     
     var settings = ConnectionSettings.Create();
     _connection = EventStoreConnection.Create(settings, _node.TcpEndPoint);
     _connection.ConnectAsync().Wait();
     
     var testEvent = new EventData(Guid.NewGuid(),"TestEvent",true,Encoding.ASCII.GetBytes("{'Test' : 'OneTwoThree'}"),null);
     _connection.AppendToStreamAsync("tests",ExpectedVersion.Any,testEvent).Wait();
     
     _portableServer = new PortableServer(_serverEndPoint);
     _portableServer.SetUp();
 }
        public void Start()
        {
            //uncommet to enable verbose logging in client.
            var settings = ConnectionSettings.Create(); //.EnableVerboseLogging().UseConsoleLogger();

            using (_conn = EventStoreConnection.Create(settings, new IPEndPoint(IPAddress.Loopback, DEFAULTPORT)))
            {
                _conn.ConnectAsync().Wait();

                CreateSubscription();
                ConnectToSubscription();

                Console.WriteLine("waiting for events. press enter to exit");
                Console.ReadLine();
            }
        }
        public override void TestFixtureSetUp()
        {
            base.TestFixtureSetUp();
            _node = new MiniNode(PathName, inMemDb: true);
            _node.Start();

            _conn = BuildConnection(_node);
            _conn.ConnectAsync().Wait();
            //Create 80000 events
            for(var i = 0; i < 80; i++)
            {
                _conn.AppendToStreamAsync(_streamName, ExpectedVersion.Any, CreateThousandEvents()).Wait();
            }

            _settings = new CatchUpSubscriptionSettings(100, 1, false, true);
        }
        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.HttpEndPoint,
                    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
        }
        public override void SetUp()
        {
            base.SetUp();
            _node = new MiniNode(PathName);
            _node.Start();

            _firstEvent = TestEvent.NewTestEvent();

            _connection = TestConnection.Create(_node.TcpEndPoint);
            _connection.ConnectAsync().Wait();

            Assert.AreEqual(2, _connection.AppendToStreamAsync("test-stream",
                                                          ExpectedVersion.NoStream,
                                                          _firstEvent,
                                                          TestEvent.NewTestEvent(),
                                                          TestEvent.NewTestEvent()).Result.NextExpectedVersion);

            using (var transaction = _connection.StartTransactionAsync("test-stream", 2).Result)
            {
                Assert.AreEqual(2, transaction.Commit().NextExpectedVersion);
            }
        }
        //TODO: Need restore point configuration
        private static void Start(ProjectionGatewayConfiguration projectionGatewayConfiguration, IEventStoreConnection eventStoreConnection)
        {
            projectionGatewayConfiguration.Locator.Register(() => eventStoreConnection);
            eventStoreConnection.ConnectAsync().Wait();

            foreach (var subscription in projectionGatewayConfiguration.Subscriptions)
            {
                var eventHandlers = subscription.Value;
                eventStoreConnection.SubscribeToStreamFrom(
                    stream: subscription.Key + "View",
                    lastCheckpoint: StreamCheckpoint.StreamStart,
                    resolveLinkTos: true,
                    eventAppeared: (upSubscription, @event) =>
                    {
                        var eventType = Type.GetType(@event.Event.EventType);
                        var deserializedEvent = JsonConvert.DeserializeObject(Encoding.UTF8.GetString(@event.Event.Data), eventType);
                        eventHandlers
                            .Single(x => x.EventType == eventType)
                            .EventHandler(deserializedEvent);
                    });
            }
        }
Ejemplo n.º 54
0
 public MessageBinderBase(IEventStoreConnection eventStoreConnection)
 {
     _eventStoreConnection = eventStoreConnection;
     _eventStoreConnection.ConnectAsync();
 }
Ejemplo n.º 55
0
        protected override void Given()
        {
            _conn = EventStoreConnection.Create(_node.TcpEndPoint.ToESTcpUri());
            _conn.ConnectAsync().Wait();
            _conn.CreatePersistentSubscriptionAsync(_streamName, _groupName, _settings,
                    DefaultData.AdminCredentials).Wait();
            _sub1 = _conn.ConnectToPersistentSubscription(_streamName,_groupName,
                        (subscription, @event) => Console.WriteLine(), 
                        (subscription, reason, arg3) => Console.WriteLine());
            _sub2 = _conn.ConnectToPersistentSubscription(_streamName, _groupName,
                        (subscription, @event) => Console.WriteLine(),
                        (subscription, reason, arg3) => Console.WriteLine(),
                        DefaultData.AdminCredentials);

        }
        public static void SetupEventStore(StartConflictOption opt = StartConflictOption.Connect)
        {

            //TODO: Convert to Embedded when I can figure out loading the miniWeb component
            var runningEventStores = Process.GetProcessesByName("EventStore.ClusterNode");
            if (runningEventStores.Length != 0)
            {
                switch (opt)
                {
                    case StartConflictOption.Connect:
                        _process = runningEventStores[0];
                        break;
                    case StartConflictOption.Kill:
                        foreach (var es in runningEventStores)
                        {
                            es.Kill();
                        }
                        break;
                    case StartConflictOption.Error:
                        throw new Exception("Conflicting EventStore running.");
                    default:
                        throw new ArgumentOutOfRangeException(nameof(opt), opt, null);
                }
            }
            if (_process == null)
            {
                _process = new Process
                {
                    StartInfo =
                    {
                        UseShellExecute = false, CreateNoWindow = true, FileName = Path, Arguments = Args, Verb = "runas"
                    }
                };
                _process.Start();
            }
            var tcp = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 1113);
            var http = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 2113);
            Connection = EventStoreConnection.Create(tcp);
            Connection.ConnectAsync().Wait();
            var pManager = new ProjectionsManager(new NullLogger(), http, TimeSpan.FromSeconds(5));
            var creds = new UserCredentials("admin", "changeit");
            bool ready = false;
            int retry = 0;
            while (!ready)
            {
                try
                {
                    pManager.EnableAsync("$streams", creds).Wait();
                    pManager.EnableAsync("$by_event_type", creds).Wait();
                    pManager.EnableAsync("$by_category", creds).Wait();
                    pManager.EnableAsync("$stream_by_category", creds).Wait();
                    ready = true;
                }
                catch
                {
                    retry++;
                    if (retry > 8)
                        throw new Exception("EventStore Projection Start Error.");
                    System.Threading.Thread.Sleep(250);
                }
            }
        }