public T Deserialize <T>(Amazon.SQS.Model.Message busMessage) where T : Message
        {
            var busBodyMessage = JsonConvert.DeserializeObject <BusBodyMessage>(busMessage.Body);
            var message        = JsonConvert.DeserializeObject <T>(busBodyMessage.Message);

            return(message);
        }
        private Message ToStandardMessage(Amazon.SQS.Model.Message sqsMessage)
        {
            if (sqsMessage == null)
            {
                throw new ArgumentNullException(nameof(sqsMessage));
            }

            var message = new Message {
                Content = sqsMessage.Body
            };

            foreach (var attributeKey in sqsMessage.MessageAttributes.Keys)
            {
                var attributeValue = sqsMessage.MessageAttributes[attributeKey].StringValue;

                if (attributeKey == PlatformAttributes.Id)
                {
                    message.Id = attributeValue;
                }
                else
                {
                    message.Attributes[attributeKey] = attributeValue;
                }
            }

            return(message);
        }
        public void When_posting_a_message_via_the_messaging_gateway()
        {
            _messageProducer.Send(_message);
            _listenedMessage = _queueListener.Listen();

            //should_send_the_message_to_aws_sqs
            Assert.NotNull(_listenedMessage.Body);
        }
Exemplo n.º 4
0
 protected HeaderResult <string> ReadReceiptHandle(Amazon.SQS.Model.Message sqsMessage)
 {
     if (sqsMessage.ReceiptHandle != null)
     {
         return(new HeaderResult <string>(sqsMessage.ReceiptHandle, true));
     }
     return(new HeaderResult <string>(string.Empty, true));
 }
        public void Convert_throws_PossiblyPoisonMessageException_if_cant_deserialize()
        {
            var queue = new MarketDataRequestQueue();
            var message = new Amazon.SQS.Model.Message
                              {
                                  Body = "some garbage",
                              };

            Assert.Throws<PossiblyPoisonMessageException>(() => queue.Convert(message));
        }
        private static bool MessageIsExpiredUsingNativeSqsSentTimestamp(Message message, TimeSpan timeToBeReceived)
        {
            if (message.Attributes.TryGetValue("SentTimestamp", out var sentTimeStampString) == false)
            {
                return(false);
            }

            var sentTime = GetTimeFromUnixTimestamp(sentTimeStampString);

            return(RebusTime.Now.UtcDateTime - sentTime > timeToBeReceived);
        }
        public static bool MessageIsExpired(this TransportMessage message, Message sqsMessage)
        {
            if (message.Headers.TryGetValue(Headers.TimeToBeReceived, out var value) == false)
            {
                return(false);
            }

            var timeToBeReceived = TimeSpan.Parse(value, CultureInfo.InvariantCulture);

            return(MessageIsExpiredUsingRebusSentTime(message, timeToBeReceived) || MessageIsExpiredUsingNativeSqsSentTimestamp(sqsMessage, timeToBeReceived));
        }
Exemplo n.º 8
0
 /// <summary>
 /// This class encapsulates a messages context as it passes through a middleware pipeline.
 /// </summary>
 /// <param name="message">The JustSaying message that was deserialized from SQS.</param>
 /// <param name="messageType">The type of the JustSaying message contained in <see cref="Message"/>.</param>
 /// <param name="queueName">The queue from which this message was received.</param>
 /// <param name="visibilityUpdater">The <see cref="IMessageVisibilityUpdater"/> to use to update message visibilities on failure.</param>
 /// <param name="messageDeleter">The <see cref="IMessageDeleter"/> to use to remove a message from the queue on success.</param>
 public HandleMessageContext(string queueName, Amazon.SQS.Model.Message rawMessage, Message message,
                             Type messageType, IMessageVisibilityUpdater visibilityUpdater, IMessageDeleter messageDeleter,
                             Uri queueUri, MessageAttributes messageAttributes)
 {
     Message           = message;
     MessageType       = messageType;
     QueueName         = queueName;
     VisibilityUpdater = visibilityUpdater;
     MessageDeleter    = messageDeleter;
     QueueUri          = queueUri;
     MessageAttributes = messageAttributes;
     RawMessage        = rawMessage;
 }
