public async Task <ListTopicsResponse> ListTopics() { var request = new ListTopicsRequest(); var response = await snsClient.ListTopicsAsync(request); return(response); }
public async void passwordreset([FromBody] Users u) { Users a = _context.Users.Find(u.Email); _log.LogInformation("Listing all items"); Console.WriteLine("Hello inside the reset"); if (a != null) { var client = new AmazonSimpleNotificationServiceClient(RegionEndpoint.USEast1); var request = new ListTopicsRequest(); var response = new ListTopicsResponse(); _log.LogInformation("going inside for"); response = await client.ListTopicsAsync(); foreach (var topic in response.Topics) { _log.LogInformation(topic.TopicArn); if (topic.TopicArn.EndsWith("SNSTopicResetPassword")) { _log.LogInformation(topic.TopicArn); var respose = new PublishRequest { TopicArn = topic.TopicArn, Message = a.Email }; await client.PublishAsync(respose); } } } }
public Topic CheckSnsTopic(string topicName) { using (var client = new AmazonSimpleNotificationServiceClient(_credentials)) { return(client.ListTopicsAsync().Result.Topics.SingleOrDefault(topic => topic.TopicArn == topicName)); } }
public void DeleteTopic(string topicName) { using (var client = new AmazonSimpleNotificationServiceClient(_credentials)) { var topic = client.ListTopicsAsync().Result.Topics.SingleOrDefault(t => t.TopicArn == topicName); client.DeleteTopicAsync(topic.TopicArn).Wait(); } }
public static async Task <IEnumerable <string> > ListTopicArns() { using (var client = new AmazonSimpleNotificationServiceClient(ConfigManager.ConfigSettings.AccessKey, ConfigManager.ConfigSettings.Secret, Amazon.RegionEndpoint.USWest2)) { var response = await client.ListTopicsAsync(new ListTopicsRequest()); return(response.Topics.Select(x => x.TopicArn).ToList()); } }
private async Task GetTopicList() { var topicList = await snsClient.ListTopicsAsync(); Console.WriteLine("Topic list:"); foreach (var topic in topicList.Topics) { Console.WriteLine(" - {0}", topic.TopicArn); } }
private static async Task <string> CreateSnsTopic(AmazonSimpleNotificationServiceClient amazonSnsServiceClient, string topicName) { await amazonSnsServiceClient.CreateTopicAsync(topicName); var listTopicsResponse = await amazonSnsServiceClient.ListTopicsAsync(); string topicArn = listTopicsResponse.Topics.FirstOrDefault()?.TopicArn; return(topicArn); }
public void DeleteTopic(Connection connection) { 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 == connection.RoutingKey); if (exists != null) { snsClient.DeleteTopicAsync(connection.RoutingKey).Wait(); } } }
/// <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(); }
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)); }
private bool FindTopicByArn(AmazonSimpleNotificationServiceClient snsClient) { bool exists = false; ListTopicsResponse response; do { response = snsClient.ListTopicsAsync().GetAwaiter().GetResult(); exists = response.Topics.Any(topic => topic.TopicArn == _channelTopicArn); } while (!exists && response.NextToken != null); return(exists); }
public async System.Threading.Tasks.Task <ListTopicsResponse> GetTopicsAsync() { ListTopicsResponse listTopics = new ListTopicsResponse(); using (AmazonSimpleNotificationServiceClient snsClient = new AmazonSimpleNotificationServiceClient(credentials, Amazon.RegionEndpoint.USEast2)) { ListTagsForResourceRequest request = new ListTagsForResourceRequest(); listTopics = await snsClient.ListTopicsAsync(); } return(listTopics); }
public bool TopicExists(string topicName) { var exists = false; var matchString = string.Format(":{0}", topicName); var response = _snsClient.ListTopicsAsync().Result; var matches = response.Topics.Where(x => x.TopicArn.EndsWith(matchString)); if (matches.Count() == 1) { _topicArn = matches.ElementAt(0).TopicArn; exists = true; } return(exists); }
private static async Task SetupAws() { try { Environment.SetEnvironmentVariable("AWS_ACCESS_KEY_ID", "XXX", EnvironmentVariableTarget.Process); Environment.SetEnvironmentVariable("AWS_SECRET_ACCESS_KEY", "XXX", EnvironmentVariableTarget.Process); Environment.SetEnvironmentVariable("AWS_SESSION_TOKEN", "XXX", EnvironmentVariableTarget.Process); Environment.SetEnvironmentVariable("AWS_DEFAULT_REGION", "us-east-1", EnvironmentVariableTarget.Process); var snsClient = new AmazonSimpleNotificationServiceClient(new AmazonSimpleNotificationServiceConfig { ServiceURL = "http://localhost:4575" }); var sqsClient = new AmazonSQSClient(new AmazonSQSConfig { ServiceURL = "http://localhost:4576" }); var topicName = topic.Replace(".", "_"); var topicRequest = new CreateTopicRequest(topicName); var topicResponse = await snsClient.CreateTopicAsync(topicRequest); var queueRequest = new CreateQueueRequest($"{topicName}.queue"); var queueResponse = await sqsClient.CreateQueueAsync(queueRequest); var subscribeRequest = new SubscribeRequest { Endpoint = queueResponse.QueueUrl, TopicArn = topicResponse.TopicArn, Protocol = "sqs", ReturnSubscriptionArn = true, Attributes = new Dictionary <string, string> { ["RawMessageDelivery"] = "true" } }; var subscribeResponse = await snsClient.SubscribeAsync(subscribeRequest); (await snsClient.ListTopicsAsync()).Topics.ForEach(x => Console.WriteLine($"[AWS] Topic: {x.TopicArn}")); (await sqsClient.ListQueuesAsync(new ListQueuesRequest())).QueueUrls.ForEach(x => Console.WriteLine($"[AWS] Queue: {x}")); (await snsClient.ListSubscriptionsAsync(new ListSubscriptionsRequest())).Subscriptions.ForEach(x => Console.WriteLine($"[AWS] Subscription: {x.TopicArn} -> {x.Endpoint}")); } catch (Exception e) { Console.WriteLine($"[AWS] {e.Message}"); } }
public async Task <bool> TopicExists(string topic, AmazonSimpleNotificationServiceClient client) { string nextToken = null; if (_topics == null) { _topics = new List <Topic>(); do { var topicsResponse = await client.ListTopicsAsync(nextToken); _topics.AddRange(topicsResponse.Topics); nextToken = topicsResponse.NextToken; } while (nextToken != null); } return(_topics.Any(a => a.TopicArn == topic)); }
public async Task <IActionResult> Get() { var topicList = new List <Dictionary <string, string> >(); Dictionary <string, string> dictAttributes = null; using (_SnsClient = new AmazonSimpleNotificationServiceClient(_AwsCredentials, RegionEndpoint.USEast2)) { try { _SnsRequest = new ListTopicsRequest(); do { _SnsResponse = await _SnsClient.ListTopicsAsync(_SnsRequest); foreach (var topic in _SnsResponse.Topics) { // Get topic attributes var topicAttributes = await _SnsClient.GetTopicAttributesAsync(request : new GetTopicAttributesRequest { TopicArn = topic.TopicArn }); // this is see attributes of topic if (topicAttributes.Attributes.Count > 0) { dictAttributes = new Dictionary <string, string>(); foreach (var topicAttribute in topicAttributes.Attributes) { dictAttributes.Add(topicAttribute.Key, topicAttribute.Value.ToString()); } topicList.Add(dictAttributes); } } _SnsRequest.NextToken = _SnsResponse.NextToken; } while (_SnsResponse.NextToken != null); } catch (AmazonSimpleNotificationServiceException ex) { return(Content(HandleSNSError(ex))); } } return(Ok(JsonConvert.SerializeObject(topicList))); }
public async Task <IActionResult> ListTopics() { try { using (var client = new AmazonSimpleNotificationServiceClient()) { var topics = await client.ListTopicsAsync(); var list = topics.Topics; return(new JsonResult(list)); } } catch (KeyNotFoundException) { return(new NotFoundResult()); } catch (Exception ex) { return(StatusCode(StatusCodes.Status500InternalServerError, ex.Message)); } }
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}"); } } } }
/// <summary> /// Method to run light work Health Check for AWS /// </summary> /// <param name="serviceKey"></param> /// <param name="value"></param> /// <returns></returns> public LightHealth.HealthCheck HealthCheck(string serviceKey, string value) { try { if (_queues.Count > 0) { var queueEnum = _queues.GetEnumerator(); var queue = queueEnum.Current; SqsSnsConfiguration config = GetConnection(queue); MethodInfo method = GetMethod(queue); string queueName = queue.Value.QueueName; int takeQuantity = queue.Value.TakeQuantity; AmazonSQSClient sqsClient = new AmazonSQSClient(config.AwsAccessKeyId, config.AwsSecretAccessKey); sqsClient.ListQueuesAsync("healthQueue"); } if (_topics.Count > 0) { var topicEnum = _topics.GetEnumerator(); var topic = topicEnum.Current; SqsSnsConfiguration config = GetConnection(topic); MethodInfo method = GetMethod(topic); string topicName = topic.Value.TopicName; string subscriptName = topic.Value.Subscription; AmazonSimpleNotificationServiceClient snsClient = new AmazonSimpleNotificationServiceClient(config.AwsAccessKeyId, config.AwsSecretAccessKey); snsClient.ListTopicsAsync("healthTopic"); } return(LightHealth.HealthCheck.Healthy); } catch { return(LightHealth.HealthCheck.Unhealthy); } }
public async Task <IActionResult> Subscribe(RegisterViewModel registerViewModel) { var emailAddress = registerViewModel.Email; var sns = new AmazonSimpleNotificationServiceClient(); if (!string.IsNullOrEmpty(emailAddress)) { var listTopicsRequest = new ListTopicsRequest(); ListTopicsResponse listTopicsResponse; listTopicsResponse = await sns.ListTopicsAsync(listTopicsRequest); var selectedTopic = listTopicsResponse.Topics.FirstOrDefault(); await sns.SubscribeAsync(new SubscribeRequest { TopicArn = selectedTopic.TopicArn, Protocol = "email", Endpoint = emailAddress }); } return(View("Index")); }
/// <summary> /// A simple function that takes a string and does a ToUpper /// </summary> /// <param name="evnt"></param> /// <param name="context"></param> /// <returns></returns> public async Task <string> FunctionHandler(DynamoDBEvent dynamoEvent, ILambdaContext context) { var client = new AmazonSimpleNotificationServiceClient(); context.Logger.LogLine($"Event Received by Lambda Function from {dynamoEvent}"); context.Logger.LogLine($"Beginning to process {dynamoEvent.Records.Count} records..."); foreach (var record in dynamoEvent.Records) { var dbRecord = record.Dynamodb.NewImage; if (dbRecord != null) { var itemStore = dbRecord["Store"].S; var itemName = dbRecord["Item"].S; var itemStock = Convert.ToInt32(dbRecord["Count"].N); var message = itemStore + " is out of stock of " + itemName; context.Logger.LogLine($"Records {itemStore} - {itemName} - {itemStock.ToString()}"); if (itemStock == 0) { var allTopics = await client.ListTopicsAsync(); var NoStockTopic = allTopics.Topics.FirstOrDefault(x => x.TopicArn.Contains("NoStock")).TopicArn; var request = new PublishRequest { TopicArn = NoStockTopic, Message = message, Subject = "Inventory Alert!" }; client.PublishAsync(request).Wait(); } } } return("OK"); }
private void WaitTillReady() { for (var i = 0; i < 20; i++) { try { Log.Logger.Information("Waiting for SNS SQS..."); var cancellationToken = new CancellationTokenSource(2000).Token; var snsResponse = _snsClient.ListTopicsAsync(cancellationToken).Result; var sqsResponse = _sqsClient.ListQueuesAsync("", cancellationToken).Result; if (snsResponse.HttpStatusCode == HttpStatusCode.OK && sqsResponse.HttpStatusCode == HttpStatusCode.OK) { return; } } catch (Exception ex) { Log.Logger.Information($"Failed to connect, attempt - {i} - {ex.Message}"); } } throw new Exception("SNS/SQS initialization failed"); }
public void DeleteAllTopics() { AmazonSimpleNotificationServiceClient clientSNS = AwsFactory.CreateClient <AmazonSimpleNotificationServiceClient>(); AmazonSQSClient clientSQS = AwsFactory.CreateClient <AmazonSQSClient>(); AmazonLambdaClient lambdaClient = AwsFactory.CreateClient <AmazonLambdaClient>(); var topics = clientSNS.ListTopicsAsync(); // var subs = clientSNS.ListSubscriptionsAsync(new ListSubscriptionsRequest()); var filas = clientSQS.ListQueuesAsync("subs"); filas.Result.QueueUrls.ForEach(i => { var deleted = clientSQS.DeleteQueueAsync(i); if (deleted.Result.HttpStatusCode != HttpStatusCode.OK) { int x = 0; } }); string nextToken = ""; do { var subs = clientSNS.ListSubscriptionsAsync(new ListSubscriptionsRequest(nextToken)); subs.Result.Subscriptions.ForEach(i => { var deleted = clientSNS.UnsubscribeAsync(i.SubscriptionArn); }); nextToken = subs.Result.NextToken; } while (!String.IsNullOrEmpty(nextToken)); var mapper = lambdaClient.ListEventSourceMappingsAsync(new Amazon.Lambda.Model.ListEventSourceMappingsRequest { FunctionName = "WebhookDispatcher" }); mapper.Result.EventSourceMappings.ToList().ForEach(i => { var result = lambdaClient.DeleteEventSourceMappingAsync(new Amazon.Lambda.Model.DeleteEventSourceMappingRequest() { UUID = i.UUID }); if (result.Result.HttpStatusCode != HttpStatusCode.OK) { int x = 0; } }); topics.Result.Topics.ForEach(i => { var deleted = clientSNS.DeleteTopicAsync(new DeleteTopicRequest() { TopicArn = i.TopicArn }); }); }
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); }
public async Task <IEnumerable <string> > ListTopicArns() { var response = await _sns.ListTopicsAsync(new ListTopicsRequest()); return(response.Topics.Select(x => x.TopicArn).ToList()); }
private void EnsureQueue(Connection connection) { using (var sqsClient = new AmazonSQSClient(_awsConnection.Credentials, _awsConnection.Region)) { //Does the queue exist - this is an HTTP call, we should cache the results for a period of time (bool exists, string name)queueExists = QueueExists(sqsClient, connection.ChannelName.ToValidSQSQueueName()); if (!queueExists.exists) { try { var request = new CreateQueueRequest(connection.ChannelName.ToValidSQSQueueName()) { Attributes = { { "VisibilityTimeout", connection.VisibilityTimeout.ToString() }, { "ReceiveMessageWaitTimeSeconds", ToSecondsAsString(connection.TimeoutInMiliseconds) } } }; var response = sqsClient.CreateQueueAsync(request).Result; var queueUrl = response.QueueUrl; if (!string.IsNullOrEmpty(queueUrl)) { //topic might not exist using (var snsClient = new AmazonSimpleNotificationServiceClient(_awsConnection.Credentials, _awsConnection.Region)) { var exists = snsClient.ListTopicsAsync().Result.Topics.SingleOrDefault(topic => topic.TopicArn == connection.RoutingKey); if (exists == null) { var createTopic = snsClient.CreateTopicAsync(new CreateTopicRequest(connection.RoutingKey.ToValidSNSTopicName())).Result; if (!string.IsNullOrEmpty(createTopic.TopicArn)) { var subscription = snsClient.SubscribeQueueAsync(createTopic.TopicArn, sqsClient, queueUrl).Result; //We need to support raw messages to allow the use of message attributes snsClient.SetSubscriptionAttributesAsync(new SetSubscriptionAttributesRequest(subscription, "RawMessageDelivery", "true")); } } } } } catch (AggregateException ae) { //TODO: We need some retry semantics here //TODO: We need to flatten the ae and handle some of these with ae.Handle((x) => {}) ae.Handle(ex => { if (ex is QueueDeletedRecentlyException) { //QueueDeletedRecentlyException - wait 30 seconds then retry //Although timeout is 60s, we could be partway through that, so apply Copernican Principle //and assume we are halfway through var error = $"Could not create queue {connection.ChannelName.ToValidSQSQueueName()} because {ae.Message} waiting 60s to retry"; _logger.Value.Error(error); Task.Delay(TimeSpan.FromSeconds(30)); throw new ChannelFailureException(error, ae); } return(false); }); } } } }