Exemplo n.º 1
0
        private async Task <string> EnsureTopic(string topicName)
        {
            try
            {
                _topicLock.EnterReadLock();
                if (_snsTopics.TryGetValue(topicName, out var url))
                {
                    return(url);
                }
            }
            finally
            {
                _topicLock.ExitReadLock();
            }

            try
            {
                _topicLock.EnterWriteLock();
                var snsCreateResponse = await _snsClient.CreateTopicAsync(topicName);

                var arn = snsCreateResponse.TopicArn;
                _snsTopics.Add(topicName, arn);
                return(arn);
            }
            finally
            {
                _topicLock.ExitWriteLock();
            }
        }
Exemplo n.º 2
0
        public async Task <string> CreateTopic(string topicName)
        {
            var request  = new CreateTopicRequest(topicName);
            var response = await _sns.CreateTopicAsync(request);

            return(response.TopicArn);
        }
        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);
        }
Exemplo n.º 4
0
        /// <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);
        }
Exemplo n.º 5
0
        public async Task Initialise()
        {
            _topicArn = (await _snsClient.CreateTopicAsync(_topicName)).TopicArn;
            _queueUrl = (await _sqsClient.CreateQueueAsync(_queueName)).QueueUrl;
            await SubscribeTopicToQueue();

            _initialised = true;
        }
Exemplo n.º 6
0
        public async Task SetTopicConfigurationTests()
        {
            using (var snsClient = new AmazonSimpleNotificationServiceClient())
            {
                string topicName         = UtilityMethods.GenerateName("events-test");
                var    snsCreateResponse = await snsClient.CreateTopicAsync(topicName);

                var bucketName = await UtilityMethods.CreateBucketAsync(Client, "SetTopicConfigurationTests");

                try
                {
                    await snsClient.AuthorizeS3ToPublishAsync(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
                                }
                            }
                        }
                    };
                    await Client.PutBucketNotificationAsync(putRequest);

                    var getResponse = WaitUtils.WaitForComplete(
                        () =>
                    {
                        return(Client.GetBucketNotificationAsync(bucketName).Result);
                    },
                        (r) =>
                    {
                        return(r.TopicConfigurations.Count > 0);
                    });

                    Assert.Equal(1, getResponse.TopicConfigurations.Count);
                    Assert.Equal(1, getResponse.TopicConfigurations[0].Events.Count);
                    Assert.Equal(EventType.ObjectCreatedPut, getResponse.TopicConfigurations[0].Events[0]);

#pragma warning disable 618
                    Assert.Equal("s3:ObjectCreated:Put", getResponse.TopicConfigurations[0].Event);
#pragma warning restore 618
                    Assert.Equal("the-topic-test", getResponse.TopicConfigurations[0].Id);
                    Assert.Equal(snsCreateResponse.TopicArn, getResponse.TopicConfigurations[0].Topic);
                }
                finally
                {
                    await snsClient.DeleteTopicAsync(snsCreateResponse.TopicArn);

                    await UtilityMethods.DeleteBucketWithObjectsAsync(Client, bucketName);
                }
            }
        }
        public async Task Publish_HasMessageTypeAttributeAndBody()
        {
            //Arrange
            var queueName    = Guid.NewGuid().ToString();
            var topicName    = Guid.NewGuid().ToString();
            var firstMessage = new FirstMessage {
                Value = "value1"
            };
            var secondMessage = new SecondMessage {
                Value = "value2"
            };

            var snsClient = new AmazonSimpleNotificationServiceClient(
                AppConfig.AccessKey,
                AppConfig.SecretKey,
                new AmazonSimpleNotificationServiceConfig {
                ServiceURL = AppConfig.ServiceUrl
            });

            var topicArn  = (await snsClient.CreateTopicAsync(topicName)).TopicArn;
            var sqsClient = new AmazonSQSClient(
                AppConfig.AccessKey,
                AppConfig.SecretKey,
                new AmazonSQSConfig {
                ServiceURL = AppConfig.ServiceUrl
            });
            await sqsClient.CreateQueueAsync(queueName);

            var queueUrl = (await sqsClient.GetQueueUrlAsync(queueName)).QueueUrl;

            await snsClient.SubscribeQueueAsync(topicArn, sqsClient, queueUrl);

            //Act
            await snsClient.PublishAsync(topicArn, firstMessage);

            await snsClient.PublishAsync(topicArn, secondMessage);

            var response = await sqsClient.ReceiveMessageAsync(new ReceiveMessageRequest
            {
                QueueUrl              = queueUrl,
                MaxNumberOfMessages   = 2,
                MessageAttributeNames = new List <string> {
                    "All"
                }
            });

            var messageTypes = response.Messages
                               .Select(message => JsonConvert.DeserializeObject <MessageBody>(message.Body))
                               .Select(body => body.MessageAttributes.Single(pair => pair.Key == "MessageType").Value.Value)
                               .ToList();

            //Assert
            new[] { nameof(FirstMessage), nameof(SecondMessage) }
            .ShouldAllBe(s => messageTypes.Contains(s));
            new [] { firstMessage.Value, secondMessage.Value }
            .ShouldAllBe(s => response.Messages.Any(message => message.Body.Contains(s)));
        }
