static async Task <TimeSpan> PublishEvents(IMessageSession bus, int numberOfMessages, int numberOfThreads, bool createTransaction) { var sw = new Stopwatch(); sw.Start(); var tasks = Enumerable.Range(0, numberOfThreads) .Select(i => Task.Factory.StartNew(async() => { for (var j = 0; j < numberOfMessages / numberOfThreads; i++) { if (createTransaction) { using (var tx = new TransactionScope()) { await bus.Publish <TestEvent>().ConfigureAwait(false); tx.Complete(); } } else { await bus.Publish <TestEvent>().ConfigureAwait(false); } Interlocked.Increment(ref Statistics.NumberOfMessages); } }, CancellationToken.None, TaskCreationOptions.LongRunning, TaskScheduler.Default)).ToArray(); await Task.WhenAll(tasks).ConfigureAwait(false); sw.Stop(); return(sw.Elapsed); }
public async Task EveryMinuteTick() { GlobalSettings globalSettings; try { globalSettings = await _globalSettingsClient.GetGlobalSettings(); } catch (HttpRequestException hre) when(LogError(hre)) { return; } var gweeks = globalSettings.Gameweeks; var next = gweeks.FirstOrDefault(gw => gw.IsNext); if (next != null) { if (_dateTimeUtils.IsWithinMinutesToDate(60, next.Deadline)) { await _session.Publish(new OneHourToDeadline(new GameweekNearingDeadline(next.Id, next.Name, next.Deadline))); } if (_dateTimeUtils.IsWithinMinutesToDate(24 * 60, next.Deadline)) { await _session.Publish(new TwentyFourHoursToDeadline(new GameweekNearingDeadline(next.Id, next.Name, next.Deadline))); } } else { _logger.LogInformation($"No next gameweek"); } }
public async Task <IActionResult> AddStock(int id) { var message = new ItemStockUpdated { ProductId = id, IsAvailable = true }; await messageSession.Publish(message) .ConfigureAwait(false); return(View("Restock", id)); }
public virtual async Task DeleteAsync <T>(T record) where T : RecordBase { DbContext .Set <T>() .Remove(record); await DbContext.SaveChangesAsync(); var ievent = record.DeletedMessages(); if (ievent != null) { await _messageSession.Publish(ievent); } }
public async Task EveryFiveMinutesTick(CancellationToken token) { EventStatusResponse fetched; try { fetched = await _eventStatusClient.GetEventStatus(); } catch (Exception e) when(LogError(e)) { return; } // init/ app-startup if (_storedCurrent == null) { _logger.LogDebug("Executing initial fetch"); _storedCurrent = fetched; return; } _logger.LogInformation("Checking status"); var bonusAdded = GetBonusAdded(fetched, _storedCurrent); if (bonusAdded != null) { _logger.LogInformation("Bonus added!"); await _session.Publish(bonusAdded); } var pointsReady = GetPointsReady(fetched, _storedCurrent); if (pointsReady != null) { _logger.LogInformation("Points ready!"); await _session.Publish(pointsReady); } var leaguesStatusChanged = fetched.Leagues != _storedCurrent.Leagues; if (leaguesStatusChanged && fetched.Leagues == EventStatusConstants.LeaguesStatus.Updated) { _logger.LogInformation($"League status changed from ${_storedCurrent.Leagues} to ${fetched.Leagues}"); await _session.Publish(new MatchdayLeaguesUpdated()); } _storedCurrent = fetched; }
private static async Task Start(IMessageSession endpointInstance) { Console.WriteLine("Press '1' to publish the OrderReceived event"); Console.WriteLine("Press any other key to exit"); while (true) { var key = Console.ReadKey(); Console.WriteLine(); var observation = Guid.NewGuid().ToString(); var time = DateTime.Now; if (key.Key == ConsoleKey.D1) { var somethingHappenedMessage = new SomethingHappenedMessage { Time = time, Observation = observation }; await endpointInstance.Publish(somethingHappenedMessage) .ConfigureAwait(false); Console.WriteLine($"Published SomethingHappenedMessage. Time: {time}, Observation: {observation}."); } else { return; } } }
public async Task <IActionResult> PlaceOrder() { var orderId = Guid.NewGuid().ToString().Substring(0, 8); var payloadLocation = await _storageRepository .SaveMessageToStorage("very big message from storage"); //Create the order then publish that the order was placed var orderPlaced = new OrderPlaced { OrderId = orderId, PayloadLocation = payloadLocation }; _log.Info($"Publishing OrderPlaced, OrderId = {orderId}"); await _messageSession.Publish(orderPlaced) .ConfigureAwait(false); dynamic model = new ExpandoObject(); model.OrderId = orderId; return(View(model)); }
private async Task SendAppointmentDealCreatedEventAsync(Domain.AggregatesModel.PostAggregate.Post deal) { var @event = new AppointmentDealCreatedEvent { User1Id = deal.UserId, User2Id = deal.AppointmentedUserId.Value, // user1是约拍发出方,他的角色应该和约拍时希望约的角色相反 User1Type = (int)(deal.AppointmentedUserType == AppointmentedUserType.Model ? AppointmentedUserType.Photographer : AppointmentedUserType.Model), // user2是约拍接收方,他的角色就是约拍时希望约的角色 User2Type = (int)deal.AppointmentedUserType, DealId = deal.Id, AppointmentedUserType = (int)deal.AppointmentedUserType, PayerType = (int)deal.PayerType, Price = deal.Price ?? 0, AppointedTime = deal.AppointedTime.Value, PayerId = deal.PayerType == PayerType.Free ? null : (deal.PayerType == PayerType.Me ? deal.UserId : deal.AppointmentedUserId), Text = deal.Text, Latitude = deal.Latitude.Value, Longitude = deal.Longitude.Value, LocationName = deal.LocationName, Address = deal.Address }; _messageSession = (IMessageSession)_serviceProvider.GetService(typeof(IMessageSession)); await _messageSession.Publish(@event); _logger.LogInformation("----- Published AppointmentDealCreatedEvent: {IntegrationEventId} from {AppName} - ({@IntegrationEvent})", @event.Id, Program.AppName, @event); }
public async Task Publish <T>(string bucket, string streamId, IEnumerable <IWritableEvent> events, IDictionary <string, string> commitHeaders) where T : class, IEventSource { var options = new PublishOptions(); foreach (var header in commitHeaders) { if (header.Key == Headers.OriginatingHostId) { //is added by bus in v5 continue; } options.SetHeader(header.Key, header.Value); } await events.WhenAllAsync(async @event => { options.SetHeader("EventId", @event.EventId.ToString()); options.SetHeader("EntityType", @event.Descriptor.EntityType); options.SetHeader("Timestamp", @event.Descriptor.Timestamp.ToString(CultureInfo.InvariantCulture)); options.SetHeader("Version", @event.Descriptor.Version.ToString()); foreach (var header in @event.Descriptor.Headers) { options.SetHeader(header.Key, header.Value); } await _endpoint.Publish(@event, options).ConfigureAwait(false); }).ConfigureAwait(false); }
static async Task RunLoop(IMessageSession endpointInstance) { while (true) { Log.Info("Press 'P' to place an order, or 'Q' to quit."); ConsoleKeyInfo key = Console.ReadKey(); Console.WriteLine(); switch (key.Key) { case ConsoleKey.P: var @event = new OrderPlaced(); await endpointInstance .Publish(@event) .ConfigureAwait(false); Log.Info($"Sending OrderPlaced event, OrderId = {33}"); break; case ConsoleKey.Q: return; default: Log.Info("Unknown input. Please try again."); break; } } }
/// <summary> /// Instantiates a message of type T and publishes it. /// </summary> /// <typeparam name="T">The type of message, usually an interface.</typeparam> /// <param name="session">The instance of <see cref="IMessageSession" /> to use for the action.</param> /// <param name="messageConstructor">An action which initializes properties of the message.</param> /// <param name="cancellationToken">A <see cref="CancellationToken"/> to observe.</param> public static Task Publish <T>(this IMessageSession session, Action <T> messageConstructor, CancellationToken cancellationToken = default) { Guard.AgainstNull(nameof(session), session); Guard.AgainstNull(nameof(messageConstructor), messageConstructor); return(session.Publish(messageConstructor, new PublishOptions(), cancellationToken)); }
/// <summary> /// Publish the message to subscribers. /// </summary> /// <param name="session">The instance of <see cref="IMessageSession" /> to use for the action.</param> /// <param name="message">The message to publish.</param> /// <param name="cancellationToken">A <see cref="CancellationToken"/> to observe.</param> public static Task Publish(this IMessageSession session, object message, CancellationToken cancellationToken = default) { Guard.AgainstNull(nameof(session), session); Guard.AgainstNull(nameof(message), message); return(session.Publish(message, new PublishOptions(), cancellationToken)); }
protected override async Task ExecuteAsync(CancellationToken stoppingToken) { try { while (!stoppingToken.IsCancellationRequested) { session = provider.GetService <IMessageSession>(); Console.WriteLine("Press 1 to publish the event, any other key to exit"); var key = Console.ReadKey(); Console.WriteLine(); var regId = Guid.NewGuid(); if (key.Key != ConsoleKey.D1) { var registerSmartMeter = new SmartMeterRegistered() { RegistrationId = regId.ToString(), Mpxn = "1234567890123", SupplyStartDate = DateTime.Now.AddDays(5) }; await session.Publish(registerSmartMeter).ConfigureAwait(false); Console.WriteLine($"Published SmartMeterRegistered Event with Registration Id {registerSmartMeter.RegistrationId}."); } } await Task.Delay(100, stoppingToken).ConfigureAwait(false); } catch (OperationCanceledException e) { log.Warn($"{e.InnerException.ToString() ?? e.StackTrace}"); } }
private async Task SendEvent(BaseEvent @event) { _messageSession = (IMessageSession)_serviceProvider.GetService(typeof(IMessageSession)); await _messageSession.Publish(@event); _logger.LogInformation("----- Published {IntegrationEventName}: {IntegrationEventId} from {AppName} - ({@IntegrationEvent})", @event.GetType().Name, @event.Id, Program.AppName, @event); }
public Task Start(IMessageSession session) { Console.WriteLine("Press C to send a command"); Console.WriteLine("Press E to send an event"); Console.WriteLine("Press any other key to exit"); while (true) { var key = Console.ReadKey(); if (key.Key != ConsoleKey.C && key.Key != ConsoleKey.E) { break; } if (key.Key == ConsoleKey.C) { session.Send(new RefundPayment(Guid.NewGuid(), 100m)); Console.WriteLine("\nCommand sent"); } if (key.Key == ConsoleKey.E) { session.Publish <IPaymentIntentGuaranteeRequested>(@event => { @event.PaymentReference = Guid.NewGuid(); }); Console.WriteLine("\nEvent published"); } } return(Task.CompletedTask); }
protected override async Task OnStop(IMessageSession session) { await session.Publish(new MyEvent()) .ConfigureAwait(false); resetEvent.Reset(); }
protected override async Task OnStop(IMessageSession session, CancellationToken cancellationToken = default) { await session.Publish(new MyEvent(), cancellationToken) .ConfigureAwait(false); resetEvent.Reset(); }
private Task PublishMessage(TransportOperation o) { var publishOptions = new PublishOptions(); publishOptions.SetMessageId(o.MessageId.ToString()); return(_messageSession.Publish(o.Message, publishOptions)); }
/// <summary> /// Instantiates a message of type T and publishes it. /// </summary> /// <typeparam name="T">The type of message, usually an interface.</typeparam> /// <param name="session">The instance of <see cref="IMessageSession" /> to use for the action.</param> /// <param name="messageConstructor">An action which initializes properties of the message.</param> public static Task Publish <T>(this IMessageSession session, Action <T> messageConstructor) { Guard.AgainstNull(nameof(session), session); Guard.AgainstNull(nameof(messageConstructor), messageConstructor); return(session.Publish(messageConstructor, new PublishOptions())); }
public void Complete() { //await _messageSession.Send(command, sendOptions); foreach (Object _event in _messages.Events) { try { _logger.Technical().Information($"Publish event: {_event.GetType().FullName}.").Log(); _messageSession.Publish(_event).Wait(); } catch (Exception ex) { _logger.Technical().Exception(ex).Log(); } } // Send commands. foreach (Object command in _messages.Commands) { try { _logger.Technical().Information($"Send command: {command.GetType().FullName}.").Log(); _messageSession.Send(command).Wait(); } catch (Exception ex) { _logger.Technical().Exception(ex).Log(); } } _messages.Clear(); }
/// <summary> /// Publish the message to subscribers. /// </summary> /// <param name="session">The instance of <see cref="IMessageSession" /> to use for the action.</param> /// <param name="message">The message to publish.</param> public static Task Publish(this IMessageSession session, object message) { Guard.AgainstNull(nameof(session), session); Guard.AgainstNull(nameof(message), message); return(session.Publish(message, new PublishOptions())); }
public async Task PublishUserCreated(Guid id, string login, string firstName, string lastName) { var options = new PublishOptions(); var @event = new UserCreated { Id = id, Login = login, FirstName = firstName, LastName = lastName }; options.SetMessageId(id.ToString()); await _endpoint.Publish(@event, options); }
protected override async Task OnStart(IMessageSession session) { await session.Publish <MyEvent>() .ConfigureAwait(false); resetEvent.Set(); }
public async Task <EventHandledResponse> Handle(EventMetaData eventMetadata, AppMentionEvent slackEvent) { string mentionTextStripped = Regex.Replace(slackEvent.Text, "<@(\\w+)>", "$1"); await _session.Publish(new UnknownAppMentionReceived(eventMetadata.Team_Id, slackEvent.User, mentionTextStripped)); return(new EventHandledResponse("OK")); }
static async Task SendMessages(IMessageSession messageSession) { Console.WriteLine("Press [c] to send a command, or [e] to publish an event. Press [Esc] to exit."); while (true) { var input = Console.ReadKey(); Console.WriteLine(); switch (input.Key) { case ConsoleKey.C: await messageSession.Send(new MyCommand()); break; case ConsoleKey.E: await messageSession.Publish(new MyEvent()); break; case ConsoleKey.Escape: return; } } }
static async Task SendMessages(IMessageSession messageSession) { Console.WriteLine(@"Press [1] to send a command [2] to send a command with a large body [3] to publish an event [4] to publish an event with a large body [Esc] to exit."); while (true) { var input = Console.ReadKey(); Console.WriteLine(); switch (input.Key) { case ConsoleKey.D1: await messageSession.Send(new MyCommand()); break; case ConsoleKey.D2: await messageSession.Send(new MyCommand { Data = new byte[257 * 1024] }); break; case ConsoleKey.D3: await messageSession.Publish(new MyEvent()); break; case ConsoleKey.D4: await messageSession.Publish(new MyEvent() { Data = new byte[257 * 1024] }); break; case ConsoleKey.Escape: return; } } }
public async Task <IActionResult> AddToCart(dynamic data) { var cartId = new Guid((string)data.CartId); var productId = (int)data.ProductId; var quantity = (int)data.Quantity; var requestId = Request.Headers["request-id"].Single(); if (quantity <= 0) { return(BadRequest()); } using (var db = SalesContext.Create()) { var requestAlreadyHandled = await db.ShoppingCarts .Where(o => o.Items.Any(i => i.RequestId == requestId)) .AnyAsync(); if (!requestAlreadyHandled) { var cart = db.ShoppingCarts .Include(c => c.Items) .Where(o => o.Id == cartId) .SingleOrDefault(); if (cart == null) { cart = db.ShoppingCarts.Add(new ShoppingCart() { Id = data.CartId }).Entity; } var product = db.ProductsPrices .Where(o => o.Id == productId) .Single(); cart.Items.Add(new ShoppingCartItem() { CartId = cartId, RequestId = requestId, ProductId = productId, CurrentPrice = product.Price, LastPrice = product.Price, Quantity = quantity }); await messageSession.Publish <ProductAddedToCart>(e => { e.CartId = cartId; e.ProductId = productId; }); await db.SaveChangesAsync(); } } return(StatusCode(200)); }
//ActionResult delete(int id) //{ // return _patientRepository.Delete(id); //} public async Task PublishPatientCreated(int PatientId) { await _messageSession.Publish <IPatientCreatedV_2>(message => { message.PatientId = PatientId; }) .ConfigureAwait(false); }
public async Task Run() { var newEvent = new CohortApprovalRequestedByProvider(); await _messageSession.Publish(newEvent); // TODO: assert the document is updated }
public async Task Uninstall(string teamId) { var team = await _slackTeamRepo.GetTeam(teamId); await _slackTeamRepo.DeleteByTeamId(teamId); await _messageSession.Publish(new AppUninstalled(team.TeamId, team.TeamName, (int)team.FplbotLeagueId, team.FplBotSlackChannel)); }
protected override async Task OnStart(IMessageSession session) { await session.Publish<MyEvent>() .ConfigureAwait(false); resetEvent.Set(); }
protected override async Task OnStop(IMessageSession session) { await session.Publish<MyEvent>(); resetEvent.Reset(); }