示例#1
0
        private void CreateSnsTopic()
        {
            var snsAttrs = new Dictionary <string, string>();

            snsAttrs.Add("fifo_topic", "true");
            snsAttrs.Add("content_based_deduplication", "true");

            var response = _amazonSimpleNotificationService.CreateTopicAsync(new CreateTopicRequest
            {
                Name       = "person",
                Attributes = snsAttrs
            }).Result;

            Environment.SetEnvironmentVariable("PERSON_SNS_ARN", response.TopicArn);
        }
示例#2
0
        public ICollection <string> FetchTopics(IEnumerable <string> topicNames)
        {
            if (topicNames == null)
            {
                throw new ArgumentNullException(nameof(topicNames));
            }

            Connect(initSNS: true, initSQS: false);

            var topicArns = new List <string>();

            foreach (var topic in topicNames)
            {
                var createTopicRequest = new CreateTopicRequest(topic.NormalizeForAws());

                var createTopicResponse = _snsClient.CreateTopicAsync(createTopicRequest).GetAwaiter().GetResult();

                topicArns.Add(createTopicResponse.TopicArn);
            }

            GenerateSqsAccessPolicyAsync(topicArns)
            .GetAwaiter().GetResult();

            return(topicArns);
        }
示例#3
0
        public void Subscribe(IEnumerable <string> topics)
        {
            if (topics == null)
            {
                throw new ArgumentNullException(nameof(topics));
            }

            Connect(initSNS: true, initSQS: false);

            var topicArns = new List <string>();

            foreach (var topic in topics)
            {
                var createTopicRequest = new CreateTopicRequest(topic.NormalizeForAws());

                var createTopicResponse = _snsClient.CreateTopicAsync(createTopicRequest).GetAwaiter().GetResult();

                topicArns.Add(createTopicResponse.TopicArn);
            }

            Connect(initSNS: false, initSQS: true);

            _snsClient.SubscribeQueueToTopicsAsync(topicArns, _sqsClient, _queueUrl)
            .GetAwaiter().GetResult();
        }
示例#4
0
        public async Task <string> CreateTopic(Topology.Entities.Topic topic)
        {
            lock (_lock)
            {
                if (_topicArns.TryGetValue(topic.EntityName, out var result))
                {
                    return(result);
                }
            }

            var request = new CreateTopicRequest(topic.EntityName)
            {
                Attributes = topic.TopicAttributes.ToDictionary(x => x.Key, x => x.Value.ToString()),
                Tags       = topic.TopicTags.Select(x => new Tag
                {
                    Key   = x.Key,
                    Value = x.Value
                }).ToList()
            };

            TransportLogMessages.CreateTopic(topic.EntityName);

            var response = await _amazonSns.CreateTopicAsync(request, _cancellationToken).ConfigureAwait(false);

            EnsureSuccessfulResponse(response);

            var topicArn = response.TopicArn;

            lock (_lock)
                _topicArns[topic.EntityName] = topicArn;

            await Task.Delay(500, _cancellationToken).ConfigureAwait(false);

            return(topicArn);
        }
示例#5
0
        async Task <TopicInfo> CreateMissingTopic(Topology.Entities.Topic topic, CancellationToken cancellationToken)
        {
            Dictionary <string, string> attributes = topic.TopicAttributes.ToDictionary(x => x.Key, x => x.Value.ToString());

            var request = new CreateTopicRequest(topic.EntityName)
            {
                Attributes = attributes,
                Tags       = topic.TopicTags.Select(x => new Tag
                {
                    Key   = x.Key,
                    Value = x.Value
                }).ToList()
            };

            var response = await _client.CreateTopicAsync(request, cancellationToken).ConfigureAwait(false);

            response.EnsureSuccessfulResponse();

            var topicArn = response.TopicArn;

            var attributesResponse = await _client.GetTopicAttributesAsync(topicArn, cancellationToken).ConfigureAwait(false);

            attributesResponse.EnsureSuccessfulResponse();

            var missingTopic = new TopicInfo(topic.EntityName, topicArn, attributesResponse.Attributes);

            if (topic.Durable && topic.AutoDelete == false)
            {
                lock (_durableTopics)
                    _durableTopics[missingTopic.EntityName] = missingTopic;
            }

            return(missingTopic);
        }