Exemplo n.º 9
0
        /// <summary>
        /// GetNext:  If no job available on queue return null
        /// </summary>
        /// <returns></returns>
        public IJobConsumerContract GetNext()
        {
            Amazon.SQS.Model.ReceiveMessageResponse receiveMsgResponse;
            Debug.WriteLine(String.Format("Register: Poll Queue {0} for response", jobQueueUrl), GetType().Name);
            receiveMsgResponse = Queue.ReceiveMessage(new Amazon.SQS.Model.ReceiveMessageRequest()
                                                      .WithMaxNumberOfMessages(1)
                                                      .WithWaitTimeSeconds(5)
                                                      .WithQueueUrl(jobQueueUrl));

            if (receiveMsgResponse.IsSetReceiveMessageResult() == false || receiveMsgResponse.ReceiveMessageResult.IsSetMessage() == false)
            {
                return(null);
            }

            // Response Message Should Have ResponseQueue & SNS Topic
            List <Amazon.SQS.Model.Message> msgResultMsg = receiveMsgResponse.ReceiveMessageResult.Message;

            if (msgResultMsg.Count != 1)
            {
                var exStr = String.Format("Protocol Error: Response should have 1 Message found: {0}", msgResultMsg.Count);
                Debug.WriteLine(exStr, GetType().Name);
                throw new Exception(exStr);
            }

            Amazon.SQS.Model.Message msg = msgResultMsg[0];

            Turbine.Orchestrator.AWS.Data.Contract.Messages.SubmitJobMessage rsp = null;

            try
            {
                rsp = JsonConvert.DeserializeObject <Turbine.Orchestrator.AWS.Data.Contract.Messages.SubmitJobMessage>(msg.Body);
            }
            catch (Exception ex)
            {
                Debug.WriteLine(String.Format("Exception deserializing SubmitJobMessage: {0}", ex), GetType().Name);
                throw;
            }

            //Amazon.SQS.Model.DeleteMessageResponse delMsgRsp = Queue.DeleteMessage(

            var jobConsumer = new JobConsumer(rsp);

            jobConsumer.AddSetupCB(Queue.DeleteMessage, new Amazon.SQS.Model.DeleteMessageRequest()
                                   .WithReceiptHandle(msg.ReceiptHandle)
                                   .WithQueueUrl(jobQueueUrl),
                                   CheckDeleteMessageResponse);

            return(jobConsumer);
        }
Exemplo n.º 10
0
        private MessageBody ReadMessageBody(Amazon.SQS.Model.Message sqsMessage)
        {
            try
            {
                var jsonDocument = JsonDocument.Parse(sqsMessage.Body);

                if (jsonDocument.RootElement.TryGetProperty("Message", out var value))
                {
                    return(new MessageBody(value.GetString()));
                }
            }
            catch (Exception ex)
            {
                s_logger.LogWarning($"Failed to parse Sqs Message Body to valid Json Document, ex: {ex}");
            }

            return(new MessageBody(string.Empty));
        }
        /// <summary>Creates the specified message.</summary>
        /// <param name="message">The message.</param>
        /// <returns></returns>
        public IAmazonMessageProcessor Create(Message message)
        {
            if (message.Body.StartsWith("{", false, CultureInfo.InvariantCulture))
            {
                var messageJObject = JObject.Parse(message.Body);

                var isFromSnsTopic = messageJObject["Type"]?.Value <string>() == Amazon.SimpleNotificationService.Util.Message.MESSAGE_TYPE_NOTIFICATION;

                if (isFromSnsTopic)
                {
                    return(new SnsTopicAmazonMessageProcessor(messageJObject, _amazonInternalSettings));
                }
                else
                {
                    return(new RebusMessageAmazonMessageProcessor(message, _amazonInternalSettings));
                }
            }

            return(new RebusMessageAmazonMessageProcessor(message, _amazonInternalSettings));
        }
Exemplo n.º 12
0
        private Dictionary <string, JsonElement> ReadMessageAttributes(Amazon.SQS.Model.Message sqsMessage)
        {
            var messageAttributes = new Dictionary <string, JsonElement>();

            try
            {
                var jsonDocument = JsonDocument.Parse(sqsMessage.Body);

                if (jsonDocument.RootElement.TryGetProperty("MessageAttributes", out var attributes))
                {
                    messageAttributes = JsonSerializer.Deserialize <Dictionary <string, JsonElement> >(
                        attributes.GetRawText(),
                        JsonSerialisationOptions.Options);
                }
            }
            catch (Exception ex)
            {
                s_logger.LogWarning($"Failed while deserializing Sqs Message body, ex: {ex}");
            }

            return(messageAttributes);
        }
