private async Task ProcessMessagesAsync(Microsoft.Azure.ServiceBus.Message message, CancellationToken token)
        {
            var msg = Encoding.UTF8.GetString(message.Body);

            string filePath = Path.GetTempFileName();

            try
            {
                BlobClient blob = _container.GetBlobClient(msg);

                BlobDownloadInfo download = blob.Download();
                using (FileStream file = System.IO.File.Create(filePath))
                {
                    download.Content.CopyTo(file);
                }


                var ratings = _serializationService.Deserialize(filePath);
            }
            catch (Exception ex)
            {
            }
            finally
            {
                await _queueClient.CompleteAsync(message.SystemProperties.LockToken);
            }
        }
        public virtual void Publish(string queueName, IMessage message)
        {
            queueName       = queueName.SafeQueueName();
            message.ReplyTo = message.ReplyTo.SafeQueueName();

            var sbClient = parentFactory.GetOrCreateClient(queueName);

            using (JsConfig.With(includeTypeInfo: true))
            {
                var msgBody = JsonSerializer.SerializeToString(message, typeof(IMessage));
#if NETSTANDARD2_0
                var msg = new Microsoft.Azure.ServiceBus.Message()
                {
                    Body      = msgBody.ToUtf8Bytes(),
                    MessageId = message.Id.ToString()
                };
                sbClient.SendAsync(msg).Wait();
#else
                var msg = new BrokeredMessage(msgBody)
                {
                    MessageId = message.Id.ToString()
                };

                sbClient.Send(msg);
#endif
            }
        }
Example #3
0
        public static void Run([QueueTrigger("myqueue-items", Connection = "quequeconnection")] string myQueueItem, ILogger log)
        {
            log.LogInformation($"C# Queue trigger function processed: {myQueueItem}");
            dynamic json = JsonConvert.DeserializeObject <Sample>(myQueueItem);
            int     id;



            //Int32.TryParse(json.id, out id);
            //Shardinghelper obj = new Shardinghelper();
            //obj.AddShard(id);


            const string connectionString = "Endpoint=sb://servicebus347.servicebus.windows.net/;SharedAccessKeyName=RootManageSharedAccessKey;SharedAccessKey=5tDP6HC7kthwV7+bOzdhE+PxRERAHu0AmleGJxgK2lU=";


            const string queueName = "myqueue-items";
            ServiceBusConnectionStringBuilder objconnection = new ServiceBusConnectionStringBuilder(connectionString);
            var _client = new Microsoft.Azure.ServiceBus.QueueClient(connectionString, queueName);

            string Message = "I'm in Azure Service Bus Queue";

            Microsoft.Azure.ServiceBus.Message message = new Microsoft.Azure.ServiceBus.Message(Encoding.UTF8.GetBytes(Message));
            _client.SendAsync(message);
        }
 public ReceiveExceptionContext(QueueClient queueClient, Microsoft.Azure.ServiceBus.Message message,
                                Exception exception)
 {
     QueueClient = queueClient;
     Message     = message;
     Exception   = exception;
 }
Example #5
0
        private async Task MessageReceived(Microsoft.Azure.ServiceBus.Message message, CancellationToken cancelationToken)
        {
            try
            {
                using (var compressedStream = new MemoryStream(message.Body))
                    using (var decompressorStream = new DeflateStream(compressedStream, CompressionMode.Decompress))
                    {
                        using (var decompressedStream = new MemoryStream())
                        {
                            decompressorStream.CopyTo(decompressedStream);

                            await ReceiveAsync(new Request(decompressedStream.ToArray()));

                            await _subscriptionClient.CompleteAsync(message.SystemProperties.LockToken);
                        }
                    }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"{ex.GetType().Name}: {ex.Message}");
                Console.WriteLine(ex.StackTrace);
                await _subscriptionClient.DeadLetterAsync(message.SystemProperties.LockToken, ex.GetType().FullName, ex.Message);

                throw;
            }
        }
        private async Task OnMessage2(Microsoft.Azure.ServiceBus.Message message, CancellationToken token)
        {
            if (token.IsCancellationRequested || message == null)
            {
                return;
            }

            try
            {
                var tuple            = _converter.FromAzureMessage(message);
                var outboundMessages = new List <Message>();
                var ctx = new InvocationContext(message.Label, tuple.Item1, _invoker, outboundMessages);
                await _invoker.ProcessAsync(ctx, tuple.Item2);


                var azureMsgs = new List <Microsoft.Azure.ServiceBus.Message>();
                foreach (var outboundMessage in outboundMessages)
                {
                    var azureMsg = _converter.ToAzureMessage(outboundMessage, tuple.Item1);
                    azureMsgs.Add(azureMsg);
                }

                if (azureMsgs.Any())
                {
                    await _queueClient.SendAsync(azureMsgs);
                }
            }
            catch (Exception ex)
            {
                await _queueClient.AbandonAsync(message.SystemProperties.LockToken);

                ExceptionLogger?.OnReceiveException(new ReceiveExceptionContext(_queueClient, message, ex));
            }
        }
        /// <summary>
        /// Utilizar esse SendMessageAsync
        /// </summary>
        /// <param name="message"></param>
        public async void SendMessagesAsync(Microsoft.Azure.ServiceBus.Message message)
        {
            var connectionString = _configuration["serviceBus:connectionString"];
            var topicClient      = new TopicClient(_configuration["serviceBus:connectionString"], "UserChanged");

            //var queueClient = new QueueClient(connectionString, "UserChanged");
            int tries = 0;

            while (true)
            {
                try
                {
                    if ((tries > 10))
                    {
                        break;
                    }

                    await topicClient.SendAsync(message);

                    break;
                }
                catch { tries++; }
            }
            await topicClient.CloseAsync();
        }
