Пример #1
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();
        }
Пример #2
0
        static async Task Main(string[] args)
        {
            await SubscriptionsTest();

            EventStoreClientSettings settings = Program.ConfigureEventStoreSettings();

            EventStoreClient client = new(settings);


            EventStoreProjectionManagementClient projectionManagementClient = new EventStoreProjectionManagementClient(settings);

            //var x = await projectionManagementClient.GetStatusAsync("$by_category", cancellationToken: CancellationToken.None);

            IEventStoreContext context = new EventStoreContext(client, projectionManagementClient);
            IAggregateRepository <TestAggregate, DomainEvent> aggregateRepository = new AggregateRepository <TestAggregate, DomainEvent>(context);

            Guid          aggregateId = Guid.Parse("02398284-8284-8284-8284-165402398284");
            TestAggregate aggregate   = await aggregateRepository.GetLatestVersion(aggregateId, CancellationToken.None);

            aggregate.SetAggregateName("Test Name");
            //aggregate.SetAggregateName("Test Name1");
            //aggregate.SetAggregateName("Test Name2");
            //aggregate.SetAggregateName("Test Name3");
            //aggregate.SetAggregateName("Test Name4");

            await aggregateRepository.SaveChanges(aggregate, CancellationToken.None);

            //TestDockerHelper t = new TestDockerHelper();
            //await t.StartContainersForScenarioRun("");
        }
Пример #3
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);
        }
        private static EventStoreClient CreateEventStoreClientWithConnection()
        {
            /** https://discuss.eventstore.com/t/basic-eventstoredb-v20-example/2553
             *  read this for settings workaround for certificate issues when trying out the client
             *  I didn't have this problem but if you are running event store in --dev mode this might be an issue'
             * @see example code in .Writer project (same as in link above)
             */

            var settings = new EventStoreClientSettings
            {
                ConnectivitySettings = new EventStoreClientConnectivitySettings
                {
                    /*
                     * Note: gRPC uses the https and thus needs to use port 2113 (same as admin UI),
                     * instead of 1113 as the tcp client uses.
                     */
                    Address = new Uri("https://localhost:2113/")
                }
            };

            var client = new EventStoreClient(settings);

            return(client);

            /*
             *  In this example we used the EventStoreConnection.Create() overloaded method but others are available.
             * https://eventstore.com/docs/dotnet-api/code/EventStore.ClientAPI.EventStoreConnection.html
             *  instead of using tcp for the client connection gRPC is recommended. (but not yet in documentation)
             */
        }
        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);
        }
Пример #7
0
        private static EventStoreClientSettings ConfigureEventStoreSettings(Int32 eventStoreHttpPort)
        {
            String connectionString = $"http://127.0.0.1:{eventStoreHttpPort}";

            EventStoreClientSettings settings = new EventStoreClientSettings();

            settings.CreateHttpMessageHandler = () => new SocketsHttpHandler
            {
                SslOptions =
                {
                    RemoteCertificateValidationCallback = (sender,
                                                           certificate,
                                                           chain,
                                                           errors) => true,
                }
            };
            settings.ConnectionName       = "Specflow";
            settings.ConnectivitySettings = new EventStoreClientConnectivitySettings
            {
                Insecure = true,
                Address  = new Uri(connectionString),
            };

            settings.DefaultCredentials = new UserCredentials("admin", "changeit");
            return(settings);
        }
Пример #8
0
        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();
        }
Пример #9
0
    EventStoreClient GetEventStore()
    {
        const string connectionString =
            "esdb://localhost:2113?tls=false";

        return(new EventStoreClient(EventStoreClientSettings.Create(connectionString)));
    }
Пример #10
0
        public EventStoreOperationsClient(EventStoreClientSettings settings = null)
        {
            settings ??= new EventStoreClientSettings();
            var httpHandler = settings.CreateHttpMessageHandler?.Invoke() ?? new HttpClientHandler();

            _channel = GrpcChannel.ForAddress(settings.ConnectivitySettings.Address ?? new UriBuilder {
                Scheme = Uri.UriSchemeHttps,
                Port   = 2113
            }.Uri, new GrpcChannelOptions {
                HttpClient = new HttpClient(httpHandler)
                {
                    Timeout = Timeout.InfiniteTimeSpan,
                    DefaultRequestVersion = new Version(2, 0),
                },
                LoggerFactory = settings.LoggerFactory
            });
            var connectionName = settings.ConnectionName ?? $"ES-{Guid.NewGuid()}";

            var callInvoker = (settings.Interceptors ?? Array.Empty <Interceptor>()).Aggregate(
                _channel.CreateCallInvoker()
                .Intercept(new TypedExceptionInterceptor())
                .Intercept(new ConnectionNameInterceptor(connectionName)),
                (invoker, interceptor) => invoker.Intercept(interceptor));

            _client = new Operations.OperationsClient(callInvoker);
        }
