Beispiel #1
0
        /// <summary>
        /// Unmarshaller the response from the service to the response class.
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public override AmazonWebServiceResponse Unmarshall(XmlUnmarshallerContext context)
        {
            ListSubscriptionsByTopicResponse response = new ListSubscriptionsByTopicResponse();

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

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

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

            return(response);
        }
Beispiel #2
0
        private static void UnmarshallResult(XmlUnmarshallerContext context, ListSubscriptionsByTopicResponse 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("NextToken", targetDepth))
                    {
                        var unmarshaller = StringUnmarshaller.Instance;
                        response.NextToken = unmarshaller.Unmarshall(context);
                        continue;
                    }
                    if (context.TestExpression("Subscriptions/member", targetDepth))
                    {
                        var unmarshaller = SubscriptionUnmarshaller.Instance;
                        var item         = unmarshaller.Unmarshall(context);
                        response.Subscriptions.Add(item);
                        continue;
                    }
                }
            }

            return;
        }
        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);

            ListSubscriptionsByTopicResponse resp = new ListSubscriptionsByTopicResponse();

            do
            {
                ListSubscriptionsByTopicRequest req = new ListSubscriptionsByTopicRequest
                {
                    NextToken = resp.NextToken
                };

                resp = client.ListSubscriptionsByTopic(req);
                CheckError(resp.HttpStatusCode, "200");

                foreach (var obj in resp.Subscriptions)
                {
                    AddObject(obj);
                }
            }while (!string.IsNullOrEmpty(resp.NextToken));
        }
        public Task <IReadOnlyList <Subscription> > ListSubscriptionsByTopicAsync(string topicName)
        {
            if (string.IsNullOrWhiteSpace(topicName))
            {
                throw new ArgumentException($"A non-null/empty '{topicName}' is required.", nameof(topicName));
            }

            return(listSubscriptionsAsync());

            async Task <IReadOnlyList <Subscription> > listSubscriptionsAsync()
            {
                var topic = await _sns.FindTopicAsync(topicName);

                if (topic == null)
                {
                    throw new ArgumentException($"The topic '{topicName}' does not exist.");
                }

                var request = new ListSubscriptionsByTopicRequest
                {
                    TopicArn = topic.TopicArn
                };

                ListSubscriptionsByTopicResponse response = null;

                var subscriptions = new List <Subscription>();

                do
                {
                    response = await _sns.ListSubscriptionsByTopicAsync(request);

                    if (response.HttpStatusCode != HttpStatusCode.OK)
                    {
                        throw new InvalidOperationException($"Unable to list subscriptions for topic '{topicName}'");
                    }

                    subscriptions.AddRange(response.Subscriptions);
                    request.NextToken = response.NextToken;
                } while (response.NextToken != null);

                return(subscriptions);
            }
        }
Beispiel #5
0
        public static async Task <string> FindMatchingSubscription(this IAmazonSimpleNotificationService sns, string topicArn, string queueArn)
        {
            ListSubscriptionsByTopicResponse upToAHundredSubscriptions = null;

            do
            {
                upToAHundredSubscriptions = await sns.ListSubscriptionsByTopicAsync(topicArn, upToAHundredSubscriptions?.NextToken)
                                            .ConfigureAwait(false);

                foreach (var upToAHundredSubscription in upToAHundredSubscriptions.Subscriptions)
                {
                    if (upToAHundredSubscription.Endpoint == queueArn)
                    {
                        return(upToAHundredSubscription.SubscriptionArn);
                    }
                }
            } while (upToAHundredSubscriptions.NextToken != null && upToAHundredSubscriptions.Subscriptions.Count > 0);

            return(null);
        }
Beispiel #6
0
        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);
            }
        }
Beispiel #7
0
        public async Task VerifySubscriptionDeleted(string topicArn, string queueArn)
        {
            ListSubscriptionsByTopicResponse upToAHundredSubscriptions = null;
            Subscription subscription = null;

            do
            {
                upToAHundredSubscriptions = await sns.ListSubscriptionsByTopicAsync(topicArn, upToAHundredSubscriptions?.NextToken)
                                            .ConfigureAwait(false);

                foreach (var upToAHundredSubscription in upToAHundredSubscriptions.Subscriptions)
                {
                    if (upToAHundredSubscription.Endpoint == queueArn)
                    {
                        subscription = upToAHundredSubscription;
                    }
                }
            } while (upToAHundredSubscriptions.NextToken != null && upToAHundredSubscriptions.Subscriptions.Count > 0);

            Assert.IsNull(subscription);
        }
