コード例 #1
0
ファイル: SQS.cs プロジェクト: WOLAS-Revolution/aws-tools
        /// <summary>
        /// Gets messages from an SQS queue.
        /// </summary>
        /// <param name="queueUrl">The sqs queue endpoint to get the messages from.</param>
        /// <param name="maxMessages">The maximum number of messages to return (max 10)</param>
        /// <param name="visibilityTimeout">The number of minutes to hide the message from other consumers for (max 12 hours or 720 minutes)</param>
        /// <returns></returns>
        public static Amazon.SQS.Model.ReceiveMessageResponse ReceiveMessages(string queueUrl, int maxMessages = 10, int visibilityTimeout = 0)
        {
            // Check for the maximum number of messages to get.
            if (maxMessages > 10)
                throw new ArgumentException("The maximum number of messages that can be returned is 10");

            // Check that the visibility timeout is okay.
            if (visibilityTimeout > 720)
                throw new ArgumentException("The maximum amount of time that the message can be hidden for is 12 hours.");

            // Get the messages from the queue.
            Amazon.SQS.Model.ReceiveMessageResponse response = new Amazon.SQS.Model.ReceiveMessageResponse();
            using (Amazon.SQS.IAmazonSQS client = new Factory().SQSClient())
            {
                Amazon.SQS.Model.ReceiveMessageRequest request = new Amazon.SQS.Model.ReceiveMessageRequest()
                {
                    QueueUrl = queueUrl,
                    MaxNumberOfMessages = maxMessages
                };

                if (visibilityTimeout > 0)
                {
                    request.VisibilityTimeout = visibilityTimeout;
                }

                response = client.ReceiveMessage(request);
            }
            return response;
        }
コード例 #2
0
        public int GetNotifications()
        {
            int count = 0;
            // Check Queue For Shutdown Message
            var request = new Amazon.SQS.Model.ReceiveMessageRequest();

            request.WithQueueUrl(AppUtility.GetContext().ShutdownNotificationQueue);

            var rsp = queue.ReceiveMessage(request);

            if (rsp.IsSetReceiveMessageResult())
            {
                foreach (var msg in rsp.ReceiveMessageResult.Message)
                {
                    if (msg.IsSetMessageId())
                    {
                        Debug.WriteLine("Notification Instance shutdown: " + msg.Body);
                        var delMsg = new Amazon.SQS.Model.DeleteMessageRequest();
                        delMsg.WithQueueUrl(AppUtility.GetContext().ShutdownQueue);
                        delMsg.WithReceiptHandle(msg.ReceiptHandle);
                        var delRsp = queue.DeleteMessage(delMsg);
                        count += 1;
                    }
                }
            }

            return(count);
        }
コード例 #3
0
        /*
         * Remove all messages from shutdown queue
         */
        private void ClearShutdownQueue()
        {
            var QueueURL = AppUtility.GetContext().ShutdownQueue;

            Amazon.SQS.Model.ReceiveMessageRequest request = new Amazon.SQS.Model.ReceiveMessageRequest();
            request.WithMaxNumberOfMessages(10);
            request.WithQueueUrl(QueueURL);
            var rsp = queue.ReceiveMessage(request);

            while (rsp.IsSetReceiveMessageResult() && rsp.ReceiveMessageResult.Message.Count > 0)
            {
                Debug.WriteLine("Remove Shutdown Messages: " + rsp.ReceiveMessageResult.Message.Count);
                var result = rsp.ReceiveMessageResult.Message;
                foreach (var msg in rsp.ReceiveMessageResult.Message)
                {
                    //Console.WriteLine("Message: " + msg);
                    if (msg.IsSetMessageId())
                    {
                        //Console.WriteLine("Body: " + msg.Body);
                        //if (msg.Body == "shutdown")
                        //{
                        //}
                        var delMsg = new Amazon.SQS.Model.DeleteMessageRequest();
                        delMsg.WithQueueUrl(QueueURL);
                        delMsg.WithReceiptHandle(msg.ReceiptHandle);
                        var delRsp = queue.DeleteMessage(delMsg);
                    }
                }
                rsp = queue.ReceiveMessage(request);
            }
        }
