示例#1
0
        private async Task CheckQueueForNewStatus(CancellationToken cancellationToken)
        {
            try
            {
                var sqs = new AmazonSQSClient(RegionEndpoint.EUWest1);
                var receiveMessageRequest = new ReceiveMessageRequest
                {
                    QueueUrl = "https://sqs.eu-west-1.amazonaws.com/166778461577/StatusCheckSchedulerNotifierQueue"
                };
                ReceiveMessageResponse receiveMessageResponse = null;

                try
                {
                    receiveMessageResponse = await sqs.ReceiveMessageAsync(receiveMessageRequest, cancellationToken);
                }
                catch (Exception ex)
                {
                    _logger.LogError(ex, "Error in scheduler while working with SQS");
                }

                if (receiveMessageResponse?.Messages != null && receiveMessageResponse.Messages.Any())
                {
                    int counter = -1;
                    foreach (var message in receiveMessageResponse.Messages)
                    {
                        counter++;
                        if (!string.IsNullOrEmpty(message.Body))
                        {
                            var dto    = JsonHelper.ReadObject <AwsSnsMessageDto>(message.Body);
                            var status = JsonHelper.ReadObject <VehicleStatusModel>(dto.Message);
                            OnNewStatusArrived(new NewVehicleStatusEventArgs(status));
                        }

                        var messageRecieptHandle = receiveMessageResponse.Messages[counter].ReceiptHandle;

                        var deleteRequest = new DeleteMessageRequest
                        {
                            QueueUrl      = "https://sqs.eu-west-1.amazonaws.com/166778461577/StatusCheckSchedulerNotifierQueue",
                            ReceiptHandle = messageRecieptHandle
                        };
                        await sqs.DeleteMessageAsync(deleteRequest, cancellationToken);
                    }
                }
            }
            catch (AmazonSQSException ex)
            {
                _logger.LogError(ex, "Error in scheduler while working with SQS");
                // do nothing, you may want to log, but let it give it another try in the next run
            }
        }
示例#2
0
        public async Task DeleteNewBookNotifyFromAWSSQSAsync(string receiptHandle)
        {
            if (!_AWSSQSSettings.IsActive)
            {
                throw new Exception("Serviço aws está desabilitado no appsettings.");
            }

            var deleteMessageRequest = new DeleteMessageRequest();

            deleteMessageRequest.QueueUrl      = _AWSSQSSettings.QueueUrl;
            deleteMessageRequest.ReceiptHandle = receiptHandle + "aaa";

            await _amazonSQSClient.DeleteMessageAsync(deleteMessageRequest);
        }
示例#3
0
        static void Main(string[] args)
        {
            var accessKey = ConfigurationManager.AppSettings.Get("AccessKey");
            var secretKey = ConfigurationManager.AppSettings.Get("SecretKey");
            var queueName = "EmailQueue2";

            AWSCredentials credentials = new BasicAWSCredentials(accessKey, secretKey);

            IAmazonSQS amazonSQS = new AmazonSQSClient(credentials, RegionEndpoint.EUWest2);

            var queueUrl = amazonSQS.GetQueueUrlAsync(queueName).Result.QueueUrl;

            var receveMessagerequest = new ReceiveMessageRequest()
            {
                QueueUrl = queueUrl
            };

            var receiveMessageResponse = amazonSQS.ReceiveMessageAsync(receveMessagerequest).Result;

            foreach (var message in receiveMessageResponse.Messages)
            {
                Console.WriteLine("Message \n");
                Console.WriteLine($" MessageId: {message.MessageId} \n");
                Console.WriteLine($" Receipthandle: {message.ReceiptHandle} \n");
                Console.WriteLine($" MSD5Body: {message.MD5OfBody} \n");
                Console.WriteLine($" Body: {message.Body} \n");

                foreach (var attributes in message.Attributes)
                {
                    Console.WriteLine("Attributes \n");
                    Console.WriteLine($" Name: {attributes.Key} \n");
                    Console.WriteLine($" Value: {attributes.Value} \n");
                }

                var messageHandle = receiveMessageResponse.Messages.FirstOrDefault()?.ReceiptHandle;

                var deleteRequest = new DeleteMessageRequest
                {
                    QueueUrl      = queueUrl,
                    ReceiptHandle = messageHandle
                };

                Console.WriteLine($"deleting message with MessageHandle: {messageHandle}");

                amazonSQS.DeleteMessageAsync(deleteRequest);

                Console.ReadLine();
            }
        }
