Esempio n. 1
0
        public static void SQSSetQueueAttributes()
        {
            #region SQSSetQueueAttributes
            var client = new AmazonSQSClient();

            var attrs = new Dictionary <string, string>();

            // Maximum message size of 128 KiB (1,024 bytes * 128 KiB = 131,072 bytes).
            int maxMessage = 128 * 1024;

            attrs.Add(QueueAttributeName.DelaySeconds,
                      TimeSpan.FromSeconds(5).TotalSeconds.ToString());
            attrs.Add(QueueAttributeName.MaximumMessageSize, maxMessage.ToString());
            attrs.Add(QueueAttributeName.MessageRetentionPeriod,
                      TimeSpan.FromDays(1).TotalSeconds.ToString());
            attrs.Add(QueueAttributeName.ReceiveMessageWaitTimeSeconds,
                      TimeSpan.FromSeconds(5).TotalSeconds.ToString());
            attrs.Add(QueueAttributeName.VisibilityTimeout,
                      TimeSpan.FromHours(1).TotalSeconds.ToString());
            // Dead-letter queue attributes.
            attrs.Add(QueueAttributeName.RedrivePolicy,
                      "{\"maxReceiveCount\":" +
                      "\"5\"," +
                      "\"deadLetterTargetArn\":" +
                      "\"arn:aws:sqs:us-east-1:80398EXAMPLE:MyTestDeadLetterQueue\"}");

            var request = new SetQueueAttributesRequest
            {
                Attributes = attrs,
                QueueUrl   = "https://sqs.us-east-1.amazonaws.com/80398EXAMPLE/MyTestQueue"
            };

            client.SetQueueAttributes(request);
            #endregion
        }
Esempio n. 2
0
        internal void AllowSnsToSendMessages(TopicClient topicClient)
        {
            var policyFormat = @"{
                                  ""Statement"": [
                                    {
                                      ""Sid"": ""MySQSPolicy001"",
                                      ""Effect"": ""Allow"",
                                      ""Principal"": {
                                        ""AWS"": ""*""
                                      },
                                      ""Action"": ""sqs:SendMessage"",
                                      ""Resource"": ""%QueueArn%"",
                                      ""Condition"": {
                                        ""ArnEquals"": {
                                          ""aws:SourceArn"": ""%TopicArn%""
                                        }
                                      }
                                    }
                                  ]
                                }";
            var policy       = policyFormat.Replace("%QueueArn%", QueueArn).Replace("%TopicArn%", topicClient.TopicArn);
            var request      = new SetQueueAttributesRequest();

            request.Attributes.Add("Policy", policy);
            request.QueueUrl = QueueUrl;
            var response = _sqsClient.SetQueueAttributes(request);
        }
Esempio n. 3
0
        public virtual void GrantNotificationPermission(AmazonSQSClient sqsClient, string queueArn, string queueUrl,
                                                        string topicArn)
        {
            // Create a policy to allow the queue to receive notifications from the SNS topic
            var policy = new Policy("SubscriptionPermission")
            {
                Statements =
                {
                    new Statement(Statement.StatementEffect.Allow)
                    {
                        Actions    = { SQSActionIdentifiers.SendMessage },
                        Principals ={ new Principal("*")                                },
                        Conditions ={ ConditionFactory.NewSourceArnCondition(topicArn)  },
                        Resources  = { new Resource(queueArn)           }
                    }
                }
            };

            var attributes = new Dictionary <string, string>();

            attributes.Add("Policy", policy.ToJson());

            // Create the request to set the queue attributes for policy
            var setQueueAttributesRequest = new SetQueueAttributesRequest
            {
                QueueUrl   = queueUrl,
                Attributes = attributes
            };

            // Set the queue policy
            sqsClient.SetQueueAttributes(setQueueAttributesRequest);
        }
