public AWSClass() { if (clients3 == null) clients3 = new AmazonS3Client(Amazon.RegionEndpoint.USWest2); if(clientsns == null) clientsns = new AmazonSimpleNotificationServiceClient(); }
private void CreatePlatformApplication() { using (var sns = new Amazon.SimpleNotificationService.AmazonSimpleNotificationServiceClient()) { // Create target topic var topicArn = sns.CreateTopic(new CreateTopicRequest { Name = "TestTopic" + new Random().Next() }).TopicArn; topicArns.Add(topicArn); var platformAppName = "NetSDKTestApp" + new Random().Next(); // Create a platform application for GCM. platformApplicationArn = sns.CreatePlatformApplication(new CreatePlatformApplicationRequest { Name = platformAppName, Platform = "GCM", Attributes = new Dictionary <string, string> { { "PlatformCredential", PlatformCredential }, { "PlatformPrincipal", "NA" }, { "EventEndpointCreated", topicArn }, { "EventEndpointDeleted", topicArn }, { "EventEndpointUpdated", topicArn }, { "EventDeliveryAttemptFailure", topicArn }, { "EventDeliveryFailure", topicArn }, } }).PlatformApplicationArn; } }
public static void PublishMessage(string topicArn, string message, string subject = null) { using (var client = new AmazonSimpleNotificationServiceClient(Settings.AccessKey, Settings.Secret)) { client.Publish(topicArn, message, subject); } }
/// <summary> /// returns nothing on error /// </summary> public string PublishRawMessage(string topicArn, string rawMessage) { try { using (var client = new AmazonSimpleNotificationServiceClient(this.AwsCredentials, this.AwsRegion)) { var pr = new PublishRequest(); pr.TopicArn = topicArn; pr.Message = rawMessage; var t = client.PublishAsync(pr); t.Wait(); if (t.IsCompleted && t.Result is object) { Trace.TraceInformation($"Outgoing SNS-Message for Topic '{topicArn}' Msg-ID: {t.Result.MessageId}"); return(t.Result.MessageId); } else { Trace.TraceError($"Publish SNS-Message for Topic '{topicArn}' FAILED: AWS responded non-success"); return(null); } } } catch (Exception ex) { Trace.TraceError($"Publish SNS-Message for Topic '{topicArn}' EXCEPTION: {ex.Message}"); return(null); } }
public Topic CheckSnsTopic(string topicName) { using (var client = new AmazonSimpleNotificationServiceClient(_credentials)) { return client.ListTopicsAsync().Result.Topics.SingleOrDefault(topic => topic.TopicArn == topicName); } }
protected virtual void Dispose(bool disposing) { if (!disposing) return; if (_client == null) return; _client.Dispose(); _client = null; }
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 Topic CheckSnsTopic(string topicName) { using (var client = new AmazonSimpleNotificationServiceClient()) { return client.FindTopic(topicName); } }
public void DeleteTopic(string topicName) { using (var client = new AmazonSimpleNotificationServiceClient()) { var topic = client.FindTopic(topicName); client.DeleteTopic(topic.TopicArn); } }
public static IEnumerable<string> ListTopicArns() { using (var client = new AmazonSimpleNotificationServiceClient(Settings.AccessKey, Settings.Secret)) { var response = client.ListTopics(new ListTopicsRequest()); return response.Topics.Select(x => x.TopicArn).ToList(); } }
public static IEnumerable<Subscription> ListSubscriptions(string topicArn) { using (var client = new AmazonSimpleNotificationServiceClient(Settings.AccessKey, Settings.Secret)) { var request = new ListSubscriptionsByTopicRequest(topicArn); return client.ListSubscriptionsByTopic(request).Subscriptions; } }
public static void CreateEmailSubscription(string topicArn, string emailAddress) { using (var client = new AmazonSimpleNotificationServiceClient(Settings.AccessKey, Settings.Secret)) { var request = new SubscribeRequest(topicArn, "email", emailAddress); client.Subscribe(request); } }
public static string CreateTopic(string topicName) { using (var client = new AmazonSimpleNotificationServiceClient(Settings.AccessKey, Settings.Secret)) { var request = new CreateTopicRequest(topicName); return client.CreateTopic(request).TopicArn; } }
private string EnsureTopic(string topicName, AmazonSimpleNotificationServiceClient client) { var topic = client.FindTopic(topicName); if (topic != null) return topic.TopicArn; _logger.DebugFormat("Topic with name {0} does not exist. Creating new topic", topicName); var topicResult = client.CreateTopic(topicName); return topicResult.HttpStatusCode == HttpStatusCode.OK ? topicResult.TopicArn : string.Empty; }
public static string createSNSTopic(string _topicname) { if (clientsns == null) clientsns = new AmazonSimpleNotificationServiceClient(); var topicArn = clientsns.CreateTopic(new CreateTopicRequest { Name = _topicname }).TopicArn; return topicArn.ToString(); }
/// <summary> /// Sends the specified message. /// </summary> /// <param name="message">The message.</param> public void Send(Message message) { var messageString = JsonConvert.SerializeObject(message); _logger.Value.DebugFormat("SQSMessageProducer: Publishing message with topic {0} and id {1} and message: {2}", message.Header.Topic, message.Id, messageString); using (var client = new AmazonSimpleNotificationServiceClient(_credentials)) { var topicArn = EnsureTopic(message.Header.Topic, client); var publishRequest = new PublishRequest(topicArn, messageString); client.PublishAsync(publishRequest).Wait(); } }
public static void publishToTopic(string _topicarn, string _subject, string _message) { if (clientsns == null) clientsns = new AmazonSimpleNotificationServiceClient(); clientsns.Publish(new PublishRequest { Subject = _subject, Message = _message, TopicArn = _topicarn }); }
private void UnSubscribe(string subscriptionArn) { using (var client = new AmazonSimpleNotificationServiceClient(this.AwsCredentials, this.AwsRegion)) { Task <UnsubscribeResponse> t; t = client.UnsubscribeAsync(subscriptionArn); t.Wait(); if (t.IsCompleted) { this.ReloadExistingSubscriptions(); } } }
public virtual void CreateSubscription(AmazonSimpleNotificationServiceClient snsClient, string queueArn, string topicArn) { // Create the request var subscriptionRequest = new SubscribeRequest { Endpoint = queueArn, Protocol = "sqs", TopicArn = topicArn }; // Create the subscription snsClient.Subscribe(subscriptionRequest); }
public void Confirm(string topicArn, string token) { using (var client = new AmazonSimpleNotificationServiceClient(this.AwsCredentials, this.AwsRegion)) { var cr = new ConfirmSubscriptionRequest(); cr.TopicArn = topicArn; cr.Token = token; var t = client.ConfirmSubscriptionAsync(cr); t.Wait(); if (t.IsCompleted && t.Result is object) { this.ReloadExistingSubscriptions(); } } }
public void SetTopicConfigurationTests() { var s3Config = new AmazonS3Config(); using (var s3Client = new AmazonS3Client(s3Config)) using (var snsClient = new AmazonSimpleNotificationServiceClient()) { var snsCreateResponse = snsClient.CreateTopic("events-test-" + DateTime.Now.Ticks); var bucketName = S3TestUtils.CreateBucket(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 = s3Client.GetBucketNotification(bucketName); 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); } } }
public virtual string CreateTopic(AmazonSimpleNotificationServiceClient snsClient, string topicName) { string topicArn; // Create the request var createTopicRequest = new CreateTopicRequest { Name = topicName }; // Submit the request CreateTopicResponse topicResponse = snsClient.CreateTopic(createTopicRequest); // Return the ARN topicArn = topicResponse.TopicArn; return topicArn; }
public void DeleteEndpoint(string endpointarn) { try { using (var snsclient = new AmazonSimpleNotificationServiceClient(_accesskey, _secretkey)) { snsclient.DeleteEndpoint(new DeleteEndpointRequest() { EndpointArn = endpointarn }); } } catch (Exception ex) { throw new Exception("DeleteEndpoint " + ex.Message); } }
public string CreateEndpoint(string registrationid, string description, string aplicationarn) { try { var endpoint1 = GetEndpoint(registrationid, String.Empty); if (endpoint1 != null) throw new ArgumentException("registrationid"); var endpoint2 = GetEndpoints(description); if (endpoint2 != null) { if (endpoint2.Count == 1) return endpoint2.FirstOrDefault(); if (endpoint2.Count > 1) throw new ArgumentException("description"); } var app = GetApplication(aplicationarn, string.Empty); if (string.IsNullOrEmpty(app)) throw new ArgumentException("aplicationtoken"); using (var snsclient = new AmazonSimpleNotificationServiceClient(_accesskey, _secretkey)) { var request = new CreatePlatformEndpointRequest() { CustomUserData = description, Token = registrationid, PlatformApplicationArn = aplicationarn }; var result = snsclient.CreatePlatformEndpoint(request); return result?.EndpointArn; } } catch (Exception ex) { throw new Exception("CreateEndpoint " + ex.Message); } }
public void PushSNSNotification(string topicARN, string subject, string message) { AmazonSimpleNotificationServiceClient client = new AmazonSimpleNotificationServiceClient(); try { _logger.Log(LogLevel.Info, String.Format("Pushing Message {0} to Amazon SNS", message)); client.Publish(new PublishRequest() { Message = message, TopicArn = topicARN, Subject = subject }); } catch (Exception ex) { _logger.Log(LogLevel.Fatal, String.Format("Exception Pusing Message {0} to Amazon SNS. {1}", message, ex.Message)); } }
public void publish(FolderVaultMapping mapping, bool publishToEmailTopic) { StringBuilder message = new StringBuilder("{\"Action\":"); message.Append(safeString(Action)); foreach (KeyValuePair<string, string> pair in Properties) { message.Append(','); message.Append(safeString(pair.Key)); message.Append(':'); message.Append(safeString(pair.Value)); } message.Append("}"); using (AmazonSimpleNotificationServiceClient client = new AmazonSimpleNotificationServiceClient(mapping.AccessKey, mapping.SecretKey, mapping.Endpoint)) { PublishRequest req = new PublishRequest(); req.TopicArn = publishToEmailTopic ? mapping.EmailTopicARN : mapping.NotificationTopicARN; req.Message = message.ToString(); MessageId = client.Publish(req).PublishResult.MessageId; } }
public static void SNSListTopics() { #region SNSListTopics var snsClient = new AmazonSimpleNotificationServiceClient(); var request = new ListTopicsRequest(); var response = new ListTopicsResponse(); do { response = snsClient.ListTopics(request); foreach (var topic in response.Topics) { Console.WriteLine("Topic: {0}", topic.TopicArn); var attrs = snsClient.GetTopicAttributes( new GetTopicAttributesRequest { TopicArn = topic.TopicArn }).Attributes; if (attrs.Count > 0) { foreach (var attr in attrs) { Console.WriteLine(" -{0} : {1}", attr.Key, attr.Value); } } Console.WriteLine(); } request.NextToken = response.NextToken; } while (!string.IsNullOrEmpty(response.NextToken)); #endregion Console.ReadLine(); }
public bool SendPersonUpdatedNotification(int personId, string message) { var topicArn = ConfigurationManager.AppSettings["AWSSNSTopicArn"]; var snsClient = new AmazonSimpleNotificationServiceClient(RegionEndpoint.USEast1); try { var publishRequest = new Amazon.SimpleNotificationService.Model.PublishRequest(); publishRequest.TopicArn = topicArn; publishRequest.Message = message; publishRequest.Subject = personId.ToString(); snsClient.Publish(publishRequest); return true; } catch (Exception ex) { // TODO Log exception return false; } }
public void UnSubscribeAll() { bool reloadRequired = false; using (var client = new AmazonSimpleNotificationServiceClient(this.AwsCredentials, this.AwsRegion)) { Task <UnsubscribeResponse> t; foreach (var s in this.Subscriptions) { t = client.UnsubscribeAsync(s.SubscriptionArn); t.Wait(); if (t.IsCompleted) { reloadRequired = true; } } lock ( _LocalPendingSubscriptions) { _LocalPendingSubscriptions.Clear(); } if (reloadRequired) { this.ReloadExistingSubscriptions(); } } }
protected override void InitializeTarget() { base.InitializeTarget(); var size = MaxMessageSize ?? DefaultMaxMessageSize; if (size <= 0 || size >= 256) { ConfiguredMaxMessageSizeInBytes = 256 * 1024; } else if (size <= DefaultMaxMessageSize) { ConfiguredMaxMessageSizeInBytes = DefaultMaxMessageSize * 1024; } else { ConfiguredMaxMessageSizeInBytes = size * 1024; } InternalLogger.Info(string.Format("Max message size is set to {0} KB.", ConfiguredMaxMessageSizeInBytes / 1024)); truncateSizeInBytes = ConfiguredMaxMessageSizeInBytes - TransferEncoding.GetByteCount(TruncateMessage); try { if (string.IsNullOrEmpty(AwsAccessKey) && string.IsNullOrEmpty(AwsSecretKey)) { InternalLogger.Info("AWS Access Keys are not specified. Use Application Setting or EC2 Instance profile for keys."); client = new AmazonSimpleNotificationServiceClient(RegionEndpoint.GetBySystemName(Endpoint)); } else { client = new AmazonSimpleNotificationServiceClient(AwsAccessKey, AwsSecretKey, RegionEndpoint.GetBySystemName(Endpoint)); } } catch (Exception e) { InternalLogger.Fatal("Amazon SNS client failed to be configured. This logger wont'be send any message. Error is\n{0}\n{1}", e.Message, e.StackTrace); } }
public virtual void DeleteSubscriptions(AmazonSimpleNotificationServiceClient snsClient, string topicArn) { var listSubscriptionsByTopicRequest = new ListSubscriptionsByTopicRequest { TopicArn = topicArn }; ListSubscriptionsByTopicResponse listSubscriptionsByTopicResponse = snsClient.ListSubscriptionsByTopic(listSubscriptionsByTopicRequest); foreach ( Subscription subscription in listSubscriptionsByTopicResponse.Subscriptions) { var unsubscribeRequest = new UnsubscribeRequest { SubscriptionArn = subscription.SubscriptionArn }; snsClient.Unsubscribe(unsubscribeRequest); } }
public virtual void PublishTopicMessage(AmazonSimpleNotificationServiceClient snsClient, string topicArn, string subject, string message) { // Create the request var publishRequest = new PublishRequest { Subject = subject, Message = message, TopicArn = topicArn }; // Submit the request snsClient.Publish(publishRequest); }
public virtual void DeleteTopic(AmazonSimpleNotificationServiceClient snsClient, string topicArn) { // Create the request var deleteTopicRequest = new DeleteTopicRequest { TopicArn = topicArn }; snsClient.DeleteTopic(deleteTopicRequest); }
public void ReloadExistingSubscriptions() { var subscriptions = new List <SubscriptionInfo>(); using (var client = new AmazonSimpleNotificationServiceClient(this.AwsCredentials, this.AwsRegion)) { var request = new ListTopicsRequest(); ListTopicsResponse response; Task <ListTopicsResponse> ltt; do { ltt = client.ListTopicsAsync(request); ltt.Wait(); response = ltt.Result; foreach (var topic in response.Topics) { var lsRequest = new ListSubscriptionsByTopicRequest() { TopicArn = topic.TopicArn }; ListSubscriptionsByTopicResponse lsResponse; Task <ListSubscriptionsByTopicResponse> lst; do { lst = client.ListSubscriptionsByTopicAsync(lsRequest); lst.Wait(); lsResponse = lst.Result; //íterate all subscriptions which are bound to our SubscriptionCallbackUrl... foreach (var subscription in lsResponse.Subscriptions.Where(s => string.Equals(s.Endpoint, this.SubscriptionCallbackUrl, StringComparison.InvariantCultureIgnoreCase))) { //skip pending subscriptions... if (!subscription.SubscriptionArn.Equals(AwsMagicArnForPendingSubscription)) { subscriptions.Add(new SubscriptionInfo(this, subscription.TopicArn, subscription.SubscriptionArn, false)); } } lsRequest.NextToken = lsResponse.NextToken; } while (!string.IsNullOrEmpty(lsResponse.NextToken)); } request.NextToken = response.NextToken; } while (!string.IsNullOrEmpty(response.NextToken)); lock (_ConfirmedSubscriptions) { _ConfirmedSubscriptions = subscriptions; } lock (_LocalPendingSubscriptions) { foreach (var lps in _LocalPendingSubscriptions.ToArray()) { if (subscriptions.Where(s => (s.TopicArn ?? "") == (lps.TopicArn ?? "")).Any()) { _LocalPendingSubscriptions.Remove(lps); } } } } }
public SubscriptionInfo GetOrSubscribe(string topicArn) { SubscriptionInfo item; lock (_ConfirmedSubscriptions) { item = _ConfirmedSubscriptions.Where(s => string.Equals(s.TopicArn, topicArn, StringComparison.InvariantCultureIgnoreCase)).SingleOrDefault(); if (item is object) { return(item); } } lock (_LocalPendingSubscriptions) { item = _LocalPendingSubscriptions.Where(s => string.Equals(s.TopicArn, topicArn, StringComparison.InvariantCultureIgnoreCase)).SingleOrDefault(); if (item is object) { //orphaned - usually is takes only a few seconds until a subscription is confirmed! if (item.Initiated.AddSeconds(30) < DateTime.Now) { //just remoce thie item, becasue a new one will be created below... _LocalPendingSubscriptions.Remove(item); } return(item); } #if DEBUG if (SuppressSubscriptionDevmode) { item = new SubscriptionInfo(this, topicArn, "<dummy>", false); //simulate already confirmed subscription _LocalPendingSubscriptions.Add(item); return(item); } #endif try { using (var client = new AmazonSimpleNotificationServiceClient(this.AwsCredentials, this.AwsRegion)) { Task <SubscribeResponse> t; if (this.SubscriptionCallbackUrl.StartsWith("https:")) { t = client.SubscribeAsync(topicArn, "https", this.SubscriptionCallbackUrl); } else { t = client.SubscribeAsync(topicArn, "http", this.SubscriptionCallbackUrl); } t.Wait(); if (t.IsCompleted && t.Result is object) { item = new SubscriptionInfo(this, topicArn, t.Result.SubscriptionArn, true); _LocalPendingSubscriptions.Add(item); } else { if (t.Exception != null) { throw t.Exception; } else if (t.Result is object) { throw new Exception($"Subscribe-Task failed with Http-Status-Code: {t.Result.HttpStatusCode}!"); } else { throw new Exception($"Subscribe-Task failed!"); } } } } catch (AggregateException aex) { foreach (var subex in aex.InnerExceptions) { _ExceptionHandler.Invoke(subex); } } catch (Exception ex) { _ExceptionHandler.Invoke(ex); } } return(item); }
public SnsCaller(ICredentialsRetriever credentialsRetriever) { credentials = credentialsRetriever.GetCredentials(); client = new AmazonSimpleNotificationServiceClient(credentials, RegionEndpoint.USEast1); }
/// <summary> /// This is the main function for sending notification /// </summary> public void sendNotification() { foreach (Client client in clients) { int clientID = client.getClientID(); #region AWS connection - This code block is same for every push message type - This is the basic block. _client = new AmazonSimpleNotificationServiceClient("XXXXXXX", "XXXXXXXXXX", Amazon.RegionEndpoint.EUCentral1); string token = client.getPushToken(); Platfroms mobilOsType = client.getMobileType() == 0 ? Platfroms.IOS_PATFORM : Platfroms.ANDROID_PLATFORM; try { string applicationArn = ""; try { applicationArn = applications[(int)mobilOsType].getArn(); } catch { continue; } string endPointArn = createEndPointArn(token, applicationArn); if (string.IsNullOrEmpty(endPointArn)) { continue; } else { PublishRequest publishRequest = new PublishRequest(); Dictionary <string, string> messageMap = new Dictionary <string, string>(); messageMap.Add("default", "default message"); string platform = mobilOsType == 0 ? "APNS_SANDBOX" : "GCM"; // This application developed for IOS and Android if (mobilOsType != Platfroms.IOS_PATFORM && mobilOsType != Platfroms.ANDROID_PLATFORM) { continue; } int clientsID = client.getClientID(); Guid pushesID = client.getPushID(); string message = mobilOsType == 0 ? getAPNSMessage(notification, title, pushesID, clientsID) : getGCMMessage(notification, title, pushesID, clientsID); messageMap.Add(platform, message); publishRequest.TargetArn = endPointArn; publishRequest.MessageStructure = "json"; string messageJSON = ""; try { messageJSON = JsonConvert.SerializeObject(messageMap); } catch { continue; } try { publishRequest.Message = messageJSON; _client.Publish(publishRequest); } catch { continue; } try { // for deleting endPointArn DeleteEndpointRequest _request = new DeleteEndpointRequest(); _request.EndpointArn = endPointArn; _client.DeleteEndpoint(_request); } catch { continue; } } } catch { continue; } #endregion } }
/// <summary> /// Creates a user account for SNS /// </summary> /// <param name="userName">The user to create a SNS account for</param> /// <param name="number">The user's phone number</param> private void CreateSNSAccount(String userName, String number) { AmazonSimpleNotificationServiceClient client = new AmazonSimpleNotificationServiceClient(); //Create topic first. CreateTopicRequest request = new CreateTopicRequest { Name = userName }; try { CreateTopicResponse response = client.CreateTopic(request); CreateTopicResult result = response.CreateTopicResult; String[] strings = new String[1]; strings[0] = "Success! Assigned ARN is: " + result.TopicArn + "\n"; TempData["result"] = strings; } catch (Exception e) { TempData["error"] = e.Message; } String arn = "arn:aws:sns:us-east-1:727060774285:" + userName; SetTopicAttributesRequest request2 = new SetTopicAttributesRequest { AttributeName = "DisplayName", AttributeValue = "Cookbook", TopicArn = arn }; try { SetTopicAttributesResponse response = client.SetTopicAttributes(request2); ResponseMetadata result = response.ResponseMetadata; Console.WriteLine(result.RequestId); } catch (Exception e) { Console.WriteLine(e.Message); } //Add SMS number to topic. SubscribeRequest request3 = new SubscribeRequest { TopicArn = arn, Endpoint = number, Protocol = "sms" }; try { SubscribeResponse response = client.Subscribe(request3); SubscribeResult result = response.SubscribeResult; string resultSubscribe = "Success! Subscription Arn is: " + result.SubscriptionArn + "\n"; Console.WriteLine(resultSubscribe); } catch (Exception e) { Console.WriteLine(e.Message); } }