Example #1
0
 private void MockCreateTopic(Mock <IAmazonSimpleNotificationService> client,
                              CreateTopicResponse response)
 {
     client
     .Setup(c => c.CreateTopicAsync(It.IsAny <string>(), It.IsAny <CancellationToken>()))
     .ReturnsAsync(response);
 }
Example #2
0
        public async Task <string> CreateSnsTopic(IAmazonSimpleNotificationService snsClient,
                                                  string topicName)
        {
            try
            {
                Console.WriteLine("Creating SNS Topic");
                var attrs = new Dictionary <string, string>
                {
                    { "FifoTopic", "true" },
                    { "ContentBasedDeduplication", "false" }
                };
                CreateTopicResponse responseCreate = await snsClient.CreateTopicAsync(
                    new CreateTopicRequest()
                {
                    Name = topicName, Attributes = attrs
                });

                Console.WriteLine($"Topic Arn: {responseCreate.TopicArn}");
                return(responseCreate.TopicArn);
            }
            catch (Exception e)
            {
                Console.WriteLine($"Creating SNS Topic failed: {e}");
                throw;
            }
        }
        /// <summary>
        /// Unmarshaller the response from the service to the response class.
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public override AmazonWebServiceResponse Unmarshall(XmlUnmarshallerContext context)
        {
            CreateTopicResponse response = new CreateTopicResponse();

            context.Read();
            int targetDepth = context.CurrentDepth;

            while (context.ReadAtDepth(targetDepth))
            {
                if (context.IsStartElement)
                {
                    if (context.TestExpression("CreateTopicResult", 2))
                    {
                        UnmarshallResult(context, response);
                        continue;
                    }

                    if (context.TestExpression("ResponseMetadata", 2))
                    {
                        response.ResponseMetadata = ResponseMetadataUnmarshaller.Instance.Unmarshall(context);
                    }
                }
            }

            return(response);
        }
        private static void UnmarshallResult(XmlUnmarshallerContext context, CreateTopicResponse response)
        {
            int originalDepth = context.CurrentDepth;
            int targetDepth   = originalDepth + 1;

            if (context.IsStartOfDocument)
            {
                targetDepth += 2;
            }

            while (context.ReadAtDepth(originalDepth))
            {
                if (context.IsStartElement || context.IsAttribute)
                {
                    if (context.TestExpression("TopicArn", targetDepth))
                    {
                        var unmarshaller = StringUnmarshaller.Instance;
                        response.TopicArn = unmarshaller.Unmarshall(context);
                        continue;
                    }
                }
            }

            return;
        }
Example #5
0
        public string GetTopic(string topic)
        {
            ListTopicsResponse tmp = client.ListTopics();
            //on va storer le arn dans la db  pour le moment si le topic existe ça retourne le topic sinon le crée
            CreateTopicResponse x = client.CreateTopic(topic);

            return(x.TopicArn);
        }
Example #6
0
 private Task PublishNotificationToCreatedTopic(CreateTopicResponse topicResponse,
                                                SmsNotificationDto smsNotification)
 {
     return(SubscribeToTopic(topicResponse, AwsNotificationProtocolName,
                             smsNotification.PhoneNumbers)
            .ContinueWith(response => PublishMessageToTopic(smsNotification.Content, topicResponse.TopicArn))
            .ContinueWith(response => DeleteTopic(topicResponse.TopicArn)));
 }
Example #7
0
 private Task PublishNotificationToCreatedTopic(CreateTopicResponse topicResponse,
                                                EmailNotificationDto emailNotification)
 {
     return(SubscribeToTopic(topicResponse, AwsNotificationProtocolName,
                             emailNotification.Emails)
            .ContinueWith(response => PublishMessageToTopic(emailNotification.Content, topicResponse.TopicArn))
            .ContinueWith(response => DeleteTopic(topicResponse.TopicArn)));
 }
Example #8
0
        public override WebServiceResponse Unmarshall(XmlUnmarshallerContext context)
        {
            var response = new CreateTopicResponse();

            if (context.ResponseData.IsHeaderPresent(HttpHeader.LocationHeader))
            {
                response.TopicUrl = context.ResponseData.GetHeaderValue(HttpHeader.LocationHeader);
            }
            return(response);
        }
Example #9
0
        /// <summary>
        /// Creates a topic.  Should only be needed to be used once.
        /// </summary>
        /// <param name="topicName"></param>
        /// <returns></returns>
        public string CreateTopic(string topicName)
        {
            var request = new CreateTopicRequest {
                Name = topicName
            };

            CreateTopicResponse response = Client.CreateTopic(request);

            return(response.CreateTopicResult.TopicArn);
        }
