예제 #1
0
        async Task <GetQueueAttributesResponse> GetQueueAttributesFromDelayedDeliveryQueueWithRetriesToWorkaroundSDKIssue()
        {
            var attributeNames = new List <string>
            {
                "DelaySeconds",
                "MessageRetentionPeriod",
                "RedrivePolicy"
            };

            GetQueueAttributesResponse queueAttributes = null;

            for (var i = 0; i < 4; i++)
            {
                queueAttributes = await sqsClient.GetQueueAttributesAsync(delayedDeliveryQueueUrl, attributeNames)
                                  .ConfigureAwait(false);

                if (queueAttributes.DelaySeconds != 0)
                {
                    break;
                }

                await Task.Delay(TimeSpan.FromSeconds(i))
                .ConfigureAwait(false);
            }

            return(queueAttributes);
        }
        private GetQueueAttributesResult GetTaskQueueAttr(Priority oPriority)
        {
            string strUrlQueue = GetQueueUrl(oPriority);

            GetQueueAttributesResult oGetQueueAttributesResult = null;

            try
            {
                using (AmazonSQS oSQSClient = AWSClientFactory.CreateAmazonSQSClient())
                {
                    GetQueueAttributesRequest oGetQueueAttributesRequest = new GetQueueAttributesRequest();
                    oGetQueueAttributesRequest.QueueUrl = strUrlQueue;

                    GetQueueAttributesResponse oGetQueueAttributesResponse = oSQSClient.GetQueueAttributes(oGetQueueAttributesRequest);
                    if (oGetQueueAttributesResponse.IsSetGetQueueAttributesResult())
                    {
                        oGetQueueAttributesResult = oGetQueueAttributesResponse.GetQueueAttributesResult;
                    }
                }
            }
            catch (AmazonSQSException)
            {
            }
            catch
            {
            }

            return(oGetQueueAttributesResult);
        }
        private static void UnmarshallResult(XmlUnmarshallerContext context, GetQueueAttributesResponse 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("Attribute", targetDepth))
                    {
                        KeyValueUnmarshaller <string, string, StringUnmarshaller, StringUnmarshaller> unmarshaller = new KeyValueUnmarshaller <string, string, StringUnmarshaller, StringUnmarshaller>(StringUnmarshaller.GetInstance(), StringUnmarshaller.GetInstance());
                        KeyValuePair <string, string> kvp = unmarshaller.Unmarshall(context);
                        response.Attributes.Add(kvp.Key, kvp.Value);
                        continue;
                    }
                }
                else if (context.IsEndElement && context.CurrentDepth < originalDepth)
                {
                    return;
                }
            }



            return;
        }
        protected async Task <CreateQueueResponse> CreateQueue(string queueName = null, string dlQueueName = null)
        {
            var createDlqRequest = new CreateQueueRequest {
                QueueName = dlQueueName ?? TestDlQueueName, Attributes = new Dictionary <string, string> {
                    { "FifoQueue", "true" },
                }
            };

            CreateQueueResponse createDlqResult = await AmazonSqs.CreateQueueAsync(createDlqRequest);

            GetQueueAttributesResponse attributes = await AmazonSqs.GetQueueAttributesAsync(new GetQueueAttributesRequest
            {
                QueueUrl       = createDlqResult.QueueUrl,
                AttributeNames = new List <string> {
                    "QueueArn"
                }
            });

            var redrivePolicy = new { maxReceiveCount = "1", deadLetterTargetArn = attributes.Attributes["QueueArn"] };

            var createQueueRequest = new CreateQueueRequest
            {
                QueueName  = queueName ?? TestQueueName,
                Attributes = new Dictionary <string, string> {
                    { "FifoQueue", "true" }, { "RedrivePolicy", JsonSerializer.Serialize(redrivePolicy) },
                }
            };

            return(await AmazonSqs.CreateQueueAsync(createQueueRequest));
        }