示例#6
0
        public async Task CreateAsync(CancellationToken cancellationToken)
        {
            try
            {
                var response = await _client.CreateTopicAsync(new CreateTopicRequest(TopicName), cancellationToken)
                               .ConfigureAwait(false);

                if (string.IsNullOrEmpty(response.TopicArn))
                {
                    var requestId = response.ResponseMetadata.RequestId;
                    _logger.LogError("Failed to create or obtain ARN for topic {TopicName}. RequestId: {RequestId}.",
                                     TopicName, requestId);
                    throw new InvalidOperationException($"Failed to create or obtain ARN for topic '{TopicName}'. RequestId: {requestId}.");
                }

                Arn = response.TopicArn;
                _logger.LogDebug("Created topic '{TopicName}' with ARN '{Arn}'.", TopicName, Arn);
            }
            catch (AuthorizationErrorException ex)
            {
                _logger.LogWarning(0, ex, "Not authorized to create topic '{TopicName}'.", TopicName);
                if (!await ExistsAsync(cancellationToken).ConfigureAwait(false))
                {
                    throw new InvalidOperationException(
                              $"Topic '{TopicName}' does not exist, and no permission to create it.");
                }
            }
        }
示例#7
0
        public async Task <string> CreateSnsTopic(IAmazonSimpleNotificationService snsClient,
                                                  string topicName)
        {
            try
            {
                Console.WriteLine("Creating SNS Topic");
                var attrs = new Dictionary <string, string>
                {
                    { "FifoTopic", "true" },
                    { "ContentBasedDeduplication", "false" }
                };
                CreateTopicResponse responseCreate = await snsClient.CreateTopicAsync(
                    new CreateTopicRequest()
                {
                    Name = topicName, Attributes = attrs
                });

                Console.WriteLine($"Topic Arn: {responseCreate.TopicArn}");
                return(responseCreate.TopicArn);
            }
            catch (Exception e)
            {
                Console.WriteLine($"Creating SNS Topic failed: {e}");
                throw;
            }
        }
        public async Task <string> GetTopic(string topicName)
        {
            var response = await _amazonSns.CreateTopicAsync(topicName).ConfigureAwait(false);

            await Task.Delay(500).ConfigureAwait(false);

            return(response.TopicArn);
        }
示例#9
0
        // snippet-start:[SNS.dotnetv3.CreateSNSTopic]

        /// <summary>
        /// Creates a new SNS topic using the supplied topic name.
        /// </summary>
        /// <param name="client">The initialized SNS client object used to
        /// create the new topic.</param>
        /// <param name="topicName">A string representing the topic name.</param>
        /// <returns>The Amazon Resource Name (ARN) of the created topic.</returns>
        public static async Task <string> CreateSNSTopicAsync(IAmazonSimpleNotificationService client, string topicName)
        {
            var request = new CreateTopicRequest
            {
                Name = topicName,
            };

            var response = await client.CreateTopicAsync(request);

            return(response.TopicArn);
        }
示例#10
0
        public static async Task <string> Create(IAmazonSimpleNotificationService sns, string prefix, string eventType)
        {
            var topicName = $"{prefix}{eventType}";
            var sanitized = TopicSanitization.GetSanitizedTopicName(topicName);
            await Console.Out.WriteLineAsync($"Creating SNS Topic with name '{sanitized}'.");

            var createTopicResponse = await sns.CreateTopicAsync(sanitized).ConfigureAwait(false);

            await Console.Out.WriteLineAsync($"Created SNS Topic with name '{sanitized}'.");

            return(createTopicResponse.TopicArn);
        }
        public async Task <string> EnsureSnsTopic(string alertingGroupName, bool dryRun)
        {
            var topicName = alertingGroupName + "-Alerts";

            if (dryRun)
            {
                _logger.Info($"Skipped: Created SNS topic {topicName}");
                return(topicName);
            }

            // https://docs.aws.amazon.com/sns/latest/api/API_CreateTopic.html
            // "This action is idempotent, so if the requester already owns a topic with the specified name,
            // that topic's ARN is returned without creating a new topic."
            var createResponse = await _snsClient.CreateTopicAsync(topicName);

            _logger.Info($"Created SNS topic {topicName} with ARN {createResponse.TopicArn}");
            return(createResponse.TopicArn);
        }
        public async Task <string> CreateTopic(string topicName)
        {
            lock (_lock)
                if (_topicArns.TryGetValue(topicName, out var result))
                {
                    return(result);
                }

            var response = await _amazonSns.CreateTopicAsync(topicName).ConfigureAwait(false);

            await Task.Delay(500).ConfigureAwait(false);

            var topicArn = response.TopicArn;

            lock (_lock)
                _topicArns[topicName] = topicArn;

            return(topicArn);
        }