Exemplo n.º 13
0
            public void DeserializeMessage()
            {
                var testMessage = new TestMessage();

                testMessage.Name = "Test";
                var testMessageJson = JsonConvert.SerializeObject(testMessage);

                BusBodyMessage busBodyMessage = new BusBodyMessage();

                busBodyMessage.Message = testMessageJson;
                var busBodyJson = JsonConvert.SerializeObject(busBodyMessage);

                var message = new Amazon.SQS.Model.Message
                {
                    Body = busBodyJson
                };

                var sut = new MessageDeserializer();

                var actual = sut.Deserialize <TestMessage>(message);

                actual.Name = "ExpectedMessage";
            }
        public async void ProcessNotification(object message)
        {
            try
            {
                Amazon.SQS.Model.Message msg = (Amazon.SQS.Model.Message)message;

                string queMessage = msg.Body;
                //LogInfo.Information("8 - bsubscription is  {" + msg.MessageId + "} object");
                SNSSubscription subscription = JsonConvert.DeserializeObject <SNSSubscription>(queMessage);

                //LogInfo.Information("8 - bsubscription is  {" + subscription.MessageId + "} object");
                NotificationMessage NotMessage = JsonConvert.DeserializeObject <NotificationMessage>(subscription.Message);
                //LogInfo.Information("9 - NotMessage is  {" + NotMessage.Message +" "+ NotMessage.MessageType + "} object");
                // SNSSubscription messageObject= new SNSSubscription {  Message=me};

                //   NotificationMessage notification= JsonConvert.DeserializeObject<NotificationMessage>(messageObject.Message);
                if (NotMessage.MessageType == NotificationMsgType.Email.GetDescription())
                {
                    OutboundEmail _email = new OutboundEmail();

                    ConfigDataAccess _configAccess = new ConfigDataAccess(_iconfiguration);

                    DatabaseResponse emailTemplate = await _configAccess.GetEmailNotificationTemplate(NotMessage.Message.messagetemplate.ToString());

                    EmailTemplate template = (EmailTemplate)emailTemplate.Results;

                    var responses = await _email.SendEmail(NotMessage, _iconfiguration, template);


                    foreach (Mandrill.Model.MandrillSendMessageResponse response in responses)
                    {
                        foreach (NotificationParams param in NotMessage.Message.parameters)
                        {
                            if (response.Email == param.emailaddress)
                            {
                                DatabaseResponse notificationLogResponse = await _configAccess.CreateEMailNotificationLog(new NotificationLog {
                                    Status          = response.Status.ToString() == "Sent" ? 1 : 0, Email = response.Email,
                                    EmailTemplateID = template.EmailTemplateID, EmailBody = template.EmailBody,
                                    EmailSubject    = template.EmailSubject, ScheduledOn = subscription.Timestamp, SendOn = DateTime.Now
                                });
                            }
                        }
                    }
                }
                else if (NotMessage.MessageType == NotificationMsgType.SMS.GetDescription())
                {
                    OutboundSMS      _SMS          = new OutboundSMS();
                    TextMessage      smsData       = new TextMessage();
                    ConfigDataAccess _configAccess = new ConfigDataAccess(_iconfiguration);

                    DatabaseResponse smsTemplate = await _configAccess.GetSMSNotificationTemplate(NotMessage.Message.messagetemplate.ToString());

                    SMSTemplates template = (SMSTemplates)smsTemplate.Results;

                    foreach (var item in NotMessage.Message.parameters)
                    {
                        smsData.PhoneNumber = item.mobilenumber;

                        smsData.SMSText = template.SMSTemplate.Replace("*|NAME|*", item.name)
                                          .Replace("*|PARAM1|*", item.param1)
                                          .Replace("*|PARAM2|*", item.param2)
                                          .Replace("*|PARAM3|*", item.param3)
                                          .Replace("*|PARAM4|*", item.param4)
                                          .Replace("*|PARAM5|*", item.param5)
                                          .Replace("*|PARAM6|*", item.param6)
                                          .Replace("*|PARAM7|*", item.param7)
                                          .Replace("*|PARAM8|*", item.param8)
                                          .Replace("*|PARAM9|*", item.param9)
                                          .Replace("*|PARAM10|*", item.param10);
                        //LogInfo.Information("10 - SendSMS is  { "+ smsData+ "}");
                        string response = await _SMS.SendSMSNotification(smsData, _iconfiguration);

                        await _configAccess.CreateSMSNotificationLog(new SMSNotificationLog()
                        {
                            Email         = NotMessage.Message.parameters.Select(x => x.emailaddress).FirstOrDefault(),
                            Mobile        = smsData.PhoneNumber,
                            SMSTemplateID = template.SMSTemplateID,
                            SMSText       = smsData.SMSText,
                            Status        = response != "failure" ? 1 : 0,
                            ScheduledOn   = subscription.Timestamp,
                            SendOn        = DateTime.Now
                        });
                    }

                    //LogInfo.Information("10 - SendSMSLog is  { " + NotMessage.Message.parameters.Select(x => x.emailaddress).FirstOrDefault() + " " + smsData.PhoneNumber + " "+ response + "}");
                }
            }

            catch (Exception ex)
            {
                LogInfo.Error(new ExceptionHelper().GetLogString(ex, ErrorLevel.Critical));
            }
        }