예제 #5
0
        /// <summary>
        /// Returns the approximate number of queued messages
        /// </summary>
        public int ApproximateNumberOfMessages()
        {
            ClearErrorInfo();

            int result = 0;

            try
            {
                GetQueueAttributesRequest attrreq = new GetQueueAttributesRequest();
                attrreq.QueueUrl = queueurl.QueueUrl;
                attrreq.AttributeNames.Add("ApproximateNumberOfMessages");
                GetQueueAttributesResponse attrresp = queue.GetQueueAttributes(attrreq);
                if (attrresp != null)
                {
                    result = attrresp.ApproximateNumberOfMessages;
                }
            }
            catch (Exception ex)
            {
                ErrorCode    = e_Exception;
                ErrorMessage = ex.Message;
            }

            return(result);
        }
예제 #6
0
        /// <summary>
        /// The callback for the Get-Queue-Attribute action.
        /// </summary>
        /// <param name="result">The <see cref="ISQSResponse"/> instance.</param>
        void GetQueueAttributeResponse(object sender, ResponseEventArgs args)
        {
            AmazonSQSException sqsResponse = args.Response as AmazonSQSException;

            sqs.OnSQSResponse -= GetQueueAttributeResponse;
            if (null != sqsResponse)
            {
                SQSErrorResponse(sqsResponse);
                this.Dispatcher.BeginInvoke(() =>
                {
                    this.AttributeValue = "Error getting attribute.";
                });
                return;
            }
            GetQueueAttributesResponse response = args.Response as GetQueueAttributesResponse;

            if (null == response)
            {
                return;
            }

            if (response.GetQueueAttributesResult.Attribute.Count > 0)
            {
                this.Dispatcher.BeginInvoke(() => this.AttributeValue =
                                                response.GetQueueAttributesResult.Attribute[0].Value);
            }
        }
        /// <summary>
        /// Helper method for AuthorizeS3ToSendMessage()
        /// </summary>
        /// <param name="response"></param>
        /// <param name="bucket"></param>
        /// <param name="policy"></param>
        /// <param name="statement"></param>
        private static void GetNewPolicyAndStatement(GetQueueAttributesResponse response, string bucket, out Policy policy, out Statement statement)
        {
            if (!string.IsNullOrEmpty(response.Policy))
            {
                policy = Policy.FromJson(response.Policy);
            }
            else
            {
                policy = new Policy();
            }

            var sourceArn = string.Format(CultureInfo.InvariantCulture, "arn:aws:s3:*:*:{0}", bucket);

            statement = new Statement(Statement.StatementEffect.Allow);
            statement.Actions.Add(SQSActionIdentifiers.SendMessage);
            statement.Resources.Add(new Resource(response.QueueARN));
            statement.Principals.Add(new Principal("*"));
            statement.Conditions.Add(ConditionFactory.NewSourceArnCondition(sourceArn));


            // If the arn doesn't have the required tokens then it is most likely be called from a mock or fake AWS service.
            // Since this is an existing method we don't want to introduce a new exception. So if there is no account id then
            // don't add the extra condition.
            if (Arn.TryParse(response.QueueARN, out Arn arn) && !string.IsNullOrEmpty(arn.AccountId))
            {
                statement.Conditions.Add(ConditionFactory.NewCondition(ConditionFactory.StringComparisonType.StringEquals, ConditionFactory.SOURCE_ACCOUNT_KEY, arn.AccountId));
            }
        }
예제 #8
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)
        {
            GetQueueAttributesResponse response = new GetQueueAttributesResponse();

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

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

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

            return(response);
        }
예제 #9
0
        private static void UnmarshallResult(XmlUnmarshallerContext context, GetQueueAttributesResponse 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("Attribute", targetDepth))
                    {
                        var unmarshaller = new KeyValueUnmarshaller <string, string, StringUnmarshaller, StringUnmarshaller>(StringUnmarshaller.Instance, StringUnmarshaller.Instance);
                        var item         = unmarshaller.Unmarshall(context);
                        response.Attributes.Add(item);
                        continue;
                    }
                }
            }

            return;
        }
