public string createPlatformApplicationAndAttachToTopic(string deviceToken, string username)
        {
            if (deviceToken == null || username == null)
            {
                throw new ArgumentException("Passing null device token or username");
            }

            var topicRequest = new CreateTopicRequest
            {
                Name = username + "_myTopic"
            };

            var topicResponse = snsClient.CreateTopic(topicRequest);


            var createPlatformApplicationRequest = new CreatePlatformApplicationRequest
            {
                // Platform Credential is the SERVER API KEY FOR GCM
                Attributes = new Dictionary <string, string>()
                {
                    { "PlatformCredential", API_KEY }, { "EventEndpointCreated", topicResponse.TopicArn }
                },
                Name     = username + "_platform",
                Platform = "GCM"
            };

            var createPlatformResponse = snsClient.CreatePlatformApplication(createPlatformApplicationRequest);

            string platformApplicationArn = createPlatformResponse.PlatformApplicationArn;

            var request1 = new CreatePlatformEndpointRequest
            {
                CustomUserData         = "",
                PlatformApplicationArn = platformApplicationArn,
                Token = deviceToken
            };

            // Getting the endpoint result
            // It contains Endpoint ARN that needs to be subscripted to a topic
            var createPlatformEndpointResult = snsClient.CreatePlatformEndpoint(request1);


            try
            {
                snsClient.Subscribe(new SubscribeRequest
                {
                    Protocol = "application",
                    TopicArn = topicResponse.TopicArn,
                    Endpoint = createPlatformEndpointResult.EndpointArn
                });
            }

            catch (Exception e)
            {
                Console.WriteLine(e.Message.ToString());
                return(null);
            }

            return(topicResponse.TopicArn);
        }
Example #2
0
        private static string CreateSNSTopic(AmazonSimpleNotificationServiceClient sns, string name, string displayName)
        {
            string topicArn = "";

            try
            {
                // Create topic
                Console.WriteLine("Creating topic...");
                topicArn = sns.CreateTopic(new CreateTopicRequest
                {
                    Name = name
                }).TopicArn;

                // Set display name to a friendly value
                Console.WriteLine();
                Console.WriteLine("Setting topic attributes...");
                sns.SetTopicAttributes(new SetTopicAttributesRequest
                {
                    TopicArn       = topicArn,
                    AttributeName  = "DisplayName",
                    AttributeValue = displayName
                });
            }
            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);
            }
            return(topicArn);
        }
Example #3
0
        public string CreateTopic(string topicName, string topicDisplayName)
        {
            string topicArn = null;

            try
            {
                Console.WriteLine("Creating topic...");
                topicArn = sns.CreateTopic(new CreateTopicRequest
                {
                    Name = topicName
                }).TopicArn;
                Console.WriteLine($"Topic created with Arn: {topicArn}");


                // Set display name to a friendly value
                Console.WriteLine();
                Console.WriteLine("Setting topic attributes...");
                sns.SetTopicAttributes(new SetTopicAttributesRequest
                {
                    TopicArn       = topicArn,
                    AttributeName  = "DisplayName",
                    AttributeValue = topicDisplayName
                });
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
                throw;
            }
            return(topicArn);
        }
Example #4
0
 private void Ensure()
 {
     if (!TopicExists())
     {
         var request = new CreateTopicRequest();
         request.Name = TopicName;
         var response = _snsClient.CreateTopic(request);
         TopicArn = response.TopicArn;
     }
     if (!string.IsNullOrEmpty(SubscriptionName))
     {
         _queueClient = new QueueClient(SubscriptionName);
         if (!SubscriptionExists())
         {
             var response = _snsClient.Subscribe(new SubscribeRequest
             {
                 TopicArn = TopicArn,
                 Protocol = "sqs",
                 Endpoint = _queueClient.QueueArn
             });
             _subscriptionArn = response.SubscriptionArn;
             var attrRequest = new SetSubscriptionAttributesRequest
             {
                 AttributeName   = "RawMessageDelivery",
                 AttributeValue  = "true",
                 SubscriptionArn = _subscriptionArn
             };
             _snsClient.SetSubscriptionAttributes(attrRequest);
             _queueClient.AllowSnsToSendMessages(this);
         }
     }
 }
Example #5
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 }
                    }
                });
            }