Esempio n. 4
0
            void SetupTopicAndQueue()
            {
                long ticks = DateTime.Now.Ticks;

                // Setup SNS topic.
                snsClient = new AmazonSimpleNotificationServiceClient(
                    settings.AWSAccessKeyID,
                    settings.AWSSecretAccessKey,
                    RegionEndpoint.GetBySystemName(settings.AWSS3Region.SystemName));

                sqsClient = new AmazonSQSClient(
                    settings.AWSAccessKeyID,
                    settings.AWSSecretAccessKey,
                    RegionEndpoint.GetBySystemName(settings.AWSS3Region.SystemName));

                topicArn = snsClient.CreateTopic(new CreateTopicRequest {
                    Name = "GlacierDownload-" + ticks
                }).TopicArn;
                Debug.WriteLine($"topicArn: {topicArn}");

                var createQueueRequest = new CreateQueueRequest {
                    QueueName = "GlacierDownload-" + ticks
                };
                var createQueueResponse = sqsClient.CreateQueue(createQueueRequest);

                this.queueUrl = createQueueResponse.QueueUrl;
                Debug.WriteLine($"QueueURL: {this.queueUrl}");

                var getQueueAttributesRequest = new GetQueueAttributesRequest {
                    AttributeNames = new List <string> {
                        "QueueArn"
                    },
                    QueueUrl = this.queueUrl
                };
                var response = sqsClient.GetQueueAttributes(getQueueAttributesRequest);

                queueArn = response.QueueARN;
                Debug.WriteLine($"QueueArn: {queueArn}");

                // Setup the Amazon SNS topic to publish to the SQS queue.
                snsClient.Subscribe(new SubscribeRequest()
                {
                    Protocol = "sqs",
                    Endpoint = queueArn,
                    TopicArn = topicArn
                });

                // Add the policy to the queue so SNS can send messages to the queue.
                var policy = SQS_POLICY.Replace("{TopicArn}", topicArn).Replace("{QuernArn}", queueArn);

                sqsClient.SetQueueAttributes(new SetQueueAttributesRequest {
                    QueueUrl   = this.queueUrl,
                    Attributes = new Dictionary <string, string>
                    {
                        { QueueAttributeName.Policy, policy }
                    }
                });
            }
        static void SetupTopicAndQueue(Amazon.RegionEndpoint region)
        {
            long ticks = DateTime.Now.Ticks;

            // Setup SNS topic.
            s_snsClient = new AmazonSimpleNotificationServiceClient(region);
            s_sqsClient = new AmazonSQSClient(region);

            s_topicArn = s_snsClient.CreateTopic(new CreateTopicRequest
            {
                Name = "GlacierDownload-" + ticks
            }).TopicArn;

            WriteLogConsole("topicArn: " + s_topicArn);

            CreateQueueRequest createQueueRequest = new CreateQueueRequest();

            createQueueRequest.QueueName = "GlacierDownload-" + ticks;
            CreateQueueResponse createQueueResponse = s_sqsClient.CreateQueue(createQueueRequest);

            s_queueUrl = createQueueResponse.QueueUrl;

            WriteLogConsole("QueueURL: " + s_queueUrl);

            GetQueueAttributesRequest getQueueAttributesRequest = new GetQueueAttributesRequest();

            getQueueAttributesRequest.AttributeNames = new List <string> {
                "QueueArn"
            };
            getQueueAttributesRequest.QueueUrl = s_queueUrl;

            GetQueueAttributesResponse response = s_sqsClient.GetQueueAttributes(getQueueAttributesRequest);

            s_queueArn = response.QueueARN;
            WriteLogConsole("QueueArn: " + s_queueArn);

            // Setup the Amazon SNS topic to publish to the SQS queue.
            s_snsClient.Subscribe(new SubscribeRequest()
            {
                Protocol = "sqs",
                Endpoint = s_queueArn,
                TopicArn = s_topicArn
            });

            // Add the policy to the queue so SNS can send messages to the queue.
            var policy = SQS_POLICY.Replace("{TopicArn}", s_topicArn).Replace("{QuernArn}", s_queueArn);

            s_sqsClient.SetQueueAttributes(new SetQueueAttributesRequest()
            {
                QueueUrl   = s_queueUrl,
                Attributes = new Dictionary <string, string>
                {
                    { QueueAttributeName.Policy, policy }
                }
            });
        }
