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);
                        }
                    }
        }
示例#2
0
        public static void GetInventory(string vaultName, string jobId, string outputPath, Amazon.RegionEndpoint awsRegion)
        {
            AmazonGlacierClient client;

            try
            {
                // Get AWS account info (needed to configure the SNS queue)
                using (var iamClient = new AmazonSecurityTokenServiceClient(awsRegion))
                {
                    var identityResponse = iamClient.GetCallerIdentity(new GetCallerIdentityRequest());
                    awsAccount = identityResponse.Account;
                    accountArn = identityResponse.Arn;
                }

                Console.WriteLine("accountArn: {accountArn}");

                using (client = new AmazonGlacierClient(awsRegion))
                {
                    if (string.IsNullOrEmpty(jobId))
                    {
                        Console.WriteLine("Setup SNS topic and SQS queue.");
                        SetupTopicAndQueue(awsRegion);
                        Console.WriteLine("To continue, press Enter");
                        Console.ReadKey();

                        Console.WriteLine("Retrieve Inventory List");
                        jobId = GetVaultInventoryJobId(vaultName, client);

                        // Check queue for a message and if job completed successfully, download inventory.
                        ProcessQueue(vaultName, jobId, client, outputPath);
                    }
                    else
                    {
                        Console.WriteLine("Downloading job output");
                        DownloadOutput(vaultName, jobId, client, outputPath); // Save job output to the specified file location.
                    }
                }
                Console.WriteLine("Operations successful.");
                Console.WriteLine("To continue, press Enter");
                Console.ReadKey();
            }
            catch (AmazonGlacierException e) { Console.WriteLine(e.Message); }
            catch (AmazonServiceException e) { Console.WriteLine(e.Message); }
            catch (Exception e) { Console.WriteLine(e.Message); }
            finally
            {
                // Delete SNS topic and SQS queue.
                if (!string.IsNullOrEmpty(topicArn))
                {
                    snsClient.DeleteTopic(new DeleteTopicRequest()
                    {
                        TopicArn = topicArn
                    });
                }

                if (!string.IsNullOrEmpty(queueUrl))
                {
                    sqsClient.DeleteQueue(new DeleteQueueRequest()
                    {
                        QueueUrl = queueUrl
                    });
                }
            }
        }
        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);
                }
            }
        }
示例#4
0
文件: Program.cs 项目: mikerains/aws
        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();
        }
示例#5
0
        public JsonResult sendSmsNotification(List <SmsContact> phones, string message)
        {
            var             client               = new AmazonSimpleNotificationServiceClient(accessKey, secretKey, RegionEndpoint.USEast1);
            PublishRequest  smsRequest           = new PublishRequest();
            PublishResponse smsResponse          = new PublishResponse();
            var             snsMessageAttributes = new Dictionary <string, MessageAttributeValue>();

            ResponseNotification response = new ResponseNotification();
            var cont      = 0;
            var phoneCont = 0;

            foreach (var phone in phones)
            {
                phoneCont++;

                var subscribe = subscribePhoneToTopic(phone.phone);
                if (subscribe.HttpStatusCode == HttpStatusCode.OK)
                {
                    cont++;
                }
            }

            if (cont == 0)
            {
                response.Success = false;
                response.Message = "Ocurrió un error al suscribir los contactos";
            }

            //ENVIO DEL SMS
            if (message != "")
            {
                var smsType = new MessageAttributeValue
                {
                    DataType    = "String",
                    StringValue = "Transactional"
                };
                snsMessageAttributes.Add("AWS.SNS.SMS.SMSType", smsType);

                smsRequest.TopicArn          = topicArn;
                smsRequest.Message           = message;
                smsRequest.MessageAttributes = snsMessageAttributes;

                //SEND SMS
                try
                {
                    smsResponse = client.Publish(smsRequest);
                    var MessageId = smsResponse.MessageId;

                    //DELETE SUSCRIPTORS
                    if (MessageId != "")
                    {
                        DeleteTopicRequest topicToDelete = new DeleteTopicRequest(topicArn);
                        client.DeleteTopic(topicToDelete);
                    }

                    response.Success = true;
                    response.Message = "Sms campain sended with de ID: " + MessageId;
                }
                catch (Exception ex)
                {
                    response.Success = false;
                    response.Message = ex.InnerException.InnerException.Message;
                }
            }


            var jsonResult = Json(response, JsonRequestBehavior.AllowGet);

            jsonResult.MaxJsonLength = int.MaxValue;
            return(jsonResult);
        }