示例#4
0
        /**
         * Process a message
         * See https://github.com/Azure/azure-sdk-for-js/tree/master/sdk/servicebus/service-bus#register-message-handler
         */
        private static void messageHandler(Message message, AmazonSQSClient queue)
        {
            string test = null;
            string xml  = null;
            // If there is an error the program will catch it and the JSONCreated will change to false
            bool   JSONCreated   = true;
            string ReceiptHandle = message.ReceiptHandle;

            if (DSConfig.Debug.Equals("true"))
            {
                String str = " Processing message id " + message.MessageId;
                Console.WriteLine(DateTime.Now + str);
            }

            // Parse the information from message body. the information contains contains fields like test and xml
            try
            {
                string  body = message.Body;
                JObject json = JObject.Parse(body);
                xml  = (string)json.GetValue("xml");
                test = (string)json.GetValue("test");
            }
            // Catch exceptions while trying to create a JSON object
            catch (JsonException e)
            {
                Console.WriteLine(DateTime.Now + " " + e.Message);
                JSONCreated = false;
            }
            // Catch java.lang exceptions (trying to convert null to String) - make sure your message contains both those fields
            catch (Exception e)
            {
                Console.WriteLine(DateTime.Now + " " + e.Message);
                JSONCreated = false;
            }

            // If JSON object created successfully - continue
            if (JSONCreated)
            {
                ProcessNotification.process(test, xml);
            }
            // If JSON object wasn't created - ignore message
            else
            {
                String errorMessage = " Null or bad body in message id " + message.MessageId + ". Ignoring.";
                Console.WriteLine(DateTime.Now + errorMessage);
            }
            // Delete the message after all its information has been parsed
            queue.DeleteMessageAsync(queueUrl, ReceiptHandle);
        }
示例#5
0
        private static void ReceiveMessage(string queueUrl, AmazonSQSClient sqsClient)
        {
            ReceiveMessageRequest receiveMessageRequest = new ReceiveMessageRequest();

            receiveMessageRequest.QueueUrl = queueUrl;

            var counter = 0;

            var lenght = NumbersOfMessagesInQueue(queueUrl, sqsClient);

            while (counter < lenght)
            {
                ReceiveMessageResponse receiveMessageResponse =
                    Task.Run(async() => await sqsClient.ReceiveMessageAsync(receiveMessageRequest)).Result;

                if (receiveMessageResponse.HttpStatusCode == HttpStatusCode.OK)
                {
                    Message message = receiveMessageResponse.Messages[0];

                    ReportFilters filter = JsonSerializer.Deserialize <ReportFilters>(message.Body);

                    Console.WriteLine("*********************************");
                    Console.WriteLine($"SQS Message Id: {message.MessageId}");
                    Console.WriteLine($"SQS Message Id: {message.ReceiptHandle}");
                    Console.WriteLine($"Message Id: {filter.Id}");
                    Console.WriteLine($"Message DataIni: {filter.DataIni}");
                    Console.WriteLine($"Message DateEnd: {filter.DataEnd}");
                    Console.WriteLine("*********************************");
                    Console.WriteLine($"Deleting Message...");

                    DeleteMessageRequest deleteMessageRequest = new DeleteMessageRequest();
                    deleteMessageRequest.QueueUrl      = queueUrl;
                    deleteMessageRequest.ReceiptHandle = message.ReceiptHandle;
                    DeleteMessageResponse response =
                        Task.Run(async() => await sqsClient.DeleteMessageAsync(deleteMessageRequest)).Result;
                    if (response.HttpStatusCode == HttpStatusCode.OK)
                    {
                        Console.WriteLine($"Deleted Message...");
                    }
                    else
                    {
                        Console.WriteLine($"ERROR: {response.HttpStatusCode}");
                    }
                    Console.WriteLine();
                }
                counter++;
            }
        }
示例#6
0
        public async Task DeleteMessageAsync(string queueName, string receiptHandle)
        {
            try
            {
                var response = await _client.DeleteMessageAsync(GetQueueUrl(), receiptHandle);

                if (response.HttpStatusCode != HttpStatusCode.OK)
                {
                    throw new AmazonSQSException($"Failed to DeleteMessageAsync with for [{receiptHandle}] from queue '{queueName}'. Response: {response.HttpStatusCode}");
                }
            }
            catch (Exception)
            {
                throw;
            }
        }
        public async Task <IActionResult> DeleteMessage()
        {
            var queueUrl = await QueueUrl.Build(_client, QueueName, _sqsConfigParam.QueueAttributes);

            var receiveMessageRequest = new ReceiveMessageRequest {
                QueueUrl = queueUrl.Value
            };
            var response = await _client.ReceiveMessageAsync(receiveMessageRequest);

            var deleteResults = new List <dynamic>();

            foreach (var message in response.Messages)
            {
                _logger.LogDebug($"messageId:{message.MessageId} / ReceiptHandle:{message.ReceiptHandle}");

                var deleteRequest = new DeleteMessageRequest
                {
                    QueueUrl      = queueUrl.Value,
                    ReceiptHandle = message.ReceiptHandle
                };

                var deleteResponse = await _client.DeleteMessageAsync(deleteRequest);

                if (deleteResponse.HttpStatusCode == HttpStatusCode.OK)
                {
                    deleteResults.Add(new { MessageId = message.MessageId, Status = "success" });
                }
                else
                {
                    deleteResults.Add(new { MessageId = message.MessageId, Status = "fail" });
                }
            }

            if (deleteResults.All(result => result.Status == "success"))
            {
                var result = new
                {
                    StatusCode = "正常終了",
                    Message    = "SQSへメッセージの削除に成功しました。",
                };
                return(Ok(JsonConvert.SerializeObject(result)));
            }
            else
            {
                return(new StatusCodeResult(500));
            }
        }