예제 #10
0
        public override async Task <int> GetMessageCountAsync()
        {
            GetQueueAttributesResponse attrs = await _client.GetQueueAttributesAsync(_queueUrl, new List <string> {
                "All"
            }).ConfigureAwait(false);

            return(attrs.ApproximateNumberOfMessages);
        }
예제 #11
0
        //
        // Method to get the ARN of a queue
        private static async Task <string> GetQueueArn(IAmazonSQS sqsClient, string qUrl)
        {
            GetQueueAttributesResponse responseGetAtt = await sqsClient.GetQueueAttributesAsync(
                qUrl, new List <string> {
                QueueAttributeName.QueueArn
            });

            return(responseGetAtt.QueueARN);
        }
        static void SetupTopicAndQueue(Amazon.RegionEndpoint region)
        {
            long ticks = DateTime.Now.Ticks;

            // Setup SNS topic.
            s_snsClient = new AmazonSimpleNotificationServiceClient(region);
            s_sqsClient = new AmazonSQSClient(region);

            s_topicArn = s_snsClient.CreateTopic(new CreateTopicRequest
            {
                Name = "GlacierDownload-" + ticks
            }).TopicArn;

            WriteLogConsole("topicArn: " + s_topicArn);

            CreateQueueRequest createQueueRequest = new CreateQueueRequest();

            createQueueRequest.QueueName = "GlacierDownload-" + ticks;
            CreateQueueResponse createQueueResponse = s_sqsClient.CreateQueue(createQueueRequest);

            s_queueUrl = createQueueResponse.QueueUrl;

            WriteLogConsole("QueueURL: " + s_queueUrl);

            GetQueueAttributesRequest getQueueAttributesRequest = new GetQueueAttributesRequest();

            getQueueAttributesRequest.AttributeNames = new List <string> {
                "QueueArn"
            };
            getQueueAttributesRequest.QueueUrl = s_queueUrl;

            GetQueueAttributesResponse response = s_sqsClient.GetQueueAttributes(getQueueAttributesRequest);

            s_queueArn = response.QueueARN;
            WriteLogConsole("QueueArn: " + s_queueArn);

            // Setup the Amazon SNS topic to publish to the SQS queue.
            s_snsClient.Subscribe(new SubscribeRequest()
            {
                Protocol = "sqs",
                Endpoint = s_queueArn,
                TopicArn = s_topicArn
            });

            // Add the policy to the queue so SNS can send messages to the queue.
            var policy = SQS_POLICY.Replace("{TopicArn}", s_topicArn).Replace("{QuernArn}", s_queueArn);

            s_sqsClient.SetQueueAttributes(new SetQueueAttributesRequest()
            {
                QueueUrl   = s_queueUrl,
                Attributes = new Dictionary <string, string>
                {
                    { QueueAttributeName.Policy, policy }
                }
            });
        }
        /// <summary>
        /// Gets the Queue's attributes
        /// </summary>
        /// <param name="client"></param>
        /// <param name="queueUrl"></param>
        /// <returns></returns>
        /// <remarks>
        /// All - returns all values.
        /// ApproximateNumberOfMessages — returns the approximate number of visible messages in a queue. For more information, see Resources Required to Process Messages in the Amazon SQS Developer Guide.
        /// ApproximateNumberOfMessagesNotVisible — returns the approximate number of messages that are not timed-out and not deleted. For more information, see Resources Required to Process Messages in the Amazon SQS Developer Guide.
        /// VisibilityTimeout — returns the visibility timeout for the queue. For more information about visibility timeout, see Visibility Timeout in the Amazon SQS Developer Guide.
        /// CreatedTimestamp — returns the time when the queue was created (epoch time in seconds).
        /// LastModifiedTimestamp — returns the time when the queue was last changed (epoch time in seconds).
        /// Policy — returns the queue's policy.
        /// MaximumMessageSize — returns the limit of how many bytes a message can contain before Amazon SQS rejects it.
        /// MessageRetentionPeriod — returns the number of seconds Amazon SQS retains a message.
        /// QueueArn — returns the queue's Amazon resource name (ARN).
        /// </remarks>
        public GetQueueAttributesResult GetQueueAttributes(AmazonSQS client, string queueUrl)
        {
            var request = new GetQueueAttributesRequest {
                QueueUrl = queueUrl, AttributeName = new List <string>(new[] { "All" })
            };

            GetQueueAttributesResponse response = client.GetQueueAttributes(request);

            return(response.GetQueueAttributesResult);
        }
