private static async Task Execute()
        {
            var connectionFactory = new EventStoreConnectionFactory("ConnectTo=tcp://127.0.0.1:1113;");
            var bus            = new EventStoreBus(connectionFactory);
            var canUnsubscribe = bus.RegisterHandler(new EventSubscriptionRequest <Event>(OnEventReceived, "$ce-hello", lastProcessedEventStreamPosition: null));

            var eventStore = new EventStore(connectionFactory, null);

            var streamName = StreamNameBuilder.BuildStreamName <Hello>(Guid.NewGuid());
            await eventStore.CreateNewStream(streamName, new Event[] { new HelloEvent(), });

            bool keepContinue = true;

            while (keepContinue)
            {
                switch (Console.ReadKey().Key)
                {
                case ConsoleKey.RightArrow:

                    var lastExpectedEventVersion = eventStore.GetStreamLastExpectedEventVersion(streamName);
                    await eventStore.AppendEventsToStream(streamName, new[]  { new HelloEvent(), }, lastExpectedEventVersion);

                    break;

                case ConsoleKey.LeftArrow:
                    keepContinue = false;
                    break;
                }
            }
        }
        private static async Task Execute()
        {
            var connectionFactory = new EventStoreConnectionFactory("ConnectTo=tcp://127.0.0.1:1113;");

            var eventStore = new EventStore(connectionFactory, null);

            var streamName = StreamNameBuilder.BuildStreamName <Hello>(Guid.NewGuid());
            await eventStore.CreateNewStream(streamName, new Event[] { new HelloEvent() });

            bool keepContinue = true;

            while (keepContinue)
            {
                switch (Console.ReadKey().Key)
                {
                case ConsoleKey.RightArrow:

                    var lastExpectedEventVersion = eventStore.GetStreamLastExpectedEventVersion(streamName);
                    await eventStore.AppendEventsToStream(streamName, new[] { new HelloEvent() }, lastExpectedEventVersion);

                    break;

                case ConsoleKey.LeftArrow:
                    keepContinue = false;
                    break;
                }
            }
        }
        public static void AddApplicationServices(this IServiceCollection services)
        {
            services.AddSingleton <IEventStore, EventStore>(provider =>
            {
                var connection = EventStoreConnectionFactory.Create(
                    new EventStoreSingleNodeConfiguration(),
                    new EventStoreLogger(provider.GetRequiredService <ILoggerFactory>()),
                    "admin", "changeit");

                connection.ConnectAsync().Wait();

                var schemas = new List <IEventSchema>
                {
                    new AccountSchema(),
                    new CardSchema()
                };

                return(new EventStore(connection, schemas));
            });

            services.AddSingleton <IAccountDomainRepository, AccountDomainRepository>();
            services.AddSingleton <ICardDomainRepository, CardDomainRepository>();

            services.AddTransient <CreditCardPurchaseService>();
        }
예제 #4
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();
        }
예제 #5
0
        public static IServiceCollection AddEventStoreSubscription(this IServiceCollection services, EventStoreOptions options)
        {
            services.AddSingleton <IEventStoreConnection>(EventStoreConnectionFactory.Create(options.ConnectionString));
            services.AddSingleton <EventTypeResolver>(new EventTypeResolver(ReflectionHelper.MessagesAssembly));

            return(services);
        }
        public void InitializeEventStore(IEventStoreConfiguration configuration)
        {
            var eventStoreConnection = EventStoreConnectionFactory.Create(EventStoreLocation.External, configuration);

            eventStoreConnection.ConnectAsync().Wait();

            ReferenceDataHelper.PopulateRefData(eventStoreConnection).Wait();
        }
예제 #7
0
파일: Startup.cs 프로젝트: JimmyBcn/quiz
        private void AddEventStore(IServiceCollection services)
        {
            var options = EventStoreOptions.Create(Configuration);

            services.AddSingleton(EventStoreConnectionFactory.Create(options.ConnectionString));
            services.AddSingleton(new EventTypeResolver(ReflectionHelper.MessagesAssembly));
            services.AddTransient <IRepository, EventStoreRepository>();
        }