コード例 #4
0
ファイル: frmMail.cs プロジェクト: phonglam29305/FAMail
        private void button2_Click(object sender, EventArgs e)
        {
            string AccessKey= System.Configuration.ConfigurationManager.AppSettings["AccessKey"];
            string SecrectKey = System.Configuration.ConfigurationManager.AppSettings["SecrectKey"];
            Amazon.SimpleEmail.AmazonSimpleEmailServiceClient mailClient = new Amazon.SimpleEmail.AmazonSimpleEmailServiceClient(AccessKey,SecrectKey);
            //var obj = mailClient.GetSendQuota();
            SendEmailRequest request = new SendEmailRequest();
            List<string> toaddress = new List<string>();
            toaddress.Add("*****@*****.**");
            Destination des = new Destination(toaddress);
            request.Destination = des;
            request.Source = "*****@*****.**";
            Amazon.SimpleEmail.Model.Message mes = new Amazon.SimpleEmail.Model.Message();
            mes.Body = new Body(new Content( @"Hiện tại, Windows Phone mới hỗ trợ đến màn hình full HD, do đó để tương thích với màn hình 2K, hệ điều hành chắc chắn phải có bản cập nhật mới. Mặt khác, vi xử lý Snapdragon 805 của Qualcomm được biết sẽ phát hành đại trà vào nửa sau năm nay, nên thời điểm xuất hiện Lumia 1820 dùng vi xử lý này tại MWC 2014 vào tháng Hai sẽ là dấu hỏi lớn.

            Microsoft đã từng nói hãng đã chi tới 2,6 tỉ USD để phát triển cho hệ điều hành Windows Phone. Và năm nay, Microsoft đang có kế hoạch lớn dành cho Windows Phone lẫn Nokia. Do đó, chúng ta hãy cứ hy vọng Lumia 1525 và Lumia 1820 sẽ là bom tấn smartphone được kích hoạt trong 2014 này."));
            mes.Subject = new Content("Test send via amazon");

            request.Message = mes;

            SendEmailResponse response = mailClient.SendEmail(request);
            var messageId = response.SendEmailResult.MessageId;
            /*GetIdentityNotificationAttributesRequest notifyRequest = new GetIdentityNotificationAttributesRequest();
            List<string> iden = new List<string>();
            iden.Add("*****@*****.**"); //iden.Add(response.ResponseMetadata.RequestId);
            notifyRequest.Identities = iden;
            var notify = mailClient.GetIdentityNotificationAttributes(notifyRequest);
            //MessageBox.Show(notify.GetIdentityNotificationAttributesResult.NotificationAttributes["Bounces"].BounceTopic);

            var temp = mailClient.GetSendStatistics();
            MessageBox.Show("Total: "+temp.GetSendStatisticsResult.SendDataPoints.Count+"\nDeliveryAttempts: "+temp.GetSendStatisticsResult.SendDataPoints[265].DeliveryAttempts+"\n"
                + "Complaints: " + temp.GetSendStatisticsResult.SendDataPoints[265].Complaints + "\n"
                + "Bounces: " + temp.GetSendStatisticsResult.SendDataPoints[265].Bounces + "\n"
                + "Rejects: " + temp.GetSendStatisticsResult.SendDataPoints[265].Rejects + "\n");
               // MessageBox.Show("Max24HourSend:" + obj.GetSendQuotaResult.Max24HourSend + "\nMaxSendRate:" + obj.GetSendQuotaResult.MaxSendRate + "\nSentLast24Hours:" + obj.GetSendQuotaResult.SentLast24Hours);

            Amazon.SimpleNotificationService.Model.GetEndpointAttributesRequest endpointRequest = new Amazon.SimpleNotificationService.Model.GetEndpointAttributesRequest();
            Amazon.SimpleNotificationService.AmazonSimpleNotificationServiceClient notifyClient = new Amazon.SimpleNotificationService.AmazonSimpleNotificationServiceClient();
            //string result = notifyClient.GetEndpointAttributes(notify).GetEndpointAttributesResult.ToXML();
            //MessageBox.Show(result);
            */
            Amazon.SQS.AmazonSQSClient client = new Amazon.SQS.AmazonSQSClient(AccessKey, SecrectKey);
            Amazon.SQS.Model.ReceiveMessageRequest SQSrequest = new Amazon.SQS.Model.ReceiveMessageRequest();
            SQSrequest.MaxNumberOfMessages = 10;
            SQSrequest.QueueUrl = "https://sqs.us-east-1.amazonaws.com/063719400628/bounce-queue";
            AmazonQueues.ProcessQueuedBounce(client.ReceiveMessage(SQSrequest));
        }
コード例 #5
0
        private TaskQueueData GetTask(Priority oPriority)
        {
            string strUrlQueue = GetQueueUrl(oPriority);

            TaskQueueData oData = null;

            try
            {
                using (Amazon.SQS.AmazonSQS oSQSClient = Amazon.AWSClientFactory.CreateAmazonSQSClient())
                {
                    Amazon.SQS.Model.ReceiveMessageRequest oReceiveMessageRequest = new Amazon.SQS.Model.ReceiveMessageRequest();
                    oReceiveMessageRequest.QueueUrl            = strUrlQueue;
                    oReceiveMessageRequest.MaxNumberOfMessages = 1;

                    Amazon.SQS.Model.ReceiveMessageResponse oReceiveMessageResponse = oSQSClient.ReceiveMessage(oReceiveMessageRequest);
                    if (oReceiveMessageResponse.IsSetReceiveMessageResult())
                    {
                        Amazon.SQS.Model.ReceiveMessageResult oReceiveMessageResult = oReceiveMessageResponse.ReceiveMessageResult;
                        foreach (Amazon.SQS.Model.Message oMessage in oReceiveMessageResult.Message)
                        {
                            oData = TaskQueueData.DeserializeFromXml(oMessage.Body);

                            SQSDataKey oSQSDataKey = new SQSDataKey();
                            oSQSDataKey.m_oPriority        = oPriority;
                            oSQSDataKey.m_strReceiptHandle = oMessage.ReceiptHandle;
                            oData.m_oDataKey = oSQSDataKey;
                            break;
                        }
                    }
                }
            }
            catch (Amazon.SQS.AmazonSQSException)
            {
            }
            catch
            {
            }

            return(oData);
        }
コード例 #6
0
        private TaskQueueData GetTask(Priority oPriority)
        {
            string strUrlQueue = GetQueueUrl(oPriority);

            TaskQueueData oData = null;
            try
            {

                using (Amazon.SQS.AmazonSQS oSQSClient = Amazon.AWSClientFactory.CreateAmazonSQSClient())
                {

                    Amazon.SQS.Model.ReceiveMessageRequest oReceiveMessageRequest = new Amazon.SQS.Model.ReceiveMessageRequest();
                    oReceiveMessageRequest.QueueUrl = strUrlQueue;
                    oReceiveMessageRequest.MaxNumberOfMessages = 1;

                    Amazon.SQS.Model.ReceiveMessageResponse oReceiveMessageResponse = oSQSClient.ReceiveMessage(oReceiveMessageRequest);
                    if (oReceiveMessageResponse.IsSetReceiveMessageResult())
                    {
                        Amazon.SQS.Model.ReceiveMessageResult oReceiveMessageResult = oReceiveMessageResponse.ReceiveMessageResult;
                        foreach (Amazon.SQS.Model.Message oMessage in oReceiveMessageResult.Message)
                        {
                            oData = TaskQueueData.DeserializeFromXml(oMessage.Body);

                            SQSDataKey oSQSDataKey = new SQSDataKey();
                            oSQSDataKey.m_oPriority = oPriority;
                            oSQSDataKey.m_strReceiptHandle = oMessage.ReceiptHandle;
                            oData.m_oDataKey = oSQSDataKey;
                            break;
                        }
                    }
                }
            }
            catch (Amazon.SQS.AmazonSQSException)
            {
            }
            catch
            {
            }

            return oData;
        }
コード例 #7
0
        public void TestMethod1()
        {
            try
            {
                Guid guid = Guid.NewGuid();

                string testMessageBody = "Test message from NLog.Targets.SQS {" + guid + "]";

                NLog.Targets.SQS.AwsSqsTarget target = (NLog.Targets.SQS.AwsSqsTarget)NLog.LogManager.Configuration.FindTargetByName("SQS Target");

                var region = Amazon.RegionEndpoint.GetBySystemName(target.RegionEndPoint);
                using (var sqs_client = new Amazon.SQS.AmazonSQSClient(target.AwsAccessKeyId, target.AwsSecretAccessKey, region))
                {
                    //Purge the target queue of existing messages
                    var att = sqs_client.GetQueueAttributes(target.QueueUrl, new System.Collections.Generic.List <string>()
                    {
                        "All"
                    });

                    if (att.ApproximateNumberOfMessages > 0 | att.ApproximateNumberOfMessagesDelayed > 0 | att.ApproximateNumberOfMessagesNotVisible > 0)
                    {
                        sqs_client.PurgeQueue(target.QueueUrl);
                    }



                    var logger = NLog.LogManager.GetCurrentClassLogger();


                    logger.Info(testMessageBody);


                    System.Threading.Thread.Sleep(1000);



                    Amazon.SQS.Model.ReceiveMessageRequest recReq = new Amazon.SQS.Model.ReceiveMessageRequest(target.QueueUrl);
                    recReq.MessageAttributeNames.Add("All");

                    var messages = sqs_client.ReceiveMessage(recReq);

                    Assert.AreEqual(System.Net.HttpStatusCode.OK, messages.HttpStatusCode);
                    Assert.AreEqual(1, messages.Messages.Count);
                    var message = messages.Messages[0];

                    try
                    {
                        Assert.AreEqual(testMessageBody, message.Body);
                        Assert.AreEqual("Info", message.MessageAttributes["Level"].StringValue);
                        Assert.AreEqual("NLog.Targets.SQS.Tests.UnitTests", message.MessageAttributes["Logger"].StringValue);
                        Assert.IsNotNull(message.MessageAttributes["SequenceID"].StringValue);
                    }
                    finally
                    {
                        sqs_client.DeleteMessage(target.QueueUrl, message.ReceiptHandle);
                    }
                }
            }
            catch (Exception)
            {
                throw;
            }
        }
コード例 #8
0
        /// <summary>
        /// The main entrypoint for the thread that listens to messages.
        /// </summary>
        private void AWSMessageListener()
        {
            // Used to eliminate over logging
            bool receivedMessage = true;

            while (!stopping)
            {
                try
                {
                    var receiveMessageRequest = new SQS.Model.ReceiveMessageRequest()
                    {
                        WaitTimeSeconds = 10,
                        QueueUrl        = sqsQueueUrl
                    };
                    if (receivedMessage)
                    {
                        Logger.LogTrace("Waiting for message from queue");
                    }
                    receivedMessage = false;
                    var messageResponse = AsyncTaskHelper.RunSync(() => sqsClient.ReceiveMessageAsync(receiveMessageRequest));

                    if (messageResponse.HttpStatusCode == HttpStatusCode.OK &&
                        messageResponse.Messages.Count > 0 &&
                        !stopping)
                    {
                        receivedMessage = true;
                        Logger.LogDebug($"Received {messageResponse.Messages.Count} message(s)");
                        foreach (var messageResponseMessage in messageResponse.Messages)
                        {
                            try
                            {
                                ProcessMessage(messageResponseMessage);
                            }
                            finally
                            {
#if (!DONTDELETEMESSAGE)
                                // Delete the message even in error since it will keep coming back
                                // Perhaps a better action would be to put in a dead letter queue
                                DeleteMessage(messageResponseMessage);
#endif
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    Logger.LogError("Error processing message: {0}", ex);
                }
            }

            // Process the received message
            void ProcessMessage(SQS.Model.Message messageResponseMessage)
            {
                Logger.LogTrace($"Received Message ({messageResponseMessage.MessageId}): {messageResponseMessage.Body}");
                var snsMessage = SNS.Util.Message.ParseMessage(messageResponseMessage.Body);
                var feedEvent  = JsonConvert.DeserializeObject <FeedEvent>(snsMessage.MessageText);

                Logger.LogInformation($"Feed: {feedEvent.Feed}, Event: {feedEvent.Event}, Package: {feedEvent.Package}, Version: {feedEvent.Version}");
                Logger.LogTrace($"Package URL: {feedEvent.PackageUrl}");

                var actionableActions =
                    ApplicationSettings.Actions.Where(action => string.Equals(action.SourceFeed, feedEvent.Feed, StringComparison.InvariantCultureIgnoreCase) && action.Enabled);
                Package retrievedPackage = null;

                foreach (var actionableAction in actionableActions)
                {
                    Logger.LogTrace($"Found Action ({actionableAction.Name}) for {feedEvent.Feed}");
                    if (feedEvent.Version.IsPrerelease() && !actionableAction.IncludePrerelease)
                    {
                        Logger.LogDebug($"{actionableAction.Name} is ignoring prelease package ({feedEvent.Package}.{feedEvent.Version})");
                        continue;
                    }

                    using (var scope = ServiceProvider.CreateScope())
                    {
                        var action = ActionProcessor.CreateAction(scope, actionableAction);
                        switch (feedEvent.Event)
                        {
                        case EventType.Added:

                            if (retrievedPackage == null)
                            {
                                retrievedPackage = AsyncTaskHelper.RunSync(() => action.SourceRepository.FetchAsync(feedEvent.Package, feedEvent.Version));
                            }

                            if (retrievedPackage == null)
                            {
                                Logger.LogWarning($"{feedEvent.Package}.{feedEvent.Version} not found in feed {feedEvent.Feed}. Ignoring.");
                            }
                            else
                            {
                                AsyncTaskHelper.RunSync(() => action.ProcessPackageAsync(retrievedPackage, PackageEvent.Added));
                            }
                            break;

                        case EventType.Deleted:
                        case EventType.Purged:
                            // We can't retrieve the package because it has been deleted
                            var deletePackage = new Package
                            {
                                Id      = feedEvent.Package,
                                Version = feedEvent.Version
                            };
                            AsyncTaskHelper.RunSync(() => action.ProcessPackageAsync(deletePackage, PackageEvent.Deleted));
                            break;
                        }
                    }
                }
            }

#if (!DONTDELETEMESSAGE)
            // Delete the processed message from the queue
            void DeleteMessage(SQS.Model.Message messageResponseMessage)
            {
                var deleteMessageRequest = new SQS.Model.DeleteMessageRequest
                {
                    QueueUrl      = sqsQueueUrl,
                    ReceiptHandle = messageResponseMessage.ReceiptHandle
                };

                Logger.LogTrace($"Deleting Message: {messageResponseMessage.ReceiptHandle}");
                var deleteMessageResponse = AsyncTaskHelper.RunSync(() => sqsClient.DeleteMessageAsync(deleteMessageRequest));

                if (deleteMessageResponse.HttpStatusCode == HttpStatusCode.OK)
                {
                    Logger.LogTrace($"Delete Message: {messageResponseMessage.ReceiptHandle}");
                }
                else
                {
                    Logger.LogWarning($"Unable to delete Message: {messageResponseMessage.ReceiptHandle}. Ignoring.");
                }
            }
#endif
        }