Esempio n. 1
0
        /// <summary>
        /// Method created to connect and process the Topic/Subscription in the AWS.
        /// </summary>
        /// <returns></returns>
        public void ProcessSubscription()
        {
            try
            {
                foreach (var topic in _topics)
                {
                    SqsSnsConfiguration config = GetConnection(topic);
                    MethodInfo          method = GetMethod(topic);
                    string topicName           = topic.Value.TopicName;
                    string subscriptName       = topic.Value.Subscription;

                    //Register Trace on the telemetry
                    WorkBench.Telemetry.TrackTrace($"Topic {topicName} registered");
                    AmazonSimpleNotificationServiceClient snsClient = new AmazonSimpleNotificationServiceClient(config.AwsAccessKeyId, config.AwsSecretAccessKey);
                    var topicRequest = new CreateTopicRequest
                    {
                        Name = topicName
                    };
                    var topicResponse = snsClient.CreateTopicAsync(topicRequest).Result;
                    var subsRequest   = new ListSubscriptionsByTopicRequest
                    {
                        TopicArn = topicResponse.TopicArn
                    };

                    var subs = snsClient.ListSubscriptionsByTopicAsync(subsRequest).Result.Subscriptions;
                    foreach (Subscription subscription in subs)
                    {
                        try
                        {
                            WorkBench.Telemetry.TrackEvent("Method invoked");
                            //Use of the Metrics to monitoring the queue's processes, start the metric
                            WorkBench.Telemetry.BeginMetricComputation("MessageProcessed");
                            //Processing the method defined with queue
                            InvokeProcess(method, Encoding.UTF8.GetBytes(subscription.SubscriptionArn));
                            WorkBench.Telemetry.ComputeMetric("MessageProcessed", 1);
                            //Finish the monitoring the queue's processes
                            WorkBench.Telemetry.EndMetricComputation("MessageProcessed");

                            WorkBench.Telemetry.TrackEvent("Method terminated");
                            WorkBench.Telemetry.TrackEvent("Queue's message completed");
                        }
                        catch (Exception exRegister)
                        {
                            //Use the class instead of interface because tracking exceptions directly is not supposed to be done outside AMAW (i.e. by the business code)
                            ((LightTelemetry)WorkBench.Telemetry).TrackException(exRegister);
                        }
                    }
                }
            }
            catch (Exception exception)
            {
                //Use the class instead of interface because tracking exceptions directly is not supposed to be done outside AMAW (i.e. by the business code)
                ((LightTelemetry)WorkBench.Telemetry).TrackException(exception);
            }
        }
Esempio n. 2
0
        public static async Task <IEnumerable <Subscription> > ListSubscriptions(string topicArn)
        {
            using (var client = new AmazonSimpleNotificationServiceClient(ConfigManager.ConfigSettings.AccessKey, ConfigManager.ConfigSettings.Secret, Amazon.RegionEndpoint.USWest2))
            {
                var request = new ListSubscriptionsByTopicRequest(topicArn);

                var response = await client.ListSubscriptionsByTopicAsync(request);

                return(response.Subscriptions);
            }
        }