Example #8
0
        public async Task PublishAsync(TType entry, IMessageMetadata messageMeta = null)
        {
            string messageData = (typeof(TType) == typeof(string)) ? entry as string : _serializationUtility.Serialize(entry);

            var message = new BrokeredMessage(messageMeta.MessageEncoding.GetBytes(messageData));

            if (messageMeta != null && !string.IsNullOrEmpty(messageMeta.CorrelationId))
            {
                message.CorrelationId = messageMeta.CorrelationId;
            }

            if (messageMeta != null && !string.IsNullOrEmpty(messageMeta.MessageId))
            {
                message.MessageId = messageMeta.MessageId;
            }

            if (messageMeta != null && !string.IsNullOrEmpty(messageMeta.MessagePart))
            {
                message.UserProperties.Add("messagePart", messageMeta.MessagePart);
            }

            if (messageMeta != null && !string.IsNullOrEmpty(messageMeta.MessageType))
            {
                message.UserProperties.Add("messageType", messageMeta.MessageType);
            }

            await _topicClient.SendAsync(message);
        }
 // Call all handlers for the message type given by the message label.
 // There can be multiple handlers per message type
 public async Task ProcessMessage(Microsoft.Azure.ServiceBus.Message message, CancellationToken token)
 {
     using (LogCorrelationOptions.PushToLogContext.Invoke(message))
     {
         var body = Encoding.UTF8.GetString(message.Body);
         Log.Debug($"Received message: SequenceNumber:{message.SystemProperties.SequenceNumber} Body:{body}");
         try
         {
             if (!string.IsNullOrWhiteSpace(message.Label))
             {
                 await ProcessMessage(message.Label, body,
                                      () => Client.CompleteAsync(message.SystemProperties.LockToken),
                                      m => AddToDeadLetter(message.SystemProperties.LockToken, m));
             }
             else
             {
                 Log.Error("Message label is not set. \n Message: {@messageBody} \n Forwarding to DLX", body);
                 await AddToDeadLetter(message.SystemProperties.LockToken, "Message label is not set.");
             }
         }
         catch (JsonException jsonException)
         {
             Log.Error(jsonException, "Unable to deserialize message. \n Message: {@messageBody} \n Forwarding to DLX", body);
             await AddToDeadLetter(message.SystemProperties.LockToken, jsonException.Message);
         }
     }
 }
Example #10
0
        public async Task SendMessage(string connectionString, string topicPath, AzureMessage message)
        {
            var topicClient = new TopicClient(connectionString, topicPath);
            await topicClient.SendAsync(message);

            await topicClient.CloseAsync();
        }