Example #6
0
        public static string CreateTopic(string topicName)
        {
            using (var client = new AmazonSimpleNotificationServiceClient(Settings.AccessKey, Settings.Secret))
            {
                var request = new CreateTopicRequest(topicName);

                return(client.CreateTopic(request).TopicArn);
            }
        }
        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 }
                }
            });
        }
Example #8
0
        public object initializerService()
        {
            var sns = new AmazonSimpleNotificationServiceClient();

            // Create topic
            var topicArn = sns.CreateTopic(new CreateTopicRequest
            {
                Name = "SampleSNSTopic"
            }).TopicArn;
        }
 //
 //====================================================================================================
 /// <summary>
 /// Create a topic. The actual topic will be appended to the appName
 /// </summary>
 /// <param name="core"></param>
 /// <param name="topic"></param>
 /// <returns></returns>
 public static string createTopic(CoreController core, AmazonSimpleNotificationServiceClient snsClient, string topic)
 {
     try {
         var topicResponse = snsClient.CreateTopic(core.appConfig.name + "_" + topic);
         return(topicResponse.TopicArn);
     } catch (Exception ex) {
         LogController.logError(core, ex);
         return("");
     }
 }
        public void SetTopicConfigurationTests()
        {
            var s3Config = new AmazonS3Config();

            using (var s3Client = new AmazonS3Client(s3Config))
                using (var snsClient = new AmazonSimpleNotificationServiceClient())
                {
                    var snsCreateResponse = snsClient.CreateTopic("events-test-" + DateTime.Now.Ticks);
                    var bucketName        = S3TestUtils.CreateBucketWithWait(s3Client);

                    try
                    {
                        snsClient.AuthorizeS3ToPublish(snsCreateResponse.TopicArn, bucketName);

                        PutBucketNotificationRequest putRequest = new PutBucketNotificationRequest
                        {
                            BucketName          = bucketName,
                            TopicConfigurations = new List <TopicConfiguration>
                            {
                                new TopicConfiguration
                                {
                                    Id     = "the-topic-test",
                                    Topic  = snsCreateResponse.TopicArn,
                                    Events = new List <EventType> {
                                        EventType.ObjectCreatedPut
                                    }
                                }
                            }
                        };

                        s3Client.PutBucketNotification(putRequest);

                        var getResponse = S3TestUtils.WaitForConsistency(() =>
                        {
                            var res = s3Client.GetBucketNotification(bucketName);
                            return(res.TopicConfigurations?.Count > 0 && res.TopicConfigurations[0].Id == "the-topic-test" ? res : null);
                        });

                        Assert.AreEqual(1, getResponse.TopicConfigurations.Count);
                        Assert.AreEqual(1, getResponse.TopicConfigurations[0].Events.Count);
                        Assert.AreEqual(EventType.ObjectCreatedPut, getResponse.TopicConfigurations[0].Events[0]);

#pragma warning disable 618
                        Assert.AreEqual("s3:ObjectCreated:Put", getResponse.TopicConfigurations[0].Event);
#pragma warning restore 618
                        Assert.AreEqual("the-topic-test", getResponse.TopicConfigurations[0].Id);
                        Assert.AreEqual(snsCreateResponse.TopicArn, getResponse.TopicConfigurations[0].Topic);
                    }
                    finally
                    {
                        snsClient.DeleteTopic(snsCreateResponse.TopicArn);
                        AmazonS3Util.DeleteS3BucketWithObjects(s3Client, bucketName);
                    }
                }
        }
        public static void Main(string[] args)
        {
            var sns_object = new AmazonSimpleNotificationServiceClient();

            string email_id = "*****@*****.**";

            try
            {
                // Create an SNS topic called "PACKT-PUB"
                Console.WriteLine("Creating topic...");
                var Topic_Arn_id = sns_object.CreateTopic(new CreateTopicRequest
                {
                    Name = "PACKT-PUB"
                }).TopicArn;

                // Set attributes for the topic
                sns_object.SetTopicAttributes(new SetTopicAttributesRequest
                {
                    TopicArn       = Topic_Arn_id,
                    AttributeName  = "DisplayName",
                    AttributeValue = "PACKT-PUB"
                });

                // Add an email subsciption
                sns_object.Subscribe(new SubscribeRequest
                {
                    TopicArn = Topic_Arn_id,
                    Protocol = "email",
                    Endpoint = email_id
                });

                // Publish a topic
                sns_object.Publish(new PublishRequest
                {
                    Subject  = "Test",
                    Message  = "Testing testing 1 2 3",
                    TopicArn = Topic_Arn_id
                });

                Console.WriteLine("Waiting 60 seconds before deleting the topic");
                System.Threading.Thread.Sleep(30000);
                //Delete the topic
                sns_object.DeleteTopic(new DeleteTopicRequest
                {
                    TopicArn = Topic_Arn_id
                });
            }
            catch (AmazonSimpleNotificationServiceException exception)
            {
                Console.WriteLine("Error !");
                Console.WriteLine(exception.ErrorCode);
            }
        }