示例#8
0
        public void TransformFiles()
        {
            using (var s3client = new AmazonS3Client(_accessKeyId, _secretAccessKey, AmazonRegion.USWest2))
                using (var client = new AmazonSQSClient(_accessKeyId, _secretAccessKey, AmazonRegion.USWest2))
                {
                    ReceiveMessageResponse response;
                    do
                    {
                        var recieveMessageRequest = new ReceiveMessageRequest();
                        recieveMessageRequest.QueueUrl = _queueUrl;
                        recieveMessageRequest.MessageAttributeNames = new List <string> {
                            "fileName", "transformation", "date"
                        };
                        recieveMessageRequest.MaxNumberOfMessages = 10;

                        response = client.ReceiveMessageAsync(recieveMessageRequest).Result;
                        foreach (var message in response.Messages)
                        {
                            var fileName       = message.MessageAttributes["fileName"].StringValue;
                            var transformation = Enum.Parse(typeof(Transformation), message.MessageAttributes["transformation"].StringValue);

                            var picture = s3client.GetObjectAsync(_bucketName, fileName).Result;

                            using (var inStream = new MemoryStream())
                            {
                                picture.ResponseStream.CopyTo(inStream);
                                using (var outStream = new MemoryStream())
                                {
                                    Image image = Image.FromStream(inStream);
                                    image.RotateFlip(RotateFlipType.Rotate90FlipNone);

                                    image.Save(outStream, ImageFormat.Jpeg);

                                    s3client.PutObjectAsync(new PutObjectRequest()
                                    {
                                        BucketName  = _bucketName,
                                        Key         = fileName,
                                        InputStream = outStream
                                    }).Wait();
                                }
                            }

                            client.DeleteMessageAsync(_queueUrl, message.ReceiptHandle);
                        }
                    } while (response.Messages?.Count == 10);
                }
        }
        /// <summary>
        /// Initializes the Amazon SQS client object. It then calls the
        /// ReceiveMessageAsync method to retrieve information about the
        /// available methods before deleting them.
        /// </summary>
        public static async Task Main()
        {
            string queueUrl       = "https://sqs.us-east-2.amazonaws.com/0123456789ab/Example_Queue";
            var    attributeNames = new List <string>()
            {
                "All"
            };
            int maxNumberOfMessages = 5;
            var visibilityTimeout   = (int)TimeSpan.FromMinutes(10).TotalSeconds;
            var waitTimeSeconds     = (int)TimeSpan.FromSeconds(5).TotalSeconds;

            // If the Amazon SQS message queue is not in the same AWS Region as your
            // default user, you need to provide the AWS Region as a parameter to the
            // client constructor.
            var client = new AmazonSQSClient();

            var request = new ReceiveMessageRequest
            {
                QueueUrl            = queueUrl,
                AttributeNames      = attributeNames,
                MaxNumberOfMessages = maxNumberOfMessages,
                VisibilityTimeout   = visibilityTimeout,
                WaitTimeSeconds     = waitTimeSeconds,
            };

            var response = await client.ReceiveMessageAsync(request);

            if (response.Messages.Count > 0)
            {
                response.Messages.ForEach(async m =>
                {
                    Console.Write($"Message ID: '{m.MessageId}'");

                    var delRequest = new DeleteMessageRequest
                    {
                        QueueUrl      = "https://sqs.us-east-1.amazonaws.com/0123456789ab/MyTestQueue",
                        ReceiptHandle = m.ReceiptHandle,
                    };

                    var delResponse = await client.DeleteMessageAsync(delRequest);
                });
            }
            else
            {
                Console.WriteLine("No messages to delete.");
            }
        }
示例#10
0
        static void Main(string[] args)
        {
            var batch_size = int.Parse(args[0]);
            var queue_url  = args[1];

            System.Console.WriteLine($"Reading {batch_size} messages at a time from SQS queue {queue_url}");
            var sqs = new AmazonSQSClient(); // need keys and region

            try
            {
                while (true)
                {
                    var receive_message_request = new ReceiveMessageRequest
                    {
                        AttributeNames = new List <string>()
                        {
                            "All"
                        },
                        MaxNumberOfMessages = batch_size,
                        QueueUrl            = queue_url,
                        WaitTimeSeconds     = 20
                    };

                    var result = sqs.ReceiveMessageAsync(receive_message_request).Result;

                    foreach (var message in result.Messages)
                    {
                        if (process_message(message))
                        {
                            sqs.DeleteMessageAsync(new DeleteMessageRequest
                            {
                                QueueUrl      = queue_url,
                                ReceiptHandle = message.ReceiptHandle
                            });
                        }
                        else
                        {
                            sqs.ChangeMessageVisibilityAsync(queue_url, message.ReceiptHandle, 10);
                        }
                    }
                }
            }
            catch (System.Exception)
            {
                throw;
            }
        }