Example #11
0
        /// <summary>
        /// Extract any telemetry properties from the provided <paramref name="message"/>.
        /// </summary>
        protected virtual IDictionary <string, string> ExtractTelemetryProperties(BrokeredMessage message, string baseCommunicationType)
        {
            IDictionary <string, string> telemetryProperties = new Dictionary <string, string> {
                { "Type", baseCommunicationType }
            };
            object value;

            if (message.TryGetUserPropertyValue("Type", out value))
            {
                telemetryProperties.Add("MessageType", value.ToString());
            }
            if (message.TryGetUserPropertyValue("Source", out value))
            {
                telemetryProperties.Add("MessageSource", value.ToString());
            }
            if (message.TryGetUserPropertyValue("Source-Method", out value))
            {
                telemetryProperties.Add("MessageSourceMethod", value.ToString());
            }
            if (message.TryGetUserPropertyValue("CorrelationId", out value) && !telemetryProperties.ContainsKey("CorrelationId"))
            {
                telemetryProperties.Add("CorrelationId", value.ToString());
            }

            return(telemetryProperties);
        }
        private Task HandleResponseMessage(AzureServiceBusMessage message, CancellationToken cancellationToken)
        {
            if (message.UserProperties.TryGetValue(RequestMessageIdentifierUserPropertyKey, out var requestMessageIdentifier))
            {
                var responseMessageKey = requestMessageIdentifier?.ToString();

                if (responseMessageKey.IsNullOrEmpty())
                {
                    throw new InvalidOperationException("The response message did not contain a request identifier.");
                }

                if (OutstandingResponseKeys.Contains(responseMessageKey))
                {
                    OutstandingResponseKeys.Remove(responseMessageKey);

                    if (ResponseMessageDictionary.TryAdd(responseMessageKey, message))
                    {
                        return(Task.CompletedTask);
                    }
                }
                else
                {
                    // The response is intended for another client manager.
                    return(Task.CompletedTask);
                }
            }

            throw new InvalidOperationException("The response subscriber received multiple responses or the system state is corrupt.");
        }
Example #13
0
        private static async Task ServiceBusOutput(Shared.Model.Message[] messages, StorageEndpointConfiguration configItem)
        {
            try
            {
                QueueClient queueClient = new QueueClient(configItem.ConnectionString, configItem.Name);

                List <Microsoft.Azure.ServiceBus.Message> serviceBusMessages = new List <Microsoft.Azure.ServiceBus.Message>();

                foreach (Syslog.Shared.Model.Message logMessage in messages)
                {
                    Microsoft.Azure.ServiceBus.Message serviceBusMessage = new Microsoft.Azure.ServiceBus.Message()
                    {
                        Body         = Encoding.UTF8.GetBytes(logMessage.MessageText),
                        MessageId    = logMessage.RowKey,
                        PartitionKey = logMessage.PartitionKey,
                    };

                    serviceBusMessage.UserProperties.Add("SourceIP", logMessage.SourceIP);
                    serviceBusMessage.UserProperties.Add("RecvTime", logMessage.RecvTime);

                    serviceBusMessages.Add(serviceBusMessage);
                }

                await queueClient.SendAsync(serviceBusMessages);
            }
            catch (Exception ex)
            {
                if (Program.telemetryClient != null)
                {
                    Program.telemetryClient.TrackException(ex);
                }

                Console.WriteLine("An error occured: " + ex.Message);
            }
        }
Example #14
0
        private async Task <bool> SendMessageAsync(QueueClient client, Message message)
        {
            if (Config.SystemBehaviorConfig.ServiceBusType == Config.ServiceBusTypes.Azure)
            {
                int  retry = 0;
                bool sent  = false;

                while (!sent)
                {
                    try
                    {
                        await client.SendAsync(message);

                        sent = true;
                    }
                    catch (Exception ex)
                    {
                        Logging.LogException(ex, message.ToString());

                        if (retry >= 5)
                        {
                            return(false);
                        }

                        Thread.Sleep(250);
                        retry++;
                    }
                }

                return(sent);
            }

            return(false);
        }
        public async Task SendNotification(NotificationDto payload)
        {
            var bytes   = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(payload));
            var message = new Microsoft.Azure.ServiceBus.Message(bytes);

            await client.SendAsync(message);
        }
