Beispiel #1
0
        public async Task Crate()
        {
            #region CreatePersistentSubscription

            var userCredentials = new UserCredentials("admin", "changeit");

            var settings = PersistentSubscriptionSettings
                           .Create()
                           .DoNotResolveLinkTos()
                           .StartFromCurrent();

            await conn.CreatePersistentSubscriptionAsync(
                "myStream",
                "grour1",
                settings,
                userCredentials
                );

            var subscription = await conn.ConnectToPersistentSubscriptionAsync(
                "myStream",
                "group1",
                (_, evt) => Console.WriteLine($"Received: {Encoding.UTF8.GetString(evt.Event.Data)}")
                );

            #endregion CreatePersistentSubscription
        }
Beispiel #2
0
        public static async Task <int> Main(string[] args)
        {
            // enumerate all streams
            IEventStoreConnection conn = EventStoreConnection.Create(connection);

            await Task.Run(() => conn.ConnectAsync());

            try
            {
                await conn.CreatePersistentSubscriptionAsync(stream, group,
                                                             PersistentSubscriptionSettings.Create(), null);
            }
            catch
            {
            }

            dynamic ps = conn.ConnectToPersistentSubscription(stream, group,
                                                              (s, e) => Process(s, e),
                                                              (s, r, ex) => HandleException(s, r, ex),
                                                              null,
                                                              2,
                                                              false);

            Console.ReadKey();
        }
Beispiel #3
0
 private PersistentSubscriptionSettings CreateSettings()
 => PersistentSubscriptionSettings
 .Create()
 .DoNotResolveLinkTos()
 .WithNamedConsumerStrategy(SystemConsumerStrategies.DispatchToSingle)
 .StartFrom(ProcessedEventCountHandler.ReadNumberOfProcessedEvents())
 .Build();