示例#11
0
        public async Task FunctionHandler()
        {
            var connection = DbHelper.Connection;

            var sqsClient   = new AmazonSQSClient();
            var sqsResponse = await sqsClient.ReceiveMessageAsync(QueueHelper.RequestQueueUrl);

            var lambdaClient = new AmazonLambdaClient();

            foreach (var message in sqsResponse.Messages)
            {
                var body    = message.Body;
                var handler = message.ReceiptHandle;

                var queueRequest = JsonConvert.DeserializeObject <QueueRequest>(body);

                var invokeRequest = new InvokeRequest()
                {
                    FunctionName = Enum.GetName(typeof(Service), queueRequest.TargetService),
                    Payload      = JsonConvert.SerializeObject(queueRequest)
                };

                var lambdaResponse = await lambdaClient.InvokeAsync(invokeRequest);

                var response = new StreamReader(lambdaResponse.Payload).ReadToEnd();

                if (!string.IsNullOrEmpty(queueRequest.CallbackUrl))
                {
                    var httpClient = new HttpClient();
                    await httpClient.PostAsync(
                        queueRequest.CallbackUrl,
                        new StringContent(response)
                        );
                }

                await sqsClient.DeleteMessageAsync(QueueHelper.RequestQueueUrl, handler);

                var processed = await sqsClient.SendMessageAsync(
                    QueueHelper.ProcessedQueueUrl,
                    response
                    );

                connection.Execute($"UPDATE {DbHelper.GetTableName<QueueProcess>()} SET ProcessId = @PId WHERE QueueId = @QId",
                                   new { PId = processed.MessageId, QId = message.MessageId });
            }
        }
示例#12
0
        public static void ReadAWSSQSQueueMessageAndDelete(string queueName)
        {
            using (IAmazonSQS sqs = new AmazonSQSClient(RegionEndpoint.USEast1))
            {
                var queueUrl        = sqs.GetQueueUrlAsync(queueName).Result.QueueUrl;
                var readQueueMsgReq = new ReceiveMessageRequest(queueUrl);

                var readMsgResp = sqs.ReceiveMessageAsync(readQueueMsgReq).Result;
                if (readMsgResp.HttpStatusCode == HttpStatusCode.OK && readMsgResp.Messages.Count > 0)
                {
                    Console.WriteLine("Reading Messages \n");
                    foreach (var message in readMsgResp.Messages)
                    {
                        Console.WriteLine("Message: \n");
                        Console.WriteLine($" MessageId: {message.MessageId} \n");
                        Console.WriteLine($" ReceiptHandle: {message.ReceiptHandle} \n");
                        Console.WriteLine($" MD5OfBody: {message.MD5OfBody} \n");
                        Console.WriteLine($" Body: {message.Body} \n");

                        foreach (var attribute in message.Attributes)
                        {
                            Console.WriteLine("Attributes: \n");
                            Console.WriteLine($" attribute name: {attribute.Key} \n");
                            Console.WriteLine($" attribute value: {attribute.Value} \n");
                        }

                        var deleteMsgReq = new DeleteMessageRequest()
                        {
                            QueueUrl      = queueUrl,
                            ReceiptHandle = message.ReceiptHandle
                        };
                        Console.WriteLine("deleting Message \n");
                        var deleteResp = sqs.DeleteMessageAsync(deleteMsgReq).Result;

                        if (deleteResp.HttpStatusCode == HttpStatusCode.OK)
                        {
                            Console.WriteLine("Message deleted successfully \n");
                        }
                    }
                }
                else
                {
                    Console.WriteLine("No messages to read in the queue\n");
                }
            }
        }