예제 #14
0
        public bool HasAnyMessagesInQueue()
        {
            GetQueueAttributesRequest request = new GetQueueAttributesRequest(this.queueUrl, new List <string> ()
            {
                "ApproximateNumberOfMessages"
            });
            GetQueueAttributesResponse response = this.sqsClient.GetQueueAttributes(request);

            bool hasAnyMessagesInQueue = response.ApproximateNumberOfMessages > 0;

            return(hasAnyMessagesInQueue);
        }
예제 #15
0
        static void SetupTopicAndQueue(Amazon.RegionEndpoint awsRegion)
        {
            long ticks = DateTime.Now.Ticks;

            // Setup SNS topic.
            snsClient = new AmazonSimpleNotificationServiceClient(awsRegion);
            sqsClient = new AmazonSQSClient(awsRegion);

            topicArn = snsClient.CreateTopic(new CreateTopicRequest {
                Name = "GlacierInventory-" + ticks
            }).TopicArn;
            Console.WriteLine($"topicArn: {topicArn}");

            CreateQueueRequest createQueueRequest = new CreateQueueRequest();

            createQueueRequest.QueueName = "GlacierInventory-" + ticks;
            CreateQueueResponse createQueueResponse = sqsClient.CreateQueue(createQueueRequest);

            queueUrl = createQueueResponse.QueueUrl;
            Console.WriteLine($"QueueURL: {queueUrl}");

            GetQueueAttributesRequest getQueueAttributesRequest = new GetQueueAttributesRequest();

            getQueueAttributesRequest.AttributeNames = new List <string> {
                "QueueArn"
            };
            getQueueAttributesRequest.QueueUrl = queueUrl;
            GetQueueAttributesResponse response = sqsClient.GetQueueAttributes(getQueueAttributesRequest);

            queueArn = response.QueueARN;
            Console.WriteLine($"QueueArn: {queueArn}");

            // Setup the Amazon SNS topic to publish to the SQS queue.
            snsClient.Subscribe(new SubscribeRequest()
            {
                Protocol = "sqs",
                Endpoint = queueArn,
                TopicArn = topicArn
            });

            // Add the policy to the queue so SNS can send messages to the queue.
            var policy = SQS_POLICY.Replace("{TopicArn}", topicArn).Replace("{QuernArn}", queueArn).Replace("{AccountArn}", accountArn);

            sqsClient.SetQueueAttributes(new SetQueueAttributesRequest()
            {
                QueueUrl   = queueUrl,
                Attributes = new Dictionary <string, string>
                {
                    { QueueAttributeName.Policy, policy }
                }
            });
        }
        public GetQueueAttributesResponse GetQueueAttributes(string queueUrl)
        {
            List <string> list = new List <string>();

            list.Add("All");

            GetQueueAttributesRequest getQueueAttributesRequest = new GetQueueAttributesRequest {
                QueueUrl = queueUrl, AttributeNames = list
            };
            GetQueueAttributesResponse getQueueAttributesResponse = SQSClient.GetQueueAttributes(getQueueAttributesRequest);

            return(getQueueAttributesResponse);
        }