Exemplo n.º 8
0
        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);
        }
Exemplo n.º 9
0
        static async Task <(string topicArn, Func <Task> topicCleanup)> CreateTopic(
            AmazonSimpleNotificationServiceClient snsClient,
            string timestamp,
            string name,
            CancellationToken cancellationToken)
        {
            var topic = await snsClient.CreateTopicAsync($"Beetles_{name}_{timestamp}", cancellationToken);

            return(topic.TopicArn, async() => await snsClient.DeleteTopicAsync(topic.TopicArn));
        }
Exemplo n.º 10
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);
            }
        }
Exemplo n.º 11
0
        public static async Task <string> CreateTopic(string topicName)
        {
            using (var client = new AmazonSimpleNotificationServiceClient(ConfigManager.ConfigSettings.AccessKey, ConfigManager.ConfigSettings.Secret, Amazon.RegionEndpoint.USWest2))
            {
                var request = new CreateTopicRequest(topicName);

                var response = await client.CreateTopicAsync(request);

                return(response.TopicArn);
            }
        }
        public async System.Threading.Tasks.Task <CreateTopicResponse> CreateTopic(string topicName)
        {
            CreateTopicResponse createTopicResponse = new CreateTopicResponse();

            using (AmazonSimpleNotificationServiceClient snsClient = new AmazonSimpleNotificationServiceClient(credentials, Amazon.RegionEndpoint.USEast2))
            {
                CreateTopicRequest createTopicRequest = new CreateTopicRequest(topicName);
                createTopicResponse = await snsClient.CreateTopicAsync(createTopicRequest);
            }

            return(createTopicResponse);
        }
        private async Task <bool> CreateTopicAsync()
        {
            var topicRequest = new CreateTopicRequest
            {
                Name = "AWSSkills"
            };
            var topicResponse = await _snsClient.CreateTopicAsync(topicRequest);

            _topicArn = topicResponse.TopicArn;

            return(false);
        }
Exemplo n.º 14
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();
        }
Exemplo n.º 15
0
        private void CreateTopic(RoutingKey topicName, AmazonSQSClient sqsClient, AmazonSimpleNotificationServiceClient snsClient)
        {
            //topic re-creation is a no-op, so don't bother to check first as reduces latency
            var createTopic = snsClient.CreateTopicAsync(new CreateTopicRequest(topicName)).Result;

            if (!string.IsNullOrEmpty(createTopic.TopicArn))
            {
                _channelTopicARN = createTopic.TopicArn;
            }
            else
            {
                throw new InvalidOperationException($"Could not create Topic topic: {topicName} on {_awsConnection.Region}");
            }
        }
Exemplo n.º 16
0
        public async System.Threading.Tasks.Task CreateTopicAsync()
        {
            AmazonSimpleNotificationServiceClient snsClient = new AmazonSimpleNotificationServiceClient(RegionEndpoint.APSoutheast1);

            // Create an Amazon SNS topic.
            CreateTopicRequest  createTopicRequest  = new CreateTopicRequest("MyTopic");
            CreateTopicResponse createTopicResponse = await snsClient.CreateTopicAsync(createTopicRequest);

            // Print the topic ARN.
            Console.WriteLine("TopicArn: " + createTopicResponse.TopicArn);

            // Print the request ID for the CreateTopicRequest action.
            Console.WriteLine("CreateTopicRequest: " + createTopicResponse.ResponseMetadata.RequestId);
        }
        /// <summary>
        ///
        /// </summary>
        /// <param name="topicName"></param>
        /// <param name="token"></param>
        /// <returns></returns>
        public async Task CreateTopicAsync(string topicName, CancellationToken token = default)
        {
            using (var client = new AmazonSimpleNotificationServiceClient(accessKey, secretKey, region))
            {
                var req = new CreateTopicRequest(topicName);
                req.Tags.Add(new Tag()
                {
                    Key   = "Name",
                    Value = "Topic example"
                });

                await client.CreateTopicAsync(req, token);
            }
        }