示例#13
0
        public async Task StartAsync(CancellationToken stoppingToken)
        {
            while (!stoppingToken.IsCancellationRequested)
            {
                _logger.LogInformation("Worker running at: {time}", DateTimeOffset.Now);

                //Reading configuration
                var aswSection    = _configuration.GetSection("Aws");
                var accessKey     = aswSection.GetSection("AccessKey").Value;
                var secretKey     = aswSection.GetSection("SecretKey").Value;
                var sqsUrl        = aswSection.GetSection("SQSUrl").Value;
                var localstackUrl = aswSection.GetSection("localstackUrl").Value;

                //Creating sqs client
                var credentials = new Amazon.Runtime.BasicAWSCredentials(accessKey, secretKey);

                _logger.LogInformation($"Using SQS queue url {sqsUrl}", sqsUrl);
                _logger.LogInformation("Using credentials: {access}, {secret}", accessKey, secretKey);

                AmazonSQSClient amazonSQSClient = new AmazonSQSClient(new AmazonSQSConfig
                {
                    ServiceURL = localstackUrl
                });

                //Receive request
                ReceiveMessageRequest receiveMessageRequest = new ReceiveMessageRequest(sqsUrl);
                var response = await amazonSQSClient.ReceiveMessageAsync(receiveMessageRequest, stoppingToken);

                if (response.Messages.Any())
                {
                    foreach (Message message in response.Messages)
                    {
                        Console.WriteLine($"Message received");
                        Console.WriteLine($"Message: {message.Body}");

                        //Deleting message
                        var deleteMessageRequest = new DeleteMessageRequest(sqsUrl, message.ReceiptHandle);
                        await amazonSQSClient.DeleteMessageAsync(deleteMessageRequest, stoppingToken);

                        Console.WriteLine($"Message deleted");
                    }
                }

                await Task.Delay(5000, stoppingToken);
            }
        }
示例#14
0
        public async void ReadSQS(string Source)
        {
            var sqs = new AmazonSQSClient(RegionEndpoint.CACentral1);

            var queueUrl = sqs.GetQueueUrlAsync(Source).Result.QueueUrl;

            var receiveMessageRequest = new ReceiveMessageRequest
            {
                QueueUrl = queueUrl
            };

            var receiveMessageResponse = sqs.ReceiveMessageAsync(receiveMessageRequest).Result;

            while (true)
            {
                if (receiveMessageResponse.Messages.Count != 0)
                {
                    break;
                }
                Thread.Sleep(1000);
            }
            foreach (var message in receiveMessageResponse.Messages)
            {
                Console.WriteLine($"	Body: {message.Body}");

                var messageReceptHandle = receiveMessageResponse.Messages.FirstOrDefault()?.ReceiptHandle;

                var deleteRequest = new DeleteMessageRequest
                {
                    QueueUrl      = queueUrl,
                    ReceiptHandle = messageReceptHandle
                };

                if (Source == "Slack")
                {
                    PostMessageToGlipAsync(message.Body);
                }
                else
                {
                    PostMessageToSlackbotAsync(message.Body);
                }

                sqs.DeleteMessageAsync(deleteRequest);
            }
        }
示例#15
0
        public QueueGermPlasmEvent GetNext(ILambdaContext context)
        {
            Message message = null;

            try
            {
                context.Logger.LogLine($"trying to receive messages with timeout: {this.client.Config.Timeout}.");
                CancellationTokenSource       token = new CancellationTokenSource();
                Task <ReceiveMessageResponse> receivedMessageTask = client.ReceiveMessageAsync(this.request, token.Token);
                if (!receivedMessageTask.Wait(12000))
                {
                    context.Logger.LogLine($"message was not received");
                    try
                    {
                        token.Cancel();
                    }
                    catch (Exception)
                    {
                        context.Logger.LogLine($"receive message was cancelled.");
                        return(null);
                    }
                }
                ReceiveMessageResponse receivedMessage = receivedMessageTask.Result;
                context.Logger.LogLine($"{receivedMessage.Messages.Count} messages received");
                message = receivedMessage.Messages.FirstOrDefault();
                if (message == null)
                {
                    return(null);
                }
            }
            catch (Exception exc)
            {
                context.Logger.LogLine($"Exception: {exc}.");
                return(null);
            }
            deleteRequest.ReceiptHandle = message.ReceiptHandle;

            DeleteMessageResponse deleteResponse = client.DeleteMessageAsync(deleteRequest).Result;

            if (deleteResponse.HttpStatusCode != System.Net.HttpStatusCode.OK)
            {
                throw new Exception($"failed to delete message {message.MessageId} from queue: {request.QueueUrl}: received message: {deleteResponse.HttpStatusCode}");
            }
            return(JsonConvert.DeserializeObject <QueueGermPlasmEvent>(message.Body));
        }
示例#16
0
        public async Task <string> GetMessageAsync()
        {
            ReceiveMessageRequest receiveMessageRequest = new ReceiveMessageRequest();

            receiveMessageRequest.QueueUrl = _queueUrl;
            ReceiveMessageResponse receiveMessageResponse = await _amazonSQSClient.ReceiveMessageAsync(receiveMessageRequest);

            Message message = receiveMessageResponse.Messages[0];

            DeleteMessageRequest deleteMessageRequest = new DeleteMessageRequest()
            {
                QueueUrl      = _queueUrl,
                ReceiptHandle = message.ReceiptHandle
            };
            await _amazonSQSClient.DeleteMessageAsync(deleteMessageRequest);

            return(message.Body);
        }