Example #16
0
        private async Task ProcessMessageAsync(Microsoft.Azure.ServiceBus.Message message, CancellationToken token)
        {
            QueueClient queueClient = _queueClient;

            try
            {
                if (!string.Equals(message.ContentType, "application/json"))
                {
                    throw new Exception($"Invalid content type for AMQP message: {message.ContentType}");
                }

                if (message.Body != null)
                {
                    await _messenger.ProcessMessageAsync(Address, Encoding.UTF8.GetString(message.Body)).ConfigureAwait(false);
                }
                else
                {
                    await _messenger.ProcessMessageAsync(Address, null).ConfigureAwait(false);
                }

                await queueClient.CompleteAsync(message.SystemProperties.LockToken).ConfigureAwait(false);
            }
            catch (RescheduleException)
            {
                // no log, this is "wanted"

                await queueClient.AbandonAsync(message.SystemProperties.LockToken).ConfigureAwait(false);
            }
            catch (Exception exception)
            {
                Console.WriteLine($"Exception during processing AMQP message, not abandoning it for timeout (this will avoid duplicates): {exception}");
            }
        }
        private SB.Message ToServiceBusMessage(MessageBus.Spec.Message message)
        {
            var serializedMessage = _converter.Serialize(message.Payload);
            var messageBody       = Encoding.UTF8.GetBytes(serializedMessage);
            var sbMsg             = new SB.Message(messageBody)
            {
                MessageId   = message.Id,
                ContentType = message.IsControl ? "control" : message.ContentType
            };

            if (!string.IsNullOrEmpty(message.FilterCorrelation))
            {
                sbMsg.CorrelationId = message.FilterCorrelation;
            }

            if (message.Properties != null && message.Properties.Any())
            {
                foreach (var property in message.Properties)
                {
                    sbMsg.UserProperties.Add(property);
                }
            }

            return(sbMsg);
        }
Example #18
0
        public async Task <OperateResult> SendAsync(TransportMessage transportMessage)
        {
            try
            {
                Connect();

                var message = new Microsoft.Azure.ServiceBus.Message
                {
                    MessageId     = transportMessage.GetId(),
                    Body          = transportMessage.Body,
                    Label         = transportMessage.GetName(),
                    CorrelationId = transportMessage.GetCorrelationId()
                };

                foreach (var header in transportMessage.Headers)
                {
                    message.UserProperties.Add(header.Key, header.Value);
                }

                await _topicClient.SendAsync(message);

                _logger.LogDebug($"Azure Service Bus message [{transportMessage.GetName()}] has been published.");

                return(OperateResult.Success);
            }
            catch (Exception ex)
            {
                var wrapperEx = new PublisherSentFailedException(ex.Message, ex);

                return(OperateResult.Failed(wrapperEx));
            }
        }
Example #19
0
        public async Task PublishEventsAsync(params IntegrationEvent[] events)
        {
            if (events != null)
            {
                foreach (var @event in events)
                {
                    var entity = new IntegrationEventEntity
                    {
                        Id            = @event.MessageId,
                        CorrelationId = httpContextAccessor.HttpContext?.TraceIdentifier,
                        ExecutedBy    = httpContextAccessor.HttpContext?.User.GetId(),
                        Type          = @event.GetType().AssemblyQualifiedName,
                        FullName      = @event.GetType().FullName,
                        Payload       = messageSerializer.Serialize(@event),
                        Date          = DateTimeOffset.UtcNow
                    };

                    db.IntegrationEvents.Add(entity);

                    db.SaveChanges();
                    logger.Info("[ServiceBus->PublishEventsAsync] Sending integration event of type: {0}", @event.GetType().Name);

                    var brokeredMessage = new Microsoft.Azure.ServiceBus.Message(entity.Payload);

                    brokeredMessage.UserProperties["CorrelationId"] = entity.CorrelationId;
                    brokeredMessage.UserProperties["Name"]          = @event.GetType().Name;
                    brokeredMessage.UserProperties["FullName"]      = @event.GetType().FullName;
                    brokeredMessage.UserProperties["Namespace"]     = @event.GetType().Namespace;
                    brokeredMessage.UserProperties["Type"]          = @event.GetType().AssemblyQualifiedName;
                    brokeredMessage.UserProperties["EventType"]     = "Integration";

                    await topicClient.SendAsync(brokeredMessage);
                }
            }
        }
Example #20
0
        public async Task SendMessage(string connectionString, string queueName, AzureMessage message)
        {
            var client = new QueueClient(connectionString, queueName);
            await client.SendAsync(message);

            await client.CloseAsync();
        }
Example #21
0
 private async Task CompleteMessageAsync(Microsoft.Azure.ServiceBus.Message sbMessage, CancellationToken cancelToken)
 {
     if (cancelToken.IsCancellationRequested == false)
     {
         await receiverClient.CompleteAsync(sbMessage.SystemProperties.LockToken).ConfigureAwait(false);
     }
 }
Example #22
0
        static async Task SendMessagesAsync()
        {
            string messageBody = dato;
            var    message     = new Message(Encoding.UTF8.GetBytes(messageBody));
            await queueClient.SendAsync(message);

            return;
        }
