Пример #1
0
 protected static Task <TResult> SendAsync <TQueueProcessor, TResult>(TMessageParam messageParams, string subscription,
                                                                      Func <TResult> onSent,
                                                                      Func <string, TResult> onFailure)
     where TQueueProcessor : QueueProcessor <TMessageParam>
 {
     return(Web.Configuration.Settings.GetString(
                Security.SessionServer.Configuration.AppSettings.ServiceBusConnectionString,
                async serviceBusConnectionString =>
     {
         var message = new Microsoft.Azure.ServiceBus.Message();
         EncodeMessageParams(message.UserProperties, messageParams);
         message.UserProperties[MESSAGE_PROPERTY_KEY_MESSAGE_NAME] = subscription;
         var sendClient = new Microsoft.Azure.ServiceBus.QueueClient(serviceBusConnectionString, subscription);
         try
         {
             await sendClient.SendAsync(message);
             return onSent();
         }
         catch (Exception ex)
         {
             return onFailure(ex.Message);
         }
         finally
         {
             await sendClient.CloseAsync();
         }
     },
                onFailure.AsAsyncFunc()));
 }
Пример #2
0
        public static async Task <Microsoft.Azure.ServiceBus.Message> ReceiveAsync(this Microsoft.Azure.ServiceBus.QueueClient sbClient, TimeSpan?timeout)
        {
            var receiver = (Microsoft.Azure.ServiceBus.Core.MessageReceiver)InnerReceiverProperty.GetValue(sbClient);

            var msg = timeout.HasValue
                ? await receiver.ReceiveAsync(timeout.Value)
                : await receiver.ReceiveAsync();

            return(msg);
        }
Пример #3
0
        public ServiceBusSender(IConfigureServiceBus configure)
        {
            _connectionStringServiceBus  = configure.ConnectionStringServiceBus;
            _connectionStringBlobStorage = configure.ConnectionStringBlobStorage;
            _queueName     = configure.QueueName;
            _containerName = configure.ContainerName;

            _queueClient = new Microsoft.Azure.ServiceBus.QueueClient(_connectionStringServiceBus, _queueName);
            _container   = new BlobContainerClient(_connectionStringBlobStorage, _containerName);
            _container.CreateIfNotExists();
        }
        public AzureServiceBusMqServerAppHostTests()
        {
#if !NETCORE_SUPPORT
            NamespaceManager nm = NamespaceManager.CreateFromConnectionString(ConnectionString);
            Parallel.ForEach(nm.GetQueues(), qd =>
            {
                var sbClient        = QueueClient.CreateFromConnectionString(ConnectionString, qd.Path, ReceiveMode.ReceiveAndDelete);
                BrokeredMessage msg = null;
                while ((msg = sbClient.Receive(new TimeSpan(0, 0, 1))) != null)
                {
                }
            });
#endif
        }
Пример #5
0
        public async Task <IActionResult> SendEmail([FromServices] IOptions <ServiceBusOptions> options, SendEmailRequest sendEmailRequest)
        {
            var email          = Newtonsoft.Json.JsonConvert.SerializeObject(sendEmailRequest);
            var messagecontent = System.Text.Encoding.UTF8.GetBytes(email);
            var qc             = new Microsoft.Azure.ServiceBus.QueueClient(options.Value.ConnectionString, "email-input");
            await qc.SendAsync(new Microsoft.Azure.ServiceBus.Message(messagecontent));

            // var random = new Random();
            // Thread.Sleep(random.Next(3000, 8000));

            // if(random.Next(0, 1) > 0)
            //     return StatusCode(InternalServerErrorHttpStatusCode);

            return(RedirectToAction(nameof(Index)));
        }
Пример #6
0
        protected QueueProcessor(string subscription)
        {
            subscription  = subscription.ToLower();
            subscriptions = subscriptions.Append(subscription).ToArray();
            var xexecutionThread = Web.Configuration.Settings.GetString(
                EastFive.Security.SessionServer.Configuration.AppSettings.ServiceBusConnectionString,
                serviceBusConnectionString =>
            {
                var receiveClient = new Microsoft.Azure.ServiceBus.QueueClient(serviceBusConnectionString, subscription);
                // TODO: Create the topic if it does not exist already but swallow the errors if manage privilige is not available

                Func <Microsoft.Azure.ServiceBus.Message, CancellationToken, Task> processMessagesAsync =
                    async(message, cancellationToken) =>
                {
                    try
                    {
                        processing = true;
                        await ProcessAsync(message, receiveClient);
                    }
                    catch (Exception ex)
                    {
                        ex.Message.GetType();
                    }
                    finally
                    {
                        processing = false;
                    }
                };

                var messageHandlerOptions = new Microsoft.Azure.ServiceBus.MessageHandlerOptions(ExceptionReceivedHandler)
                {
                    // Maximum number of concurrent calls to the callback ProcessMessagesAsync(), set to 1 for simplicity.
                    // Set it according to how many messages the application wants to process in parallel.
                    MaxConcurrentCalls = 1,

                    // Indicates whether the message pump should automatically complete the messages after returning from user callback.
                    // False below indicates the complete operation is handled by the user callback as in ProcessMessagesAsync().
                    AutoComplete = false,

                    MaxAutoRenewDuration = TimeSpan.FromHours(1),
                };

                // Register the function that processes messages.
                receiveClient.RegisterMessageHandler(processMessagesAsync, messageHandlerOptions);
                return(string.Empty);
            },
                (why) => why);
        }
Пример #7
0
 private async Task ProcessAsync(Microsoft.Azure.ServiceBus.Message message, Microsoft.Azure.ServiceBus.QueueClient client)
 //private async Task Execute(BrokeredMessage receivedMessage)
 {
     try
     {
         // Process the message
         var messageParams = ParseMessageParams(message.UserProperties);
         var messageAction = await ProcessMessageAsync <MessageProcessStatus>(messageParams,
                                                                              async() =>
         {
             //message.Complete();
             await client.CompleteAsync(message.SystemProperties.LockToken);
             return(MessageProcessStatus.Complete);
         },
                                                                              async() =>
         {
             // TODO: Update resent count and send error if it gets too large
             // Let message get resent
             await client.ScheduleMessageAsync(message, DateTimeOffset.UtcNow + TimeSpan.FromSeconds(10));
             return(MessageProcessStatus.ReprocessImmediately);
         },
                                                                              async (whyReturned) =>
         {
             await client.DeadLetterAsync(message.SystemProperties.LockToken, whyReturned);
             return(MessageProcessStatus.Broken);
         });
     }
     catch (Exception ex)
     {
         //var telemetryData = (new System.Collections.Generic.Dictionary<string, string>
         //        {
         //               { "receivedMessage.MessageId", receivedMessage.MessageId },
         //               { "receivedMessage.SessionId", receivedMessage.SessionId },
         //               { "receivedMessage.ContentType", receivedMessage.ContentType },
         //               { "receivedMessage.SequenceNumber", receivedMessage.SequenceNumber.ToString() },
         //               { "exception.Message", ex.Message },
         //               { "exception.StackTrace", ex.StackTrace },
         //        })
         //.Concat(receivedMessage.Properties
         //    .Select(prop => $"receivedMessage.Properties[{prop.Key}]".PairWithValue(
         //        null == prop.Value ? string.Empty : prop.Value.ToString())))
         //.ToDictionary();
         //telemetry.TrackException(ex, telemetryData);
         await client.DeadLetterAsync(message.SystemProperties.LockToken, ex.Message);
     }
 }