示例#17
0
        public async Task ListenAsync(Action <Message> messageHandler)
        {
            if (!_initialised)
            {
                await Initialise();
            }

            while (true)
            {
                var response = await _sqsClient.ReceiveMessageAsync(new ReceiveMessageRequest { QueueUrl = _queueUrl, WaitTimeSeconds = 10 });

                foreach (var message in response.Messages)
                {
                    messageHandler(message);
                    await _sqsClient.DeleteMessageAsync(_queueUrl, message.ReceiptHandle);
                }
            }
        }
示例#18
0
        // To be notified by the payment handler (e.g. Stripe Checkout) in the form of webhook
        // If the transaction ID is not the same then this payment will fail
        // If correct will carry on
        public async Task <Order> CompletePayment(string transactionId)
        {
            ReceiveMessageRequest receiveMessageRequest = new ReceiveMessageRequest
            {
                MaxNumberOfMessages   = 1,
                QueueUrl              = queueURL,
                MessageAttributeNames = new List <string> {
                    "id"
                },
            };
            ReceiveMessageResponse response = await _sqsClient.ReceiveMessageAsync(receiveMessageRequest);

            //
            if (response.HttpStatusCode == HttpStatusCode.OK)
            {
                // Even though requesting one item, just to reduce unnecessary checks
                foreach (var message in response.Messages)
                {
                    if (!message.MessageAttributes.ContainsKey("id"))
                    {
                        return(null);
                    }

                    string id = message.MessageAttributes["id"].StringValue;
                    if (id == transactionId)
                    {
                        Order order = JsonSerializer.Deserialize <Order>(message.Body);

                        // Try deleting the message from the queue after successful consumption
                        try
                        {
                            await _sqsClient.DeleteMessageAsync(queueURL, message.ReceiptHandle);
                        } catch (AmazonSQSException e)
                        {
                            Console.WriteLine(e);
                        }

                        return(order);
                    }
                }
            }

            return(null);
        }
示例#19
0
        public async Task StartReceiving(string queueUrl, CancellationToken token)
        {
            while (!token.IsCancellationRequested)
            {
                var res = await sqsClient.ReceiveMessageAsync(queueUrl, token);

                if (res.HttpStatusCode == HttpStatusCode.OK)
                {
                    foreach (var message in res.Messages)
                    {
                        Console.WriteLine($"received: {message.Body}");

                        await sqsClient.DeleteMessageAsync(queueUrl, message.ReceiptHandle, token);
                    }
                }

                await Task.Delay(800, token);
            }
        }
示例#20
0
        static async System.Threading.Tasks.Task Main(string[] args)
        {
            Boolean continuar = true;

            //Subscribe to SQS, which is being fed by the SNS topic
            myQueueUrl = "myTestQueue";
            IAmazonSQS sqs = new AmazonSQSClient(RegionEndpoint.EUCentral1);

            //Confirming the queue exists
            ListQueuesRequest  listQueuesRequest  = new ListQueuesRequest();
            ListQueuesResponse listQueuesResponse = await sqs.ListQueuesAsync(listQueuesRequest);

            while (continuar)
            {
                ReceiveMessageRequest receiveMessageRequest = new ReceiveMessageRequest();
                receiveMessageRequest.QueueUrl = myQueueUrl;
                ReceiveMessageResponse receiveMessageResponse = await sqs.ReceiveMessageAsync(receiveMessageRequest);


                Console.WriteLine("Printing received message.\n");
                foreach (Message message in receiveMessageResponse.Messages)
                {
                    //Print the message
                    Console.WriteLine("  Message");
                    Console.WriteLine("    MessageId: {0}", message.MessageId);
                    Console.WriteLine("    ReceiptHandle: {0}", message.ReceiptHandle);
                    Console.WriteLine("    MD5OfBody: {0}", message.MD5OfBody);
                    Console.WriteLine("    Body: {0}", message.Body);

                    var messageRecieptHandle = message.ReceiptHandle;

                    //Deleting each message
                    Console.WriteLine("Deleting the message.\n");
                    DeleteMessageRequest deleteRequest = new DeleteMessageRequest();
                    deleteRequest.QueueUrl      = myQueueUrl;
                    deleteRequest.ReceiptHandle = messageRecieptHandle;
                    await sqs.DeleteMessageAsync(deleteRequest);
                }

                Thread.Sleep(5000);
            }
        }
示例#21
0
        /// <inheritdoc />
        public override async Task <DeleteResponse> Delete(
            Deletable deletable,
            CancellationToken cancellationToken = default
            )
        {
            var sqsDeletable = CastAndValidate(
                deletable,
                d => (!string.IsNullOrWhiteSpace(d.ReceiptHandle), nameof(d.ReceiptHandle))
                );

            var response = await _client.DeleteMessageAsync(new DeleteMessageRequest
            {
                QueueUrl      = _options.QueueUrl,
                ReceiptHandle = sqsDeletable.ReceiptHandle
            }, cancellationToken).ConfigureAwait(false);

            return(new DeleteResponse {
                Success = response != null && (int)response.HttpStatusCode == 200
            });
        }