Exemplo n.º 18
0
        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}");
            }
        }
Exemplo n.º 19
0
 /// <summary>
 /// Method sender to connect and send the topic to azure.
 /// </summary>
 /// <typeparam name="T">Type of message to send</typeparam>
 /// <param name="message">Object of message to send</param>
 /// <returns>The task of Process topic</returns>
 public override async Task SendToTopic <T>(T message)
 {
     SqsSnsConfiguration config = GetConnection(_queueName);
     AmazonSimpleNotificationServiceClient snsClient = new AmazonSimpleNotificationServiceClient();
     var topicRequest = new CreateTopicRequest
     {
         Name = _queueName
     };
     var topicResponse = snsClient.CreateTopicAsync(topicRequest).Result;
     await snsClient.PublishAsync(new PublishRequest
     {
         TopicArn = topicResponse.TopicArn,
         Message  = message.ToStringCamelCase(),
     });
 }
        public async Task <CreateTopicResponse> CreateTopic(string topicName)
        {
            var createTopicRequest = new CreateTopicRequest(topicName);
            var response           = await snsClient.CreateTopicAsync(createTopicRequest);

            if (topics.ContainsKey(topicName))
            {
                topics[topicName] = response.TopicArn;
            }
            else
            {
                topics.Add(topicName, response.TopicArn);
            }

            return(response);
        }
Exemplo n.º 21
0
        private async Task <String> GetTopicArn(String topic)
        {
            var amazonTopic = await amazonSnsClient.FindTopicAsync(topic);

            if (amazonTopic != null)
            {
                return(amazonTopic.TopicArn);
            }

            var createTopicResponse = await amazonSnsClient.CreateTopicAsync(new CreateTopicRequest()
            {
                Name = topic
            });

            return(createTopicResponse.TopicArn);
        }
Exemplo n.º 22
0
        public async Task <JsonResult> Create([FromBody] CreateClassRoomDto dto)
        {
            var currentUser = await _userManager.GetUserAsync(User);

            var classRoom = new ClassRoom()
            {
                Name = dto.Name, TeacherId = currentUser.Id
            };

            _dbContext.ClassRoom.Add(classRoom);
            _dbContext.SaveChanges();

            AmazonSimpleNotificationServiceClient client = new AmazonSimpleNotificationServiceClient("AKIAJLAJIOHNR4Q2EQSQ", "+5t2ISSTpRYQnZomhd+C4S9LqQ8YiRqKjV1YRHLM", Amazon.RegionEndpoint.USWest2);

            CreateTopicRequest  request = new CreateTopicRequest(classRoom.Id.ToString());
            CreateTopicResponse ctr     = await client.CreateTopicAsync(request);

            return(Json(classRoom));
        }
Exemplo n.º 23
0
        private void CreateTopicsAndQueues()
        {
            var topicAndQueueName = $"toll-amount-threshold-breached-{Guid.NewGuid().ToString().Substring(0,8)}";

            var createTopicResponse = _snsClient.CreateTopicAsync(new CreateTopicRequest {
                Name = topicAndQueueName
            }).Result;
            var createQueueResponse = _sqsClient.CreateQueueAsync(new CreateQueueRequest {
                QueueName = topicAndQueueName
            }).Result;

            TopicArn = createTopicResponse.TopicArn;
            QueueUrl = createQueueResponse.QueueUrl;

            var subscriptionArn = _snsClient.SubscribeAsync(new SubscribeRequest {
                TopicArn = createTopicResponse.TopicArn, Endpoint = createQueueResponse.QueueUrl, Protocol = "sqs"
            }).Result;
            var r = _snsClient.SetSubscriptionAttributesAsync(subscriptionArn.SubscriptionArn, "RawMessageDelivery", "true").Result;
        }