예제 #8
0
        static async Task Main(string[] args)
        {
            var eventStoreConnection = EventStoreConnectionFactory.Create(
                new EventStoreSingleNodeConfiguration(),
                new ConsoleLogger(),
                "admin", "changeit");

            await eventStoreConnection.ConnectAsync();

            _eventStore = new Bank.Persistence.EventStore.EventStore(eventStoreConnection, new List <IEventSchema>
            {
                new AccountSchema()
            });
            _accountSnapshotRepository = new AccountSnapshotRepository(_eventStore);

            var tasks = new Task[NumberOfStreams];

            for (int i = 0; i < NumberOfStreams; i++)
            {
                var number = i;
                tasks[i] = Task.Run(async() => { await CreateStreams(number); });
            }

            await Task.Delay(4000);

            Task.Run(async() =>
            {
                while (true)
                {
                    await Task.Delay(2000);

                    Console.WriteLine("-----Status-----");

                    for (int i = 0; i < 5; i++)
                    {
                        double readTimings = 0;
                        if (!ReadTimings[i].IsEmpty)
                        {
                            readTimings = Math.Floor(ReadTimings[i].Average());
                        }
                        double writeTimings = 0;
                        if (!WriteTimings[i].IsEmpty)
                        {
                            writeTimings = Math.Floor(WriteTimings[i].Average());
                        }

                        Console.WriteLine($"Stream: {i}, Balance: {Balances[i]}, Read: {readTimings} ms, Write: {writeTimings} ms");
                    }

                    ReadTimings  = CreateTimingsArray(NumberOfStreams);
                    WriteTimings = CreateTimingsArray(NumberOfStreams);
                }
            });

            await Task.WhenAll(tasks);

            Console.ReadLine();
        }
예제 #9
0
        public override void Load()
        {
            LoadAssemblies(_assemblies);
            LoadAssemblies(GetType().Assembly);

            Kernel.Bind <IEventStoreConnection>()
            .ToMethod(context => EventStoreConnectionFactory.Default())
            .InSingletonScope();
        }
예제 #10
0
        private static IEventStoreConnection GetEventStoreConnection(IEventStoreConfiguration configuration)
        {
            var eventStoreConnection =
                EventStoreConnectionFactory.Create(
                    EventStoreLocation.External,
                    configuration);

            return(eventStoreConnection);
        }
예제 #11
0
 /// <summary>
 ///
 /// </summary>
 /// <param name="aggregateId"></param>
 /// <param name="eventData"></param>
 public void AppentToAggregate(Guid aggregateId, EventData eventData)
 {
     using (var connection = EventStoreConnectionFactory.Default())
     {
         connection.ConnectAsync().Wait();
         connection.AppendToStreamAsync(aggregateId.ToString(), ExpectedVersion.Any, eventData)
         .Wait();
     }
 }
예제 #12
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="aggregateId"></param>
        /// <param name="fromVersion"></param>
        public async Task <byte[]> FetchEventsByAggregateAsync(Guid aggregateId, int fromVersion)
        {
            using (var connection = EventStoreConnectionFactory.Default())
            {
                connection.ConnectAsync().Wait();
                var streamEvents = await connection.ReadEventAsync(aggregateId.ToString(), 0, false, EventStoreCredentials.Default);

                return(streamEvents.Event.Value.Event.Data);
            }
        }
 public T Create <T>()
 {
     if (typeof(T) == typeof(TaskApplicationService))
     {
         var idGenerator = new IdGenerator();
         var factory     = new AggregateFactory();
         var connection  = new EventStoreConnectionFactory().Create("TaskManager");
         var repository  = new GesRepository(connection, factory);
         var service     = new TaskApplicationService(repository, idGenerator);
         return((T)(object)service);
     }
     throw new InvalidOperationException("Unknown application service");
 }
예제 #14
0
        static async Task Main(string[] args)
        {
            var eventStoreSubscriptionConnection = EventStoreConnectionFactory.Create(
                new EventStoreSingleNodeConfiguration(),
                new ConsoleLogger(),
                "admin", "changeit");
            var eventStoreWriteConnection = EventStoreConnectionFactory.Create(
                new EventStoreSingleNodeConfiguration(),
                new ConsoleLogger(),
                "admin", "changeit");

            await eventStoreSubscriptionConnection.ConnectAsync();

            await eventStoreWriteConnection.ConnectAsync();

            _eventStore = new Bank.Persistence.EventStore.EventStore(eventStoreSubscriptionConnection, new List <IEventSchema>
            {
                new AccountSchema()
            });
            _repository = new AccountSnapshotRepository(_eventStore);

            try
            {
                await eventStoreSubscriptionConnection.CreatePersistentSubscriptionAsync(
                    "$ce-Account",
                    "Snapshot",
                    PersistentSubscriptionSettings
                    .Create()
                    .StartFromBeginning()
                    .CheckPointAfter(TimeSpan.FromSeconds(5))
                    .ResolveLinkTos()
                    .Build(), new UserCredentials("admin", "changeit"));
            }
            catch (Exception e)
            {
                Console.WriteLine($"Subscription already exist.");
            }

            await eventStoreSubscriptionConnection.ConnectToPersistentSubscriptionAsync("$ce-Account", "Snapshot", EventAppeared);

            await eventStoreSubscriptionConnection.ConnectToPersistentSubscriptionAsync("$ce-Account", "Snapshot", EventAppeared);

            await eventStoreSubscriptionConnection.ConnectToPersistentSubscriptionAsync("$ce-Account", "Snapshot", EventAppeared);

            await eventStoreSubscriptionConnection.ConnectToPersistentSubscriptionAsync("$ce-Account", "Snapshot", EventAppeared);

            await eventStoreSubscriptionConnection.ConnectToPersistentSubscriptionAsync("$ce-Account", "Snapshot", EventAppeared);

            Console.ReadLine();
        }
