public async Task <IActionResult> Get() { var message = new PingHelloWordCommand { Name = "My Name" }; await _messageSession.Send(message); return(Ok()); }
/// <summary> /// Instantiates a message of type T and sends it back to the current endpoint. Shortcut for <see cref="RoutingOptionExtensions.RouteToThisEndpoint(SendOptions)">sendOptions.RouteToThisEndpoint()</see>. /// </summary> /// <typeparam name="T">The type of message, usually an interface.</typeparam> /// <param name="session">Object being extended.</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 SendLocal <T>(this IMessageSession session, Action <T> messageConstructor, CancellationToken cancellationToken = default) { Guard.AgainstNull(nameof(session), session); Guard.AgainstNull(nameof(messageConstructor), messageConstructor); var options = new SendOptions(); options.RouteToThisEndpoint(); return(session.Send(messageConstructor, options, cancellationToken)); }
/// <summary> /// Sends the message back to the current endpoint. Shortcut for <see cref="RoutingOptionExtensions.RouteToThisEndpoint(SendOptions)">sendOptions.RouteToThisEndpoint()</see>. /// </summary> /// <param name="session">Object being extended.</param> /// <param name="message">The message to send.</param> /// <param name="cancellationToken">A <see cref="CancellationToken"/> to observe.</param> public static Task SendLocal(this IMessageSession session, object message, CancellationToken cancellationToken = default) { Guard.AgainstNull(nameof(session), session); Guard.AgainstNull(nameof(message), message); var options = new SendOptions(); options.RouteToThisEndpoint(); return(session.Send(message, options, cancellationToken)); }
public Task SubmitOrder(string theater, string movie, string time, int numberOfTickets) { return(messageSession.Send(new SubmitOrder() { Theater = Guid.Parse(theater), Movie = Guid.Parse(movie), Time = time, NumberOfTickets = numberOfTickets, UserId = Guid.Parse("218d92c4-9c42-4e61-80fa-198b22461f61") // For now, no other users allowed ;-) })); }
public async Task Handle(dynamic vm, RouteData routeData, HttpRequest request) { var productId = (string)routeData.Values["id"]; var orderId = Interlocked.Increment(ref orderIdCounter); await session.Send(new PlaceOrder { OrderId = "EShop-" + orderId, ProductId = int.Parse(productId) }); }
private void SendDoTransactionMessage(Models.Transaction transaction) { Messages.Commands.CreateTransaction doTransaction = new Messages.Commands.CreateTransaction() { FromAccountId = transaction.FromAccountId, ToAccountId = transaction.ToAccountId, Amount = transaction.Amount, TransactionId = transaction.Id }; _messageSession.Send(doTransaction).ConfigureAwait(false); }
public async Task ProcessedJobMessage(long jobId, Guid messageId, string messageName, List <GeneratedMessage> generatedMessages) { try { logger.LogVerbose($"Sending request to record successful processing of event. Job Id: {jobId}, Event: id: {messageId} "); var batchSize = 1000; //TODO: this should come from config List <GeneratedMessage> batch; var itemProcessedEvent = new RecordJobMessageProcessingStatus { JobId = jobId, Id = messageId, MessageName = messageName, EndTime = DateTimeOffset.UtcNow, GeneratedMessages = generatedMessages.Take(batchSize).ToList() ?? new List <GeneratedMessage>(), Succeeded = true, }; var partitionedEndpointName = config.GetMonitoringEndpointName(jobId); await messageSession.Send(partitionedEndpointName, itemProcessedEvent).ConfigureAwait(false); var skip = batchSize; while ((batch = generatedMessages.Skip(skip).Take(batchSize).ToList()).Count > 0) { skip += batchSize; var providerEarningsAdditionalMessages = new RecordJobAdditionalMessages { JobId = jobId, GeneratedMessages = batch, }; await messageSession.Send(partitionedEndpointName, providerEarningsAdditionalMessages).ConfigureAwait(false); } logger.LogDebug( $"Sent request to record successful processing of event. Job Id: {jobId}, Event: id: {messageId} "); } catch (Exception ex) { logger.LogWarning($"Failed to send the job status message. Job: {jobId}, Message: {messageId}, {messageName}, Error: {ex.Message}, {ex}"); } }
public Task Run([TimerTrigger("0 0 15 20 * *")] TimerInfo timer, ILogger logger) { var now = _dateTimeService.UtcNow; var month = new DateTime(now.Year, now.Month, 6, 0, 0, 0, 0, DateTimeKind.Utc); var payrollPeriod = month.AddMonths(-1); var command = new ProcessLevyDeclarationsCommand(payrollPeriod); var task = _messageSession.Send(command); logger.LogInformation($"Sent '{nameof(ProcessLevyDeclarationsCommand)}' with '{nameof(ProcessLevyDeclarationsCommand.PayrollPeriod)}' value '{command.PayrollPeriod:MM yyyy}'"); return(task); }
/// <summary> /// Sends the message. /// </summary> /// <param name="session">The instance of <see cref="IMessageSession" /> to use for the action.</param> /// <param name="destination">The address of the destination to which the message will be sent.</param> /// <param name="message">The message to send.</param> public static Task Send(this IMessageSession session, string destination, object message) { Guard.AgainstNull(nameof(session), session); Guard.AgainstNullAndEmpty(nameof(destination), destination); Guard.AgainstNull(nameof(message), message); var options = new SendOptions(); options.SetDestination(destination); return(session.Send(message, options)); }
private async Task SendEmail(EmailViewModel viewModel) { _logger.LogInformation($"CreateInvitationHandler : SendEmail : ViewModel: {JsonConvert.SerializeObject(viewModel)}"); var tokens = GetTokens(viewModel); await _messageSession.Send( new SendEmailCommand( viewModel.TemplateId.ToString(), viewModel.EmailAddress, tokens)); }
async Task SendMessagesOutsideMessageHandler(EndpointConfiguration endpointConfiguration) { #region 5to6-endpoint-send-messages-outside-handlers var endpointInstance = await Endpoint.Start(endpointConfiguration) .ConfigureAwait(false); IMessageSession messageSession = endpointInstance; await messageSession.Send(new SomeMessage()) .ConfigureAwait(false); #endregion }
/// <summary> /// Instantiates a message of type T and sends it to the given destination. /// </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="destination">The destination to which the message will be sent.</param> /// <param name="messageConstructor">An action which initializes properties of the message.</param> public static Task Send <T>(this IMessageSession session, string destination, Action <T> messageConstructor) { Guard.AgainstNull(nameof(session), session); Guard.AgainstNullAndEmpty(nameof(destination), destination); Guard.AgainstNull(nameof(messageConstructor), messageConstructor); var options = new SendOptions(); options.SetDestination(destination); return(session.Send(messageConstructor, options)); }
public async Task ApproveLoan(Guid loanId, List <ApproveRuleDTO> approveRules) { List <ApproveRuleModel> approveRulesModel = _mapper.Map <List <ApproveRuleModel> >(approveRules); ApproveLoanModel approveLoanModel = new ApproveLoanModel() { approveRules = approveRulesModel, LoanId = loanId }; CheckLoanValid checkLoanValid = await _managerLoansService.ApproveLoan(approveLoanModel); await _messageSession.Send(checkLoanValid); }
public async Task DoHandle(string filePath) { var fileToProcess = _fileDetailsProvider.GetFileInfo(filePath); await _session.Send(new StartProcessingFile { ImportId = Guid.NewGuid(), FileName = fileToProcess.FileName, FilePath = fileToProcess.FullFileName, FileType = fileToProcess.FileExtension, //TotalRecordCount = totalRecordCount }); }
public SendMessageModule(IMessageSession messageSession) : base("/sendmessage") { this.messageSession = messageSession; this.Get("/", async(r, c) => { var message = new MyMessage(); await messageSession.Send(message) .ConfigureAwait(false); return("Message sent to endpoint"); }); }
public async Task Handle() { IMessageSession context = null; #region override-conversation-id var sendOptions = new SendOptions(); sendOptions.SetHeader(Headers.ConversationId, "MyCustomConversationId/" + System.Guid.NewGuid()); await context.Send(new MyMessage(), sendOptions) .ConfigureAwait(false); #endregion }
private static async Task SimpleTransfer(IMessageSession endpoint) { var samId = Guid.NewGuid(); var bobId = Guid.NewGuid(); var accountOfBob = Guid.NewGuid(); var accountOfSam = Guid.NewGuid(); await endpoint.Send(new Open(accountOfBob, samId, 1000000.0M)); await endpoint.Send(new Open(accountOfSam, bobId, 1000000.0M)); await Task.Delay(1000); await endpoint.Send(new Transfer(Guid.NewGuid(), accountOfBob, accountOfSam, 1.0M)); await Task.Delay(1000); await endpoint.Send(new QueryBalanceRequest(accountOfSam)); string input = string.Empty; do { await endpoint.Send(new QueryBalanceRequest(accountOfSam)); await endpoint.Send(new QueryBalanceRequest(accountOfBob)); input = Console.ReadLine(); } while (input != "q"); }
public async Task <IActionResult> Get(int id) { //Alternative is to use wrapper abstraction or custom IMessageSession decorator with hidden: // var sendOptions = new SendOptions(); // sendOptions.SetHeader("ContextId", _sharedContext.ContextId); await _messageSession.Send("Host", new MyFirstMessage { MessageId = id }).ConfigureAwait(false); return(Ok()); }
static async Task SeedSagaMessages(IMessageSession bus, int numberOfMessages, string inputQueue, int concurrency) { for (var i = 0; i < numberOfMessages / concurrency; i++) { for (var j = 0; j < concurrency; j++) { await bus.Send(inputQueue, new StartSagaMessage { Id = i + 1 }).ConfigureAwait(false); } } }
public async Task Post() { _logger.LogInformation("Sending message..."); var sendOptions = new SendOptions(); sendOptions.SetHeader("Tenant", HttpContext.Request.Host.ToString()); sendOptions.SetDestination("WebApi.Receiver"); await _messageSession.Send(new Ping { From = "WebApi.Sender" }, sendOptions); _logger.LogInformation("Messag sent."); }
private async Task NotifyProvider(long providerId, long apprenticeshipId, string employerName, string apprenticeName, DateTime stopDate) { var sendEmailToProviderCommand = new SendEmailToProviderCommand(providerId, StopNotificationEmailTemplate, new Dictionary <string, string> { { "EMPLOYER", employerName }, { "APPRENTICE", apprenticeName }, { "DATE", stopDate.ToString("dd/MM/yyyy") }, { "URL", $"{providerId}/apprentices/manage/{_encodingService.Encode(apprenticeshipId, EncodingType.ApprenticeshipId)}/details" } }); await _nserviceBusContext.Send(sendEmailToProviderCommand); }
static async Task SendMessage(IMessageSession messageSession, bool emulateFailures, string text) { var id = Guid.NewGuid(); await messageSession.Send("SmokeTest.Server", new MyMessage { Id = id, KillMe = emulateFailures, SomeText = text }); Console.WriteLine("Sent a new message with id: {0}", id.ToString("N")); }
public async Task <IActionResult> Topic(Guid id, [FromBody] string payload) { string topic = "led/publish" + id.ToString(); var command = new DevicesPublishCommand(topic, payload); SendOptions sendOptions = new SendOptions(); sendOptions.SetDestination("IoT.DeviceEnactor"); await _message.Send(command, sendOptions); return(StatusCode(200)); }
private async Task Cleanup(IMessageSession messageSession, DateTime now, CancellationToken cancellationToken) { var clientOutboxMessagesTask = _clientOutboxStorage.GetAwaitingDispatchAsync(); var clientOutboxMessageV2sTask = _clientOutboxStorageV2.GetAwaitingDispatchAsync(); var clientOutboxMessages = await clientOutboxMessagesTask.ConfigureAwait(false); var clientOutboxMessageV2s = await clientOutboxMessageV2sTask.ConfigureAwait(false); var oldest = now.Subtract(_maxAge); var tasks = clientOutboxMessages .Select(m => { var sendOptions = new SendOptions(); sendOptions.SetDestination(m.EndpointName); sendOptions.SetMessageId(m.MessageId.ToString()); return(messageSession.Send(new ProcessClientOutboxMessageCommand(), sendOptions)); }) .Concat(clientOutboxMessageV2s.Select(m => { var sendOptions = new SendOptions(); sendOptions.SetDestination(m.EndpointName); sendOptions.SetMessageId(m.MessageId.ToString()); return(messageSession.Send(new ProcessClientOutboxMessageCommandV2(), sendOptions)); })) .Concat(new [] { _clientOutboxStorage.RemoveEntriesOlderThanAsync(oldest, cancellationToken), _clientOutboxStorageV2.RemoveEntriesOlderThanAsync(oldest, cancellationToken) }); await Task.WhenAll(tasks).ConfigureAwait(false); _failures = 0; }
void OtherEndpointConnectionParamsPull(EndpointConfiguration endpointConfiguration, IMessageSession messageSession) { #region sqlserver-multischema-config-for-queue var transport = endpointConfiguration.UseTransport <SqlServerTransport>(); transport.UseSchemaForQueue(queueName: "myqueue", schema: "my_schema"); transport.UseSchemaForQueue(queueName: "error", schema: "error"); messageSession.Send("myqueue", new MyMessage()); #endregion }
public async Task <IActionResult> CreateOrder() { // Save order details to DB // dbContext.Orders.Add(order); // Send commmand to kick off process await _bus.Send(new ProcessOrderCommand { OrderId = _orderId++ }); return(RedirectToAction(nameof(ThankYou))); }
public async Task <ActionResult> Index(ViewModel model) { if (!ModelState.IsValid) { return(View(model)); } await messageSession.Send(new SomeMessage { Number = model.Number }) .ConfigureAwait(false); ViewBag.Message = "Request was queued successfully."; return(View(model)); }
public static async Task PassiveCommand(this IMessageSession ctx, ICommand command) { if (string.IsNullOrEmpty(Configuration.Settings.CommandDestination)) { throw new ArgumentException($"Must use Configuration.SetCommandDestination to use destination-less extension methods"); } var options = new SendOptions(); options.SetDestination(Configuration.Settings.CommandDestination); options.SetHeader(Defaults.RequestResponse, "0"); await ctx.Send(command, options).ConfigureAwait(false); }
public async Task StartPeriodEndJob <T>(T periodEndJob) where T : RecordPeriodEndJob { var jobName = periodEndJob.GetType().Name; logger.LogDebug($"Sending request to record start of {jobName}. Job Id: {periodEndJob.JobId}, collection period: {periodEndJob.CollectionYear}-{periodEndJob.CollectionPeriod}"); var partitionedEndpointName = config.GetMonitoringEndpointName(periodEndJob.JobId); logger.LogVerbose($"Endpoint for PeriodEndJobClient for {jobName} with Job Id {periodEndJob.JobId} is `{partitionedEndpointName}`"); await messageSession.Send(partitionedEndpointName, periodEndJob).ConfigureAwait(false); logger.LogInfo($"Sent request to record period end job: {jobName}. Job Id: {periodEndJob.JobId}, collection period: {periodEndJob.CollectionYear}-{periodEndJob.CollectionPeriod}"); }
static Task SendMessage(IMessageSession s) { var uniqueValue = Guid.NewGuid().ToString(); var options = new SendOptions(); options.RouteToThisEndpoint(); options.SetHeader("Value", uniqueValue); var message = new Message { Value = uniqueValue }; return(s.Send(message, options)); }
static async Task SendMessageLargePayload(IMessageSession messageSession) { Console.WriteLine("Sending message..."); #region SendMessageLargePayload MessageWithLargePayload message = new MessageWithLargePayload { Description = "This message contains a large payload that will be sent on the Azure data bus", LargePayload = new DataBusProperty<byte[]>(new byte[1024*1024*5]) // 5MB }; await messageSession.Send("Samples.AzureBlobStorageDataBus.Receiver", message); #endregion Console.WriteLine("Message sent."); }
public async Task Start(IMessageSession session) { VerificationLogger.Write("Sender", "Pinging Receiver"); await session.Send(new Ping()); }
static Task Schedule(IMessageSession session, TaskDefinition taskDefinition) { logger.DebugFormat("Task '{0}' (with id {1}) scheduled with timeSpan {2}", taskDefinition.Name, taskDefinition.Id, taskDefinition.Every); var options = new SendOptions(); options.DelayDeliveryWith(taskDefinition.Every); options.RouteToThisEndpoint(); options.Context.GetOrCreate<ScheduleBehavior.State>().TaskDefinition = taskDefinition; var scheduledTask = new ScheduledTask { TaskId = taskDefinition.Id, Name = taskDefinition.Name, Every = taskDefinition.Every }; return session.Send(scheduledTask, options); }