Пример #11
0
        private static void ConfigureEventStoreSettings(EventStoreClientSettings settings = null)
        {
            if (settings == null)
            {
                settings = new EventStoreClientSettings();
            }

            settings.CreateHttpMessageHandler = () => new SocketsHttpHandler
            {
                SslOptions =
                {
                    RemoteCertificateValidationCallback = (sender,
                                                           certificate,
                                                           chain,
                                                           errors) => true,
                }
            };
            settings.ConnectionName       = Startup.Configuration.GetValue <String>("EventStoreSettings:ConnectionName");
            settings.ConnectivitySettings = new EventStoreClientConnectivitySettings
            {
                Address = new Uri(Startup.Configuration.GetValue <String>("EventStoreSettings:ConnectionString")),
            };

            settings.DefaultCredentials = new UserCredentials(Startup.Configuration.GetValue <String>("EventStoreSettings:UserName"),
                                                              Startup.Configuration.GetValue <String>("EventStoreSettings:Password"));
            Startup.EventStoreClientSettings = settings;
        }
Пример #12
0
        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
        }
Пример #13
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);
            }
        }
Пример #14
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;
        }
Пример #15
0
 /// <summary>
 /// Create a new EventStoreDB producer instance
 /// </summary>
 /// <param name="clientSettings">EventStoreDB gRPC client settings</param>
 /// <param name="serializer">Optional: event serializer instance</param>
 /// <param name="metaSerializer">Optional: metadata serializer instance</param>
 public EventStoreProducer(
     EventStoreClientSettings clientSettings,
     IEventSerializer?serializer        = null,
     IMetadataSerializer?metaSerializer = null
     ) : this(new EventStoreClient(Ensure.NotNull(clientSettings)), serializer, metaSerializer)
 {
 }
Пример #16
0
        private static EventStoreClient CreateClientWithConnection(string connectionString, ILoggerFactory loggerFactory)
        {
            var settings = EventStoreClientSettings.Create(connectionString);

            settings.LoggerFactory = loggerFactory;
            return(new EventStoreClient(settings));
        }
Пример #17
0
        public GetEventStore(EventStoreClientSettings settings, IJsonSerializer serializer)
        {
            this.serializer = serializer;

            client = new EventStoreClient(settings);

            projectionClient = new EventStoreProjectionClient(settings, StreamPrefix);
        }
Пример #18
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();
        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);
        }
Пример #20
0
        public EventStoreFixture()
        {
            var settings = EventStoreClientSettings
                           .Create("esdb://localhost:2113?tls=false");

            Client = new EventStoreClient(settings);
            PersistentSubscription = new EventStorePersistentSubscriptionsClient(settings);
        }
Пример #21
0
        private static EventStoreClient ConfigureEventStore(string connectionString, ILoggerFactory loggerFactory)
        {
            var settings = EventStoreClientSettings.Create(connectionString);

            settings.ConnectionName = "eshopApp";
            settings.LoggerFactory  = loggerFactory;
            return(new EventStoreClient(settings));
        }
Пример #22
0
        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
        }
Пример #23
0
        private static void OverridingTheTimeout()
        {
            #region overriding-timeout

            using var client = new EventStoreClient(
                      EventStoreClientSettings.Create($"esdb://*****:*****@localhost:2113?OperationTimeout=30000")
                      );
            #endregion overriding-timeout
        }
Пример #24
0
        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
        }
Пример #25
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
        }
Пример #26
0
        private static void ProvidingDefaultCredentials()
        {
            #region providing-default-credentials

            using var client = new EventStoreClient(
                      EventStoreClientSettings.Create("esdb://*****:*****@localhost:2113")
                      );
            #endregion providing-default-credentials
        }
Пример #27
0
        private static void SimpleConnection()
        {
            #region creating-simple-connection

            using var client = new EventStoreClient(
                      EventStoreClientSettings.Create("esdb://localhost:2113")
                      );
            #endregion creating-simple-connection
        }
Пример #28
0
        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
        }
Пример #29
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();
 }
        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));
        }