示例#22
0
        /// <summary>
        /// Rejects the specified message.
        /// </summary>
        /// <param name="message">The message.</param>
        public void Reject(Message message)
        {
            if (!message.Header.Bag.ContainsKey("ReceiptHandle"))
            {
                return;
            }

            var receiptHandle = message.Header.Bag["ReceiptHandle"].ToString();

            try
            {
                _logger.Value.InfoFormat(
                    "SqsMessageConsumer: Rejecting the message {0} with receipt handle {1} on the queue {2}",
                    message.Id, receiptHandle, _queueName
                    );

                using (var client = new AmazonSQSClient(_awsConnection.Credentials, _awsConnection.Region))
                {
                    var urlResponse = client.GetQueueUrlAsync(_queueName).Result;
                    if (_hasDlq)
                    {
                        client.ChangeMessageVisibilityAsync(new ChangeMessageVisibilityRequest(urlResponse.QueueUrl, receiptHandle, 0)).Wait();
                    }
                    else
                    {
                        client.DeleteMessageAsync(urlResponse.QueueUrl, receiptHandle).Wait();
                    }
                }

                _logger.Value.InfoFormat(
                    "SqsMessageConsumer: Message {0} with receipt handle {1} on the queue {2} with requeue paramter {3} has been rejected",
                    message.Id, receiptHandle, _queueName
                    );
            }
            catch (Exception exception)
            {
                _logger.Value.ErrorException("SqsMessageConsumer: Error during rejecting the message {0} with receipt handle {1} on the queue {2}", exception,
                                             message.Id, receiptHandle, _queueName);
                throw;
            }
        }
示例#23
0
        public static async Task OnReceive(Func <string, Task> func, bool deleteAfterRead = true)
        {
            try
            {
                var sqs = new AmazonSQSClient();
                var receiveMessageRequest = new ReceiveMessageRequest
                {
                    QueueUrl = "https://sqs.eu-west-1.amazonaws.com/166778461577/ClientHubNotifierQueue"
                };
                var receiveMessageResponse = await sqs.ReceiveMessageAsync(receiveMessageRequest);

                if (receiveMessageResponse.Messages != null && receiveMessageResponse.Messages.Any())
                {
                    int counter = -1;
                    foreach (var message in receiveMessageResponse.Messages)
                    {
                        counter++;
                        if (!string.IsNullOrEmpty(message.Body))
                        {
                            await func.Invoke(message.Body);
                        }

                        if (deleteAfterRead)
                        {
                            var messageRecieptHandle = receiveMessageResponse.Messages[counter].ReceiptHandle;

                            var deleteRequest = new DeleteMessageRequest
                            {
                                QueueUrl      = "https://sqs.eu-west-1.amazonaws.com/166778461577/ClientHubNotifierQueue",
                                ReceiptHandle = messageRecieptHandle
                            };
                            await sqs.DeleteMessageAsync(deleteRequest);
                        }
                    }
                }
            }
            catch (AmazonSQSException ex)
            {
                // do nothing, you may want to log, but let it give it another try in the next run
            }
        }
        void ProcessMessages(string category, AmazonSQSClient client, string queueName, Action <AmazonSQSClient, Message> processor, System.Threading.CancellationToken token)
        {
            token.ThrowIfCancellationRequested();

            var queueUrl = client.GetQueueUrlAsync(queueName).GetAwaiter().GetResult().QueueUrl;

            try
            {
                foreach (var message in client.ReceiveMessageAsync(queueUrl).GetAwaiter().GetResult().Messages)
                {
                    token.ThrowIfCancellationRequested();

                    Logger.TraceCall("Processor", () => processor(client, message));
                    Logger.TraceCall("DeleteMessage", () => client.DeleteMessageAsync(queueUrl, message.ReceiptHandle).Wait());
                }
            }
            catch (AmazonServiceException ex)
            {
                Logger.LogWarning(0, $"Amazon service unavailable, returns: {ex.Message}");
            }
        }