示例#13
0
        async Task <TopicInfo> CreateMissingTopic(Topology.Entities.Topic topic, CancellationToken cancellationToken)
        {
            Dictionary <string, string> attributes = topic.TopicAttributes.ToDictionary(x => x.Key, x => x.Value.ToString());

            var request = new CreateTopicRequest(topic.EntityName)
            {
                Attributes = attributes,
                Tags       = topic.TopicTags.Select(x => new Tag
                {
                    Key   = x.Key,
                    Value = x.Value
                }).ToList()
            };
            var topicArn = string.Empty;
            var doesTopicExistResponse = await _client.GetTopicAttributesAsync(topic.EntityName).ConfigureAwait(false);

            if (doesTopicExistResponse.DoesQueueExists())
            {
                topicArn = doesTopicExistResponse.Attributes
                           .First(t =>
                                  t.Key.Equals("TopicArn", System.StringComparison.InvariantCultureIgnoreCase))
                           .Value;
            }
            var response = await _client.CreateTopicAsync(request, cancellationToken).ConfigureAwait(false);

            response.EnsureSuccessfulResponse();

            topicArn = response.TopicArn;

            var attributesResponse = await _client.GetTopicAttributesAsync(topicArn, cancellationToken).ConfigureAwait(false);

            attributesResponse.EnsureSuccessfulResponse();

            var missingTopic = new TopicInfo(topic.EntityName, topicArn, attributesResponse.Attributes);

            if (topic.Durable && topic.AutoDelete == false)
            {
                lock (_durableTopics)
                    _durableTopics[missingTopic.EntityName] = missingTopic;
            }

            return(missingTopic);
        }
示例#14
0
        public async Task <string> CreateTopic(string name)
        {
            try
            {
                var topic = await _client.CreateTopicAsync(new CreateTopicRequest
                {
                    Name = name
                });

                _logger.Info($"Topic {name} successfully created");

                return(topic.TopicArn);
            }
            catch (Exception exception)
            {
                _logger.Error($"Topic {name} could not be created", exception.ToString());

                return(null);
            }
        }
示例#15
0
        private bool TryGetOrCreateTopicArn(string topicName, out string topicArn)
        {
            topicArn = null;
            if (_topicArnMaps.TryGetValue(topicName, out topicArn))
            {
                return(true);
            }

            var response = _snsClient.CreateTopicAsync(topicName).GetAwaiter().GetResult();

            if (string.IsNullOrEmpty(response.TopicArn))
            {
                return(false);
            }

            topicArn = response.TopicArn;

            _topicArnMaps.Add(topicName, topicArn);
            return(true);
        }
示例#16
0
        public Task <string> CreateTopicAsync(string topicName, IDictionary <string, string>?attributes = null)
        {
            if (string.IsNullOrWhiteSpace(topicName))
            {
                throw new ArgumentException($"A non-null/empty '{topicName}' is required.", nameof(topicName));
            }

            return(createTopicAsync());

            async Task <string> createTopicAsync()
            {
                var response = await _sns.CreateTopicAsync(topicName);

                if (response.HttpStatusCode != HttpStatusCode.OK)
                {
                    throw new InvalidOperationException($"Topic creation failed for topic '{topicName}'.");
                }

                if (attributes != null && attributes.Any())
                {
                    foreach (var attribute in attributes)
                    {
                        var request = new SetTopicAttributesRequest
                        {
                            AttributeName  = attribute.Key,
                            AttributeValue = attribute.Value,
                            TopicArn       = response.TopicArn
                        };

                        var setTopicResponse = await _sns.SetTopicAttributesAsync(request);

                        if (setTopicResponse.HttpStatusCode != HttpStatusCode.OK)
                        {
                            throw new InvalidOperationException($"Unable to set attributes for topic '{topicName}'");
                        }
                    }
                }

                return(response.TopicArn);
            }
        }
示例#17
0
        public static async Task <string> GetTopicArn(this IAmazonSimpleNotificationService snsClient, IAmazonInternalSettings m_AmazonInternalSettings, string topic)
        {
            var formatedTopicName = m_AmazonInternalSettings.TopicFormatter.FormatTopic(topic);

            var findTopicResult = await snsClient.FindTopicAsync(formatedTopicName);

            var topicArn = findTopicResult?.TopicArn;

            if (topicArn == null)
            {
                var createTopicResponse = await snsClient.CreateTopicAsync(formatedTopicName);

                if (createTopicResponse.HttpStatusCode != HttpStatusCode.OK)
                {
                    throw new SnsRebusException($"Error creating topic {formatedTopicName}.", createTopicResponse.CreateAmazonExceptionFromResponse());
                }

                topicArn = createTopicResponse.TopicArn;
            }

            return(topicArn);
        }