Example #12
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 }
                }
            });
        }
Example #13
0
        private string GetTopicArn(string topicName)
        {
            var topic = _client.FindTopic(topicName);

            if (topic != null)
            {
                return(topic.TopicArn);
            }

            var response = _client.CreateTopic(topicName);

            return(response?.TopicArn);
        }
        public void CreateTopic()
        {
            CreateTopicRequest request = new CreateTopicRequest
            {
                Name = TopicName
            };

            var response = client.CreateTopic(request);

            if (response.HttpStatusCode.IsSuccess())
            {
                Console.WriteLine($"Topic Created Successfullt! \nTopic ARN: {response.TopicArn}");
            }
        }
Example #15
0
        /// <summary>
        /// Ensures the topic.
        /// </summary>
        /// <param name="topicName">Name of the topic.</param>
        /// <param name="client">The client.</param>
        /// <returns>System.String.</returns>
        private string EnsureTopic(string topicName, AmazonSimpleNotificationServiceClient client)
        {
            var topic = client.FindTopic(topicName);

            if (topic != null)
            {
                return(topic.TopicArn);
            }

            _logger.DebugFormat("Topic with name {0} does not exist. Creating new topic", topicName);
            var topicResult = client.CreateTopic(topicName);

            return(topicResult.HttpStatusCode == HttpStatusCode.OK ? topicResult.TopicArn : string.Empty);
        }
Example #16
0
        public virtual string CreateTopic(AmazonSimpleNotificationServiceClient snsClient, string topicName)
        {
            string topicArn;
            // Create the request
            var createTopicRequest = new CreateTopicRequest
            {
                Name = topicName
            };
            // Submit the request
            CreateTopicResponse topicResponse = snsClient.CreateTopic(createTopicRequest);

            // Return the ARN
            topicArn = topicResponse.TopicArn;
            return(topicArn);
        }
Example #17
0
        public void CreateTopic()
        {
            CreateTopicRequest request = new CreateTopicRequest
            {
                Name = topicName
            };

            var response = client.CreateTopic(request);

            if (response.HttpStatusCode == System.Net.HttpStatusCode.OK)
            {
                Console.WriteLine("Topic Cretead Successfully");
                Console.WriteLine($"Topic ARN:{response.TopicArn}");
            }
            Console.ReadLine();
        }
Example #18
0
    /// <summary>
    /// Utility method for creating at topic and subscribe the email address to it.
    /// </summary>
    /// <param name="emailAddress"></param>
    /// <returns></returns>
    static string CreateTopic(string emailAddress)
    {
        var snsClient = new AmazonSimpleNotificationServiceClient();
        var topicArn  = snsClient.CreateTopic(new CreateTopicRequest
        {
            Name = "TranscodeEvents" + UNIQUE_POSTFIX
        }).TopicArn;

        snsClient.Subscribe(new SubscribeRequest
        {
            TopicArn = topicArn,
            Protocol = "email",
            Endpoint = emailAddress
        });

        return(topicArn);
    }
Example #19
0
        public static string createSMSTopic()
        {
            var client = new AmazonSimpleNotificationServiceClient(accessKey, secretKey, RegionEndpoint.USEast1);

            var topicRequest = new CreateTopicRequest
            {
                Name = "RedElectoralTopic"
            };
            var topicResponse = client.CreateTopic(topicRequest);

            if (topicResponse.HttpStatusCode == HttpStatusCode.OK)
            {
                return(topicResponse.TopicArn);
            }
            else
            {
                return("");
            }
        }
