public void NotifyOfPackageDelivery(Package package)
        {
            const string stream = "Package-delivery-stream";

            var settings = EventStoreClientSettings
                           .Create("esdb://127.0.0.1:2113?tls=false");

            var packageDeliveryInfo = new PackageDeliveryInfo
            {
                Number = package.Number,

                RecipientName         = package.RecipientName,
                RecipientEmail        = package.RecipientEmail,
                RecipientSurname      = package.RecipientSurname,
                RecipientStreet       = package.RecipientStreet,
                RecipientStreetNumber = package.RecipientStreetNumber,
                RecipientPostCode     = package.RecipientPostCode,
                RecipientCity         = package.RecipientCity,

                SenderEmail = package.Sender.Email,
            };

            using (var client = new EventStoreClient(settings))
            {
                client.AppendToStreamAsync(
                    stream,
                    StreamState.Any,
                    new[] { GetEventDataFor(packageDeliveryInfo) }).Wait();
            }
        }
        public EventStoreReadOnlyRepository(IHoldAllConfiguration configs, EventStoreClient esClient)
        {
            new EventStoreClient(EventStoreClientSettings.Create("esdb://localhost:2113?tls=false"));
            this.configs = configs ?? throw new ArgumentNullException(nameof(configs));

            reader = new EventReader(esClient, configs);
        }
Beispiel #3
0
        public async Task SaveAndGetEventsInChunks()
        {
            Random random = new Random();

            Guid id = random.NextGuid();
            PseudoAggregateRoot aggregateRoot = PseudoAggregateRoot.Create(id, "my name");

            Int32 amount = 10_000;

            for (int i = 0; i < amount; i++)
            {
                aggregateRoot.ChangeName($"iteration {i}");
            }

            var settings = EventStoreClientSettings.Create("esdb://127.0.0.1:2113?tls=false");
            var client   = new EventStoreClient(settings);

            String prefix = random.GetAlphanumericString();

            EventStoreBasedStore store = new(new EventStoreBasedStoreConnenctionOptions(client, prefix));

            try
            {
                await store.Save(aggregateRoot);

                var events = await store.GetEvents <PseudoAggregateRoot>(id, 10);

                Assert.Equal(amount + 1, events.Count());
                Assert.Equal($"iteration {amount - 1}", ((PseudoAggregateRootNameChangedEvent)events.Last()).SecondName);
            }
            finally
            {
                await EventStoreClientDisposer.CleanUp(prefix, settings);
            }
        }
        protected async Task ExecuteAsync(CancellationToken cancellationToken)
        {
            #region createClient
            var settings = EventStoreClientSettings
                           .Create("{connectionString}");
            var client = new EventStoreClient(settings);
            #endregion createClient

            #region createEvent
            var evt = new TestEvent {
                EntityId      = Guid.NewGuid().ToString("N"),
                ImportantData = "I wrote my first event!"
            };

            var eventData = new EventData(
                Uuid.NewUuid(),
                "TestEvent",
                JsonSerializer.SerializeToUtf8Bytes(evt)
                );
            #endregion createEvent

            #region writingEvent
            await client.AppendToStreamAsync(
                "testStream",
                StreamState.Any,
                new[] { eventData },
                cancellationToken : cancellationToken
                );

            #endregion writingEvent
        }
Beispiel #5
0
        private static EventStoreClient CreateClientWithConnection(string connectionString, ILoggerFactory loggerFactory)
        {
            var settings = EventStoreClientSettings.Create(connectionString);

            settings.LoggerFactory = loggerFactory;
            return(new EventStoreClient(settings));
        }
Beispiel #6
0
    EventStoreClient GetEventStore()
    {
        const string connectionString =
            "esdb://localhost:2113?tls=false";

        return(new EventStoreClient(EventStoreClientSettings.Create(connectionString)));
    }
        static async Task Main(string[] args)
        {
            // run against
            // .\EventStore-OSS-Windows-2019-v20.6.1\EventStore.ClusterNode.exe --insecure
            // make sure http://localhost:2113 works
            var connectionString = "esdb://*****:*****@localhost:2113/?TlsVerifyCert=false&Tls=false";

            // run against
            // .\EventStore-OSS-Windows-2019-v20.6.0\EventStore.ClusterNode.exe --dev
            // make sure https://localhost:2113 works
            //var connectionString = "esdb://*****:*****@localhost:2113/?TlsVerifyCert=false";

            var settings = EventStoreClientSettings.Create(connectionString);
            var client   = new EventStoreClient(settings);

            await client.SubscribeToAllAsync(EventAppeared);

            Console.WriteLine("Subscribed to all events.");

            var data      = Encoding.UTF8.GetBytes("{}");
            var eventData = new EventData(Uuid.NewUuid(), "test-event", data);
            await client.AppendToStreamAsync("test-events", StreamState.Any, new[] { eventData });

            Console.WriteLine("Keypress to exit.");
            Console.ReadKey();
        }
