private Task PublishPurchaseFailure(SellTicketsRequest request, string concertName)
 {
     return(_eventPublisher.Publish(new PurchaseFailedEvent(
                                        Guid.NewGuid().ToString(),
                                        Guid.NewGuid().ToString(),
                                        request.ConcertId,
                                        concertName,
                                        request.BuyerId,
                                        request.Quantity)));
 }
Beispiel #2
0
 private void PublishDomainEvents(IEnumerable <DomainEvent> domainEvents)
 {
     foreach (var domainEvent in domainEvents)
     {
         _eventPublisher.Publish(domainEvent);
     }
 }
Beispiel #3
0
        /// <inheritdoc />
        public void Publish <T>(
            T @event,
            [CallerMemberName] string callerMemberName = "",
            [CallerFilePath] string callerFilePath     = "",
            [CallerLineNumber] int callerLineNumber    = -1) where T : TelemetryEvent
        {
            if (TopicPublisher != null && @event is DomainEvent)
            {
                TopicPublisher.Publish(@event).Wait();
            }

            if (@event is TelemetryEvent telemetryEvent)
            {
                telemetryEvent.CallerMemberName = callerMemberName;
                telemetryEvent.CallerFilePath   = callerFilePath;
                telemetryEvent.CallerLineNumber = callerLineNumber;
            }

            if (@event is TimedTelemetryEvent timedEvent)
            {
                timedEvent.End();
            }

            TelemetryStream.OnNext(@event);
        }
        public async Task CreateConcert(CreateConcertRequest request)
        {
            var concert = new Concert(request.Name, new TicketQuantity(request.SeatingCapacity));
            await _concertRepository.AddConcert(concert);

            await _eventPublisher.Publish(new ConcertCreatedEvent(Guid.NewGuid().ToString(), concert.Id, concert.Name, concert.SeatingCapacity));
        }
Beispiel #5
0
        public async Task SaveEvents(Guid aggregateId, IEnumerable <Event> events, int expectedVersion)
        {
            // Simulate I/O, avoid blocking thread pool thread
            await Task.CompletedTask;

            ConcurrentBag <EventDescriptor> eventDescriptors;

            // try to get event descriptors list for given aggregate id
            // otherwise -> create empty dictionary
            if (!_current.TryGetValue(aggregateId, out eventDescriptors))
            {
                eventDescriptors = new ConcurrentBag <EventDescriptor>();
                _current.TryAdd(aggregateId, eventDescriptors);
            }
            // check whether latest event version matches current aggregate version
            // otherwise -> throw exception
            else if (eventDescriptors.Last().Version != expectedVersion && expectedVersion != -1)//[eventDescriptors.Count - 1]
            {
                throw new ConcurrencyException();
            }
            var i = expectedVersion;

            // iterate through current aggregate events increasing version with each processed event
            foreach (var @event in events)
            {
                i++;
                @event.Version = i;

                // push event to the event descriptors list for current aggregate
                eventDescriptors.Add(new EventDescriptor(aggregateId, @event, i));

                // publish current event to the bus for further processing by subscribers
                await _publisher.Publish(@event);
            }
        }
Beispiel #6
0
        public void Save(Guid aggregateId, IEnumerable <IEvent> events, int expectedVersion)
        {
            List <EventInfo> eventDescriptors;

            if (!_events.TryGetValue(aggregateId, out eventDescriptors))
            {
                eventDescriptors = new List <EventInfo>();
                _events.Add(aggregateId, eventDescriptors);
            }
            else if (eventDescriptors[eventDescriptors.Count - 1].Version != expectedVersion && expectedVersion != -1)
            {
                //this prevents us from trying to duplicate the same event to the event store
                //this could happen in a multi-threaded environment or if you are
                //using a messageing framework with at-least-once delivery semantics
                throw new ConcurrencyException();
            }

            var i = expectedVersion;

            foreach (var @event in events)
            {
                i++;
                eventDescriptors.Add(new EventInfo(aggregateId, @event, i));
                _serviceBus.Publish(@event);
            }
        }
        protected override IEnumerable <IEvent> Accept(IEvent @event)
        {
            log.DebugFormat("Publishing {0} to {1} publiser", @event.GetType(), publisher.GetType());

            publisher.Publish(@event);

            return(ListOfEvents.EmptyList());
        }
 public void Handle(ChangeNameCommand message)
 {
     if (message.IsValidToHandle)
     {
         //once its actually completed, let anyone who cares know that this has happened
         _bus.Publish(new NameChangedEvent(message.NewFirstname, message.NewLastname));
     }
 }