Beispiel #8
0
        public static void SNSListSubscriptionsByTopic()
        {
            #region SNSListSubscriptionsByTopic
            var snsClient = new AmazonSimpleNotificationServiceClient();
            var request   = new ListSubscriptionsByTopicRequest();
            var response  = new ListSubscriptionsByTopicResponse();

            request.TopicArn = "arn:aws:sns:us-east-1:80398EXAMPLE:CodingTestResults";

            do
            {
                response = snsClient.ListSubscriptionsByTopic(request);

                foreach (var sub in response.Subscriptions)
                {
                    Console.WriteLine("Subscription: {0}", sub.SubscriptionArn);

                    var subAttrs = snsClient.GetSubscriptionAttributes(
                        new GetSubscriptionAttributesRequest
                    {
                        SubscriptionArn = sub.SubscriptionArn
                    }).Attributes;

                    if (subAttrs.Count > 0)
                    {
                        foreach (var subAttr in subAttrs)
                        {
                            Console.WriteLine(" -{0} : {1}", subAttr.Key, subAttr.Value);
                        }
                    }

                    Console.WriteLine();
                }

                request.NextToken = response.NextToken;
            } while (!string.IsNullOrEmpty(response.NextToken));
            #endregion

            Console.ReadLine();
        }
        public static async Task <string> FindMatchingSubscription(this IAmazonSimpleNotificationService snsClient, QueueCache queueCache, Topic topic, string queueName)
        {
            var physicalQueueName = queueCache.GetPhysicalQueueName(queueName);

            ListSubscriptionsByTopicResponse upToAHundredSubscriptions = null;

            do
            {
                upToAHundredSubscriptions = await snsClient.ListSubscriptionsByTopicAsync(topic.TopicArn, upToAHundredSubscriptions?.NextToken)
                                            .ConfigureAwait(false);

                // ReSharper disable once ForeachCanBePartlyConvertedToQueryUsingAnotherGetEnumerator
                foreach (var upToAHundredSubscription in upToAHundredSubscriptions.Subscriptions)
                {
                    if (upToAHundredSubscription.Endpoint.EndsWith($":{physicalQueueName}", StringComparison.Ordinal))
                    {
                        return(upToAHundredSubscription.SubscriptionArn);
                    }
                }
            } while (upToAHundredSubscriptions.NextToken != null && upToAHundredSubscriptions.Subscriptions.Count > 0);

            return(null);
        }
Beispiel #10
0
        private static void UnmarshallResult(XmlUnmarshallerContext context, ListSubscriptionsByTopicResponse response)
        {
            int originalDepth = context.CurrentDepth;
            int targetDepth   = originalDepth + 1;

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

            while (context.Read())
            {
                if (context.IsStartElement || context.IsAttribute)
                {
                    if (context.TestExpression("Subscriptions/member", targetDepth))
                    {
                        response.Subscriptions.Add(SubscriptionUnmarshaller.GetInstance().Unmarshall(context));

                        continue;
                    }
                    if (context.TestExpression("NextToken", targetDepth))
                    {
                        response.NextToken = StringUnmarshaller.GetInstance().Unmarshall(context);

                        continue;
                    }
                }
                else if (context.IsEndElement && context.CurrentDepth < originalDepth)
                {
                    return;
                }
            }



            return;
        }