예제 #17
0
        //
        // Method to show all attributes of a queue
        private static async Task ShowAllAttributes(IAmazonSQS sqsClient, string qUrl)
        {
            var attributes = new List <string> {
                QueueAttributeName.All
            };
            GetQueueAttributesResponse responseGetAtt =
                await sqsClient.GetQueueAttributesAsync(qUrl, attributes);

            Console.WriteLine($"Queue: {qUrl}");
            foreach (var att in responseGetAtt.Attributes)
            {
                Console.WriteLine($"\t{att.Key}: {att.Value}");
            }
        }
예제 #18
0
        private static int NumbersOfMessagesInQueue(string queueUrl, AmazonSQSClient sqsClient)
        {
            GetQueueAttributesRequest attReq = new GetQueueAttributesRequest();

            attReq.QueueUrl = queueUrl;
            attReq.AttributeNames.Add("ApproximateNumberOfMessages");

            GetQueueAttributesResponse response =
                Task.Run(async() => await sqsClient.GetQueueAttributesAsync(attReq)).Result;

            var retval = response.ApproximateNumberOfMessages;

            return(retval);
        }
예제 #19
0
        private string GetQueueArn(AmazonSQS client, string queueUrl)
        {
            var request = new GetQueueAttributesRequest {
                QueueUrl = queueUrl, AttributeName = new List <string>(new[] { "QueueArn" })
            };
            GetQueueAttributesResponse response = client.GetQueueAttributes(request);

            if (response.IsSetGetQueueAttributesResult())
            {
                return(response.GetQueueAttributesResult.Attribute.Where(x => x.Name == "QueueArn").First().Value);
            }

            throw new Exception("No SetQueueAttribute result");
        }
예제 #20
0
        public async Task <string> GetQueueArn(IAmazonSQS sqsClient, string queueUrl)
        {
            try
            {
                GetQueueAttributesResponse responseGetAtt = await sqsClient.GetQueueAttributesAsync(
                    queueUrl, new List <string> {
                    QueueAttributeName.QueueArn
                });

                return(responseGetAtt.QueueARN);
            }
            catch (Exception e)
            {
                Console.WriteLine($"Get Queue Arn failed: {e}");
                throw;
            }
        }
예제 #21
0
        public static int Count(string queue_url)
        {
            AmazonSQS sqs = AWSClientFactory.CreateAmazonSQSClient();
            GetQueueAttributesRequest gqreq = new GetQueueAttributesRequest();

            gqreq.QueueUrl = queue_url;
            List <string> attr = new List <string>();

            attr.Add("All");
            gqreq.AttributeName = attr;
            GetQueueAttributesResponse gqres = sqs.GetQueueAttributes(gqreq);
            GetQueueAttributesResult   gqrst = gqres.GetQueueAttributesResult;

            //Console.WriteLine("Invisible Messages:" + gqrst.ApproximateNumberOfMessagesNotVisible.ToString());
            //Console.WriteLine("Messages:" + gqrst.ApproximateNumberOfMessages);
            return(gqrst.ApproximateNumberOfMessages);
        }
        /// <summary>
        /// Helper method for AuthorizeS3ToSendMessage()
        /// </summary>
        /// <param name="response"></param>
        /// <param name="bucket"></param>
        /// <param name="policy"></param>
        /// <param name="statement"></param>
        private static void GetNewPolicyAndStatement(GetQueueAttributesResponse response, string bucket, out Policy policy, out Statement statement)
        {
            if (!string.IsNullOrEmpty(response.Policy))
            {
                policy = Policy.FromJson(response.Policy);
            }
            else
            {
                policy = new Policy();
            }

            var sourceArn = string.Format(CultureInfo.InvariantCulture, "arn:aws:s3:*:*:{0}", bucket);

            statement = new Statement(Statement.StatementEffect.Allow);
            statement.Actions.Add(SQSActionIdentifiers.SendMessage);
            statement.Resources.Add(new Resource(response.QueueARN));
            statement.Conditions.Add(ConditionFactory.NewSourceArnCondition(sourceArn));
            statement.Principals.Add(new Principal("*"));
        }
        public async System.Threading.Tasks.Task <GetQueueAttributesResponse> GetQueueAttributes(string queueUrl)
        {
            GetQueueAttributesResponse queueAttributesResponse = new GetQueueAttributesResponse();

            using (AmazonSQSClient sqsClient = new AmazonSQSClient(credentials, Amazon.RegionEndpoint.USEast2))
            {
                GetQueueAttributesRequest request = new GetQueueAttributesRequest
                {
                    QueueUrl       = queueUrl,
                    AttributeNames = new List <string>()
                    {
                        "All"
                    }
                };
                queueAttributesResponse = await sqsClient.GetQueueAttributesAsync(request);
            }

            return(queueAttributesResponse);
        }