Esempio n. 3
0
        /// <summary>
        /// 创建sns 主题
        /// sqs 订阅该主题
        /// 发布消息
        /// </summary>
        /// <param name="args"></param>
        /// <returns></returns>
        static async Task Main(string[] args)
        {
            string topicArn;
            var    sharedFile = new SharedCredentialsFile();

            sharedFile.TryGetProfile("default", out var sourceProfile);

            var credentials = AWSCredentialsFactory.GetAWSCredentials(sourceProfile, sharedFile);

            AmazonSimpleNotificationServiceClient client = new AmazonSimpleNotificationServiceClient(credentials, new AmazonSimpleNotificationServiceConfig()
            {
                ServiceURL = "http://192.168.1.57:4566"
            });

            AmazonSQSClient as_client = new AmazonSQSClient(credentials, new AmazonSQSConfig()
            {
                ServiceURL = "http://192.168.1.57:4566"
            });
            //查找主题
            var l_response = await client.ListTopicsAsync();

            if (!l_response.Topics.Any())
            {
                //没有主题就创建主题
                var c_response = await client.CreateTopicAsync("test");

                topicArn = c_response.TopicArn;
                Console.WriteLine("topic create success,topicArn is {0}", c_response.TopicArn);
            }
            else
            {
                topicArn = l_response.Topics.First().TopicArn;
            }
            Subscription subscriptions;
            var          ls_response = await client.ListSubscriptionsByTopicAsync(topicArn);

            //if (!ls_response.Subscriptions.Any(t => t.SubscriptionArn == "arn:aws:sns:us-east-1:000000000000:test:bac7453b-ae89-4021-81f2-044890c0d68c"))
            //{
            //    //如果没有订阅创建订阅
            //    var s_response = await client.SubscribeQueueToTopicsAsync(new List<string>() { topicArn }, as_client, "http://*****:*****@qq.com");
            //}

            var p_response = await client.PublishAsync(topicArn, "from sns publish message");

            Console.WriteLine("success");

            Console.ReadLine();
        }
Esempio n. 4
0
        public async Task GetAWSTopics(AWSCredentials credentials)
        {
            var client   = new AmazonSimpleNotificationServiceClient(credentials.AccessKey, credentials.SecretKey, credentials.Region);
            var request  = new ListTopicsRequest();
            var response = new ListTopicsResponse();

            do
            {
                response = await client.ListTopicsAsync(request);

                foreach (var topic in response.Topics)
                {
                    Console.WriteLine("Topic: {0}", topic.TopicArn);
                    await SendAWSNotification(credentials, topic.TopicArn, String.Format("Message from topic: {0}", topic.TopicArn));

                    var subs = await client.ListSubscriptionsByTopicAsync(
                        new ListSubscriptionsByTopicRequest
                    {
                        TopicArn = topic.TopicArn
                    });

                    var ss = subs.Subscriptions;

                    if (ss.Any())
                    {
                        Console.WriteLine("  Subscriptions:");
                        foreach (var sub in ss)
                        {
                            Console.WriteLine("    {0}", sub.SubscriptionArn);
                        }
                    }

                    var attrs = await client.GetTopicAttributesAsync(
                        new GetTopicAttributesRequest
                    {
                        TopicArn = topic.TopicArn
                    });

                    if (attrs.Attributes.Any())
                    {
                        Console.WriteLine("  Attributes:");

                        foreach (var attr in attrs.Attributes)
                        {
                            Console.WriteLine("    {0} = {1}", attr.Key, attr.Value);
                        }
                    }
                    Console.WriteLine();
                }
                request.NextToken = response.NextToken;
            } while (!string.IsNullOrEmpty(response.NextToken));
        }
Esempio n. 5
0
        private async Task SubscribeTopicToQueue()
        {
            var currentSubscriptions = (await _snsClient.ListSubscriptionsByTopicAsync(_topicArn)).Subscriptions;

            if (currentSubscriptions.Any())
            {
                var queueArn             = (await _sqsClient.GetQueueAttributesAsync(_queueUrl, new List <string> {
                    "QueueArn"
                })).QueueARN;
                var existingSubscription = currentSubscriptions.FirstOrDefault(x => x.Endpoint == queueArn);
                if (existingSubscription != null)
                {
                    return;
                }
            }

            await _snsClient.SubscribeQueueAsync(_topicArn, _sqsClient, _queueUrl);
        }
Esempio n. 6
0
        private void UnsubscribeFromTopic(AmazonSimpleNotificationServiceClient snsClient)
        {
            ListSubscriptionsByTopicResponse response;

            do
            {
                response = snsClient.ListSubscriptionsByTopicAsync(new ListSubscriptionsByTopicRequest {
                    TopicArn = _channelTopicArn
                }).GetAwaiter().GetResult();
                foreach (var sub in response.Subscriptions)
                {
                    var unsubscribe = snsClient.UnsubscribeAsync(new UnsubscribeRequest {
                        SubscriptionArn = sub.SubscriptionArn
                    }).GetAwaiter().GetResult();
                    if (unsubscribe.HttpStatusCode != HttpStatusCode.OK)
                    {
                        s_logger.LogError("Error unsubscribing from {TopicResourceName} for sub {ChannelResourceName}", _channelTopicArn, sub.SubscriptionArn);
                    }
                }
            } while (response.NextToken != null);
        }