Exemplo n.º 24
0
        public async Task <ISubscription> SubscribeAsync(String topic)
        {
            var amazonTopic = await amazonSnsClient.CreateTopicAsync(new CreateTopicRequest()
            {
                Name = topic
            });

            var queue = await amazonSqsClient.CreateQueueAsync(new CreateQueueRequest()
            {
                QueueName = Guid.NewGuid().ToString()
            });

            var queueAttributes = await amazonSqsClient.GetQueueAttributesAsync(new GetQueueAttributesRequest()
            {
                AttributeNames = new List <String>(new String[] { "QueueArn" }),
                QueueUrl       = queue.QueueUrl
            });

            var policy = new Policy()
                         .WithStatements(
                new Statement(Statement.StatementEffect.Allow)
                .WithPrincipals(Principal.AllUsers)
                .WithConditions(ConditionFactory.NewSourceArnCondition(amazonTopic.TopicArn))
                .WithResources(new Resource(queueAttributes.QueueARN))
                .WithActionIdentifiers(SQSActionIdentifiers.SendMessage));

            await amazonSqsClient.SetQueueAttributesAsync(queue.QueueUrl, new Dictionary <String, String>()
            {
                ["Policy"] = policy.ToJson()
            });

            await amazonSnsClient.SubscribeAsync(new SubscribeRequest()
            {
                Endpoint = queueAttributes.QueueARN,
                Protocol = "sqs",
                TopicArn = amazonTopic.TopicArn
            });

            var subscription = amazonSubscriptionFactory.Create(queue.QueueUrl);

            return(subscription);
        }
Exemplo n.º 25
0
        public async Task <IActionResult> AddUserByEmail([FromBody] AddUserDto model)
        {
            var user = await _userManager.FindByEmailAsync(model.Email);

            if (user == null)
            {
                return(NotFound());
            }
            _dbContext.UserClass.Add(new UserClass()
            {
                ApplicationUserId = user.Id, ClassRoomId = model.ClassRoomId
            });
            _dbContext.SaveChanges();

            AmazonSimpleNotificationServiceClient client = new AmazonSimpleNotificationServiceClient("AKIAJLAJIOHNR4Q2EQSQ", "+5t2ISSTpRYQnZomhd+C4S9LqQ8YiRqKjV1YRHLM", Amazon.RegionEndpoint.USWest2);
            var topicArn = await client.CreateTopicAsync(new CreateTopicRequest(model.ClassRoomId.ToString()));

            await client.SubscribeAsync(new SubscribeRequest(topicArn.TopicArn, "email", model.Email));

            return(Json("All good bro!"));
        }
Exemplo n.º 26
0
        private void CreateTopic(RoutingKey topicName, SnsAttributes snsAttributes)
        {
            using (var snsClient = new AmazonSimpleNotificationServiceClient(_awsConnection.Credentials, _awsConnection.Region))
            {
                var attributes = new Dictionary <string, string>();
                if (snsAttributes != null)
                {
                    if (!string.IsNullOrEmpty(snsAttributes.DeliveryPolicy))
                    {
                        attributes.Add("DeliveryPolicy", snsAttributes.DeliveryPolicy);
                    }
                    if (!string.IsNullOrEmpty(snsAttributes.Policy))
                    {
                        attributes.Add("Policy", snsAttributes.Policy);
                    }
                }

                var createTopicRequest = new CreateTopicRequest(topicName)
                {
                    Attributes = attributes,
                    Tags       = new List <Tag> {
                        new Tag {
                            Key = "Source", Value = "Brighter"
                        }
                    }
                };

                //create topic is idempotent, so safe to call even if topic already exists
                var createTopic = snsClient.CreateTopicAsync(createTopicRequest).Result;

                if (!string.IsNullOrEmpty(createTopic.TopicArn))
                {
                    ChannelTopicArn = createTopic.TopicArn;
                }
                else
                {
                    throw new InvalidOperationException($"Could not create Topic topic: {topicName} on {_awsConnection.Region}");
                }
            }
        }