Example #20
0
        private void PublishSNSEvent(string Message, string AmazonSNSKey, string AmazonSNSSecretKey, string TopicName, string EventType)
        {
            string topicname = ProcessSNSTopicName(TopicName);

            try
            {
                var           client        = new AmazonSimpleNotificationServiceClient(AmazonSNSKey, AmazonSNSSecretKey);
                string        topicarn      = string.Empty;
                PublishResult publishResult = new PublishResult();
                if (IsTopicExists(client, topicname, out topicarn))
                {
                    PublishRequest publishRequest = new PublishRequest();
                    publishRequest.Message  = Message;
                    publishRequest.TopicArn = topicarn;
                    PublishResponse publishResponse = client.Publish(publishRequest);
                    publishResult = publishResponse.PublishResult;
                }
                else
                {
                    CreateTopicRequest topicRequest = new CreateTopicRequest();
                    topicRequest.Name = topicname;
                    CreateTopicResponse topicResponse  = client.CreateTopic(topicRequest);
                    CreateTopicResult   result         = topicResponse.CreateTopicResult;
                    PublishRequest      publishRequest = new PublishRequest();
                    publishRequest.Message  = Message;
                    publishRequest.TopicArn = result.TopicArn;
                    PublishResponse publishResponse = client.Publish(publishRequest);
                    publishResult = publishResponse.PublishResult;
                }
                if (!string.IsNullOrEmpty(publishResult.MessageId))
                {
                    CreateLogs(Message, EventType, topicname, true);
                }
            }
            catch (AmazonSimpleNotificationServiceException ex)
            {
                /*Log details to logentries server.*/
                CreateLogs(Message, EventType, topicname, false);
                throw ex;
            }
        }
        public void GenerateDatasetTest()
        {
            var iamClient = new AmazonIdentityManagementServiceClient();
            var snsClient = new AmazonSimpleNotificationServiceClient();
            var s3Client  = new AmazonS3Client();

            string bucketName = null;
            string topicArn   = null;
            Role   role       = null;

            try
            {
                bucketName = UtilityMethods.GenerateName("GenerateDatasetTestBucket");
                s3Client.PutBucket(bucketName);

                var roleName   = UtilityMethods.GenerateName("GenerateDatasetTestRole");
                var policyName = "MarketplacePolicy";
                // Create a role with trust policy
                role = iamClient.CreateRole(new CreateRoleRequest
                {
                    RoleName = roleName,
                    AssumeRolePolicyDocument = TrustPolicy
                }).Role;

                // Set access policy
                iamClient.PutRolePolicy(new PutRolePolicyRequest
                {
                    RoleName       = roleName,
                    PolicyDocument = AccessPolicy,
                    PolicyName     = policyName
                });

                var snsTopicName = UtilityMethods.GenerateName("GenerateDatasetTestTopic");
                topicArn = snsClient.CreateTopic(snsTopicName).TopicArn;

                // Throws an error as this account does not have any reports
                Utils.AssertExtensions.ExpectException <AmazonAWSMarketplaceCommerceAnalyticsException>
                    (() =>
                    Client.GenerateDataSet(new GenerateDataSetRequest
                {
                    DataSetPublicationDate  = DateTime.Now,
                    DataSetType             = DataSetType.DailyBusinessFees,
                    DestinationS3BucketName = bucketName,
                    SnsTopicArn             = topicArn,
                    RoleNameArn             = role.Arn
                })
                    );
            }
            finally
            {
                s3Client.DeleteBucket(bucketName);

                if (role != null)
                {
                    iamClient.DeleteRolePolicy(new DeleteRolePolicyRequest
                    {
                        PolicyName = "MarketplacePolicy",
                        RoleName   = role.RoleName
                    });

                    iamClient.DeleteRole(new DeleteRoleRequest
                    {
                        RoleName = role.RoleName
                    });
                }

                if (topicArn != null)
                {
                    snsClient.DeleteTopic(topicArn);
                }
            }
        }