Beispiel #8
0
        private HttpClient GetTestClient(String dbfileName, String eventStorePrefix)
        {
            var client = _factory.WithWebHostBuilder(builder =>
            {
                String currentPath = System.IO.Path.GetFullPath(".");
                Int32 startIndex   = currentPath.IndexOf("Beer.DaAPI.Service.IntegrationTests");
                String basePath    = currentPath.Substring(0, startIndex) + "Beer.DaAPI.Service.API";


                builder.UseStartup <FakeStartup>();
                builder.UseContentRoot(basePath);
                builder.ConfigureTestServices(services =>
                {
                    AddFakeAuthentication(services, "Bearer");
                    AddDatabase(services, dbfileName);

                    var settings = EventStoreClientSettings.Create("esdb://127.0.0.1:2113?tls=false");
                    var client   = new EventStoreClient(settings);

                    ReplaceService(services, new EventStoreBasedStoreConnenctionOptions(client, eventStorePrefix));
                });
            }).CreateClient();

            return(client);
        }
Beispiel #9
0
        public static async Task WithEventStore()
        {
            var connectionString = "esdb://localhost:2113?tls=true&tlsVerifyCert=false";
            var settings         = EventStoreClientSettings.Create(connectionString);

            settings.DefaultCredentials = new UserCredentials("admin", "changeit");
            var esClient = new EventStoreClient(settings);
            var esPersistenSubscriptionClient = new EventStorePersistentSubscriptionsClient(settings);

            var projection = await CreateProjection(settings, persistent : true);

            Console.ReadLine();

            repository = new EventStoreRepository <Counter>(esClient);

            for (int i = 0; i < 10; i++)
            {
                var counterId = Guid.NewGuid(); // Guid.Parse("fbb0f16b-646a-45d3-a1ee-596217897b61");
                await CreateAndSaveCounter(counterId);
                await LoadAndUpdateCounter(counterId);
            }

            Console.ReadLine();

            projection.Unsubscribe();
        }
        public EventStoreService(IOptions <EventStoreSettings> config)
        {
            var cnn      = string.IsNullOrWhiteSpace(config?.Value?.Connection) ? "esdb://localhost:2113?tls=false" : config.Value.Connection;
            var settings = EventStoreClientSettings.Create(cnn);

            Client = new EventStoreClient(settings);
            PersistentSubscription = new EventStorePersistentSubscriptionsClient(settings);
        }
        private static EventStoreClient ConfigureEventStore(string connectionString, ILoggerFactory loggerFactory)
        {
            var settings = EventStoreClientSettings.Create(connectionString);

            settings.ConnectionName = "eshopApp";
            settings.LoggerFactory  = loggerFactory;
            return(new EventStoreClient(settings));
        }
Beispiel #12
0
        public EventStoreFixture()
        {
            var settings = EventStoreClientSettings
                           .Create("esdb://localhost:2113?tls=false");

            Client = new EventStoreClient(settings);
            PersistentSubscription = new EventStorePersistentSubscriptionsClient(settings);
        }