Esempio n. 7
0
        protected async Task <bool> IsQueueSubscribedToTopic(RegionEndpoint regionEndpoint, Topic topic, string queueUrl)
        {
            var request = new GetQueueAttributesRequest
            {
                QueueUrl       = queueUrl,
                AttributeNames = new List <string> {
                    "QueueArn"
                }
            };

            var sqsclient = CreateMeABus.DefaultClientFactory().GetSqsClient(regionEndpoint);

            var queueArn = (await sqsclient.GetQueueAttributesAsync(request)).QueueARN;

            var client = new AmazonSimpleNotificationServiceClient(regionEndpoint);

            var subscriptions =
                (await client.ListSubscriptionsByTopicAsync(new ListSubscriptionsByTopicRequest(topic.TopicArn))).Subscriptions;

            return(subscriptions.Any(x => !string.IsNullOrEmpty(x.SubscriptionArn) && x.Endpoint == queueArn));
        }
Esempio n. 8
0
        private bool SubscriptionExists(AmazonSQSClient sqsClient, AmazonSimpleNotificationServiceClient snsClient)
        {
            string queueArn = GetQueueARNForChannel(sqsClient);

            if (queueArn == null)
            {
                throw new BrokerUnreachableException($"Could not find queue ARN for queue {_queueUrl}");
            }

            bool exists = false;
            ListSubscriptionsByTopicResponse response;

            do
            {
                response = snsClient.ListSubscriptionsByTopicAsync(new ListSubscriptionsByTopicRequest {
                    TopicArn = _channelTopicArn
                }).GetAwaiter().GetResult();
                exists = response.Subscriptions.Any(sub => (sub.Protocol.ToLower() == "sqs") && (sub.Endpoint == queueArn));
            } while (!exists && response.NextToken != null);

            return(exists);
        }