Example #22
0
        static void Main(string[] args)
        {
            var    sns         = new AmazonSimpleNotificationServiceClient();
            string httpAddress = "http://34.217.101.161:3018/redisServer";

            try
            {
                // Create topic
                Console.WriteLine("Creating topic...");
                var topicArn = sns.CreateTopic(new CreateTopicRequest
                {
                    Name = "SampleSNSTopic"
                }).TopicArn;

                // Set display name to a friendly value
                Console.WriteLine();
                Console.WriteLine("Setting topic attributes...");
                sns.SetTopicAttributes(new SetTopicAttributesRequest
                {
                    TopicArn       = topicArn,
                    AttributeName  = "DisplayName",
                    AttributeValue = "Sample Notifications"
                });

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

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

                // Publish message
                Console.WriteLine();
                _ = DespatchAsync(@"[ '967813618981',
                                'BPNYDCFEE-6592',
                                '2/2/2018 20:59:00',
                                'Ops Hold',
                                '2018-02-02T20:59:38',
                                'Hold',
                                'Hold',
                                '',
                                '',
                                '' ]", topicArn);
                _ = DespatchAsync(@"[ '967813618981',
                                'BPNYDCFEE-6592',
                                '2/2/2018 20:59:00',
                                'Ops Hold',
                                '2018-02-02T20:59:38',
                                'Hold',
                                'Hold',
                                '',
                                '',
                                '' ]", topicArn);
                // Verify http endpoint receieved
                Console.WriteLine();
                Console.WriteLine("Please check your http endpoint and press enter when you receive the message...");
                Console.ReadLine();

                // Delete topic
                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();
        }
Example #23
0
 public bool AddGroup(string group)
 {
     client.CreateTopic(group);
     return(true);
 }
Example #24
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();
        }
Example #25
0
        public static void SNSCreateSubscribePublish()
        {
            #region SNSCreateSubscribePublish
            var snsClient = new AmazonSimpleNotificationServiceClient();

            var topicRequest = new CreateTopicRequest
            {
                Name = "CodingTestResults"
            };

            var topicResponse = snsClient.CreateTopic(topicRequest);

            var topicAttrRequest = new SetTopicAttributesRequest
            {
                TopicArn       = topicResponse.TopicArn,
                AttributeName  = "DisplayName",
                AttributeValue = "Coding Test Results"
            };

            snsClient.SetTopicAttributes(topicAttrRequest);

            snsClient.Subscribe(new SubscribeRequest
            {
                Endpoint = "*****@*****.**",
                Protocol = "email",
                TopicArn = topicResponse.TopicArn
            });

            // Wait for up to 2 minutes for the user to confirm the subscription.
            DateTime latest = DateTime.Now + TimeSpan.FromMinutes(2);

            while (DateTime.Now < latest)
            {
                var subsRequest = new ListSubscriptionsByTopicRequest
                {
                    TopicArn = topicResponse.TopicArn
                };

                var subs = snsClient.ListSubscriptionsByTopic(subsRequest).Subscriptions;

                var sub = subs[0];

                if (!string.Equals(sub.SubscriptionArn,
                                   "PendingConfirmation", StringComparison.Ordinal))
                {
                    break;
                }

                // Wait 15 seconds before trying again.
                System.Threading.Thread.Sleep(TimeSpan.FromSeconds(15));
            }

            snsClient.Publish(new PublishRequest
            {
                Subject = "Coding Test Results for " +
                          DateTime.Today.ToShortDateString(),
                Message  = "All of today's coding tests passed.",
                TopicArn = topicResponse.TopicArn
            });
            #endregion
        }