Beispiel #13
0
        public GetEventStoreFixture()
        {
            AppContext.SetSwitch("System.Net.Http.SocketsHttpHandler.Http2UnencryptedSupport", true);

            settings = EventStoreClientSettings.Create(TestConfig.Configuration["eventStore:configuration"]);

            EventStore = new GetEventStore(settings, TestUtils.DefaultSerializer);
            EventStore.InitializeAsync(default).Wait();
        static async Task Main(string[] args)
        {
            CancellationTokenSource tokenSource       = new CancellationTokenSource();
            CancellationToken       cancellationToken = tokenSource.Token;

            #region createClient
            var settings = EventStoreClientSettings
                           .Create("{connectionString}");
            var client = new EventStoreClient(settings);
            #endregion createClient

            #region createEvent
            var evt = new TestEvent
            {
                EntityId      = Guid.NewGuid().ToString("N"),
                ImportantData = "I wrote my first event!"
            };

            var eventData = new EventData(
                Uuid.NewUuid(),
                "TestEvent",
                JsonSerializer.SerializeToUtf8Bytes(evt)
                );
            #endregion createEvent

            #region appendEvents
            await client.AppendToStreamAsync(
                "some-stream",
                StreamState.Any,
                new[] { eventData },
                cancellationToken : cancellationToken
                );

            #endregion appendEvents

            #region overriding-user-credentials
            await client.AppendToStreamAsync(
                "some-stream",
                StreamState.Any,
                new[] { eventData },
                userCredentials : new UserCredentials("admin", "changeit"),
                cancellationToken : cancellationToken
                );

            #endregion overriding-user-credentials

            #region readStream
            var result = client.ReadStreamAsync(
                Direction.Forwards,
                "some-stream",
                StreamPosition.Start,
                cancellationToken: cancellationToken);

            var events = await result.ToListAsync(cancellationToken);

            #endregion readStream
        }
        private static void ConnectingToAClusterComplex()
        {
            #region connecting-to-a-cluster-complex

            using var client = new EventStoreClient(
                      EventStoreClientSettings.Create("esdb://*****:*****@localhost:1114,localhost:2114,localhost:3114?DiscoveryInterval=30000;GossipTimeout=10000;NodePreference=leader;MaxDiscoverAttempts=5")
                      );
            #endregion connecting-to-a-cluster-complex
        }
        private static void ConnectingToACluster()
        {
            #region connecting-to-a-cluster

            using var client = new EventStoreClient(
                      EventStoreClientSettings.Create("esdb://localhost:1114,localhost:2114,localhost:3114")
                      );
            #endregion connecting-to-a-cluster
        }
Beispiel #17
0
        private static void SpecifyingAConnectionName()
        {
            #region setting-the-connection-name

            using var client = new EventStoreClient(
                      EventStoreClientSettings.Create("esdb://*****:*****@localhost:2113?ConnectionName=SomeConnection")
                      );
            #endregion setting-the-connection-name
        }
Beispiel #18
0
        private static void OverridingTheTimeout()
        {
            #region overriding-timeout

            using var client = new EventStoreClient(
                      EventStoreClientSettings.Create($"esdb://*****:*****@localhost:2113?OperationTimeout=30000")
                      );
            #endregion overriding-timeout
        }
Beispiel #19
0
        private static void SimpleConnection()
        {
            #region creating-simple-connection

            using var client = new EventStoreClient(
                      EventStoreClientSettings.Create("esdb://localhost:2113")
                      );
            #endregion creating-simple-connection
        }
Beispiel #20
0
        private static void ProvidingDefaultCredentials()
        {
            #region providing-default-credentials

            using var client = new EventStoreClient(
                      EventStoreClientSettings.Create("esdb://*****:*****@localhost:2113")
                      );
            #endregion providing-default-credentials
        }
Beispiel #21
0
 public PullRequestCommentsIntegrationTest(ITestOutputHelper output)
 {
     _output = output;
     _eventStore = new EventStoreClient(EventStoreClientSettings.Create("esdb://localhost:2113?tls=false"));
     _eventSerializer = new PullRequestCommentsEventSerializer();
     _guidGenerator = new GuidGenerator();
     var server = new TestServer(new WebHostBuilder().UseStartup<Startup>());
     _client = server.CreateClient();
 }
Beispiel #22
0
        static async Task Main(string[] args)
        {
            using var client = new EventStoreClient(
                      EventStoreClientSettings.Create("esdb://*****:*****@localhost:2113?TlsVerifyCert=false")
                      );

            await SubscribeToStream(client);
            await SubscribeToAll(client);
            await OverridingUserCredentials(client);
        }
        public AddSinglePullRequestControllerIntegrationTest()
        {
            _eventStore      = new EventStoreClient(EventStoreClientSettings.Create("esdb://localhost:2113?tls=false"));
            _eventSerializer = new AddSinglePullRequestCommentEventSerializer();
            _guidGenerator   = new GuidGenerator();
            var server = new TestServer(new WebHostBuilder().UseStartup <Startup>());

            _client = server.CreateClient();
            _clock  = server.Services.GetService <IClock>();
        }
Beispiel #24
0
        public static SubscriptionRepository Create(String eventStoreConnectionString, Int32 cacheDuration = 120)
        {
            EventStoreClientSettings settings = EventStoreClientSettings.Create(eventStoreConnectionString);
            HttpClient httpClient             = SubscriptionWorkerHelper.CreateHttpClient(settings);

            return(new SubscriptionRepository(cacheDuration)
            {
                GetAllSubscriptions = cancellationToken => SubscriptionRepository.GetSubscriptions(httpClient, cancellationToken)
            });
        }
        public static IServiceCollection AddEventStoreClient(this IServiceCollection services,
                                                             string connectionString, Action <EventStoreClientSettings>?configureSettings = null)
        {
            if (services == null)
            {
                throw new ArgumentNullException(nameof(services));
            }

            return(services.AddEventStoreClient(EventStoreClientSettings.Create(connectionString), configureSettings));
        }
Beispiel #26
0
        /// <summary>
        /// Creates a new gRPC client
        /// </summary>
        /// <returns></returns>
        public EventStoreClient CreateGrpcClient()
        {
            var connectionString = string.IsNullOrWhiteSpace(_options.ConnectionString)
                                ? $"esdb://{_options.Host}:{_options.HttpPort}?tls={_options.UseTls}&tlsVerifyCert={_options.TlsValidateServer}"
                                : _options.ConnectionString;

            _log.Debug("Creating gRPC client with connection string '{connectionString}'.", connectionString);
            var settings = EventStoreClientSettings.Create(connectionString);

            return(new EventStoreClient(settings));
        }
Beispiel #27
0
        private static async Task <EventStoreClient> SetupConnection()
        {
            var settings = EventStoreClientSettings
                           .Create("esdb://localhost:2113?tls=false");
            var client            = new EventStoreClient(settings);
            var projectionsClient = new EventStoreProjectionManagementClient(settings);
            await projectionsClient.EnableAsync("$by_category");

            await Task.Delay(TimeSpan.FromSeconds(3));

            return(client);
        }
        public static void AddEventStore(this IServiceCollection services, IConfiguration configuration)
        {
            var eventStoreConnectionString = configuration.GetConnectionString("EventStoreDb");
            var settings = EventStoreClientSettings.Create(eventStoreConnectionString);
            var client   = new EventStoreClient(settings);

            services.AddSingleton(client);

            services.AddTransient <IEventStore, EventStore>();
            services.AddTransient <IUserRepository, EventStoreUserRepository>();
            services.AddTransient <IGroupRepository, EventStoreGroupRepository>();
        }
Beispiel #29
0
        public static void AddSquidexEventSourcing(this IServiceCollection services, IConfiguration config)
        {
            config.ConfigureByOption("eventStore:type", new Alternatives
            {
                ["MongoDb"] = () =>
                {
                    var mongoConfiguration = config.GetRequiredValue("eventStore:mongoDb:configuration");
                    var mongoDatabaseName  = config.GetRequiredValue("eventStore:mongoDb:database");

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

                        return(new MongoEventStore(mongDatabase, c.GetRequiredService <IEventNotifier>()));
                    })
                    .As <IEventStore>();
                },
                ["GetEventStore"] = () =>
                {
                    var configuration = config.GetRequiredValue("eventStore:getEventStore:configuration");

                    services.AddSingletonAs(_ => EventStoreClientSettings.Create(configuration))
                    .AsSelf();

                    services.AddSingletonAs <GetEventStore>()
                    .As <IEventStore>();

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

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

            services.AddTransientAs <Rebuilder>()
            .AsSelf();

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

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

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

                return(new EventConsumerFactory(n => allEventConsumers.First(x => x.Name == n)));
            });
        }
 static async Task Main(string[] args)
 {
     using var client = new EventStorePersistentSubscriptionsClient(
               EventStoreClientSettings.Create("esdb://*****:*****@localhost:2113?TlsVerifyCert=false")
               );
     await CreatePersistentSubscription(client);
     await ConnectToPersistentSubscriptionToStream(client);
     await CreatePersistentSubscriptionToAll(client);
     await ConnectToPersistentSubscriptionToAll(client);
     await ConnectToPersistentSubscriptionWithManualAcks(client);
     await UpdatePersistentSubscription(client);
     await DeletePersistentSubscription(client);
 }