private async Task StartAsyncCore(CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); _receiver = await _messagingFactory.CreateMessageReceiverAsync(_entityPath); _receiver.OnMessageAsync(ProcessMessageAsync, new OnMessageOptions()); }
public async Task <ActionResult> Queue() { var result = new List <Account>(); try { TokenProvider tokenProvider = TokenProvider.CreateSharedAccessSignatureTokenProvider(DashboardConfig.keyName, DashboardConfig.accessKey); MessagingFactory messagingFactory = MessagingFactory.Create(DashboardConfig.baseAddress, tokenProvider); var receiver = await messagingFactory.CreateMessageReceiverAsync(DashboardConfig.queueName, ReceiveMode.ReceiveAndDelete); while (true) { var msg = await receiver.ReceiveAsync(TimeSpan.Zero); if (msg != null) { var serializer = new XmlSerializer(typeof(Account)); var objresult = (Account)serializer.Deserialize(new StreamReader(msg.GetBody <Stream>())); result.Add(objresult); } else { break; } } } catch (Exception) { } return(View(result)); }
public async Task <IEnumerable <Payload> > ReadAllMessageFromQueueAsync(string queueName) { var subscriber = await _factory.CreateMessageReceiverAsync(queueName); var payloads = new List <Payload>(); BrokeredMessage message = null; while ((message = await subscriber.ReceiveAsync(new TimeSpan(hours: 0, minutes: 0, seconds: 5))) != null) { try { using (var stream = message.GetBody <Stream>()) using (var memoryStream = new MemoryStream()) { stream.CopyTo(memoryStream); var body = Encoding.UTF8.GetString(memoryStream.ToArray()); var payload = new Payload(); payload.MessageId = message.MessageId; payload.Label = message.Label; payload.Body = body; payloads.Add(payload); await message.CompleteAsync(); } } catch (Exception) { await message.DeadLetterAsync(); } } await subscriber.CloseAsync(); return(payloads); }
public async Task SubscribeToQueue(string queueName, Func <BrokeredMessage, Task> onMessage, CancellationToken cancellation) { var receiver = await _factory.CreateMessageReceiverAsync(queueName, ReceiveMode.PeekLock); while (!cancellation.IsCancellationRequested) { try { var message = await receiver.ReceiveAsync(); if (message != null) { await onMessage(message); // await message.CompleteAsync(); // await message.DeadLetterAsync("ProcessingError", "Don't know what to do with this message"); } } catch (MessagingException e) { if (!e.IsTransient) { throw; } } } await receiver.CloseAsync(); }
async Task IFilter <ConnectionContext> .Send(ConnectionContext context, IPipe <ConnectionContext> next) { var receiveSettings = context.GetPayload <ReceiveSettings>(); string queuePath = context.GetQueuePath(receiveSettings.QueueDescription); Uri inputAddress = context.GetQueueAddress(receiveSettings.QueueDescription); if (_log.IsDebugEnabled) { _log.DebugFormat("Creating message receiver for {0}", inputAddress); } MessagingFactory messagingFactory = await context.MessagingFactory.ConfigureAwait(false); MessageReceiver messageReceiver = await messagingFactory.CreateMessageReceiverAsync(queuePath, ReceiveMode.PeekLock) .ConfigureAwait(false); try { messageReceiver.PrefetchCount = receiveSettings.PrefetchCount; messageReceiver.RetryPolicy = RetryPolicy.Default; using (var receiver = new Receiver(messageReceiver, inputAddress, _receivePipe, receiveSettings, _receiveObserver, context.CancellationToken)) { await _endpointObserver.Ready(new Ready(inputAddress)) .ConfigureAwait(false); ReceiverMetrics metrics = await receiver.CompleteTask.ConfigureAwait(false); await _endpointObserver.Completed(new Completed(inputAddress, metrics)).ConfigureAwait(false); if (_log.IsDebugEnabled) { _log.DebugFormat("Consumer {0}: {1} received, {2} concurrent", queuePath, metrics.DeliveryCount, metrics.ConcurrentDeliveryCount); } } } catch { if (!messageReceiver.IsClosed) { await messageReceiver.CloseAsync().ConfigureAwait(false); } throw; } if (!messageReceiver.IsClosed) { await messageReceiver.CloseAsync().ConfigureAwait(false); } await next.Send(context).ConfigureAwait(false); }
static async Task <MessageReceiver> RunResultsReceiver(MessagingFactory receiverMessagingFactory) { // this receiver reads from the results queue and prints out the message var receiver = await receiverMessagingFactory.CreateMessageReceiverAsync(SagaResultQueueName); receiver.OnMessage(PrintResultMessage, new OnMessageOptions { AutoComplete = true }); return(receiver); }
async Task ReceiveMessagesAsync(MessagingFactory receiverFactory, string queueName, CancellationToken cancellationToken) { var doneReceiving = new TaskCompletionSource <bool>(); var receiver = await receiverFactory.CreateMessageReceiverAsync(queueName, ReceiveMode.PeekLock); // close the receiver and factory when the CancellationToken fires cancellationToken.Register( async() => { await receiver.CloseAsync(); doneReceiving.SetResult(true); }); // register the OnMessageAsync callback receiver.OnMessageAsync( async message => { if (message.Label != null && message.ContentType != null && message.Label.Equals("Scientist", StringComparison.InvariantCultureIgnoreCase) && message.ContentType.Equals("application/json", StringComparison.InvariantCultureIgnoreCase)) { var body = message.GetBody <Stream>(); dynamic scientist = JsonConvert.DeserializeObject(new StreamReader(body, true).ReadToEnd()); lock (Console.Out) { Console.ForegroundColor = ConsoleColor.Cyan; Console.WriteLine( "\t\t\t\tMessage received: \n\t\t\t\t\t\tMessageId = {0}, \n\t\t\t\t\t\tSequenceNumber = {1}, \n\t\t\t\t\t\tEnqueuedTimeUtc = {2}," + "\n\t\t\t\t\t\tExpiresAtUtc = {5}, \n\t\t\t\t\t\tContentType = \"{3}\", \n\t\t\t\t\t\tSize = {4}, \n\t\t\t\t\t\tContent: [ firstName = {6}, name = {7} ]", message.MessageId, message.SequenceNumber, message.EnqueuedTimeUtc, message.ContentType, message.Size, message.ExpiresAtUtc, scientist.firstName, scientist.name); Console.ResetColor(); } await message.CompleteAsync(); } else { await message.DeadLetterAsync("ProcessingError", "Don't know what to do with this message"); } }, new OnMessageOptions { AutoComplete = false, MaxConcurrentCalls = 1 }); await doneReceiving.Task; }
async Task ExceedMaxDelivery(MessagingFactory receiverFactory, string queueName) { var receiver = await receiverFactory.CreateMessageReceiverAsync(queueName, ReceiveMode.PeekLock); while (true) { var msg = await receiver.ReceiveAsync(TimeSpan.Zero); if (msg != null) { Console.WriteLine("Picked up message; DeliveryCount {0}", msg.DeliveryCount); await msg.AbandonAsync(); } else { break; } } var deadletterReceiver = await receiverFactory.CreateMessageReceiverAsync(QueueClient.FormatDeadLetterPath(queueName), ReceiveMode.PeekLock); while (true) { var msg = await deadletterReceiver.ReceiveAsync(TimeSpan.Zero); if (msg != null) { Console.WriteLine("Deadletter message:"); foreach (var prop in msg.Properties) { Console.WriteLine("{0}={1}", prop.Key, prop.Value); } await msg.CompleteAsync(); } else { break; } } }
public async Task <IEnumerable <AccountNew> > Queue() { var result = new List <AccountNew>(); try { TokenProvider tokenProvider = TokenProvider.CreateSharedAccessSignatureTokenProvider(ICEConfig.keyName, ICEConfig.accessKey); MessagingFactory messagingFactory = MessagingFactory.Create(ICEConfig.baseAddress, tokenProvider); var receiver = await messagingFactory.CreateMessageReceiverAsync(ICEConfig.queueName, ReceiveMode.ReceiveAndDelete); while (true) { var msg = await receiver.ReceiveAsync(TimeSpan.Zero); if (msg != null) { var serializer = new XmlSerializer(typeof(Account)); var objresult = (Account)serializer.Deserialize(new StreamReader(msg.GetBody <Stream>())); if (objresult != null) { result.Add(new AccountNew() { Name = objresult.Name, Phone = objresult.Phone, Website = objresult.Website, SicDesc = objresult.SicDesc, Reference_Number__c = objresult.Reference_Number__c, Fax_Number__c = objresult.Fax_Number__c, CGO_Email__c = objresult.CGO_Email__c, Store_Type_Desc__c = objresult.Store_Type_Desc__c, Opening_Hours_Main__c = objresult.Opening_Hours_Main__c, Store_Manager__c = objresult.Store_Manager__c, Store_Manager_Email__c = objresult.Store_Manager_Email__c, Area_Manager_Email__c = objresult.Area_Manager_Email__c, Area_Name__c = objresult.Area_Name__c, Store_Manager_Contact__c = objresult.Store_Manager_Contact__c, Area_Manager_Contact__c = objresult.Area_Manager_Contact__c, }); } } else { break; } } } catch (Exception) { } return(result); }
async Task PickUpAndFixDeadletters(MessagingFactory receiverFactory, string queueName, MessageSender resubmitSender, CancellationToken cancellationToken) { var doneReceiving = new TaskCompletionSource <bool>(); var dlqReceiver = await receiverFactory.CreateMessageReceiverAsync(QueueClient.FormatDeadLetterPath(queueName), ReceiveMode.PeekLock); // close the receiver and factory when the CancellationToken fires cancellationToken.Register( async() => { await dlqReceiver.CloseAsync(); doneReceiving.SetResult(true); }); // register the OnMessageAsync callback dlqReceiver.OnMessageAsync( async message => { var resubmitMessage = message.Clone(); if (resubmitMessage.Label != null && resubmitMessage.Label.Equals("Physicist")) { lock (Console.Out) { Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine( "\t\tFixing: \n\t\t\tMessageId = {0}, \n\t\t\tSequenceNumber = {1}, \n\t\t\tLabel = {2}", message.MessageId, message.SequenceNumber, message.Label); Console.ResetColor(); } resubmitMessage.Label = "Scientist"; await resubmitSender.SendAsync(resubmitMessage); } await message.CompleteAsync(); }, new OnMessageOptions { AutoComplete = true, MaxConcurrentCalls = 1 }); await doneReceiving.Task; }
async Task PickUpAndFixDeadletters(MessagingFactory receiverFactory, string queueName, MessageSender resubmitSender, CancellationToken cancellationToken) { var doneReceiving = new TaskCompletionSource<bool>(); var dlqReceiver = await receiverFactory.CreateMessageReceiverAsync(QueueClient.FormatDeadLetterPath(queueName), ReceiveMode.PeekLock); // close the receiver and factory when the CancellationToken fires cancellationToken.Register( async () => { await dlqReceiver.CloseAsync(); doneReceiving.SetResult(true); }); // register the OnMessageAsync callback dlqReceiver.OnMessageAsync( async message => { var resubmitMessage = message.Clone(); if (resubmitMessage.Label != null && resubmitMessage.Label.Equals("Physicist")) { lock (Console.Out) { Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine( "\t\tFixing: \n\t\t\tMessageId = {0}, \n\t\t\tSequenceNumber = {1}, \n\t\t\tLabel = {2}", message.MessageId, message.SequenceNumber, message.Label); Console.ResetColor(); } resubmitMessage.Label = "Scientist"; await resubmitSender.SendAsync(resubmitMessage); } await message.CompleteAsync(); }, new OnMessageOptions { AutoComplete = true, MaxConcurrentCalls = 1 }); await doneReceiving.Task; }
async Task ReceiveMessagesAsync(MessagingFactory receiverFactory, string queueName, CancellationToken cancellationToken) { var doneReceiving = new TaskCompletionSource<bool>(); var receiver = await receiverFactory.CreateMessageReceiverAsync(queueName, ReceiveMode.PeekLock); // close the receiver and factory when the CancellationToken fires cancellationToken.Register( async () => { await receiver.CloseAsync(); doneReceiving.SetResult(true); }); // register the OnMessageAsync callback receiver.OnMessageAsync( async message => { if (message.Label != null && message.ContentType != null && message.Label.Equals("Scientist", StringComparison.InvariantCultureIgnoreCase) && message.ContentType.Equals("application/json", StringComparison.InvariantCultureIgnoreCase)) { var body = message.GetBody<Stream>(); dynamic scientist = JsonConvert.DeserializeObject(new StreamReader(body, true).ReadToEnd()); lock (Console.Out) { Console.ForegroundColor = ConsoleColor.Cyan; Console.WriteLine( "\t\t\t\tMessage received: \n\t\t\t\t\t\tMessageId = {0}, \n\t\t\t\t\t\tSequenceNumber = {1}, \n\t\t\t\t\t\tEnqueuedTimeUtc = {2}," + "\n\t\t\t\t\t\tExpiresAtUtc = {5}, \n\t\t\t\t\t\tContentType = \"{3}\", \n\t\t\t\t\t\tSize = {4}, \n\t\t\t\t\t\tContent: [ firstName = {6}, name = {7} ]", message.MessageId, message.SequenceNumber, message.EnqueuedTimeUtc, message.ContentType, message.Size, message.ExpiresAtUtc, scientist.firstName, scientist.name); Console.ResetColor(); } await message.CompleteAsync(); } else { await message.DeadLetterAsync("ProcessingError", "Don't know what to do with this message"); } }, new OnMessageOptions { AutoComplete = false, MaxConcurrentCalls = 1 }); await doneReceiving.Task; }
public async Task Should_be_configured_and_working() { var settings = new TestAzureServiceBusAccountSettings(); var provider = new SharedAccessKeyTokenProvider(settings); TokenProvider tokenProvider = provider.GetTokenProvider(); Uri serviceUri = ServiceBusEnvironment.CreateServiceUri("sb", Configuration.ServiceNamespace, "MassTransit.AzureServiceBusTransport.Tests"); var namespaceManager = new NamespaceManager(serviceUri, tokenProvider); CreateQueue(namespaceManager, serviceUri, "TestClient"); CreateHostQueue(tokenProvider); var mfs = new MessagingFactorySettings { TokenProvider = tokenProvider, OperationTimeout = TimeSpan.FromSeconds(30), TransportType = TransportType.Amqp, AmqpTransportSettings = new AmqpTransportSettings { BatchFlushInterval = TimeSpan.FromMilliseconds(50), }, }; MessagingFactory factory = MessagingFactory.Create( ServiceBusEnvironment.CreateServiceUri("sb", Configuration.ServiceNamespace, Environment.MachineName), mfs); MessageReceiver receiver = await factory.CreateMessageReceiverAsync("Control"); receiver.PrefetchCount = 100; var done = TaskUtil.GetTask <bool>(); int count = 0; const int limit = 1000; receiver.OnMessageAsync(async message => { await message.CompleteAsync(); int received = Interlocked.Increment(ref count); if (received == limit) { done.TrySetResult(true); } }, new OnMessageOptions { AutoComplete = false, MaxConcurrentCalls = 100, AutoRenewTimeout = TimeSpan.FromSeconds(60), }); MessageSender client = await factory.CreateMessageSenderAsync("Control"); Stopwatch stopwatch = Stopwatch.StartNew(); Task[] tasks = new Task[limit]; for (int i = 0; i < limit; i++) { tasks[i] = SendAMessage(client); } await done.Task; stopwatch.Stop(); await Task.WhenAll(tasks); await receiver.CloseAsync(); Console.WriteLine("Performance: {0:F2}/s", limit * 1000 / stopwatch.ElapsedMilliseconds); }
async Task ExceedMaxDelivery(MessagingFactory receiverFactory, string queueName) { var receiver = await receiverFactory.CreateMessageReceiverAsync(queueName, ReceiveMode.PeekLock); while(true) { var msg = await receiver.ReceiveAsync(TimeSpan.Zero); if (msg != null) { Console.WriteLine("Picked up message; DeliveryCount {0}", msg.DeliveryCount); await msg.AbandonAsync(); } else { break; } } var deadletterReceiver = await receiverFactory.CreateMessageReceiverAsync(QueueClient.FormatDeadLetterPath(queueName), ReceiveMode.PeekLock); while (true) { var msg = await deadletterReceiver.ReceiveAsync(TimeSpan.Zero); if (msg != null) { Console.WriteLine("Deadletter message:"); foreach (var prop in msg.Properties) { Console.WriteLine("{0}={1}", prop.Key, prop.Value); } await msg.CompleteAsync(); } else { break; } } }
static async Task<MessageReceiver> RunResultsReceiver(MessagingFactory receiverMessagingFactory) { // this receiver reads from the results queue and prints out the message var receiver = await receiverMessagingFactory.CreateMessageReceiverAsync(SagaResultQueueName); receiver.OnMessage(PrintResultMessage, new OnMessageOptions {AutoComplete = true}); return receiver; }
public async Task <IMessageReceiver> CreateMessageReceiver(string entitypath, ReceiveMode receiveMode) { return(new MessageReceiverAdapter(await factory.CreateMessageReceiverAsync(entitypath, receiveMode).ConfigureAwait(false))); }