Esempio n. 9
0
        public void DeleteTopic()
        {
            if (_connection == null)
            {
                return;
            }

            using (var snsClient = new AmazonSimpleNotificationServiceClient(_awsConnection.Credentials, _awsConnection.Region))
            {
                //TODO: could be a seperate method
                var exists = snsClient.ListTopicsAsync().Result.Topics.SingleOrDefault(topic => topic.TopicArn == _channelTopicARN);
                if (exists != null)
                {
                    try
                    {
                        var response = snsClient.ListSubscriptionsByTopicAsync(new ListSubscriptionsByTopicRequest {
                            TopicArn = _channelTopicARN
                        }).Result;
                        foreach (var sub in response.Subscriptions)
                        {
                            var unsubscribe = snsClient.UnsubscribeAsync(new UnsubscribeRequest {
                                SubscriptionArn = sub.SubscriptionArn
                            }).Result;
                            if (unsubscribe.HttpStatusCode != HttpStatusCode.OK)
                            {
                                _logger.Value.Error($"Error unsubscribing from {_channelTopicARN} for sub {sub.SubscriptionArn}");
                            }
                        }

                        snsClient.DeleteTopicAsync(_channelTopicARN).Wait();
                    }
                    catch (Exception)
                    {
                        //don't break on an exception here, if we can't delete, just exit
                        _logger.Value.Error($"Could not delete topic {_channelTopicARN}");
                    }
                }
            }
        }
        public string Remove(Notification input, ILambdaContext context)
        {
            var region = RegionEndpoint.APSoutheast1;

            var topicId = input.TopicId;

            //Get item from DynamoDB
            var key = new Dictionary <string, AttributeValue>();

            key.Add("id", new AttributeValue()
            {
                S = topicId
            });

            var dynamoDBClient  = new AmazonDynamoDBClient(region);
            var getItemResponse = dynamoDBClient.GetItemAsync("Topics", key).Result;

            if (getItemResponse.HttpStatusCode != HttpStatusCode.OK)
            {
                throw new TestDonkeyException("Can't find item");
            }

            var item = getItemResponse.Item;

            var topicArn = item.GetValueOrDefault("arn").S;

            //Remove permission to accept CloudWatch Events trigger for Lambda
            var lambdaClient = new AmazonLambdaClient(region);

            var removePermissionRequest = new Amazon.Lambda.Model.RemovePermissionRequest();

            removePermissionRequest.FunctionName = "TestDonkeyLambda";
            removePermissionRequest.StatementId  = $"testdonkey-lambda-{ topicId }";

            var removePermissionResponse = lambdaClient.RemovePermissionAsync(removePermissionRequest).Result;

            if (removePermissionResponse.HttpStatusCode != HttpStatusCode.NoContent)
            {
                throw new TestDonkeyException("Can't remove permission");
            }

            //Remove target for CloudWatch Events
            var cloudWatchEventClient = new AmazonCloudWatchEventsClient(region);

            var removeTargetsRequest = new RemoveTargetsRequest();

            removeTargetsRequest.Ids = new List <string> {
                $"testdonkey-target-{ topicId }"
            };
            removeTargetsRequest.Rule = $"testdonkey-rule-{ topicId }";

            var removeTargetsResponse = cloudWatchEventClient.RemoveTargetsAsync(removeTargetsRequest).Result;

            if (removeTargetsResponse.HttpStatusCode != HttpStatusCode.OK)
            {
                throw new TestDonkeyException("Can't remove target");
            }

            //Delete rule in CloudWatch Events
            var deleteRuleRequest = new DeleteRuleRequest();

            deleteRuleRequest.Name = removeTargetsRequest.Rule;

            var deleteRuleResponse = cloudWatchEventClient.DeleteRuleAsync(deleteRuleRequest).Result;

            if (deleteRuleResponse.HttpStatusCode != HttpStatusCode.OK)
            {
                throw new TestDonkeyException("Can't delete rule");
            }

            //Remove subscribers from SNS
            var snsClient = new AmazonSimpleNotificationServiceClient(region);

            var listSubscriptionsByTopicRequest = new ListSubscriptionsByTopicRequest();

            listSubscriptionsByTopicRequest.TopicArn = topicArn;

            ListSubscriptionsByTopicResponse listSubscriptionsByTopicResponse = null;

            do
            {
                listSubscriptionsByTopicResponse = snsClient.ListSubscriptionsByTopicAsync(listSubscriptionsByTopicRequest).Result;
                if (listSubscriptionsByTopicResponse.HttpStatusCode != HttpStatusCode.OK)
                {
                    throw new TestDonkeyException("Can't list subscriptions");
                }

                if (listSubscriptionsByTopicResponse.Subscriptions != null && listSubscriptionsByTopicResponse.Subscriptions.Count > 0)
                {
                    foreach (var subscription in listSubscriptionsByTopicResponse.Subscriptions)
                    {
                        if (!subscription.SubscriptionArn.Equals("pendingconfirmation", StringComparison.OrdinalIgnoreCase))
                        {
                            snsClient.UnsubscribeAsync(subscription.SubscriptionArn).GetAwaiter().GetResult();
                        }
                    }
                }

                listSubscriptionsByTopicRequest.NextToken = listSubscriptionsByTopicResponse.NextToken;

                Thread.Sleep(1_000); //Wait for 1 second. Throttle: 100 transactions per second (TPS)
            } while (!string.IsNullOrWhiteSpace(listSubscriptionsByTopicResponse.NextToken));

            //Delete topic from SNS
            var deleteTopicResponse = snsClient.DeleteTopicAsync(topicArn).Result;

            if (deleteTopicResponse.HttpStatusCode != HttpStatusCode.OK)
            {
                throw new TestDonkeyException("Can't delete topic");
            }

            //Delete item from DynamoDB
            var dynamoDBDeleteItemResponse = dynamoDBClient.DeleteItemAsync("Topics", key).Result;

            if (dynamoDBDeleteItemResponse.HttpStatusCode != HttpStatusCode.OK)
            {
                throw new TestDonkeyException("Can't delete item");
            }

            return("success");
        }
        public async Task <bool> PublishEmailAsync()
        {
            _logger.LogInformation("email Repo before retrieve promo");
            var promotionList = await _repository.RetrieveTopFiveNewestPromotions();

            _logger.LogInformation("email Repo after retrieve promo");
            /*aws sns */
            var sns = new AmazonSimpleNotificationServiceClient();
            var listTopicsRequest = new ListTopicsRequest();
            ListTopicsResponse listTopicsResponse;

            _logger.LogInformation("sns before retrieve topic");
            listTopicsResponse = await sns.ListTopicsAsync(listTopicsRequest);

            _logger.LogInformation("sns after retrieve topic");
            var selectedTopic = listTopicsResponse.Topics.FirstOrDefault();

            _logger.LogInformation("sns before retrieve subscriber");
            var subscriptionList = (await sns.ListSubscriptionsByTopicAsync(selectedTopic.TopicArn)).Subscriptions.Select(x => x.Endpoint).ToList();

            _logger.LogInformation("sns after retrieve subscriber");
            #region config
            var emailConfig = new EmailService.EmailConfiguration
            {
                SmtpServer   = _configuration.GetValue <string>("EmailConfiguration:SmtpServer"),
                SmtpPort     = Convert.ToInt32(_configuration.GetValue <string>("EmailConfiguration:SmtpPort")),
                SmtpUsername = _configuration.GetValue <string>("EmailConfiguration:SmtpUsername"),
                SmtpPassword = _configuration.GetValue <string>("EmailConfiguration:SmtpPassword")
            };



            var messageContent = new EmailService.EmailMessage().Content;
            int count          = 1;
            messageContent = "Newest promotions happening right now in SG<div>";
            foreach (var promotion in promotionList)
            {
                messageContent += "<h2>#" + count + " </h2>" +
                                  "<br /><b>Promotion Title:</b>" + promotion.Header +
                                  "<br /><b>Promotion Description:</b>" + promotion.Description +
                                  "<br /><b>Promotion Start Date:</b>" + promotion.StartDate.ToString("yyyy - MM - dd") +
                                  "<br /><b>Promotion End Date:</b>" + promotion.EndDate.ToString("yyyy - MM - dd");
                count++;
            }
            messageContent += "</div>";

            var emailMessage = new EmailService.EmailMessage
            {
                FromAddresses = new List <EmailService.EmailAddress>(),
                ToAddresses   = new List <EmailService.EmailAddress>(),
                Content       = messageContent,
                Subject       = "PromotionsSG You Should Not Miss"
            };


            var emailAddrFrom = new EmailService.EmailAddress
            {
                Address = "*****@*****.**",
                Name    = "PromotionsSG"
            };

            var emailAddrToList = new List <EmailService.EmailAddress>();
            foreach (var subscriptionEmail in subscriptionList)
            {
                emailAddrToList.Add(new EmailService.EmailAddress {
                    Address = subscriptionEmail
                });
            }

            emailMessage.FromAddresses = new List <EmailService.EmailAddress> {
                emailAddrFrom
            };
            emailMessage.ToAddresses = emailAddrToList;
            #endregion

            #region send
            var message = new MimeMessage();
            message.To.AddRange(emailMessage.ToAddresses.Select(x => new MailboxAddress(x.Name, x.Address)));
            message.From.AddRange(emailMessage.FromAddresses.Select(x => new MailboxAddress(x.Name, x.Address)));

            message.Subject = emailMessage.Subject;
            message.Body    = new TextPart(TextFormat.Html)
            {
                Text = emailMessage.Content
            };
            _logger.LogInformation("before email stmp send");
            using (var emailClient = new SmtpClient())
            {
                await emailClient.ConnectAsync(emailConfig.SmtpServer, emailConfig.SmtpPort);

                emailClient.AuthenticationMechanisms.Remove("XOAUTH2");
                await emailClient.AuthenticateAsync(emailConfig.SmtpUsername, emailConfig.SmtpPassword);

                await emailClient.SendAsync(message);

                await emailClient.DisconnectAsync(true);
            }
            _logger.LogInformation("after email stmp send");
            #endregion
            return(true);
        }