예제 #24
0
        public void Test_GetQueueAttributes_And_Check_For_Valid_Value()
        {
            bool   hasCallbackArrived = false;
            string actualValue        = "-1";
            string expectedValue      = "3";

            SQSResponseEventHandler <object, ResponseEventArgs> handler = null;

            handler = delegate(object sender, ResponseEventArgs args)
            {
                ISQSResponse result = args.Response;
                //Unhook from event.
                _client.OnSQSResponse -= handler;
                GetQueueAttributesResponse response = result as GetQueueAttributesResponse;
                if (null != response)
                {
                    GetQueueAttributesResult attributeResult = response.GetQueueAttributesResult;
                    if (null != attributeResult)
                    {
                        if (response.GetQueueAttributesResult.Attribute.Count > 0)
                        {
                            actualValue = response.GetQueueAttributesResult.Attribute[0].Value;
                        }
                    }
                }

                hasCallbackArrived = true;
            };

            //Hook to event
            _client.OnSQSResponse += handler;

            //Create request object.
            GetQueueAttributesRequest request = new GetQueueAttributesRequest();

            request.QueueUrl = string.Format("{0}/{1}", QueueURL, _queue_UnitTesting);
            request.AttributeName.Add("VisibilityTimeout");
            _client.GetQueueAttributes(request);

            EnqueueConditional(() => hasCallbackArrived);
            EnqueueCallback(() => Assert.IsTrue(expectedValue == actualValue));
            EnqueueTestComplete();
        }
예제 #25
0
        public async void GetQueueAttributesWithDegradation_Test()
        {
            var request = new GetQueueAttributesRequest();

            var message = new GetQueueAttributesResponse
            {
                HttpStatusCode = HttpStatusCode.OK
            };

            amazonSQSMock
            .Setup(e => e.GetQueueAttributesAsync(request, cancellationToken))
            .ReturnsAsync(message);

            var response = await target.GetQueueAttributesWithDegradation(request, cancellationToken);

            response.Should().NotBeNull();
            response.Should().Be(message);

            amazonSQSMock.VerifyAll();
        }
        /// <summary>
        /// Displays the attributes passed to the method on the console.
        /// </summary>
        /// <param name="attrs">The attributes for the Amazon SQS queue.</param>
        public static void DisplayAttributes(GetQueueAttributesResponse attrs)
        {
            Console.WriteLine($"Attributes for queue ARN '{attrs.QueueARN}':");
            Console.WriteLine($"  Approximate number of messages: {attrs.ApproximateNumberOfMessages}");
            Console.WriteLine($"  Approximate number of messages delayed: {attrs.ApproximateNumberOfMessagesDelayed}");
            Console.WriteLine($"  Approximate number of messages not visible: {attrs.ApproximateNumberOfMessagesNotVisible}");
            Console.WriteLine($"  Queue created on: {attrs.CreatedTimestamp}");
            Console.WriteLine($"  Delay seconds: {attrs.DelaySeconds}");
            Console.WriteLine($"  Queue last modified on: {attrs.LastModifiedTimestamp}");
            Console.WriteLine($"  Maximum message size: {attrs.MaximumMessageSize}");
            Console.WriteLine($"  Message retention period: {attrs.MessageRetentionPeriod}");
            Console.WriteLine($"  Visibility timeout: {attrs.VisibilityTimeout}");
            Console.WriteLine($"  Policy: {attrs.Policy}\n");
            Console.WriteLine("  Attributes:");

            foreach (var attr in attrs.Attributes)
            {
                Console.WriteLine($"    {attr.Key}: {attr.Value}");
            }
        }