Example #10
0
        private Task <ConfirmSubscriptionResponse[]> SubscribeToTopic(CreateTopicResponse topicResponse, string protocol,
                                                                      IEnumerable <string> endpoints)
        {
            var subscriptionConfirmationResponses = endpoints
                                                    .Select(endpoint => new SubscribeRequest(topicResponse.TopicArn, protocol, endpoint))
                                                    .Select(subscribeRequest => _snsClient.SubscribeAsync(subscribeRequest)
                                                            .ContinueWith(subscribeResponse => _snsClient.ConfirmSubscriptionAsync(topicResponse.TopicArn, subscribeResponse.Result.SubscriptionArn)).Result);

            return(Task.WhenAll(subscriptionConfirmationResponses.ToArray()));
        }
        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);
        }
        protected async Task SubscribeToSNSTopicTagAsync(string topicTag, string userId, string token, string appIdentifier, string endpointArn)
        {
            if (string.IsNullOrEmpty(topicTag))
            {
                return;
            }
            DynamoTag pnTag = await tagTableOperator.GetTagAsync(topicTag);

            if (pnTag != null && pnTag.TaggingTypeEnum != PNTagType.SNSTopic)
            {
                throw new OverrideExistingTagTypeException(pnTag.Tag, pnTag.TaggingTypeEnum.ToString());
            }
            string topicArn = pnTag?.SnsTopicArn;

            if (string.IsNullOrEmpty(topicArn))
            {
                CreateTopicRequest ctReq = new CreateTopicRequest();
                ctReq.Name = appIdentifier + "___" + topicTag;
                CreateTopicResponse ctResponse = await snsClient.CreateTopicAsync(ctReq);

                topicArn = ctResponse.TopicArn;
            }


            SubscribeRequest sReq = new SubscribeRequest();

            sReq.TopicArn = topicArn;
            sReq.Protocol = "application";
            sReq.Endpoint = endpointArn;
            SubscribeResponse sResponse = await snsClient.SubscribeAsync(sReq);


            if (pnTag == null)
            {
                pnTag                 = new DynamoTag();
                pnTag.Tag             = topicTag;
                pnTag.TaggingTypeEnum = PNTagType.SNSTopic;
                pnTag.SnsTopicArn     = topicArn;
                await tagTableOperator.AddTagAsync(pnTag);
            }

            DynamoSNSTopicTag entry = new DynamoSNSTopicTag
            {
                Tag        = topicTag,
                Subscriber = new Subscriber {
                    UserId = userId, Token = token
                },
                SnsSubscriptionArn = sResponse.SubscriptionArn
            };
            await snsTopicTagTableOperator.AddTagAsync(entry);

            // await tagTableService.IncrementNumberOfSubscribers(pnTag.Tag, 1);
        }
Example #13
0
        private void SetupArnForCreateTopic(Mock <IAmazonSimpleNotificationService> sns,
                                            string topic, string arn)
        {
            var response = new CreateTopicResponse
            {
                TopicArn = arn
            };

            sns
            .Setup(x => x.CreateTopicAsync(topic, It.IsAny <CancellationToken>()))
            .ReturnsAsync(response);
        }
Example #14
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);
        }
Example #15
0
        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);
        }
Example #16
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));
        }
Example #17
0
        private void PublishSNSEvent(string Message, string AmazonSNSKey, string AmazonSNSSecretKey, string TopicName, string EventType)
        {
            string topicname = ProcessSNSTopicName(TopicName);

            try
            {
                var           client        = new AmazonSimpleNotificationServiceClient(AmazonSNSKey, AmazonSNSSecretKey);
                string        topicarn      = string.Empty;
                PublishResult publishResult = new PublishResult();
                if (IsTopicExists(client, topicname, out topicarn))
                {
                    PublishRequest publishRequest = new PublishRequest();
                    publishRequest.Message  = Message;
                    publishRequest.TopicArn = topicarn;
                    PublishResponse publishResponse = client.Publish(publishRequest);
                    publishResult = publishResponse.PublishResult;
                }
                else
                {
                    CreateTopicRequest topicRequest = new CreateTopicRequest();
                    topicRequest.Name = topicname;
                    CreateTopicResponse topicResponse  = client.CreateTopic(topicRequest);
                    CreateTopicResult   result         = topicResponse.CreateTopicResult;
                    PublishRequest      publishRequest = new PublishRequest();
                    publishRequest.Message  = Message;
                    publishRequest.TopicArn = result.TopicArn;
                    PublishResponse publishResponse = client.Publish(publishRequest);
                    publishResult = publishResponse.PublishResult;
                }
                if (!string.IsNullOrEmpty(publishResult.MessageId))
                {
                    CreateLogs(Message, EventType, topicname, true);
                }
            }
            catch (AmazonSimpleNotificationServiceException ex)
            {
                /*Log details to logentries server.*/
                CreateLogs(Message, EventType, topicname, false);
                throw ex;
            }
        }
Example #18
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);
        }
Example #19
0
        /// <summary>
        /// 创建topic
        /// </summary>
        public void CreateTopic()
        {
            // 设置请求对象
            CreateTopicRequest request = new CreateTopicRequest
            {
                Name        = "create_by_zhangyx_test_csharp3",
                DisplayName = "testtyc12020016",
            };

            try
            {
                // 发送请求并返回响应
                CreateTopicResponse response = smnClient.SendRequest(request);
                string result = response.TopicUrn;
                Console.WriteLine("{0}", result);
                Console.ReadLine();
            }
            catch (Exception e)
            {
                // 处理异常
                Console.WriteLine("{0}", e.Message);
            }
        }
Example #20
0
        /// <summary>
        /// Creates a topic with the given name
        /// </summary>
        /// <param name="topicName">Topic name</param>
        /// <returns>Created topic ARN</returns>
        private string CreateTopic(string topicName)
        {
            CreateTopicResponse response = _sns.CreateTopic(topicName);

            return(response.TopicArn);
        }