예제 #15
0
        static void Main(string[] args)
        {
            var builder       = new ConfigurationBuilder().AddEnvironmentVariables();
            var configuration = builder.Build();

            Console.WriteLine("Starting Event Store Quiz Setup.");

            var options = EventStoreOptions.Create(configuration);
            var conn    = EventStoreConnectionFactory.Create(options.ConnectionString);

            EventStoreSetup.Create(conn, options).Wait();

            Console.WriteLine("Event Store Quiz Setup Done!");
        }
예제 #16
0
        private void ConfigureEventStore(IServiceCollection services)
        {
            var eventStoreConfiguration = new EventStoreConfiguration();

            Configuration.GetSection("EventStore").Bind(eventStoreConfiguration);
            services.AddSingleton <IEventStoreConfiguration>(eventStoreConfiguration);

            IEventStoreConnectionFactory factory = new EventStoreConnectionFactory(eventStoreConfiguration);

            services.AddSingleton(factory);

            var eventStoreClient = new EventStoreClient(SubscribedEventTypes, factory);

            services.AddSingleton <IEventStreamingClient>(eventStoreClient);
            services.AddSingleton <IEventPersistenceClient>(eventStoreClient);
        }
예제 #17
0
        protected override void Load(ContainerBuilder builder)
        {
            var eventStoreConnectionFactory            = new EventStoreConnectionFactory(this._eventStoreConfiguration);
            IEventStoreConnection eventStoreConnection = eventStoreConnectionFactory.GetEventStoreConnection();

            eventStoreConnection.ConnectAsync().Wait();
            builder.RegisterInstance <IEventStoreConnection>(eventStoreConnection);

            var eventStoreRepository = new EventStoreRepository(eventStoreConnection);

            builder.RegisterInstance <IRepository>(eventStoreRepository).SingleInstance();

            builder.Register(r => new EventDispatcher(eventStoreConnection, r.Resolve <IEventBus>()))
            .As <EventDispatcher>()
            .SingleInstance();
        }
        public async Task <byte[]> FetchEventsByAggregateAsync(Guid aggregateId, int fromVersion)
        {
            using (var connection = EventStoreConnectionFactory.Default())
            {
                try
                {
                    connection.ConnectAsync().Wait();

                    var re = await connection.ReadEventAsync(aggregateId.ToString(), 0, false, EventStoreCredentials.Default);// .ReadStreamEventsForwardAsync(aggr, 1, 1, true);

                    return(re.Event.Value.Event.Data);
                }
                catch (Exception ex)
                {
                    throw;
                }
            }
        }
예제 #19
0
파일: Startup.cs 프로젝트: razvalex/WanVet
 protected override void Load(ContainerBuilder containerBuilder)
 {
     containerBuilder.Register(c => new EventTypeResolver(typeof(DefaultModule).GetTypeInfo().Assembly)).As <IEventTypeResolver>();
     containerBuilder.Register(c => EventStoreConnectionFactory.Create())
     .As <IEventStoreConnection>();
     containerBuilder.RegisterType <Repository>().As <IRepository>();
     containerBuilder.RegisterConsumers(Assembly.GetEntryAssembly());
     containerBuilder.RegisterGeneric(typeof(AutofacConsumerFactory <>))
     .WithParameter(new NamedParameter("name", "message"))
     .As(typeof(IConsumerFactory <>))
     .InstancePerLifetimeScope();
     containerBuilder.Register((c) =>
     {
         var busControl = BusConfigurator.Instance.ConfigureBus((cfg, host) =>
         {
             ConfigureEndPoints(cfg, host, c);
         });
         busControl.Start();
         return(busControl);
     }).SingleInstance().AutoActivate();
 }