Esempio n. 6
0
        static void Main(string[] args)
        {
            try
            {
                // create SQS client
                var sqsConfig = new AmazonSQSConfig()
                {
                    ServiceURL = "https://sqs.us-east-1.amazonaws.com"
                };

                Console.WriteLine("Creating AWS SQSClient");
                var sqsClient = new AmazonSQSClient(sqsConfig);

                if (useFIFO)
                {
                    Dictionary <String, String> dictSQSAttribute = new Dictionary <string, string>();
                    {
                        dictSQSAttribute.Add("ContentBasedDeduplication", "true");
                    }
                    sqsClient.SetQueueAttributes(SQS_URL, dictSQSAttribute);
                }
                Console.WriteLine("Creating AWS SQSClient done");


                // start loop to send message
                int      count   = 0;
                DateTime dtStart = DateTime.Now;
                int      msgId   = 0;
                while ((DateTime.Now - dtStart).TotalSeconds < RUN_PERIOD_SECOND)
                {
                    // create sendMessageRequest message
                    SendMessageRequest sendMessageRequest = new SendMessageRequest();
                    {
                        String id = DateTime.Now.Hour + DateTime.Now.Minute + "." + ++msgId;
                        sendMessageRequest.QueueUrl    = SQS_URL;
                        sendMessageRequest.MessageBody = "[" + id + "] Message from C# application at " + DateTime.Now.ToString();

                        if (useFIFO)
                        {
                            sendMessageRequest.MessageGroupId = (msgId % SQS_FIFO_NUMBER_OF_GROUP).ToString();
                        }
                    }

                    // send message
                    sqsClient.SendMessage(sendMessageRequest);

                    Console.WriteLine("Publish SQS message {0}", ++count);
                }
                Console.WriteLine("Publish SQS message done");
            }
            catch (Exception e)
            {
                Console.WriteLine("ERROR: " + e.ToString());
            }
        }
Esempio n. 7
0
        static void SetupTopicAndQueue(Amazon.RegionEndpoint awsRegion)
        {
            long ticks = DateTime.Now.Ticks;

            // Setup SNS topic.
            snsClient = new AmazonSimpleNotificationServiceClient(awsRegion);
            sqsClient = new AmazonSQSClient(awsRegion);

            topicArn = snsClient.CreateTopic(new CreateTopicRequest {
                Name = "GlacierInventory-" + ticks
            }).TopicArn;
            Console.WriteLine($"topicArn: {topicArn}");

            CreateQueueRequest createQueueRequest = new CreateQueueRequest();

            createQueueRequest.QueueName = "GlacierInventory-" + ticks;
            CreateQueueResponse createQueueResponse = sqsClient.CreateQueue(createQueueRequest);

            queueUrl = createQueueResponse.QueueUrl;
            Console.WriteLine($"QueueURL: {queueUrl}");

            GetQueueAttributesRequest getQueueAttributesRequest = new GetQueueAttributesRequest();

            getQueueAttributesRequest.AttributeNames = new List <string> {
                "QueueArn"
            };
            getQueueAttributesRequest.QueueUrl = queueUrl;
            GetQueueAttributesResponse response = sqsClient.GetQueueAttributes(getQueueAttributesRequest);

            queueArn = response.QueueARN;
            Console.WriteLine($"QueueArn: {queueArn}");

            // Setup the Amazon SNS topic to publish to the SQS queue.
            snsClient.Subscribe(new SubscribeRequest()
            {
                Protocol = "sqs",
                Endpoint = queueArn,
                TopicArn = topicArn
            });

            // Add the policy to the queue so SNS can send messages to the queue.
            var policy = SQS_POLICY.Replace("{TopicArn}", topicArn).Replace("{QuernArn}", queueArn).Replace("{AccountArn}", accountArn);

            sqsClient.SetQueueAttributes(new SetQueueAttributesRequest()
            {
                QueueUrl   = queueUrl,
                Attributes = new Dictionary <string, string>
                {
                    { QueueAttributeName.Policy, policy }
                }
            });
        }
Esempio n. 8
0
        public void OnExistingQueue()
        {
            AmazonSQSClient client = new AmazonSQSClient();

            var request = new SetQueueAttributesRequest
            {
                Attributes = new Dictionary <string, string>
                {
                    { "ReceiveMessageWaitTimeSeconds", "20" }
                },
                QueueUrl = "SQS_QUEUE_URL"
            };

            var response = client.SetQueueAttributes(request);
        }