Exemplo n.º 27
0
        static async Task sendSNSMessageAsync()
        {
            //Send a message to the SNS event topic

            var snsClient = new AmazonSimpleNotificationServiceClient();

            // Creating the topic request and the topic and response
            var topicRequest = new CreateTopicRequest
            {
                Name = "TestSNSTopic"
            };

            var topicResponse = await snsClient.CreateTopicAsync(topicRequest);

            var subscribeRequest = new SubscribeRequest()
            {
                TopicArn = topicResponse.TopicArn,
                Protocol = "application", // important to chose the protocol as I am sending notification to applications I have chosen application here.
                Endpoint = ""
            };

            var reqObj = new Dictionary <String, String>();

            reqObj["field1"] = "123";
            reqObj["field2"] = "ABC";

            PublishRequest publishReq = new PublishRequest()
            {
                TargetArn        = subscribeRequest.Endpoint,
                MessageStructure = "json",
                Message          = JsonConvert.SerializeObject(reqObj)
            };

            PublishResponse response = await snsClient.PublishAsync(publishReq);

            if (response != null && response.MessageId != null)
            {
                Console.WriteLine("Notification Send Successfully");
            }
        }
Exemplo n.º 28
0
        public async Task PublishEventAsync <TEvent>(TEvent @event)
        {
            var endpoint = RegionEndpoint.GetBySystemName(_options.Value.Region);
            var client   = new AmazonSimpleNotificationServiceClient(endpoint);

            Type eventType = typeof(TEvent);
            AmazonSnsTopicAttribute attr = eventType
                                           .GetCustomAttributes(typeof(AmazonSnsTopicAttribute), inherit: false)
                                           .OfType <AmazonSnsTopicAttribute>()
                                           .FirstOrDefault();
            string topicName = attr == null
                ? eventType.FullName.ToLower().Replace('.', '-')
                : attr.Name;

            var createTopicRequest = new CreateTopicRequest(topicName);
            CreateTopicResponse createTopicResponse = await client.CreateTopicAsync(createTopicRequest);

            string topicArn = createTopicResponse.TopicArn;

            string          message         = _eventSerializer.Serialize(@event);
            var             publishRequest  = new PublishRequest(topicArn, message);
            PublishResponse publishResponse = await client.PublishAsync(publishRequest);
        }
Exemplo n.º 29
0
        public async Task <IActionResult> PostToken([FromBody] TokenDto dto)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            WebService1SoapClient client = new WebService1SoapClient
                                           (
                new BasicHttpBinding(BasicHttpSecurityMode.None),
                new EndpointAddress("http://localhost/SOAPTokenGenerator/TokenGenerator.asmx")
                                           );


            var token = new Token()
            {
                Duration        = 30,
                ClassId         = dto.ClassId,
                CreatedDateTime = DateTime.Now,
                TokenValue      = client.GenerateToken()
            };

            _context.Token.Add(token);
            _context.SaveChanges();

            AmazonSimpleNotificationServiceClient snsClient = new AmazonSimpleNotificationServiceClient("AKIAJLAJIOHNR4Q2EQSQ", "+5t2ISSTpRYQnZomhd+C4S9LqQ8YiRqKjV1YRHLM", Amazon.RegionEndpoint.USWest2);
            var topicArn = await snsClient.CreateTopicAsync(new CreateTopicRequest(dto.ClassId.ToString()));

            String         msg            = "Your token for todays class is: " + token.TokenValue;
            PublishRequest publishRequest = new PublishRequest(topicArn.TopicArn, msg);
            var            publishResult  = await snsClient.PublishAsync(publishRequest);

            //print MessageId of message published to SNS topic

            return(CreatedAtAction("GetToken", new { id = token.Id }, token));
        }