Beispiel #9
0
        public bool TryAcceptPayment(int orderNumber)
        {
            Messages.ReceiveOrder message;
            if (false == AwaitingPayment.TryRemove(orderNumber, out message))
            {
                return(false);
            }
            message.Order.Receipt = new JObject();
            next.Publish(new Messages.OrderPaid(message.Order, message.CorrelationId, message.MessageId, message.TimeToLive));

            return(true);
        }
Beispiel #10
0
        public void PlaceOrder(int orderNumber, int table, params Order.Item[] items)
        {
            var tookOrderOn = DateTime.UtcNow;
            var order       = new Order(orderNumber)
            {
                Table = table, Waiter = name, TookOrderOn = tookOrderOn
            };

            items.ForEach(order.Add);

            var customerWalksOutAt = tookOrderOn.AddSeconds(30);

            if (random.NextDouble() > 0.75)
            {
                next.Publish(new Messages.OrderPlaced(order, customerWalksOutAt));
            }
            else
            {
                next.Publish(new Messages.SuspectOrderPlaced(order, customerWalksOutAt));
            }
        }
Beispiel #11
0
        public void Handle(Messages.PrepareFood message)
        {
            foreach (var item in message.Order.Items)
            {
                item.Ingredients = BullshitRecipeDatabase[item.Plate];
            }
            var cookTime = TimeSpan.FromSeconds(random.NextDouble() / efficiency);

            Thread.Sleep(cookTime);
            message.Order.CookedOn = DateTime.UtcNow;
            message.Order.Chef     = name;
            next.Publish(new Messages.FoodPrepared(message.Order, message.CorrelationId, message.MessageId, message.TimeToLive));
        }
        public void Handle(Messages.TotalOrder message)
        {
            var order = message.Order;

            foreach (var item in order.Items)
            {
                item.Price = PricesDatabase[item.Plate];
            }

            order.Tax   = order.Subtotal * TaxRate;
            order.Total = order.Subtotal + order.Tax + order.Tip;

            next.Publish(new Messages.OrderTotalled(order, message.CorrelationId, message.MessageId, message.TimeToLive));
        }
Beispiel #13
0
        /// <summary>
        /// Dispatch all events within the specified <paramref name="commit"/>.
        /// </summary>
        /// <param name="commit">The commit instance to be dispatched.</param>
        private void DispatchCommit(Commit commit)
        {
            var commitId = commit.Id.GetValueOrDefault();
            var events   = commit.Events;

            for (var i = 0; i < events.Count; i++)
            {
                var e       = events[i];
                var version = new EventVersion(commit.Version, events.Count, i + 1);

                eventPublisher.Publish(commit.Headers, new EventEnvelope(commit.CorrelationId, commit.StreamId, version, e));
            }

            if (markDispatched)
            {
                eventStore.MarkDispatched(commitId);
            }
        }
Beispiel #14
0
        private async Task PublishEvents(IHoldAllConfiguration configuration, ItemWithType[] events, CancellationToken cancellationToken = default(CancellationToken))
        {
            bool         hasInterceptors = configuration.HasInterceptors;
            ItemWithType @event;

            for (var i = 0; i < events.Length; i++)
            {
                @event = events[i];

                TryCallInterceptor(hasInterceptors, configuration.Interceptors, @event,
                                   (interc, e, et, s, st) => interc.BeforePublish(e, et, s, st));

                //We await each one to guarantee ordering of publishing, even though it would have been more performant
                // to publish and await all of them with a WhenAll
                await eventPublisher.Publish(events[i], cancellationToken);

                TryCallInterceptor(hasInterceptors, configuration.Interceptors, @event,
                                   (interc, e, et, s, st) => interc.AfterPublish(e, et, s, st));
            }
        }
Beispiel #15
0
 public AlarmClock(IPublishEvents bus)
 {
     workerThread = new Thread(
         _ =>
     {
         while (!stopped)
         {
             lock (alarmLock)
             {
                 var now        = DateTime.UtcNow;
                 var shouldSend = alarms.Where(x => x.AlarmTime > now).ToList();
                 foreach (var alarm in shouldSend)
                 {
                     bus.Publish(alarm.Message);
                     alarms.Remove(alarm);
                 }
             }
             Thread.Sleep(1);
         }
     });
 }
 public void Push(IEvent @event)
 {
     publisher.Publish(@event);
 }
Beispiel #17
0
 /// <summary>
 /// Publishes the specified <paramref name="payload"/> on the underlying message bus.
 /// </summary>
 /// <param name="headers">The set of message headers associated with the event.</param>
 /// <param name="payload">The event payload to be published.</param>
 public void Publish(IEnumerable <Header> headers, EventEnvelope payload)
 {
     statistics.IncrementQueuedEvents();
     bus.Publish(headers, payload);
 }