Exemplo n.º 15
0
 public void HandleError(Exception ex, Amazon.SQS.Model.Message message)
 {
 }
Exemplo n.º 16
0
 public MessageContext(SQSMessage message, Uri queueUri)
 {
     Message  = message ?? throw new ArgumentNullException(nameof(message));
     QueueUri = queueUri ?? throw new ArgumentNullException(nameof(queueUri));
 }
 private async Task CompleteMessageAsync(Amazon.SQS.Model.Message sqsMessage)
 {
     await sqsClient.DeleteMessageAsync(subscriberOptions.QueueUrl, sqsMessage.ReceiptHandle).ConfigureAwait(false);
 }
 private async Task AbandonMessageAsync(Amazon.SQS.Model.Message sqsMessage)
 {
     await sqsClient.ChangeMessageVisibilityAsync(subscriberOptions.QueueUrl, sqsMessage.ReceiptHandle, 0).ConfigureAwait(false);
 }
Exemplo n.º 19
0
        public void PossiblyPoisonMessageException_contains_original_messageid()
        {
            var messageId = "baz bat";
            var queue = new MarketDataRequestQueue();
            var message = new Amazon.SQS.Model.Message
            {
                Body = "some garbage",
                MessageId = messageId,
            };

            try
            {
                queue.Convert(message);
            }
            catch (PossiblyPoisonMessageException ppme)
            {
                Assert.That(ppme.MessageId, Is.EqualTo(messageId));
                return;
            }

            Assert.Fail("Should not have gotten this far in the test!");
        }
Exemplo n.º 20
0
        public Message CreateMessage(Amazon.SQS.Model.Message sqsMessage)
        {
            var topic = HeaderResult <string> .Empty();

            var messageId = HeaderResult <Guid> .Empty();

            var contentType = HeaderResult <string> .Empty();

            var correlationId = HeaderResult <Guid> .Empty();

            var handledCount = HeaderResult <int> .Empty();

            var messageType = HeaderResult <MessageType> .Empty();

            var timeStamp = HeaderResult <DateTime> .Empty();

            var receiptHandle = HeaderResult <string> .Empty();

            var replyTo = HeaderResult <string> .Empty();

            Message message;

            try
            {
                _messageAttributes = ReadMessageAttributes(sqsMessage);

                topic         = ReadTopic();
                messageId     = ReadMessageId();
                contentType   = ReadContentType();
                correlationId = ReadCorrelationId();
                handledCount  = ReadHandledCount();
                messageType   = ReadMessageType();
                timeStamp     = ReadTimestamp();
                replyTo       = ReadReplyTo();
                receiptHandle = ReadReceiptHandle(sqsMessage);

                var messageHeader = timeStamp.Success
                    ? new MessageHeader(messageId.Result, topic.Result, messageType.Result, timeStamp.Result, handledCount.Result, 0)
                    : new MessageHeader(messageId.Result, topic.Result, messageType.Result);

                if (correlationId.Success)
                {
                    messageHeader.CorrelationId = correlationId.Result;
                }

                if (replyTo.Success)
                {
                    messageHeader.ReplyTo = replyTo.Result;
                }

                if (contentType.Success)
                {
                    messageHeader.ContentType = contentType.Result;
                }

                message = new Message(messageHeader, ReadMessageBody(sqsMessage));

                //deserialize the bag
                var bag = ReadMessageBag();
                foreach (var key in bag.Keys)
                {
                    message.Header.Bag.Add(key, bag[key]);
                }

                if (receiptHandle.Success)
                {
                    message.Header.Bag.Add("ReceiptHandle", ((Amazon.SQS.Model.Message)sqsMessage).ReceiptHandle);
                }
            }
            catch (Exception e)
            {
                s_logger.LogWarning(e, "Failed to create message from Aws Sqs message");
                message = FailureMessage(topic, messageId);
            }


            return(message);
        }
 public RebusMessageAmazonMessageProcessor(Message message, IAmazonInternalSettings amazonInternalSettings)
 {
     _amazonInternalSettings = amazonInternalSettings;
     _message = message;
 }