示例#25
0
        static async Task Main(string[] args)
        {
            Console.WriteLine("Hello World!");

            var client  = new AmazonSQSClient(RegionEndpoint.USEast1);
            var request = new ReceiveMessageRequest
            {
                QueueUrl = "https://sqs.us-east-1.amazonaws.com/"
            };

            while (true)
            {
                var response = await client.ReceiveMessageAsync(request);

                foreach (var mensagem in response.Messages)
                {
                    Console.WriteLine(mensagem.Body);
                    await client.DeleteMessageAsync("https://sqs.us-east-1.amazonaws.com/", mensagem.ReceiptHandle);
                }
            }
        }
 public async Task ExecuteAsync()
 {
     try
     {
         var creds = Utils.GetCredentials(this.Profile);
         using (var client = new AmazonSQSClient(creds, RegionEndpoint.GetBySystemName(this.Region)))
         {
             var request = new DeleteMessageRequest
             {
                 QueueUrl      = this.QueueUrl,
                 ReceiptHandle = this.ReceiptHandle
             };
             await client.DeleteMessageAsync(request);
         }
     }
     catch (Exception e)
     {
         Console.Error.WriteLine("Error deleting message from queue: " + e.Message);
         throw;
     }
 }
        static async Task Main(string[] args)
        {
            Console.WriteLine("Hello World!");

            var client  = new AmazonSQSClient(RegionEndpoint.SAEast1);
            var request = new ReceiveMessageRequest
            {
                QueueUrl = "[adicione sua url aqui]"
            };

            while (true)
            {
                var response = await client.ReceiveMessageAsync(request);

                foreach (var mensagem in response.Messages)
                {
                    Console.WriteLine(mensagem.Body);
                    await client.DeleteMessageAsync("[adicione sua url aqui]", mensagem.ReceiptHandle);
                }
            }
        }
 private void DeleteMessage(
     string queueUrl, Message message, CancellationToken cancellationToken = default)
 {
     try
     {
         _logger.LogTrace("Deleting the message with id {message_id} and ReceiptHandle {receipt_handle}");
         _amazonSqsClient
         .DeleteMessageAsync(
             new DeleteMessageRequest
         {
             QueueUrl      = queueUrl,
             ReceiptHandle = message.ReceiptHandle
         }, cancellationToken)
         .ContinueWith(
             task =>
         {
             if (task.IsFaulted)
             {
                 _logger.LogError(task.Exception,
                                  "Failed to delete message with id {message_id} and ReceiptHandle {receipt_handle}");
             }
             else if (task.IsCanceled)
             {
                 _logger.LogWarning(
                     "Failed to delete message with id {message_id} and ReceiptHandle {receipt_handle}. Task has been cancelled");
             }
             else
             {
                 _logger.LogTrace("Message {message_id} has been deleted successfully");
             }
         },
             cancellationToken,
             TaskContinuationOptions.None,
             TaskScheduler.Default);
     }
     catch (Exception ex)
     {
         _logger.LogError(ex, "Failed to delete message {message_id} from the queue", message.MessageId);
     }
 }
        private static Ev3Command PollForQueueMessage()
        {
            ReceiveMessageRequest request = new ReceiveMessageRequest();

            request.QueueUrl = "";

            while (true)
            {
                DateTime timeout      = DateTime.Now.AddMilliseconds(TIMEOUT_IN_MS);
                var      responseTask = _sqsClient.ReceiveMessageAsync(request);

                // TODO: Replace with proper async completion handling.
                while (!responseTask.IsCompleted && DateTime.Now < timeout)
                {
                }

                ReceiveMessageResponse response = responseTask.Result;

                if (response.Messages != null && response.Messages.Count > 0)
                {
                    Amazon.SQS.Model.Message nextMessage   = response.Messages.First();
                    DeleteMessageRequest     deleteRequest = new DeleteMessageRequest();
                    deleteRequest.QueueUrl      = _awsSqsAddress;
                    deleteRequest.ReceiptHandle = nextMessage.ReceiptHandle;


                    timeout = DateTime.Now.AddMilliseconds(TIMEOUT_IN_MS);
                    var deleteTask = _sqsClient.DeleteMessageAsync(deleteRequest);
                    while (!deleteTask.IsCompleted && DateTime.Now < timeout)
                    {
                    }

                    Console.WriteLine("Message: ");
                    Console.WriteLine("== " + nextMessage.Body);

                    var command = GetEv3CommandFromJson(nextMessage.Body);
                    return(command);
                }
            }
        }
示例#30
0
        public static void Main(string[] args)
        {
            var configuration = new ConfigurationBuilder()
                                .SetBasePath(Directory.GetCurrentDirectory())
                                .AddJsonFile("appsettings.json", true)
                                .Build();

            Console.Title = configuration["ApplicationName"];


            var profile = configuration["AWSProfile"];

            var credentials = new StoredProfileAWSCredentials(profile);
            var sqsClient   = new AmazonSQSClient(credentials, RegionEndpoint.EUWest1);

            // Create queue if not exist

            GetQueueUrlResponse queue = sqsClient.GetQueueUrlAsync("BFQueue").Result;

            var receiveMessageRequest = new ReceiveMessageRequest
            {
                QueueUrl          = queue.QueueUrl,
                WaitTimeSeconds   = 10,
                VisibilityTimeout = 10
            };

            while (true)
            {
                Console.WriteLine("Polling Queue");
                var messagesResponse = sqsClient.ReceiveMessageAsync(receiveMessageRequest).Result;
                foreach (var message in messagesResponse.Messages)
                {
                    Console.WriteLine($"Message: { message.Body }");

                    var deleteMessageRequest     = new DeleteMessageRequest(queue.QueueUrl, message.ReceiptHandle);
                    DeleteMessageResponse result = sqsClient.DeleteMessageAsync(deleteMessageRequest).Result;
                }
            }
        }