Exemple #1
0
        protected override void InitializeTarget()
        {
            base.InitializeTarget();
            var region = Amazon.RegionEndpoint.GetBySystemName(RegionEndPoint);

            _client = new Amazon.SQS.AmazonSQSClient(AwsAccessKeyId, AwsSecretAccessKey, region);
        }
        public ActionResult Webhook(string id)
        {
            string securityId = ConfigurationManager.AppSettings["SecurityId"];
            if (!String.IsNullOrEmpty(securityId))
            {
                if (securityId != id)
                    return new HttpStatusCodeResult((int)System.Net.HttpStatusCode.BadRequest);
            }

            // Verify the content type is json
            if (!this.Request.ContentType.StartsWith("application/json"))
                return new HttpStatusCodeResult((int)System.Net.HttpStatusCode.BadRequest);

            // TODO: Verify the user agent

            // Parse the JSON content simply to validate it as proper JSON
            this.Request.InputStream.Seek(0, System.IO.SeekOrigin.Begin);
            var textReader = new System.IO.StreamReader(this.Request.InputStream);

            {
                Newtonsoft.Json.JsonReader reader = new Newtonsoft.Json.JsonTextReader(textReader);
                JObject jObject = JObject.Load(reader);
            }

            // All is OK, so seek back to the start
            this.Request.InputStream.Seek(0, System.IO.SeekOrigin.Begin);
            // and re-read the content
            string messageBody = textReader.ReadToEnd();

            string queueUrl = ConfigurationManager.AppSettings["SqsQueueUrl"];
            if (String.IsNullOrEmpty(queueUrl))
                throw new Exception("Null or empty SqsQueueUrl setting.");

            Amazon.SQS.AmazonSQS sqsClient;

            string endPointName = ConfigurationManager.AppSettings["SqsEndpoint"];
            if (!String.IsNullOrEmpty(endPointName))
            {
                Amazon.RegionEndpoint endPoint = Amazon.RegionEndpoint.GetBySystemName(endPointName);
                if (endPoint == null)
                    throw new Exception("Invalid Amazon AWS endpoint name: " + endPointName);

                sqsClient = new Amazon.SQS.AmazonSQSClient(endPoint);
            }
            else
            {
                sqsClient = new Amazon.SQS.AmazonSQSClient();
            }

            // Build our request
            var request = new Amazon.SQS.Model.SendMessageRequest()
                .WithMessageBody(messageBody)
                .WithQueueUrl(queueUrl);

            // Send to SQS
            var response = sqsClient.SendMessage(request);
            string messageId = response.SendMessageResult.MessageId;

            return new EmptyResult();
        }
Exemple #3
0
        public async void Run()
        {
            Console.WriteLine("Welcome to the AWS SQS Demo!");

            var queueURL = "https://sqs.us-east-1.amazonaws.com/066432702053/demo";

            //Credentials should not really be using profile.  This is for development purposes.
            //In Production inside AWS an Instance profile should be used
            using (var sqs = new Amazon.SQS.AmazonSQSClient(new StoredProfileAWSCredentials("GovBrands"), RegionEndpoint.USEast1))
            {
                while (true)
                {
                    //The ReceiveMessageAsync call blocks until it receives a message or 20 seconds has expired
                    var response = await sqs.ReceiveMessageAsync(new ReceiveMessageRequest
                    {
                        QueueUrl = queueURL,
                        MessageAttributeNames = new List <string> {
                            "*"
                        }
                    });

                    foreach (var message in response.Messages)
                    {
                        Console.WriteLine("{0}: {1} {2}", message.MessageId, message.MessageAttributes["Source"].StringValue, message.Body);
                        await sqs.DeleteMessageAsync(queueURL, message.ReceiptHandle);
                    }
                }
            }
        }
Exemple #4
0
        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                if (_client != null)
                {
                    _client.Dispose();
                    _client = null;
                }
            }

            base.Dispose(disposing);
        }
Exemple #5
0
        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));
        }