示例#18
0
        public async Task <string> EnsureSnsTopic(string alertingGroupName, bool dryRun)
        {
            var topicName = alertingGroupName + "-Alerts";
            var topic     = await _snsClient.FindTopicAsync(topicName);

            if (topic != null)
            {
                _logger.Detail($"Found SNS topic {topicName} with ARN {topic.TopicArn}");
                return(topic.TopicArn);
            }

            if (dryRun)
            {
                _logger.Info($"Skipped: Created SNS topic {topicName}");
                return(topicName);
            }

            var createResponse = await _snsClient.CreateTopicAsync(topicName);

            _logger.Info($"Created SNS topic {topicName} with ARN {createResponse.TopicArn}");
            return(createResponse.TopicArn);
        }
示例#19
0
 private Amazon.SimpleNotificationService.Model.CreateTopicResponse CallAWSServiceOperation(IAmazonSimpleNotificationService client, Amazon.SimpleNotificationService.Model.CreateTopicRequest request)
 {
     Utils.Common.WriteVerboseEndpointMessage(this, client.Config, "Amazon Simple Notification Service (SNS)", "CreateTopic");
     try
     {
         #if DESKTOP
         return(client.CreateTopic(request));
         #elif CORECLR
         return(client.CreateTopicAsync(request).GetAwaiter().GetResult());
         #else
                 #error "Unknown build edition"
         #endif
     }
     catch (AmazonServiceException exc)
     {
         var webException = exc.InnerException as System.Net.WebException;
         if (webException != null)
         {
             throw new Exception(Utils.Common.FormatNameResolutionFailureMessage(client.Config, webException.Message), webException);
         }
         throw;
     }
 }
        public async Task <string> CreateTopic(Topic topic)
        {
            lock (_lock)
                if (_topicArns.TryGetValue(topic.EntityName, out var result))
                {
                    return(result);
                }

            var request = new CreateTopicRequest(topic.EntityName)
            {
                Attributes = topic.TopicAttributes.ToDictionary(x => x.Key, x => x.Value.ToString())
            };

            var response = await _amazonSns.CreateTopicAsync(request).ConfigureAwait(false);

            await Task.Delay(500).ConfigureAwait(false);

            var topicArn = response.TopicArn;

            lock (_lock)
                _topicArns[topic.EntityName] = topicArn;

            return(topicArn);
        }
示例#21
0
        private Task <CreateTopicResponse> CreateSnsTopic(string topicName)
        {
            var createTopicRequest = new CreateTopicRequest(topicName);

            return(_snsClient.CreateTopicAsync(createTopicRequest));
        }
示例#22
0
 private static async Task CreateTopic(IAmazonSimpleNotificationService client, string topicName) =>
 await client.CreateTopicAsync(topicName);
示例#23
0
        public async Task <IActionResult> SNS()
        {
            var results = new List <string>();

            var topicRequest = new CreateTopicRequest {
                Name = "borislav-topic-1"
            };
            var topicResponse = await _snsClient.CreateTopicAsync(topicRequest);

            results.Add($"Topic '{topicRequest.Name}' created with status {topicResponse.HttpStatusCode}");

            var topicAttrRequest = new SetTopicAttributesRequest
            {
                TopicArn       = topicResponse.TopicArn,
                AttributeName  = "DisplayName",
                AttributeValue = "Coding Test Results"
            };
            await _snsClient.SetTopicAttributesAsync(topicAttrRequest);

            var subscribeRequest = new SubscribeRequest
            {
                Endpoint = "*****@*****.**",
                Protocol = "email",
                TopicArn = topicResponse.TopicArn
            };
            SubscribeResponse subscribeResponse = await _snsClient.SubscribeAsync(subscribeRequest);

            results.Add($"Invitation sent by email with status {subscribeResponse.HttpStatusCode}");
            results.Add("Wait for up to 2 min for the user to confirm the subscription");

            // 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.ListSubscriptionsByTopicAsync(subsRequest).Result.Subscriptions;

                if (!string.Equals(subs[0].SubscriptionArn, "PendingConfirmation", StringComparison.Ordinal))
                {
                    break;
                }

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

            var publishRequest = new PublishRequest
            {
                Subject  = "Coding Test Results for " + DateTime.Today.ToShortDateString(),
                Message  = "All of today's coding tests passed",
                TopicArn = topicResponse.TopicArn
            };
            PublishResponse publishResponse = await _snsClient.PublishAsync(publishRequest);

            results.Add($"Message '{publishRequest.Message}' published with status {topicResponse.HttpStatusCode}");

            ViewBag.Results = new List <string>();
            ViewBag.Results.AddRange(results);

            return(View());
        }