Beispiel #4
0
        private async Task CreateSubscription(IEventStoreConnection connection, string stream, string group)
        {
            var persistentSubscriptionSettings = PersistentSubscriptionSettings.Create().DoNotResolveLinkTos().StartFromCurrent();
            var userCredentials = new UserCredentials("admin", "changeit");

            await connection.CreatePersistentSubscriptionAsync(stream, group, persistentSubscriptionSettings, userCredentials);
        }
        public void Test()
        {
            var settings = PersistentSubscriptionSettings
                           .Create()
                           .StartFromCurrent()
                           .ResolveLinkTos()
                           .Build();

            _conn.CreatePersistentSubscriptionAsync(StreamName, GroupName, settings, DefaultData.AdminCredentials)
            .Wait();
            _conn.ConnectToPersistentSubscription(StreamName, GroupName,
                                                  (subscription, resolvedEvent) =>
            {
                if (Interlocked.Increment(ref _eventReceivedCount) == EventWriteCount)
                {
                    _eventsReceived.Set();
                }
                return(Task.CompletedTask);
            },
                                                  (sub, reason, exception) =>
                                                  Console.WriteLine("Subscription dropped (reason:{0}, exception:{1}).", reason, exception),
                                                  userCredentials: DefaultData.AdminCredentials);

            for (var i = 0; i < EventWriteCount; i++)
            {
                var eventData = new EventData(Guid.NewGuid(), "SomeEvent", false, new byte[0], new byte[0]);

                _conn.AppendToStreamAsync(StreamName, ExpectedVersion.Any, DefaultData.AdminCredentials, eventData);
            }

            if (!_eventsReceived.WaitOne(TimeSpan.FromSeconds(5)))
            {
                throw new Exception("Timed out waiting for events.");
            }
        }
        protected override async Task When()
        {
            var task = new TaskCompletionSource <string>();

            var setts = PersistentSubscriptionSettings.Create()
                        .ResolveLinkTos()
                        .StartFromBeginning();

            await _conn.CreatePersistentSubscriptionAsync("link", "Agroup", setts, DefaultData.AdminCredentials);

            await _conn.ConnectToPersistentSubscriptionAsync(
                "link",
                "Agroup",
                (sub, @event) => {
                var data = Encoding.Default.GetString(@event.Event.Data);
                task.TrySetResult(data);
                return(Task.CompletedTask);
            },
                (sub, reason, ex) => { }, DefaultData.AdminCredentials);

            await _conn.AppendToStreamAsync("target@me@com", ExpectedVersion.NoStream, TestEvent.NewTestEvent("data", eventName: "AEvent"));

            await _conn.AppendToStreamAsync("link", ExpectedVersion.NoStream, TestEvent.NewTestEvent("0@target@me@com", eventName: "$>"));

            _result = await Task.WhenAny(task.Task, Task.Delay(TimeSpan.FromSeconds(30)).ContinueWith(_ => "timeout")).Result;
        }
        private void CreateStream()
        {
            var settings = PersistentSubscriptionSettings.Create();

            _connectionES.CreatePersistentSubscriptionAsync(streamName, "PictureScan", settings, _connectionES.Settings.DefaultUserCredentials);
            SetPermisions();
        }
        private static async Task AccountCreatedEventAppeared(
            EventStorePersistentSubscriptionBase eventStorePersistentSubscriptionBase, ResolvedEvent resolvedEvent)
        {
            var accountEvent = ConvertEventDataToAccountDomainEvent(resolvedEvent);

            if (accountEvent == null)
            {
                return;
            }

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

            await _subscriptionConnection.ConnectToPersistentSubscriptionAsync($"Account-{accountEvent.StreamId}", "InvoiceGeneration", AccountEventAppeared);
        }
        protected override async Task OnInitializedAsync()
        {
            await base.OnInitializedAsync();

            Counters.Clear();

            var subSettings = PersistentSubscriptionSettings.Create()
                              .ResolveLinkTos()
                              .StartFromBeginning()
                              .Build();

            try {
                await Connection.CreatePersistentSubscriptionAsync(_subscriptionStream,
                                                                   _channel,
                                                                   subSettings,
                                                                   default);
            } catch (Exception) {
                await Connection.UpdatePersistentSubscriptionAsync(_subscriptionStream,
                                                                   _channel,
                                                                   subSettings,
                                                                   default);
            }

            _subscription = await Connection.ConnectToPersistentSubscriptionAsync(
                stream : _subscriptionStream,
                groupName : _channel,
                eventAppeared : async(sub, e, position) => {
                s_log.Information("Received counter-click.");
                await InvokeAsync(() => {
                    switch (e.Event.EventType)
                    {
                    case "counter-added":
                        var added = JsonSerializer.Deserialize <AddCounter>(new ReadOnlySpan <byte>(e.Event.Data));

                        Counters.Add(new Counter {
                            CounterId      = added.Id,
                            Label          = added.Label,
                            NumberOfClicks = 0
                        });

                        s_log.Information("Counter added.");
                        break;

                    case "counter-clicked":
                        var clickedOn = JsonSerializer.Deserialize <CounterClicked>(new ReadOnlySpan <byte>(e.Event.Data));
                        var counter   = Counters.SingleOrDefault(c => c.CounterId == clickedOn.CounterId);
                        if (counter != null)
                        {
                            s_log.Information("Counter entry found.  Adding +1 to value.");
                            counter.NumberOfClicks += 1;
                        }
                        s_log.Information("Counter clicked.");
                        break;
                    }

                    StateHasChanged();
                });
            },
                subscriptionDropped : (sub, reason, exc) => { },
                userCredentials : default
        public async Task <bool> ConnectRoundRobinPersistentSubscription(string stream, string group, CancellationToken token,
                                                                         Action <string, long, IFullEvent> callback, Func <Task> disconnected)
        {
            var clientsToken = CancellationTokenSource.CreateLinkedTokenSource(token);

            foreach (var client in _clients)
            {
                Logger.Write(LogLevel.Info,
                             () => $"Connecting to persistent subscription stream [{stream}] group [{group}] on client {client.Settings.GossipSeeds[0].EndPoint.Address}");


                var settings = PersistentSubscriptionSettings.Create()
                               .StartFromBeginning()
                               .WithMaxRetriesOf(10)
                               .WithReadBatchOf(_readSize)
                               .WithBufferSizeOf(_readSize * 3)
                               .WithLiveBufferSizeOf(_readSize)
                               .DontTimeoutMessages()
                               .CheckPointAfter(TimeSpan.FromSeconds(30))
                               .MaximumCheckPointCountOf(_readSize * 3)
                               .ResolveLinkTos()
                               .WithNamedConsumerStrategy(SystemConsumerStrategies.RoundRobin);
                if (_extraStats)
                {
                    settings.WithExtraStatistics();
                }

                try
                {
                    await client.CreatePersistentSubscriptionAsync(stream, group, settings,
                                                                   client.Settings.DefaultUserCredentials).ConfigureAwait(false);

                    Logger.Info($"Created ROUND ROBIN persistent subscription stream [{stream}] group [{group}]");
                }
                catch (InvalidOperationException)
                {
                    // Already created
                }


                try
                {
                    var subscription = await client.ConnectToPersistentSubscriptionAsync(stream, group,
                                                                                         eventAppeared : (sub, e) => EventAppeared(sub, e, clientsToken.Token, callback),
                                                                                         subscriptionDropped : (sub, reason, ex) => SubscriptionDropped(sub, reason, ex, disconnected),
                                                                                         // Let us accept large number of unacknowledged events
                                                                                         bufferSize : _readSize,
                                                                                         autoAck : false).ConfigureAwait(false);

                    lock (_subLock) _persistentSubs.Add(subscription);
                    Logger.Write(LogLevel.Info,
                                 () => $"Connected to persistent subscription stream [{stream}] group [{group}] on client {client.Settings.GossipSeeds[0].EndPoint.Address}");
                }
                catch (OperationTimedOutException)
                {
                    return(false);
                }
            }
            return(true);
        }
        public async Task Subscribe(string streamName, Func <Guid, object, Task> messageSender)
        {
            await DefaultRetryAsync(() => SubscribeImpl());

            async Task SubscribeImpl()
            {
                await CreateSubscription();

                await _conn.ConnectToPersistentSubscriptionAsync(
                    streamName, _options.GroupSubscription,
                    (_, x) => messageSender(
                        GetAggregateId(x.Event.EventStreamId),
                        _eventDeserializer.Deserialize(x.Event)));

                Guid GetAggregateId(string streamId)
                {
                    var streamIdParts = streamId.Split('-');

                    return(streamIdParts.Length == 2
                            ? Guid.TryParse(streamIdParts[1], out Guid aggregateId)
                                ? aggregateId
                                : Guid.Empty
                            : Guid.Empty);
                }

                async Task CreateSubscription()
                {
                    var settings = PersistentSubscriptionSettings.Create()
                                   .ResolveLinkTos()
                                   .StartFromCurrent();

                    await _conn.CreatePersistentSubscriptionAsync(streamName, _options.GroupSubscription, settings, _options.Credentials);
                }
            }
        }
Beispiel #12
0
        static async Task Main(string[] args)
        {
            var builder = ConnectionSettings.Create()
                          .UseConsoleLogger();

            var conn = EventStoreConnection.Create("ConnectTo=tcp://admin:changeit@localhost:1113", builder);

            await conn.ConnectAsync();

            const string streamName = "e-commerce-stream";
            const string groupName  = "start-from-beg";

            var settings = PersistentSubscriptionSettings.Create()
                           .DoNotResolveLinkTos()
                           .StartFromBeginning();

            try
            {
                await conn.CreatePersistentSubscriptionAsync(streamName, groupName, settings, null);
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
            }

            await conn.ConnectToPersistentSubscriptionAsync(streamName, groupName, EventAppeared);

            Console.WriteLine("Waiting for events. Press a key to quit.");
            Console.ReadLine();
        }
Beispiel #13
0
        static async Task Step2Subs()
        {
            var conn = await Connection.CreateConnection();

            var streamName       = Globals.StreamName;
            var adminCredentials = Globals.AdminCredentials;

            #region PersistentSubscription
            var settings = PersistentSubscriptionSettings
                           .Create()
                           .DoNotResolveLinkTos()
                           .StartFromCurrent();

            await conn.CreatePersistentSubscriptionAsync(streamName, "examplegroup", settings, adminCredentials);

            await conn.ConnectToPersistentSubscriptionAsync(
                streamName,
                "examplegroup",
                (_, x) =>
            {
                var data = Encoding.ASCII.GetString(x.Event.Data);
                Console.WriteLine($"Received: {x.Event.EventStreamId}:{x.Event.EventNumber}");
                Console.WriteLine(data);
            },
                (sub, reason, ex) => { },
                adminCredentials
                );

            Console.WriteLine("waiting for events. press enter to exit");
            Console.ReadLine();
            #endregion PersistentSubscription
        }
Beispiel #14
0
        public async Task CreatePersistentSubscriptionAsync(string stream, string group)
        {
            _logger.LogDebug("CreatePersistentSubscriptionAsync {Stream} {Group}", stream, group);

            var manager = _provider.CreatePersistentSubscriptionsManager();
            var cred    = _provider.AdminCredentials;

            //var con = await _provider.GetActiveConnection().ConfigureAwait(false);
            var con = _provider.GetActiveConnection();

            var list = await manager.List(cred).ConfigureAwait(false);

            var exists = list.Any(x => string.Equals(x.EventStreamId, stream) &&
                                  string.Equals(x.GroupName, group));

            if (!exists)
            {
                _logger.LogInformation("Creating PersistentSubscription {Group} on {Stream}", group, stream);

                PersistentSubscriptionSettings settings = PersistentSubscriptionSettings.Create()
                                                          .DoNotResolveLinkTos()
                                                          .StartFromBeginning();

                //   configure?.Invoke(settings);

                await con.CreatePersistentSubscriptionAsync(stream, @group, settings, cred).ConfigureAwait(false);
            }
            else
            {
                _logger.LogDebug("PersistensSubscription {Group} on {Stream} exists", group, stream);
            }
        }
Beispiel #15
0
        public void should_be_able_to_connect_to_persistent_subscription()
        {
            var groupId  = "group-" + Guid.NewGuid().ToString();
            var settings = PersistentSubscriptionSettings.Create().StartFrom(intMaxValue);

            Assert.DoesNotThrow(() => _store.CreatePersistentSubscriptionAsync(_streamId, groupId, settings, DefaultData.AdminCredentials).Wait());

            var evnt = new EventData(Guid.NewGuid(), "EventType", false, new byte[10], new byte[15]);
            List <EventStore.ClientAPI.ResolvedEvent> receivedEvents = new List <EventStore.ClientAPI.ResolvedEvent>();
            var countdown = new CountdownEvent(3);

            _store.ConnectToPersistentSubscriptionAsync(_streamId, groupId, (s, e) => {
                receivedEvents.Add(e);
                countdown.Signal();
                return(Task.CompletedTask);
            }).Wait();

            _store.AppendToStreamAsync(_streamId, intMaxValue + 2, evnt).Wait();

            Assert.That(countdown.Wait(TimeSpan.FromSeconds(5)), "Timed out waiting for events to appear");

            Assert.AreEqual(_r1.EventId, receivedEvents[0].Event.EventId);
            Assert.AreEqual(_r2.EventId, receivedEvents[1].Event.EventId);
            Assert.AreEqual(evnt.EventId, receivedEvents[2].Event.EventId);
        }
Beispiel #16
0
        public void should_be_able_to_create_the_persistent_subscription()
        {
            var groupId  = "group-" + Guid.NewGuid().ToString();
            var settings = PersistentSubscriptionSettings.Create().StartFrom(intMaxValue);

            Assert.DoesNotThrow(() => _store.CreatePersistentSubscriptionAsync(_streamId, groupId, settings, DefaultData.AdminCredentials).Wait());
        }
Beispiel #17
0
        /// <summary>
        /// Transforms the <see cref="SubscriptionOptionsDto"/> into a new <see cref="PersistentSubscriptionSettings"/>
        /// </summary>
        /// <param name="subscriptionOptions">The <see cref="SubscriptionOptionsDto"/> to transform</param>
        /// <returns>A new <see cref="PersistentSubscriptionSettings"/></returns>
        public static PersistentSubscriptionSettings ToPersistentSubscriptionSettings(this SubscriptionOptionsDto subscriptionOptions)
        {
            PersistentSubscriptionSettingsBuilder builder = PersistentSubscriptionSettings.Create();

            if (subscriptionOptions.StreamPosition.HasValue)
            {
                switch (subscriptionOptions.StreamPosition.Value)
                {
                case StreamPosition.Start:
                    builder.StartFromBeginning();
                    break;

                case StreamPosition.End:
                    builder.StartFromCurrent();
                    break;

                default:
                    builder.StartFrom(subscriptionOptions.StreamPosition.Value);
                    break;
                }
            }
            builder.ResolveLinkTos();
            builder.WithMaxSubscriberCountOf(1);
            builder.MinimumCheckPointCountOf(1);
            builder.MaximumCheckPointCountOf(1);
            return(builder.Build());
        }
        /// <summary>
        /// Creates the persistent subscription from position.
        /// </summary>
        /// <param name="stream">The stream.</param>
        /// <param name="groupName">Name of the group.</param>
        /// <param name="position">The position.</param>
        /// <returns></returns>
        public async Task CreatePersistentSubscriptionFromPosition(String stream, String groupName, Int32 position)
        {
            PersistentSubscriptionSettingsBuilder settingsBuilder = PersistentSubscriptionSettings.Create()
                                                                    .ResolveLinkTos().WithMaxRetriesOf(10).WithMessageTimeoutOf(TimeSpan.FromSeconds(10)).StartFrom(position);

            await this.CreatePersistentSubscription(stream, groupName, settingsBuilder.Build());
        }
Beispiel #19
0
        private static async Task CreateSubscription(IEventStoreConnection conn, EventStoreOptions options)
        {
            var settings = PersistentSubscriptionSettings.Create()
                           .ResolveLinkTos()
                           .StartFromCurrent();

            await conn.CreatePersistentSubscriptionAsync(options.Subscription.stream, options.Subscription.group, settings, options.Credentials);
        }
        public async Task with_credentials(bool useSsl)
        {
            var streamName = $"{GetStreamName()}_{useSsl}";
            var connection = _fixture.Connections[useSsl];

            await connection.CreatePersistentSubscriptionAsync(streamName, Group,
                                                               PersistentSubscriptionSettings.Create(), DefaultUserCredentials.Admin).WithTimeout();
        }
        public async Task should_be_able_to_update_the_persistent_subscription()
        {
            var groupId  = "group-" + Guid.NewGuid().ToString();
            var settings = PersistentSubscriptionSettings.Create();
            await _store.CreatePersistentSubscriptionAsync(_streamId, groupId, settings, DefaultData.AdminCredentials);

            settings = PersistentSubscriptionSettings.Create().StartFrom(intMaxValue);
            await _store.UpdatePersistentSubscriptionAsync(_streamId, groupId, settings, DefaultData.AdminCredentials);
        }
        public async Task without_credentials_throws(bool useSsl)
        {
            var streamName = $"{GetStreamName()}_{useSsl}";
            var connection = _fixture.Connections[useSsl];

            await Assert.ThrowsAsync <AccessDeniedException>(() => connection.CreatePersistentSubscriptionAsync(
                                                                 streamName, Group,
                                                                 PersistentSubscriptionSettings.Create(), null).WithTimeout());
        }
        public async Task persistent_subscription_delivers_all_events(int iteration)
        {
            const int eventCount  = 250;
            const int totalEvents = eventCount * 2;
            EventStorePersistentSubscriptionBase subscription = null;

            try {
                var userCredentials = new UserCredentials("admin", "changeit");

                int hitCount = 0;

                var streamName       = $"stream_{iteration}";
                var subscriptionName = $"subscription_{iteration}";

                var completed = new AutoResetEvent(false);

                var connection = _fixture.Connection;

                for (var i = 0; i < eventCount; i++)
                {
                    await connection.AppendToStreamAsync(streamName, ExpectedVersion.Any, _fixture.CreateTestEvents())
                    .WithTimeout();
                }

                var builder = PersistentSubscriptionSettings.Create()
                              .StartFromBeginning()
                              .ResolveLinkTos();

                await connection.CreatePersistentSubscriptionAsync(streamName,
                                                                   subscriptionName,
                                                                   builder.Build(),
                                                                   userCredentials).WithTimeout();

                subscription = await connection.ConnectToPersistentSubscriptionAsync(streamName, subscriptionName,
                                                                                     (_, resolvedEvent) => {
                    var result = Interlocked.Increment(ref hitCount);
                    _.Acknowledge(resolvedEvent);

                    if (totalEvents == result)
                    {
                        completed.Set();
                    }
                });

                for (var i = 0; i < eventCount; i++)
                {
                    await connection.AppendToStreamAsync(streamName, ExpectedVersion.Any, _fixture.CreateTestEvents())
                    .WithTimeout();
                }

                completed.WaitOne(TimeSpan.FromSeconds(30));
                Assert.Equal(totalEvents, hitCount);
            } finally {
                subscription?.Stop(TimeSpan.FromSeconds(5));
            }
        }
Beispiel #24
0
        public void Test() => Assert.DoesNotThrowAsync(async() => {
            _attempts++;
            if (_attempts == 1)
            {
                throw new Exception("throw on first attempt to ensure retry is working");
            }

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

            var streamName = Guid.NewGuid().ToString();
            var groupName  = Guid.NewGuid().ToString();
            var settings   = PersistentSubscriptionSettings
                             .Create()
                             .StartFromCurrent()
                             .WithMaxRetriesOf(0)    // Don't retry messages
                             .Build();

            await _conn.CreatePersistentSubscriptionAsync(streamName, groupName, settings, DefaultData.AdminCredentials);
            await _conn.ConnectToPersistentSubscriptionAsync(streamName, groupName,
                                                             (subscription, resolvedEvent) => {
                _conn.Close();
                return(Task.CompletedTask);
            },
                                                             (sub, reason, exception) => {
                Console.WriteLine("Subscription dropped (reason:{0}, exception:{1}).", reason, exception);
                _subscriptionDropped.TrySetResult(true);
            },
                                                             bufferSize: 10, autoAck: false, userCredentials: DefaultData.AdminCredentials);

            var parkedEventData = new EventData(Guid.NewGuid(), "SomeEvent", false, new byte[0], new byte[0]);
            await _conn.AppendToStreamAsync(streamName, ExpectedVersion.Any, DefaultData.AdminCredentials, parkedEventData);

            await _subscriptionDropped.Task.WithTimeout();

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

            await _conn.ConnectToPersistentSubscriptionAsync(streamName, groupName, (subscription, resolvedEvent) => {
                subscription.Acknowledge(resolvedEvent);
                _receivedEvent = resolvedEvent;
                _eventReceived.TrySetResult(true);
            }, (sub, reason, exception) => {
                Console.WriteLine("Second Subscription dropped (reason:{0}, exception:{1}).", reason, exception);
            }, bufferSize: 10, autoAck: false, userCredentials: DefaultData.AdminCredentials);

            // Ensure we only get the new event, not the previous one
            var newEventData = new EventData(Guid.NewGuid(), "SomeEvent", false, new byte[0], new byte[0]);
            await _conn.AppendToStreamAsync(streamName, ExpectedVersion.Any, DefaultData.AdminCredentials, newEventData);

            await _eventReceived.Task.WithTimeout();
            Assert.AreEqual(newEventData.EventId, _receivedEvent.Event.EventId);
        });
        static async Task Main(string[] args)
        {
            var streamName      = "tcp-person-stream";
            var groupName       = "tcp-subscription-group";
            var userCredentials = new UserCredentials("admin", "changeit");

            var connection = CreateEventStoreConnection(userCredentials.Username, userCredentials.Password);

            /*
             * do not resolve linktos (todo: add explanation here. reference blog article.
             * start subscription from current position in stream,
             * - meaning only act on events coming in after this subscription is created.
             * - you can start from the beginning, StartFromBeginning, or any given position
             */
            var settings = PersistentSubscriptionSettings
                           .Create()
                           .DoNotResolveLinkTos()
                           .StartFromCurrent();

            /*
             * since a subscription might already have been created
             * we need to wrap the creation, catch the exception and "silence" it.
             */
            try
            {
                await connection.CreatePersistentSubscriptionAsync(
                    streamName,
                    groupName,
                    settings,
                    userCredentials
                    );
            }
            catch (InvalidOperationException e)
                when(e.Message.Contains($"Subscription group {groupName} on stream {streamName} already exists")
                     )
                {
                    //InvalidOperationException: Subscription group tcp-subscription-group on stream tcp-person-stream already exists
                    Console.WriteLine($"subscription {groupName} already exist, continuing");
                }

            /*
             * as long as the console is not closed the subscription will log new events
             */
            var subscription = connection.ConnectToPersistentSubscriptionAsync(
                stream: streamName,
                groupName: groupName,
                eventAppeared: (_, resolvedEvent) =>
            {
                Console.WriteLine("Received: " + Encoding.UTF8.GetString(resolvedEvent.Event.Data));
            }).Result;

            Console.WriteLine($"waiting... new events in stream '{streamName}' will be logged to the console. press Enter to Quit");
            Console.Read();
        }
Beispiel #26
0
        public async Task that_does_exist_succeeds(bool useSsl)
        {
            var streamName = $"{GetStreamName()}_{useSsl}";
            var connection = _fixture.Connections[useSsl];

            await connection.CreatePersistentSubscriptionAsync(streamName, Group,
                                                               PersistentSubscriptionSettings.Create(), DefaultUserCredentials.Admin).WithTimeout();

            await connection.ConnectToPersistentSubscriptionAsync(streamName, Group,
                                                                  delegate { return(Task.CompletedTask); }).WithTimeout();
        }
Beispiel #27
0
 private static void CreatePersistentSubscription(IEventStoreConnection conn)
 {
     try
     {
         conn.CreatePersistentSubscriptionAsync(StreamName, GroupName, PersistentSubscriptionSettings.Create().StartFromBeginning(),
                                                new UserCredentials("admin", "changeit")).Wait();
     }
     catch (Exception e)
     {
         // Already exist
     }
 }
Beispiel #28
0
        public static void Method()
        {
            var userCredentials = new UserCredentials("admin", "changeit");
            var settings        = PersistentSubscriptionSettings.Create()
                                  .DoNotResolveLinkTos().StartFromCurrent();

            conn.CreatePersistentSubscriptionAsync("newstream", "gr1", settings, userCredentials).Wait();
            var subscription = conn.ConnectToPersistentSubscriptionAsync(
                "newstream", "gr1", (_, evt) =>
            {
                Console.WriteLine("Received: " + Encoding.UTF8.GetString(evt.Event.Data));
            }).Result;
        }
 private async Task EnsureSubscriptionExists(string queue, IEventStoreConnection connection)
 {
     try
     {
         await connection.CreatePersistentSubscriptionAsync(queue, queue, PersistentSubscriptionSettings.Create(), null).ConfigureAwait(false);
     }
     catch (Exception ex)
     {
         if (ex.Message != string.Format("Subscription group {0} on stream {0} already exists", queue))
         {
             throw;
         }
     }
 }
Beispiel #30
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();
        }