Exemple #6
0
        /// <summary>
        /// Deletes the list of messages from SQS.
        /// </summary>
        /// <param name="messages">The messages to delete.</param>
        private void DeleteMessageBatch(List <Amazon.SQS.Model.Message> messages)
        {
            if (messages == null)
            {
                throw new System.ArgumentNullException("messages");
            }

            using (var sqs = new Amazon.SQS.AmazonSQSClient())
            {
                sqs.DeleteMessageBatch(new Amazon.SQS.Model.DeleteMessageBatchRequest()
                {
                    QueueUrl = _options.QueueUrl,
                    Entries  = messages.Select(ToDeleteMessageBatchRequestEntry).ToList(),
                });
            }

            // keep track of stats
            Interlocked.Add(ref _deleteTotal, messages.Count);
        }
Exemple #7
0
        public SQSModule() : base("/sqs")
        {
            Post("/", async(x, ct) =>
            {
                using (var sqs = new Amazon.SQS.AmazonSQSClient(new StoredProfileAWSCredentials("GovBrands"), RegionEndpoint.USEast1))
                {
                    var resp = await sqs.SendMessageAsync(new SendMessageRequest
                    {
                        QueueUrl          = "https://sqs.us-east-1.amazonaws.com/066432702053/demo",
                        MessageAttributes = new Dictionary <string, MessageAttributeValue>
                        {
                            { "Source", new MessageAttributeValue {
                                  StringValue = "Nancy", DataType = "String"
                              } }
                        },
                        MessageBody = "Message from the Web at " + DateTime.UtcNow
                    });

                    return(resp.MessageId);
                }
            });
        }
Exemple #8
0
        /// <summary>
        /// Reads more <see cref="Amazon.SQS.Model.Message"/>.
        /// </summary>
        /// <returns>A list of <see cref="Amazon.SQS.Model.Message"/>.</returns>
        protected override List <Amazon.SQS.Model.Message> Read()
        {
            using (var sqs = new Amazon.SQS.AmazonSQSClient())
            {
                var response = sqs.ReceiveMessage(new Amazon.SQS.Model.ReceiveMessageRequest()
                {
                    QueueUrl              = _options.QueueUrl,
                    MaxNumberOfMessages   = 10,
                    MessageAttributeNames = this._optionsMessageAttributeNames,
                    AttributeNames        = this._optionsAttributeNames,
                });

                Interlocked.Add(ref _readTotal, response.Messages.Count);

                if (Logger.IsDebugEnabled)
                {
                    Logger.Debug("Received messages. Count: {0}", response.Messages.Count);
                }

                return(response.Messages);
            }
        }