예제 #20
0
        public static IServiceCollection AddEasyEventSourcing <TAggregateRoot>(this IServiceCollection services,
                                                                               EventStoreOptions options = null) where TAggregateRoot : IAggregate
        {
            services = services ?? throw new ArgumentNullException(nameof(services));
            options  = options ?? EventStoreOptions.Create();

            var connection        = EventStoreConnectionFactory.Create(options.ConnectionString);
            var eventDeserializer = new EventDeserializer(typeof(TAggregateRoot).GetTypeInfo().Assembly);
            var projections       = new EventStoreProjectionsClient(options);

            services.AddSingleton(connection);
            services.AddSingleton(eventDeserializer);

            services.AddSingleton <IEventStoreProjections>(projections);
            services.AddSingleton <IEventStoreBus>(new EventStoreSubscription(connection, options, eventDeserializer, projections));

            services.AddTransient <IRepository, EventStoreRepository>();
            services.AddTransient <IEventStore, EventStoreRepository>();

            return(services);
        }
예제 #21
0
        /// <summary>
        /// Method called when jobhost starts.
        /// </summary>
        /// <param name="context"></param>
        public void Initialize(ExtensionConfigContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }

            if (EventStoreConnectionFactory == null)
            {
                EventStoreConnectionFactory = new EventStoreConnectionFactory();
            }

            if (UserCredentialFactory == null)
            {
                UserCredentialFactory = new UserCredentialFactory();
            }

            if (MaxLiveQueueSize == 0)
            {
                MaxLiveQueueSize = 200;
            }

            _eventStoreSubscription = new EventStoreCatchUpSubscriptionObservable(EventStoreConnectionFactory.Create(ConnectionString),
                                                                                  LastPosition,
                                                                                  MaxLiveQueueSize,
                                                                                  UserCredentialFactory.CreateAdminCredentials(Username, Password),
                                                                                  context.Trace);

            var triggerBindingProvider = new EventTriggerAttributeBindingProvider <EventTriggerAttribute>(
                BuildListener, context.Config, context.Trace);

            var liveProcessingStartedBindingProvider = new LiveProcessingStartedAttributeBindingProvider(
                BuildListener, context.Trace);

            // Register our extension binding providers
            context.Config.RegisterBindingExtensions(
                triggerBindingProvider);
            context.Config.RegisterBindingExtensions(
                liveProcessingStartedBindingProvider);
        }
예제 #22
0
        static async Task Main(string[] args)
        {
            var eventStoreSubscriptionConnection = EventStoreConnectionFactory.Create(
                new EventStoreSingleNodeConfiguration(),
                new ConsoleLogger(),
                "admin", "changeit");

            await eventStoreSubscriptionConnection.ConnectAsync();

            var stopWatch = new Stopwatch();

            stopWatch.Start();

            var subscription = eventStoreSubscriptionConnection.SubscribeToAllFrom(null,
                                                                                   new CatchUpSubscriptionSettings(10000, 3000, false, false), EventAppeared);

            Console.ReadLine();

            //Console.WriteLine($"time: {stopWatch.ElapsedMilliseconds} ms, count: {_count}");

            Console.ReadLine();
        }
예제 #23
0
파일: Program.cs 프로젝트: JimmyBcn/quiz
        public static void Main(string[] args)
        {
            var quitEvent = new ManualResetEvent(false);

            Console.CancelKeyPress += (sender, eArgs) => {
                quitEvent.Set();
                eArgs.Cancel = true;
                Console.WriteLine("Application is shutting down...");
            };

            var builder       = new ConfigurationBuilder().AddEnvironmentVariables();
            var configuration = builder.Build();

            var options      = EventStoreOptions.Create(configuration);
            var typeResolver = new EventTypeResolver(ReflectionHelper.MessagesAssembly);
            var eventBus     = EventStoreConnectionFactory.Create(options.ConnectionString);

            eventBus.Subscribe(
                typeResolver, options.Subscription,
                msg =>
            {
                if (msg is QuestionRightAnsweredEvent rightEvent)
                {
                    Console.WriteLine($"Type:{rightEvent.GetType().Name}, OptionId:{rightEvent.OptionId}, QuestionId: {rightEvent.QuestionId}");
                }

                if (msg is QuestionWrongAnsweredEvent wrongEvent)
                {
                    Console.WriteLine($"Type:{wrongEvent.GetType().Name}, OptionId:{wrongEvent.OptionId}, QuestionId: {wrongEvent.QuestionId}");
                }
            })
            .Wait();

            Console.Write("Application started. Press Ctrl+C to shut down.");
            quitEvent.WaitOne();
        }
 public EventStoreConnectionProvider()
 {
     Connection = EventStoreConnectionFactory.Create(
         "ConnectTo=tcp://localhost:1113",
         "admin", "changeit");
 }