Example #23
0
        public async Task SendMessage(string connectionString, string queueName, string content)
        {
            var message = new AzureMessage {
                Body = Encoding.UTF8.GetBytes(content)
            };

            await SendMessage(connectionString, queueName, message);
        }
        protected override async Task PublishCore(Message message)
        {
            var sbMessage = new SbMessage(message.Body);

            sbMessage.ContentType = message.ContentType;
            sbMessage.MessageId   = message.MessageId;
            await _topicClient.SendAsync(sbMessage);
        }
Example #25
0
 private async Task ProcessMessageAsync(SB.Message message, CancellationToken token)
 {
     await Task.Run(() =>
     {
         var messageReceivedArgs = new MessageReceivedArgs(message);
         MessageReceived(this, messageReceivedArgs);
     });
 }
        private Task OnConsumerReceived(Message message, CancellationToken token)
        {
            var context = ConvertMessage(message);

            OnMessageReceived?.Invoke(new AzureServiceBusConsumerCommitInput(message.SystemProperties.LockToken), context);

            return(Task.CompletedTask);
        }
        private TransportMessage ConvertMessage(Message message)
        {
            var header = message.UserProperties.ToDictionary(x => x.Key, y => y.Value?.ToString());

            header.Add(Headers.Group, _subscriptionName);

            return(new TransportMessage(header, message.Body));
        }
Example #28
0
        protected override void ReceiveCommand(IMessageReceiver client, BrokeredMessage message)
#endif
        {
            try
            {
                Logger.LogDebug(string.Format("A command message arrived with the id '{0}'.", message.MessageId));
                string messageBody = message.GetBodyAsString();
                ICommand <TAuthenticationToken> command = MessageSerialiser.DeserialiseCommand(messageBody);

                CorrelationIdHelper.SetCorrelationId(command.CorrelationId);
#if NET452
                string topicPath = serviceBusReceiver == null ? "UNKNOWN" : serviceBusReceiver.TopicPath;
#endif
#if NETSTANDARD2_0
                string topicPath = client == null ? "UNKNOWN" : client.Path;
#endif
                Logger.LogInfo($"A command message arrived from topic {topicPath} with the {message.MessageId} was of type {command.GetType().FullName}.");

                Type commandType = command.GetType();

                string targetQueueName = commandType.FullName;

                try
                {
                    object rsn = commandType.GetProperty("Rsn").GetValue(command, null);
                    targetQueueName = string.Format("{0}.{1}", targetQueueName, rsn);
                }
                catch
                {
                    Logger.LogDebug(string.Format("A command message arrived with the id '{0}' was of type {1} but with no Rsn property.", message.MessageId, commandType));
                    // Do nothing if there is no rsn. Just use command type name
                }

                CreateQueueAndAttachListenerIfNotExist(targetQueueName);
                EnqueueCommand(targetQueueName, command);

                // remove the original message from the incoming queue
#if NET452
                message.Complete();
#endif
#if NETSTANDARD2_0
                client.CompleteAsync(message.SystemProperties.LockToken).Wait(1500);
#endif

                Logger.LogDebug(string.Format("A command message arrived and was processed with the id '{0}'.", message.MessageId));
            }
            catch (Exception exception)
            {
                // Indicates a problem, unlock message in queue
                Logger.LogError(string.Format("A command message arrived with the id '{0}' but failed to be process.", message.MessageId), exception: exception);
#if NET452
                message.Abandon();
#endif
#if NETSTANDARD2_0
                client.AbandonAsync(message.SystemProperties.LockToken).Wait(1500);
#endif
            }
        }
Example #29
0
        private async Task HandleMessageAsync(Microsoft.Azure.ServiceBus.Message sbMessage, CancellationToken cancelToken)
        {
            var messageContext = new MessageContext(
                sbMessage.ToStandardMessage(),
                () => AbandonMessageAsync(sbMessage, cancelToken),
                () => CompleteMessageAsync(sbMessage, cancelToken));

            await messageHandler.HandleMessageAsync(messageContext);
        }
        public async void Send <TEvent>(TEvent message) where TEvent : Event
        {
            var serviceBusMessage = new Microsoft.Azure.ServiceBus.Message(SerializeMessage(message));

            serviceBusMessage.UserProperties.Add(EventName, typeof(TEvent).AssemblyQualifiedName);

            // Send the message to the topic
            await topicClient.SendAsync(serviceBusMessage);
        }