Esempio n. 9
0
        public void DeadLetterQueueExample()
        {
            AmazonSQSClient client = new AmazonSQSClient();

            var setQueueAttributeRequest = new SetQueueAttributesRequest
            {
                Attributes = new Dictionary <string, string>
                {
                    { "RedrivePolicy", @"{ ""deadLetterTargetArn"" : ""DEAD_LETTER_QUEUE_ARN"", ""maxReceiveCount"" : ""10""}" }
                },
                QueueUrl = "SOURCE_QUEUE_URL"
            };

            client.SetQueueAttributes(setQueueAttributeRequest);
        }
Esempio n. 10
0
        public void set_permissions()
        {
            var setQueueAttributeRequest = new SetQueueAttributesRequest()
                                           .WithQueueUrl(_queueUrl)
                                           .WithAttribute(new Attribute {
                Name = "Policy", Value = AllowSnsAttribute()
            });
            var result = _client.SetQueueAttributes(setQueueAttributeRequest);

            Console.WriteLine(result.ToXML());

            var getQueueAttributesResponse = _client.GetQueueAttributes(
                new GetQueueAttributesRequest().WithAttributeName("Policy").WithQueueUrl(_queueUrl));

            foreach (var attribute in getQueueAttributesResponse.GetQueueAttributesResult.Attribute)
            {
                Console.WriteLine("{0} : {1}", attribute.Name, attribute.Value);
            }
        }
Esempio n. 11
0
        private static Topic SetupTopicAndSubscriptions(string topicFileName, string outputDirectory, string regionSystemName, string archiveId = null, string filename = null)
        {
            var topic = new Topic {
                TopicFileName   = topicFileName,
                OutputDirectory = outputDirectory,
                ArchiveId       = archiveId,
                FileName        = filename,
                DateRequested   = DateTime.Now
            };
            long ticks    = DateTime.Now.Ticks;
            var  settings = SettingsManager.GetSettings();

            #region Setup SNS topic
            var snsClient = new AmazonSimpleNotificationServiceClient(
                settings.AWSAccessKeyID,
                settings.AWSSecretAccessKey,
                RegionEndpoint.GetBySystemName(regionSystemName));

            var sqsClient = new AmazonSQSClient(
                settings.AWSAccessKeyID,
                settings.AWSSecretAccessKey,
                RegionEndpoint.GetBySystemName(regionSystemName));

            var topicArn = snsClient.CreateTopic(new CreateTopicRequest {
                Name = "GlacierDownload-" + ticks
            }).TopicArn;
            //Debug.WriteLine($"topicArn: {topicArn}");
            topic.TopicARN = topicArn;
            #endregion

            #region Setup SQS queue
            var createQueueRequest = new CreateQueueRequest {
                QueueName = "GlacierDownload-" + ticks
            };
            var createQueueResponse = sqsClient.CreateQueue(createQueueRequest);
            var queueUrl            = createQueueResponse.QueueUrl;
            //Debug.WriteLine($"QueueURL: {queueUrl}");
            topic.QueueUrl = queueUrl;

            var getQueueAttributesRequest = new GetQueueAttributesRequest
            {
                AttributeNames = new List <string> {
                    "QueueArn"
                },
                QueueUrl = queueUrl
            };
            var response = sqsClient.GetQueueAttributes(getQueueAttributesRequest);
            var queueArn = response.QueueARN;
            Debug.WriteLine($"QueueArn: {queueArn}");
            topic.QueueARN = queueArn;
            #endregion

            // Setup the Amazon SNS topic to publish to the SQS queue.
            // TODO SMS subscription
            snsClient.Subscribe(new SubscribeRequest()
            {
                Protocol = "sqs",
                Endpoint = queueArn,
                TopicArn = topicArn
            });

            // Add the policy to the queue so SNS can send messages to the queue.
            var policy = SQS_POLICY.Replace("{TopicArn}", topicArn).Replace("{QuernArn}", queueArn);

            sqsClient.SetQueueAttributes(new SetQueueAttributesRequest
            {
                QueueUrl   = queueUrl,
                Attributes = new Dictionary <string, string>
                {
                    { QueueAttributeName.Policy, policy }
                }
            });

            return(topic);
        }