Exemplo n.º 30
0
        public async Task RegisterUserNotifications()
        {
            string deviceToken = GetDeviceToken();

            var notificationsSubscriptions = GetNotificationsSubscriptions();

            if (string.IsNullOrEmpty(deviceToken))
            {
                return;
            }

            var credentials = new BasicAWSCredentials(
                AppSettings.Instance.AwsKey,
                AppSettings.Instance.AwsSecret
                );

            var client = new AmazonSimpleNotificationServiceClient(
                credentials,
                Amazon.RegionEndpoint.EUWest1
                );

            if (string.IsNullOrEmpty(notificationsSubscriptions.ApplicationEndPoint) ||
                notificationsSubscriptions.DeviceToken != deviceToken)
            {
                // **********************************************
                // de-register old endpoint and all subscriptions
                if (!string.IsNullOrEmpty(notificationsSubscriptions.ApplicationEndPoint))
                {
                    try
                    {
                        var response = await client.DeleteEndpointAsync(new DeleteEndpointRequest { EndpointArn = notificationsSubscriptions.ApplicationEndPoint });

                        if (response.HttpStatusCode != System.Net.HttpStatusCode.OK)
                        {
                            ShowAlert("Debug", $"Error eliminando endpoint: {response.HttpStatusCode}");
                        }
                    }
                    catch { /*Silent error in case endpoint doesn´t exist */ }

                    notificationsSubscriptions.ApplicationEndPoint = null;

                    foreach (var sub in notificationsSubscriptions.Subscriptions)
                    {
                        try
                        {
                            await client.UnsubscribeAsync(sub.Value);
                        }
                        catch { /*Silent error in case endpoint doesn´t exist */ }
                    }

                    notificationsSubscriptions.Subscriptions.Clear();
                }

                // register with SNS to create a new endpoint
                var endPointResponse = await client.CreatePlatformEndpointAsync(
                    new CreatePlatformEndpointRequest
                {
                    Token = deviceToken,
                    PlatformApplicationArn = Device.RuntimePlatform == Device.iOS ?
                                             AppSettings.Instance.AwsPlatformApplicationArnIOS :
                                             AppSettings.Instance.AwsPlatformApplicationArnAndroid
                }
                    );

                if (endPointResponse.HttpStatusCode != System.Net.HttpStatusCode.OK)
                {
                    ShowAlert("Debug", $"Error registrando endpoint: {endPointResponse.HttpStatusCode}, {endPointResponse.ResponseMetadata}");
                }

                // Save device token and application endpoint created
                notificationsSubscriptions.DeviceToken         = deviceToken;
                notificationsSubscriptions.ApplicationEndPoint = endPointResponse.EndpointArn;
            }

            // Retrieve subscriptions
            var subscriptions = await AudioLibrary.Instance.GetUserSubscriptions(false);

            if (subscriptions == null)
            {
                subscriptions = new UserSubscriptions {
                    Subscriptions = new List <Models.Api.Subscription>()
                }
            }
            ;

            // Register non existings subscriptions
            var subscriptionsCodes = subscriptions.Subscriptions.Select(s => s.Code).ToList();

            foreach (var code in subscriptionsCodes)
            {
                if (!notificationsSubscriptions.Subscriptions.ContainsKey(code))
                {
                    var topicArn = AppSettings.Instance.AwsTopicArn;
                    topicArn += string.IsNullOrEmpty(code) ? "" : $"-{code}";

                    if (!await TopicExists(topicArn, client))
                    {
                        var topicResponse = await client.CreateTopicAsync(new CreateTopicRequest { Name = $"{AppSettings.Instance.AwsTopicName}-{code}" });

                        if (topicResponse.HttpStatusCode != System.Net.HttpStatusCode.OK)
                        {
                            ShowAlert("Debug", $"Error creando topic: {topicResponse.HttpStatusCode}, {topicResponse.ResponseMetadata}");
                        }

                        topicArn = topicResponse.TopicArn;
                    }


                    // Subscribe
                    var subscribeResponse = await client.SubscribeAsync(new SubscribeRequest
                    {
                        Protocol = "application",
                        Endpoint = notificationsSubscriptions.ApplicationEndPoint,
                        TopicArn = topicArn
                    });

                    if (subscribeResponse.HttpStatusCode != System.Net.HttpStatusCode.OK)
                    {
                        ShowAlert("Debug", $"Error creando suscripción: {subscribeResponse.HttpStatusCode}, {subscribeResponse.ResponseMetadata}");
                    }

                    // Add to the list
                    notificationsSubscriptions.Subscriptions.Add(code, subscribeResponse.SubscriptionArn);
                }
            }

            // Remove subscriptions not in user list
            var currentSubscriptions = notificationsSubscriptions.Subscriptions.ToList();

            foreach (var subs in currentSubscriptions)
            {
                if (!subscriptionsCodes.Contains(subs.Key))
                {
                    try
                    {
                        await client.UnsubscribeAsync(subs.Value);
                    }
                    catch { /*Silent error in case endpoint doesn´t exist */ }

                    notificationsSubscriptions.Subscriptions.Remove(subs.Key);
                }
            }

            // Save notifications subscriptions
            await SaveNotificationsSubscriptions(notificationsSubscriptions);
        }