예제 #27
0
        /// <summary>
        /// Get the number of items in an SQS queue
        /// </summary>
        /// <param name="QueueUrl">The SQS queue URL</param>
        /// <returns>Number of messages in the queue. Returns zero in the event of an error.</returns>
        public int GetSQSQueueCount(string QueueUrl)
        {
            if (!IsSQSValid)
            {
                return(0);
            }

            GetQueueAttributesRequest AttribRequest = new GetQueueAttributesRequest
            {
                QueueUrl       = QueueUrl,
                AttributeNames = new List <string>
                {
                    "ApproximateNumberOfMessages"
                }
            };

            GetQueueAttributesResponse AttribResponse = SqsClient.GetQueueAttributes(AttribRequest);

            return(AttribResponse.ApproximateNumberOfMessages);
        }
예제 #28
0
        public async Task <GetQueueAttributesResponse> GetQueueAttributesWithDegradation(GetQueueAttributesRequest request, CancellationToken cancellationToken)
        {
            var       failedAttemptCount        = 0;
            Exception lastException             = null;
            GetQueueAttributesResponse response = null;

            while (failedAttemptCount < 10 && !cancellationToken.IsCancellationRequested)
            {
                var delayTime = SuspendTimeInMilliseconds(failedAttemptCount);

                if (delayTime > 0)
                {
                    await Task.Delay(delayTime, cancellationToken);
                }

                try
                {
                    response = await sqsClient.GetQueueAttributesAsync(request, cancellationToken);

                    if (response?.HttpStatusCode == HttpStatusCode.OK)
                    {
                        return(response);
                    }

                    lastException = new HttpRequestException($"Got HttpStatusCode {response?.HttpStatusCode} by request");
                    failedAttemptCount++;
                }
                catch (AmazonSQSException ex)
                {
                    lastException = ex;
                    failedAttemptCount++;
                }
            }

            if (cancellationToken.IsCancellationRequested)
            {
                return(null);
            }

            throw new GetResponseFailedException(lastException);
        }
예제 #29
0
        public virtual string GetQueueArn(AmazonSQSClient sqsClient, string queueUrl)
        {
            string queueArn;
            // Construct a GetQueueAttributesRequest for the URL to retrieve the ARN
            var getQueueAttributesRequest = new GetQueueAttributesRequest
            {
                QueueUrl       = queueUrl,
                AttributeNames =
                {
                    "QueueArn"
                }
            };

            // Submit the request
            GetQueueAttributesResponse getQueueAttributesResponse =
                sqsClient.GetQueueAttributes(getQueueAttributesRequest);

            // Add the discovered ARN to the queueArnList variable.
            queueArn = getQueueAttributesResponse.QueueARN;
            return(queueArn);
        }
예제 #30
0
        public async Task <long> GetMessageCountAsync(string channelName, CancellationToken cancellationToken = default)
        {
            if (channelName is null)
            {
                throw new ArgumentNullException(nameof(channelName));
            }

            try
            {
                GetQueueAttributesResponse attributes =
                    await _client.GetQueueAttributesAsync(GetQueueUri(channelName), new List <string> {
                    "All"
                }, cancellationToken).ConfigureAwait(false);

                return(attributes.ApproximateNumberOfMessages);
            }
            catch (AmazonSQSException ex) when(ex.ErrorCode == "AWS.SimpleQueueService.NonExistentQueue")
            {
                return(0);
            }
        }