Beispiel #11
0
        /// <summary>
        /// 分页获取特定主题的订阅列表
        /// </summary>
        public void ListSubscriptionsByTopic()
        {
            // 设置请求对象
            ListSubscriptionsByTopicRequest request = new ListSubscriptionsByTopicRequest
            {
                Limit    = 5,
                Offset   = 0,
                TopicUrn = "urn:smn:cn-north-1:cffe4fc4c9a54219b60dbaf7b586e132:SmnApi"
            };

            try
            {
                // 发送请求并返回响应
                ListSubscriptionsByTopicResponse response = smnClient.SendRequest(request);
                int result = response.SubscriptionCount;
                Console.WriteLine("{0}", result);
                Console.ReadLine();
            }
            catch (Exception e)
            {
                // 处理异常
                Console.WriteLine("{0}", e.Message);
            }
        }
        public string Remove(Notification input, ILambdaContext context)
        {
            var region = RegionEndpoint.APSoutheast1;

            var topicId = input.TopicId;

            //Get item from DynamoDB
            var key = new Dictionary <string, AttributeValue>();

            key.Add("id", new AttributeValue()
            {
                S = topicId
            });

            var dynamoDBClient  = new AmazonDynamoDBClient(region);
            var getItemResponse = dynamoDBClient.GetItemAsync("Topics", key).Result;

            if (getItemResponse.HttpStatusCode != HttpStatusCode.OK)
            {
                throw new TestDonkeyException("Can't find item");
            }

            var item = getItemResponse.Item;

            var topicArn = item.GetValueOrDefault("arn").S;

            //Remove permission to accept CloudWatch Events trigger for Lambda
            var lambdaClient = new AmazonLambdaClient(region);

            var removePermissionRequest = new Amazon.Lambda.Model.RemovePermissionRequest();

            removePermissionRequest.FunctionName = "TestDonkeyLambda";
            removePermissionRequest.StatementId  = $"testdonkey-lambda-{ topicId }";

            var removePermissionResponse = lambdaClient.RemovePermissionAsync(removePermissionRequest).Result;

            if (removePermissionResponse.HttpStatusCode != HttpStatusCode.NoContent)
            {
                throw new TestDonkeyException("Can't remove permission");
            }

            //Remove target for CloudWatch Events
            var cloudWatchEventClient = new AmazonCloudWatchEventsClient(region);

            var removeTargetsRequest = new RemoveTargetsRequest();

            removeTargetsRequest.Ids = new List <string> {
                $"testdonkey-target-{ topicId }"
            };
            removeTargetsRequest.Rule = $"testdonkey-rule-{ topicId }";

            var removeTargetsResponse = cloudWatchEventClient.RemoveTargetsAsync(removeTargetsRequest).Result;

            if (removeTargetsResponse.HttpStatusCode != HttpStatusCode.OK)
            {
                throw new TestDonkeyException("Can't remove target");
            }

            //Delete rule in CloudWatch Events
            var deleteRuleRequest = new DeleteRuleRequest();

            deleteRuleRequest.Name = removeTargetsRequest.Rule;

            var deleteRuleResponse = cloudWatchEventClient.DeleteRuleAsync(deleteRuleRequest).Result;

            if (deleteRuleResponse.HttpStatusCode != HttpStatusCode.OK)
            {
                throw new TestDonkeyException("Can't delete rule");
            }

            //Remove subscribers from SNS
            var snsClient = new AmazonSimpleNotificationServiceClient(region);

            var listSubscriptionsByTopicRequest = new ListSubscriptionsByTopicRequest();

            listSubscriptionsByTopicRequest.TopicArn = topicArn;

            ListSubscriptionsByTopicResponse listSubscriptionsByTopicResponse = null;

            do
            {
                listSubscriptionsByTopicResponse = snsClient.ListSubscriptionsByTopicAsync(listSubscriptionsByTopicRequest).Result;
                if (listSubscriptionsByTopicResponse.HttpStatusCode != HttpStatusCode.OK)
                {
                    throw new TestDonkeyException("Can't list subscriptions");
                }

                if (listSubscriptionsByTopicResponse.Subscriptions != null && listSubscriptionsByTopicResponse.Subscriptions.Count > 0)
                {
                    foreach (var subscription in listSubscriptionsByTopicResponse.Subscriptions)
                    {
                        if (!subscription.SubscriptionArn.Equals("pendingconfirmation", StringComparison.OrdinalIgnoreCase))
                        {
                            snsClient.UnsubscribeAsync(subscription.SubscriptionArn).GetAwaiter().GetResult();
                        }
                    }
                }

                listSubscriptionsByTopicRequest.NextToken = listSubscriptionsByTopicResponse.NextToken;

                Thread.Sleep(1_000); //Wait for 1 second. Throttle: 100 transactions per second (TPS)
            } while (!string.IsNullOrWhiteSpace(listSubscriptionsByTopicResponse.NextToken));

            //Delete topic from SNS
            var deleteTopicResponse = snsClient.DeleteTopicAsync(topicArn).Result;

            if (deleteTopicResponse.HttpStatusCode != HttpStatusCode.OK)
            {
                throw new TestDonkeyException("Can't delete topic");
            }

            //Delete item from DynamoDB
            var dynamoDBDeleteItemResponse = dynamoDBClient.DeleteItemAsync("Topics", key).Result;

            if (dynamoDBDeleteItemResponse.HttpStatusCode != HttpStatusCode.OK)
            {
                throw new TestDonkeyException("Can't delete item");
            }

            return("success");
        }