Example #26
0
        public static void Main(string[] args)
        {
            var    sns          = new AmazonSimpleNotificationServiceClient();
            string emailAddress = string.Empty;

            while (string.IsNullOrEmpty(emailAddress))
            {
                Console.Write("Please enter an email address to use: ");
                emailAddress = Console.ReadLine();
            }

            try
            {
                // Create topic
                Console.WriteLine("Creating topic...");
                var topicArn = sns.CreateTopic(new CreateTopicRequest
                {
                    Name = "SampleSNSTopic"
                }).TopicArn;

                // Set display name to a friendly value
                Console.WriteLine();
                Console.WriteLine("Setting topic attributes...");
                sns.SetTopicAttributes(new SetTopicAttributesRequest
                {
                    TopicArn       = topicArn,
                    AttributeName  = "DisplayName",
                    AttributeValue = "Sample Notifications"
                });

                // List all topics
                Console.WriteLine();
                Console.WriteLine("Retrieving all topics...");
                var listTopicsRequest = new ListTopicsRequest();
                ListTopicsResponse listTopicsResponse;
                do
                {
                    listTopicsResponse = sns.ListTopics(listTopicsRequest);
                    foreach (var topic in listTopicsResponse.Topics)
                    {
                        Console.WriteLine(" Topic: {0}", topic.TopicArn);

                        // Get topic attributes
                        var topicAttributes = sns.GetTopicAttributes(new GetTopicAttributesRequest
                        {
                            TopicArn = topic.TopicArn
                        }).Attributes;
                        if (topicAttributes.Count > 0)
                        {
                            Console.WriteLine(" Topic attributes");
                            foreach (var topicAttribute in topicAttributes)
                            {
                                Console.WriteLine(" -{0} : {1}", topicAttribute.Key, topicAttribute.Value);
                            }
                        }
                        Console.WriteLine();
                    }
                    listTopicsRequest.NextToken = listTopicsResponse.NextToken;
                } while (listTopicsResponse.NextToken != null);

                // 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();

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

                // Verify email receieved
                Console.WriteLine();
                Console.WriteLine("Please check your email and press enter when you receive the message...");
                Console.ReadLine();

                // Delete topic
                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();
        }
Example #27
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);
        }
        public void SetTopicConfigurationTests()
        {
            var s3Config = new AmazonS3Config();

            using (var s3Client = new AmazonS3Client(s3Config))
                using (var snsClient = new AmazonSimpleNotificationServiceClient())
                    using (var stsClient = new AmazonSecurityTokenServiceClient())
                    {
                        var snsCreateResponse = snsClient.CreateTopic("events-test-" + DateTime.Now.Ticks);
                        var bucketName        = S3TestUtils.CreateBucketWithWait(s3Client);

                        try
                        {
                            snsClient.AuthorizeS3ToPublish(snsCreateResponse.TopicArn, bucketName);

                            PutBucketNotificationRequest putRequest = new PutBucketNotificationRequest
                            {
                                BucketName          = bucketName,
                                TopicConfigurations = new List <TopicConfiguration>
                                {
                                    new TopicConfiguration
                                    {
                                        Id     = "the-topic-test",
                                        Topic  = snsCreateResponse.TopicArn,
                                        Events = new List <EventType> {
                                            EventType.ObjectCreatedPut
                                        }
                                    }
                                }
                            };

                            s3Client.PutBucketNotification(putRequest);

                            var getResponse = S3TestUtils.WaitForConsistency(() =>
                            {
                                var res = s3Client.GetBucketNotification(bucketName);
                                return(res.TopicConfigurations?.Count > 0 && res.TopicConfigurations[0].Id == "the-topic-test" ? res : null);
                            });

                            var getAttributeResponse = snsClient.GetTopicAttributes(new GetTopicAttributesRequest
                            {
                                TopicArn = snsCreateResponse.TopicArn
                            });

                            var policy = Policy.FromJson(getAttributeResponse.Attributes["Policy"]);

                            // SNS topics already have a default statement. We need to evaluate the second statement that the SDK appended.
                            var conditions = policy.Statements[1].Conditions;
                            Assert.AreEqual(2, conditions.Count);

                            var accountCondition = conditions.FirstOrDefault(x => string.Equals(x.ConditionKey, ConditionFactory.SOURCE_ACCOUNT_KEY));
                            Assert.IsNotNull(accountCondition);
                            Assert.AreEqual(ConditionFactory.StringComparisonType.StringEquals.ToString(), accountCondition.Type);
                            Assert.AreEqual(12, accountCondition.Values[0].Length);

                            var currentAccountId = stsClient.GetCallerIdentity(new GetCallerIdentityRequest()).Account;
                            Assert.AreEqual(currentAccountId, accountCondition.Values[0]);

                            Assert.AreEqual(1, getResponse.TopicConfigurations.Count);
                            Assert.AreEqual(1, getResponse.TopicConfigurations[0].Events.Count);
                            Assert.AreEqual(EventType.ObjectCreatedPut, getResponse.TopicConfigurations[0].Events[0]);

#pragma warning disable 618
                            Assert.AreEqual("s3:ObjectCreated:Put", getResponse.TopicConfigurations[0].Event);
#pragma warning restore 618
                            Assert.AreEqual("the-topic-test", getResponse.TopicConfigurations[0].Id);
                            Assert.AreEqual(snsCreateResponse.TopicArn, getResponse.TopicConfigurations[0].Topic);
                        }
                        finally
                        {
                            snsClient.DeleteTopic(snsCreateResponse.TopicArn);
                            AmazonS3Util.DeleteS3BucketWithObjects(s3Client, bucketName);
                        }
                    }
        }