Exemple #9
0
        /// <summary>
        /// A simple function that takes a string and does a ToUpper
        /// </summary>
        /// <param name="input"></param>
        /// <param name="context"></param>
        /// <returns></returns>
        public void FunctionHandler(ILambdaContext context)
        {
            string storageConnectionString;

            if (!ssmParameterManager.TryGetValue(Constants.StorageConnectionStringSSMPath, out storageConnectionString))
            {
                throw new Exception("Storage connection path not defined.");
            }
            else
            {
                Console.WriteLine($"Storage connection path is set at '{storageConnectionString}'");
            }

            if (!S3Manager.CheckS3Parameters())
            {
                return;
            }

            // Check whether the connection string can be parsed.
            if (CloudStorageAccount.TryParse(storageConnectionString, out storageAccount))
            {
                string ContainerNames;
                if (ssmParameterManager.TryGetValue(Constants.StorageContainerNamesSSMPath, out ContainerNames))
                {
                    var         arrContainerNames = ContainerNames.Split(',', StringSplitOptions.RemoveEmptyEntries);
                    List <Task> lstTasks          = new List <Task>();
                    foreach (var ContainerName in arrContainerNames)
                    {
                        var t = Task.Factory.StartNew(() =>
                        {
                            var lstBlobItems = AzureManager.ListBlobContainer(storageAccount, ContainerName, null);

                            if (lstBlobItems.Count > 0)
                            {
                                Console.WriteLine("Listing S3 items.");
                                var S3Objects = S3Manager.GetS3Items();

                                Console.WriteLine($"{S3Objects.Count.ToString()} items retrieved from S3.");

                                foreach (var S3Object in S3Objects)
                                {
                                    Console.WriteLine($"Item retrieved from S3: {S3Object.BucketName} - {S3Object.Key} ({S3Object.Size.ToString()} bytes) - ETag {S3Object.ETag}");
                                }

                                StringBuilder sb = new StringBuilder();

                                Amazon.SQS.AmazonSQSClient sqsClient = new Amazon.SQS.AmazonSQSClient();


                                lstBlobItems.ForEach((a) =>
                                {
                                    if (!S3Objects.Any(s => s.Key == a.BlobName && s.Size == a.Size))
                                    {
                                        CopyItem copyItem = new CopyItem {
                                            BlobItem = a
                                        };
                                        // No S3 objects that match the Azure blob, copy it over
                                        var strCopyItem = JsonConvert.SerializeObject(copyItem);
                                        SendMessageRequest sendRequest = new SendMessageRequest {
                                            MessageBody = strCopyItem, QueueUrl = System.Environment.GetEnvironmentVariable("QueueName")
                                        };

                                        var sendMessageResult = sqsClient.SendMessageAsync(sendRequest).GetAwaiter().GetResult();

                                        Console.WriteLine($"Item not found in S3, adding to copy queue - {a.BlobName} - send message result: {sendMessageResult.HttpStatusCode.ToString()}");
                                    }
                                });
                            }
                        });
                        lstTasks.Add(t);
                    }

                    Task.WaitAll(lstTasks.ToArray());
                }
            }
            else
            {
                // Otherwise, let the user know that they need to define the environment variable.
                throw new Exception("Storage connection path not defined.");
            }
        }
        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;
            }
        }
        public ActionResult Webhook(string id)
        {
            string securityId = ConfigurationManager.AppSettings["SecurityId"];

            if (!String.IsNullOrEmpty(securityId))
            {
                if (securityId != id)
                {
                    return(new HttpStatusCodeResult((int)System.Net.HttpStatusCode.BadRequest));
                }
            }

            // Verify the content type is json
            if (!this.Request.ContentType.StartsWith("application/json"))
            {
                return(new HttpStatusCodeResult((int)System.Net.HttpStatusCode.BadRequest));
            }

            // TODO: Verify the user agent

            // Parse the JSON content simply to validate it as proper JSON
            this.Request.InputStream.Seek(0, System.IO.SeekOrigin.Begin);
            var textReader = new System.IO.StreamReader(this.Request.InputStream);

            {
                Newtonsoft.Json.JsonReader reader = new Newtonsoft.Json.JsonTextReader(textReader);
                JObject jObject = JObject.Load(reader);
            }

            // All is OK, so seek back to the start
            this.Request.InputStream.Seek(0, System.IO.SeekOrigin.Begin);
            // and re-read the content
            string messageBody = textReader.ReadToEnd();

            string queueUrl = ConfigurationManager.AppSettings["SqsQueueUrl"];

            if (String.IsNullOrEmpty(queueUrl))
            {
                throw new Exception("Null or empty SqsQueueUrl setting.");
            }

            Amazon.SQS.AmazonSQS sqsClient;

            string endPointName = ConfigurationManager.AppSettings["SqsEndpoint"];

            if (!String.IsNullOrEmpty(endPointName))
            {
                Amazon.RegionEndpoint endPoint = Amazon.RegionEndpoint.GetBySystemName(endPointName);
                if (endPoint == null)
                {
                    throw new Exception("Invalid Amazon AWS endpoint name: " + endPointName);
                }

                sqsClient = new Amazon.SQS.AmazonSQSClient(endPoint);
            }
            else
            {
                sqsClient = new Amazon.SQS.AmazonSQSClient();
            }

            // Build our request
            var request = new Amazon.SQS.Model.SendMessageRequest()
                          .WithMessageBody(messageBody)
                          .WithQueueUrl(queueUrl);

            // Send to SQS
            var    response  = sqsClient.SendMessage(request);
            string messageId = response.SendMessageResult.MessageId;

            return(new EmptyResult());
        }