private async void registrarPush(NSData token) { var access_key = "AKIAJLTJVDVD3ECKFSBQ"; var secret_key = "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"; var snsClient = new AmazonSimpleNotificationServiceClient(access_key, secret_key, RegionEndpoint.USWest2); var deviceToken = token.Description.Replace("<", "").Replace(">", "").Replace(" ", ""); Console.WriteLine("token=" + deviceToken + "__"); if (!string.IsNullOrEmpty(deviceToken)) { //register with SNS to create an endpoint ARN Console.WriteLine("token=" + deviceToken); var response = await snsClient.CreatePlatformEndpointAsync( new CreatePlatformEndpointRequest { CustomUserData = "*****@*****.**", Token = deviceToken, PlatformApplicationArn = "arn:aws:sns:us-west-2:490523474570:app/APNS_SANDBOX/idd_ios_dev" /* insert your platform application ARN here */ }); Console.WriteLine("arn_endoint ios" + response.EndpointArn + "__"); } }
public void SetEndpointAttribute(string endpointarn, string key, string value) { try { var endpoint = GetEndpoint(string.Empty, endpointarn); if (string.IsNullOrEmpty(endpoint)) { throw new ArgumentNullException("endpointarn"); } Dictionary <string, string> attributes = (Dictionary <string, string>)GetEndpointAttributes(endpointarn); attributes[key] = value; using (var snsclient = new AmazonSimpleNotificationServiceClient(_accesskey, _secretkey)) { var result = snsclient.SetEndpointAttributes(new SetEndpointAttributesRequest() { EndpointArn = endpointarn, Attributes = attributes }); } } catch (Exception ex) { throw new Exception("SetEndpointAttribute " + ex.Message); } }
/// <summary> /// Ensures the topic. The call to create topic is idempotent and just returns the arn if it already exists. Therefore there is /// no nee to check then create if it does not exist, as this would be extral calls /// </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) { _logger.DebugFormat("Topic with name {0} does not exist. Creating new topic", topicName); var topicResult = client.CreateTopicAsync(new CreateTopicRequest(topicName)).Result; return(topicResult.HttpStatusCode == HttpStatusCode.OK ? topicResult.TopicArn : string.Empty); }
public async Task <string> SubEmail(string email) { var client = new AmazonSimpleNotificationServiceClient(); var subArn = await SubscribeEmail(client, email); return(subArn); }
public SnsDispatcher(IOptions <SNSOptions <T> > options, ISerializer serializer, ILogger <SnsDispatcher <T> > logger) : base(logger) { _serializer = serializer ?? throw new ArgumentNullException(nameof(serializer)); var config = options?.Value ?? throw new ArgumentNullException(nameof(options)); var snsConfig = new AmazonSimpleNotificationServiceConfig { ServiceURL = config.ServiceURL }; if (!string.IsNullOrEmpty(config.RegionEndpoint)) { snsConfig.RegionEndpoint = RegionEndpoint.GetBySystemName(config.RegionEndpoint); } config.AwsDispatcherConfiguration?.Invoke(snsConfig); _client = new AmazonSimpleNotificationServiceClient(snsConfig); _contentType = new MessageAttributeValue { DataType = AttributeType, StringValue = _serializer.ContentType }; _valueTypeName = new MessageAttributeValue { DataType = AttributeType, StringValue = typeof(T).AssemblyQualifiedName }; _topicArn = config.TopicArn ?? throw new Exception("No topic arn set for type: " + (TypeCache <T> .FriendlyName ?? string.Empty)); }
public override void Invoke(AWSCredentials creds, RegionEndpoint region, int maxItems) { AmazonSimpleNotificationServiceConfig config = new AmazonSimpleNotificationServiceConfig(); config.RegionEndpoint = region; ConfigureClient(config); AmazonSimpleNotificationServiceClient client = new AmazonSimpleNotificationServiceClient(creds, config); ListEndpointsByPlatformApplicationResponse resp = new ListEndpointsByPlatformApplicationResponse(); do { ListEndpointsByPlatformApplicationRequest req = new ListEndpointsByPlatformApplicationRequest { NextToken = resp.NextToken }; resp = client.ListEndpointsByPlatformApplication(req); CheckError(resp.HttpStatusCode, "200"); foreach (var obj in resp.Endpoints) { AddObject(obj); } }while (!string.IsNullOrEmpty(resp.NextToken)); }
public void DeleteTopic() { if (_subscription == null) { return; } using (var snsClient = new AmazonSimpleNotificationServiceClient(_awsConnection.Credentials, _awsConnection.Region)) { (bool exists, string topicArn) = new ValidateTopicByArn(snsClient).Validate(_channelTopicArn); if (exists) { try { UnsubscribeFromTopic(snsClient); DeleteTopic(snsClient); } catch (Exception) { //don't break on an exception here, if we can't delete, just exit s_logger.LogError("Could not delete topic {TopicResourceName}", _channelTopicArn); } } } }
/// <summary> /// Push a notification to the topic /// </summary> /// <param name="message"> The message to publish </param> /// <returns> The publish response </returns> public static PublishResponse PushNotification(string message) { var client = new AmazonSimpleNotificationServiceClient(); var res = client.PublishAsync(TopicArn, message).Result; return(res); }
public void SNSSubscriptionPost() { var snsClient = new AmazonSimpleNotificationServiceClient(Amazon.RegionEndpoint.USEast2); string nombreTopic = "nuevo Tema"; var nuevoTopic = new CreateTopicRequest { Name = nombreTopic, Attributes = new Dictionary <string, string> () { { accessKey, accessSecret } } }; // var a = snsClient.CreateTopicAsync // String topicArn = "arn:aws:sns:us-west-2:433048134094:mytopic"; // Console.WriteLine("va bien"); // String msg = "If you receive this message, publishing a message to an Amazon SNS topic works."; // PublishRequest publishRequest = new PublishRequest(topicArn, msg); // Console.WriteLine("va bien 2"); // var publishResponse = await snsClient.PublishAsync(publishRequest); // Console.WriteLine("va bien 3"); // // Print the MessageId of the published message. // Console.WriteLine ("MessageId: " + publishResponse.MessageId); // await snsClient.PublishAsync(publishRequest); }
static void Main(string[] args) { // US phone numbers must be in the correct format: // +1 (nnn) nnn-nnnn OR +1nnnnnnnnnn string number = args[0]; string message = "Hello at " + DateTime.Now.ToShortTimeString(); var client = new AmazonSimpleNotificationServiceClient(region: Amazon.RegionEndpoint.USWest2); var request = new PublishRequest { Message = message, PhoneNumber = number }; try { var response = client.Publish(request); Console.WriteLine("Message sent to " + number + ":"); Console.WriteLine(message); } catch (Exception ex) { Console.WriteLine("Caught exception publishing request:"); Console.WriteLine(ex.Message); } }
public AmznSnsWrapper() { try { IsSandboxMode = bool.Parse(ConfigurationSettings.AppSettings.Get("AmazonSNS_UseSandbox")); } catch (Exception e) { IsSandboxMode = false; } try { client = new AmazonSimpleNotificationServiceClient(); platformArnAPNS_Basketball = ConfigurationSettings.AppSettings.Get("PlatformArnAPNS_Basketball"); platformArnAPNS_Volleyball = ConfigurationSettings.AppSettings.Get("PlatformArnAPNS_Volleyball"); platformArnAPNS_Netball = ConfigurationSettings.AppSettings.Get("PlatformArnAPNS_Netball"); platformArnAPNS_Waterpolo = ConfigurationSettings.AppSettings.Get("PlatformArnAPNS_Waterpolo"); platformArnAPNS_SANDBOX_Basketball = ConfigurationSettings.AppSettings.Get("PlatformArnAPNS_SANDBOX_Basketball"); platformArnAPNS_SANDBOX_Volleyball = ConfigurationSettings.AppSettings.Get("PlatformArnAPNS_SANDBOX_Volleyball"); platformArnAPNS_SANDBOX_Netball = ConfigurationSettings.AppSettings.Get("PlatformArnAPNS_SANDBOX_Netball"); platformArnAPNS_SANDBOX_Waterpolo = ConfigurationSettings.AppSettings.Get("PlatformArnAPNS_SANDBOX_Waterpolo"); platformArnGCM = ConfigurationSettings.AppSettings.Get("PlatformArnGCM"); platformArnGCM_TEST = ConfigurationSettings.AppSettings.Get("PlatformArnGCM_TEST"); } catch (Exception e) { log.ErrorFormat("Failed to create AmazonSimpleNotificationServiceClient Instance. Exception Details: {0}", e); } }
static async Task Main(string[] args) { var config = new ConfigurationBuilder() .AddUserSecrets <AmazonSnsSettings>() .Build(); var settings = config.GetSection("AmazonSNS").Get <AmazonSnsSettings>(); Console.WriteLine($"TopicArn : '{settings.TopicArn}'."); string message = $"This test message was sent at {DateTime.Now}."; Console.WriteLine($"Message : '{message}'."); var client = new AmazonSimpleNotificationServiceClient(region: RegionEndpoint.USWest1); Console.WriteLine(); try { var response = await client.PublishAsync(new PublishRequest { Message = message, TopicArn = settings.TopicArn }); Console.WriteLine($"Message has been sent to topic."); } catch (Exception ex) { Console.WriteLine(ex); } }
public static void sendMessage(User user, MessageTypeEnum type) { if (user.first_name == "control") { return; } AmazonSimpleNotificationServiceClient snsClient = new AmazonSimpleNotificationServiceClient(AWSConstants.SNS_ACCESS_KEY, AWSConstants.SNS_SECRET_ACCESS_KEY, Amazon.RegionEndpoint.USEast1); PublishRequest pubRequest = new PublishRequest(); // get the message that corresponds to the type of notification pubRequest.Message = MessageTypeExtension.GetDescription(type); // sending sms message if (user._Notification_Type == NotificationTypeEnum.SMS || user._Notification_Type == NotificationTypeEnum.ALL) { // we need to have +1 on the beginning of the number in order to send if (user.phone_number.Substring(0, 2) != "+1") { pubRequest.PhoneNumber = "+1" + user.phone_number; } else { pubRequest.PhoneNumber = user.phone_number; } PublishResponse pubResponse = snsClient.Publish(pubRequest); Console.WriteLine(pubResponse.MessageId); } }
public override async Task <Response> HandlerFunction(Request request, ILambdaContext context) { string topicArn = System.Environment.GetEnvironmentVariable("TOPIC_ARN"); Console.WriteLine("topicArn = "); Console.WriteLine(topicArn); string message = "Hello at " + DateTime.Now.ToShortTimeString(); var client = new AmazonSimpleNotificationServiceClient(region: Amazon.RegionEndpoint.USEast1); var snsRequest = new PublishRequest { Message = message, TopicArn = topicArn }; try { var response = await client.PublishAsync(snsRequest); Console.WriteLine("Message sent to topic:"); Console.WriteLine(message); } catch (Exception ex) { Console.WriteLine("Caught exception publishing request:"); Console.WriteLine(ex.Message); } return(new Response("SNS Message sent", request)); }
public void Cleanup() { CognitoIdentity.CleanupIdentityPools(); CleanupCreatedRoles(); if (facebookUser != null) { FacebookUtilities.DeleteFacebookUser(facebookUser); } using (var sns = new AmazonSimpleNotificationServiceClient()) { foreach (var topicArn in topicArns) { sns.DeleteTopic(topicArn); } topicArns.Clear(); if (platformApplicationArn != null) { sns.DeletePlatformApplication(new DeletePlatformApplicationRequest { PlatformApplicationArn = platformApplicationArn }); } } }
public APIGatewayProxyResponse FunctionHandler(APIGatewayProxyRequest input, ILambdaContext context) { context.Logger.LogLine(">FunctionHandler\n"); var config = new AmazonSimpleNotificationServiceConfig(); config.ServiceURL = Environment.ExpandEnvironmentVariables("%SNSENDPOINT%"); var client = new AmazonSimpleNotificationServiceClient(config); context.Logger.LogLine("AmazonSNSClient created\n"); var request = new PublishRequest { TopicArn = Environment.ExpandEnvironmentVariables("%TOPICARN%"), Message = input.Body, }; client.PublishAsync(request).Wait(); context.Logger.LogLine("PublishAsync completed\n"); var response = new APIGatewayProxyResponse { StatusCode = (int)HttpStatusCode.OK, Body = input.Body, Headers = new Dictionary <string, string> { { "Content-Type", "text/plain" } }, }; context.Logger.LogLine("<FunctionHandler\n"); return(response); }
// TODO: move this method to service private async Task RaiseAdvertConfirmedMessageAsync(ConfirmAdvertDto confirmModel) { var topicArn = _configuration.GetValue <string>("TopicArn"); // To get the title we fetch the advert from db, // or in another way you can pass Title with ConfirmAdvertDto var advert = await _advertStorageService.GetByIdAsync(confirmModel.Id); if (advert == null) { throw new KeyNotFoundException($"Record with Id: {confirmModel.Id} was not found."); } using (var snsClient = new AmazonSimpleNotificationServiceClient()) { var message = new AdvertConfirmedMessage { Id = confirmModel.Id, Title = advert.Title }; var messageJson = JsonConvert.SerializeObject(message); await snsClient.PublishAsync(topicArn, messageJson); } }
public async Task SendMessage(string message) { AmazonSimpleNotificationServiceClient snsClient = new AmazonSimpleNotificationServiceClient(_settings.Key, _settings.SecretKey, Amazon.RegionEndpoint.EUWest1); PublishRequest pubRequest = new PublishRequest { Message = message, PhoneNumber = _settings.Phone }; pubRequest.MessageAttributes["AWS.SNS.SMS.SenderID"] = new MessageAttributeValue { StringValue = "NOTICE", DataType = "String" }; pubRequest.MessageAttributes["AWS.SNS.SMS.MaxPrice"] = new MessageAttributeValue { StringValue = "0.10", DataType = "Number" }; pubRequest.MessageAttributes["AWS.SNS.SMS.SMSType"] = new MessageAttributeValue { StringValue = "Promotional", DataType = "String" }; try { PublishResponse pubResponse = await snsClient.PublishAsync(pubRequest); Console.WriteLine("Successfully sent message " + pubResponse.MessageId); } catch (Exception e) { Console.WriteLine("Caught error in Messenger.cs"); Console.WriteLine(e); } }
public Topic CheckSnsTopic(string topicName) { using (var client = new AmazonSimpleNotificationServiceClient(_credentials)) { return(client.ListTopicsAsync().Result.Topics.SingleOrDefault(topic => topic.TopicArn == topicName)); } }
public BulkEventLambdaFunctionalTests() { _fakeS3Event = new S3Event() { Records = new List <S3EventNotification.S3EventNotificationRecord> { new S3EventNotification.S3EventNotificationRecord { S3 = new S3EventNotification.S3Entity { Bucket = new S3EventNotification.S3BucketEntity { Name = "fakeBucket" }, Object = new S3EventNotification.S3ObjectEntity { Key = "fakeKey" } } } } }; _fakeSns = A.Fake <AmazonSimpleNotificationServiceClient>(); _fakeS3 = A.Fake <AmazonS3Client>(); _s3GetObjectRequest = new GetObjectRequest() { BucketName = "fakeBucket", Key = "fakeKey" }; _snsTopic = "test-topic"; }
public bool Send() { bool status = true; try { AmazonSimpleNotificationServiceClient smsClient = new AmazonSimpleNotificationServiceClient(security.AccessKeyId, security.SecretKeyId, security.Region); PublishRequest request = new PublishRequest(); PublishResponse response = new PublishResponse(); Dictionary <string, MessageAttributeValue> attributes = new Dictionary <string, MessageAttributeValue>(); attributes.Add("AWS.SNS.SMS.SenderID", new MessageAttributeValue() { DataType = "String", StringValue = settings.SenderId }); attributes.Add("AWS.SNS.SMS.SMSType", new MessageAttributeValue() { DataType = "String", StringValue = settings.SMSType }); attributes.Add("AWS.SNS.SMS.MaxPrice", new MessageAttributeValue() { DataType = "String", StringValue = settings.MaxPrice.ToString() }); request.MessageAttributes = attributes; request.PhoneNumber = message.MobileNo; request.Message = message.Message; response = smsClient.Publish(request); } catch (Exception ex) { status = false; } return(status); }
/// <summary> /// Notification configuration window load event /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void NcWindow_Loaded(object sender, RoutedEventArgs e) { try { AmazonAutoScalingConfig config = new AmazonAutoScalingConfig(); config.ServiceURL = ((ViewModel)this.DataContext).Region.Url; AmazonAutoScalingClient client = new AmazonAutoScalingClient(config); DescribeAutoScalingNotificationTypesRequest dasntreq = new DescribeAutoScalingNotificationTypesRequest(); DescribeAutoScalingNotificationTypesResponse dasntresp = client.DescribeAutoScalingNotificationTypes(dasntreq); foreach (string asnt in dasntresp.DescribeAutoScalingNotificationTypesResult.AutoScalingNotificationTypes) { this.notificationTypes.Add(asnt); } AmazonSimpleNotificationServiceConfig snsconfig = new AmazonSimpleNotificationServiceConfig(); config.ServiceURL = ((ViewModel)this.DataContext).Region.Url; AmazonSimpleNotificationServiceClient snsclient = new AmazonSimpleNotificationServiceClient(snsconfig); ListTopicsRequest ltrequest = new ListTopicsRequest(); ListTopicsResponse ltresp = snsclient.ListTopics(ltrequest); foreach (Topic topic in ltresp.ListTopicsResult.Topics) { this.snstopics.Add(topic.TopicArn); } rlbNcTypes.ItemsSource = this.notificationTypes; cboTopics.ItemsSource = this.snstopics; } catch { MessageBox.Show(Window.GetWindow(this), "Error occured while loading the notification configuration options.", "Error", MessageBoxButton.OK); this.Close(); } }
// Notify through sms (or email) private static void snsPublish(string contact, string message) { AmazonSimpleNotificationServiceClient client = new AmazonSimpleNotificationServiceClient(RegionEndpoint.USEast1); string arn = "arn:aws:sns:xxxxxxxx:TrafficTicket"; // subscribe user to the ticketing policy SubscribeRequest request = new SubscribeRequest(arn, "sms", contact); // ("sms" can be replaced by "email) var task = client.SubscribeAsync(request, new System.Threading.CancellationToken()); task.Wait(); // Publish the message PublishRequest p = new PublishRequest ( message: message, topicArn: arn ); var task2 = client.PublishAsync(p, new System.Threading.CancellationToken()); task2.Wait(); PublishResponse r = task2.Result; Console.WriteLine("PublishRequest: " + r.ResponseMetadata.RequestId); Console.WriteLine("Message sent succesfully."); }
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 Subscriber(AmazonSQSClient sqsClient, AmazonSimpleNotificationServiceClient snsClient, string topicName, string queueName) { _sqsClient = sqsClient; _snsClient = snsClient; _topicName = topicName; _queueName = queueName; }
public TopicClient(string topicName, string subscriptionName) { _snsClient = new AmazonSimpleNotificationServiceClient(AccessKey, SecretKey, RegionEndpoint.USEast1); TopicName = topicName; SubscriptionName = subscriptionName; Ensure(); }
private async Task <Application> CreateTopics(Application app) { string queueName = $"queue-{app.Name.Replace(" ", "")}-{app.Id}-subs"; AmazonSimpleNotificationServiceClient clientSNS = AwsFactory.CreateClient <AmazonSimpleNotificationServiceClient>(); //create topics and subscribe them await app.Events.ToList().ForEachAsync(e => { string topic_name = $"topic-{app.Name.Replace(" ", "")}-event-{e.EventName}"; CreateTopicResponse topicResponse = clientSNS.CreateTopicAsync(new CreateTopicRequest(topic_name)).Result; if (topicResponse.HttpStatusCode != System.Net.HttpStatusCode.OK) { throw new Exception($"Error creating topic {topic_name}"); } e.TopicArn = topicResponse.TopicArn; }); return(app); }
private string FindTopicArn(AWSCredentials credentials, RegionEndpoint region, string topicName) { var snsClient = new AmazonSimpleNotificationServiceClient(credentials, region); var topicResponse = snsClient.FindTopicAsync(topicName).GetAwaiter().GetResult(); return(topicResponse.TopicArn); }
private static void DeleteTopic(Topic topic) { var settings = SettingsManager.GetSettings(); var snsClient = new AmazonSimpleNotificationServiceClient( settings.AWSAccessKeyID, settings.AWSSecretAccessKey, RegionEndpoint.GetBySystemName(settings.AWSS3Region.SystemName)); var sqsClient = new AmazonSQSClient( settings.AWSAccessKeyID, settings.AWSSecretAccessKey, RegionEndpoint.GetBySystemName(settings.AWSS3Region.SystemName)); // Cleanup topic & queue & local file try { snsClient.DeleteTopic(new DeleteTopicRequest() { TopicArn = topic.TopicARN }); } catch (Exception ex) { Debug.WriteLine(ex.Message); } try { sqsClient.DeleteQueue(new DeleteQueueRequest() { QueueUrl = topic.QueueUrl }); } catch (Exception ex) { Debug.WriteLine(ex.Message); } // TODO Delete the errored/complete files on startup? File.Delete(Path.Combine(GetTempDirectory(), topic.TopicFileName)); Debug.WriteLine($"Deleted topic {topic.TopicARN}"); Debug.WriteLine($"Deleted topic file {topic.TopicFileName}"); }
public async Task FunctionHandler(IotButtonPayload @event, ILambdaContext context) { context.Logger.LogLine($"Received event: {JsonConvert.SerializeObject(@event)}"); var publishRequest = new PublishRequest { TopicArn = TOPIC_ARN, Subject = "Greetings from IoT Button", Message = $"Pressed: {@event.ClickType}", }; string topicArn = Environment.GetEnvironmentVariable("TopicArn"); context.Logger.LogLine($"TopicArn: {topicArn.Substring(0, 30)}..."); string accessKey = Environment.GetEnvironmentVariable("AccessKey"); context.Logger.LogLine($"AccessKey: {accessKey.Substring(0, 5)}..."); string secretKey = Environment.GetEnvironmentVariable("SecretKey"); context.Logger.LogLine($"SecretKey: {secretKey.Substring(0, 5)}..."); var client = new AmazonSimpleNotificationServiceClient(accessKey, secretKey, RegionEndpoint.EUWest1); await client.PublishAsync(publishRequest).ConfigureAwait(false); context.Logger.LogLine("Event published successfully"); }