Esempio n. 12
0
        public static void Main(string[] args)
        {
            const bool useEasySubscription = false;
            var        sns = new AmazonSimpleNotificationServiceClient();
            var        sqs = new AmazonSQSClient();

            string nameOfNewTopic = args[0];  //Sanitise this to ensure no illegal characters.
            var    emailAddress   = args[1];

            try
            {
                var topicArn = sns.CreateTopic(
                    new CreateTopicRequest {
                    Name = nameOfNewTopic
                }).TopicArn;

                sns.SetTopicAttributes(new SetTopicAttributesRequest
                {
                    TopicArn       = topicArn,
                    AttributeName  = "DisplayName",
                    AttributeValue = "Sample Notifications"
                });

                RetrieveAllTopics(sns);

                if (string.IsNullOrEmpty(emailAddress) == false)
                {
                    // Subscribe an endpoint - in this case, an email address
                    Console.WriteLine();
                    Console.WriteLine("Subscribing email address {0} to topic...", emailAddress);
                    sns.Subscribe(new SubscribeRequest
                    {
                        TopicArn = topicArn,
                        Protocol = "email",
                        Endpoint = emailAddress
                    });

                    // When using email, recipient must confirm subscription
                    Console.WriteLine();
                    Console.WriteLine("Please check your email and press enter when you are subscribed...");
                    Console.ReadLine();
                }

                Console.WriteLine();
                var sqsRequest = new CreateQueueRequest
                {
                    QueueName = "MyExperimentQueue"
                };

                var createQueueResponse = sqs.CreateQueue(sqsRequest);
                var myQueueUrl          = createQueueResponse.QueueUrl;

                var myQueueArn = sqs.GetQueueAttributes(
                    new GetQueueAttributesRequest
                {
                    QueueUrl       = myQueueUrl,
                    AttributeNames = new List <string> {
                        "All"
                    }
                }).QueueARN;

                ListQueues(sqs);

                if (myQueueArn != null)
                {
                    //https://aws.amazon.com/blogs/developer/subscribing-an-sqs-queue-to-an-sns-topic/

                    if (useEasySubscription)
                    {
                        sns.SubscribeQueue(topicArn, sqs, myQueueUrl);
                    }
                    else
                    {
                        var subscribeRequest = new SubscribeRequest(topicArn, "SQS", myQueueArn);

                        sns.Subscribe(subscribeRequest);

                        ActionIdentifier[] actions = new ActionIdentifier[2];
                        actions[0] = SQSActionIdentifiers.SendMessage;
                        actions[1] = SQSActionIdentifiers.ReceiveMessage;

                        Policy sqsPolicy = new Policy()
                                           .WithStatements(new Statement(Statement.StatementEffect.Allow)
                                                           .WithPrincipals(Principal.AllUsers)
                                                           .WithResources(new Resource(myQueueArn))
                                                           .WithConditions(ConditionFactory.NewSourceArnCondition(topicArn))
                                                           .WithActionIdentifiers(actions));


                        var attributeDictionary = new Dictionary <string, string>();
                        attributeDictionary.Add("Policy", sqsPolicy.ToJson());
                        var attributes = new SetQueueAttributesRequest {
                            QueueUrl = myQueueUrl, Attributes = attributeDictionary
                        };

                        sqs.SetQueueAttributes(attributes);
                    }

                    Thread.Sleep(TimeSpan.FromSeconds(5));

                    // Publish message
                    Console.WriteLine();
                    Console.WriteLine("Publishing message to topic...");
                    sns.Publish(new PublishRequest
                    {
                        Subject  = "Test",
                        Message  = "Testing testing 1 2 3",
                        TopicArn = topicArn
                    });
                    var receivedMessageResponse = ReceiveMessage(sqs, myQueueUrl);

                    DeleteReceivedMessage(receivedMessageResponse, myQueueUrl, sqs);
                }

                //Console.WriteLine();
                //Console.WriteLine("Deleting topic...");
                //sns.DeleteTopic(new DeleteTopicRequest
                //{
                //    TopicArn = topicArn
                //});
            }
            catch (AmazonSimpleNotificationServiceException ex)
            {
                Console.WriteLine("Caught Exception: " + ex.Message);
                Console.WriteLine("Response Status Code: " + ex.StatusCode);
                Console.WriteLine("Error Code: " + ex.ErrorCode);
                Console.WriteLine("Error Type: " + ex.ErrorType);
                Console.WriteLine("Request ID: " + ex.RequestId);
            }

            Console.WriteLine();
            Console.WriteLine("Press enter to exit...");
            Console.ReadLine();
        }