public override WebServiceResponse Unmarshall(XmlUnmarshallerContext context) { var response = new CreateQueueResponse(); if (context.ResponseData.IsHeaderPresent(HttpHeader.LocationHeader)) response.QueueUrl = context.ResponseData.GetHeaderValue(HttpHeader.LocationHeader); return response; }
public void CreateQueue(AmazonSQSClient client) { CreateQueueRequest createDlqRequest = new CreateQueueRequest { QueueName = "ArmutLocalStack-Test-DLQ.fifo", Attributes = new Dictionary <string, string> { { "FifoQueue", "true" }, } }; CreateQueueResponse createDlqResult = client.CreateQueueAsync(createDlqRequest).GetAwaiter().GetResult(); var attributes = client.GetQueueAttributesAsync(new GetQueueAttributesRequest { QueueUrl = createDlqResult.QueueUrl, AttributeNames = new List <string> { "QueueArn" } }).GetAwaiter().GetResult(); var redrivePolicy = new { maxReceiveCount = "1", deadLetterTargetArn = attributes.Attributes["QueueArn"] }; CreateQueueRequest createQueueRequest = new CreateQueueRequest { QueueName = "ArmutLocalStack-Test.fifo", Attributes = new Dictionary <string, string> { { "FifoQueue", "true" }, { "RedrivePolicy", JsonSerializer.Serialize(redrivePolicy) }, } }; CreateQueueResponse createQueueResult = client.CreateQueueAsync(createQueueRequest).GetAwaiter().GetResult(); }
public async Task TestGetQueueUrl() { string queueName = UtilityMethods.GenerateName("TestGetQueueUrl"); CreateQueueResponse createResponse = await Client.CreateQueueAsync(new CreateQueueRequest() { QueueName = queueName }); _queueUrls.Add(createResponse.QueueUrl); GetQueueUrlRequest request = new GetQueueUrlRequest() { QueueName = queueName }; GetQueueUrlResponse response = await Client.GetQueueUrlAsync(request); Assert.Equal(createResponse.QueueUrl, response.QueueUrl); }
public async Task Queueが存在しないときBuildにより指定したQueue名のQueueが作成されURLが取得できること() { _clientMock.Setup(c => c.GetQueueUrlAsync(It.IsAny <string>(), CancellationToken.None)) .Throws(new QueueDoesNotExistException("test_message")); var createQueueResponse = new CreateQueueResponse() { QueueUrl = "fuga" }; _clientMock.Setup(c => c.CreateQueueAsync(It.IsAny <CreateQueueRequest>(), CancellationToken.None)) .ReturnsAsync(createQueueResponse); var actual = await QueueUrl.Build(_clientMock.Object, "test", new Dictionary <string, string>()); Assert.NotNull(actual); Assert.Equal(createQueueResponse.QueueUrl, actual.Value); }
public async Task TestCreateSameQueueTwiceAsync() { // Create the queue queueName = setQueueName(); CreateQueueResponse createResponse = await sqsClient.CreateQueueAsync(queueName); // Get the queue list. Assert is added to make sure that the queue is created and make sure that we only create 1 queue var sqsQueueList = sqsClient.ListQueuesAsync(prefix); Assert.IsTrue(sqsQueueList.Result.QueueUrls.Count == 1, "Queue is not created or more than one queue is created"); // Create another queue that have the same name createResponse = await sqsClient.CreateQueueAsync(queueName); // Verify there are only 1 queue created sqsQueueList = sqsClient.ListQueuesAsync(prefix); Assert.IsFalse(sqsQueueList.Result.QueueUrls.Count == 2, "Extra queue was added in the list"); }
public async System.Threading.Tasks.Task <CreateQueueResponse> CreateSQS(string queueName) { CreateQueueResponse createQueueResponse = new CreateQueueResponse(); using (AmazonSQSClient sqsClient = new AmazonSQSClient(credentials, Amazon.RegionEndpoint.USEast2)) { CreateQueueRequest request = new CreateQueueRequest { QueueName = queueName, Attributes = new Dictionary <string, string> { { "VisibilityTimeout", "20" } } }; createQueueResponse = await sqsClient.CreateQueueAsync(request); } return(createQueueResponse); }
public override T Unmarshall <T>(IResponseContext context) { try { var response = new CreateQueueResponse(); ResultUnmarshall(context, response); var xmlRootNode = GetXmlElement(context.ContentStream); response.QueueUrl = xmlRootNode.SelectSingleNode("CreateQueueResult/QueueUrl")?.InnerText; response.ResponseMetadata.RequestId = xmlRootNode.SelectSingleNode("ResponseMetadata/RequestId")?.InnerText; return(response as T); } catch (Exception ex) { throw ErrorUnmarshall(ex.Message, ex, context.StatusCode); } }
protected override bool Execute(AmazonSQS client) { Logger.LogMessage(MessageImportance.Normal, "Creating SQS Queue {0}", QueueName); var request = new CreateQueueRequest { QueueName = QueueName }; CreateQueueResponse response = client.CreateQueue(request); if (response.IsSetCreateQueueResult()) { QueueUrl = response.CreateQueueResult.QueueUrl; Logger.LogMessage(MessageImportance.Normal, "Creates SQS Queue {0} at {1}", QueueName, QueueUrl); return(true); } Logger.LogMessage(MessageImportance.Normal, "Failed to create SQS Queue {0}", QueueName); return(false); }
/// <summary> /// Unmarshaller the response from the service to the response class. /// </summary> /// <param name="context"></param> /// <returns></returns> public override AmazonWebServiceResponse Unmarshall(JsonUnmarshallerContext context) { CreateQueueResponse response = new CreateQueueResponse(); context.Read(); int targetDepth = context.CurrentDepth; while (context.ReadAtDepth(targetDepth)) { if (context.TestExpression("queue", targetDepth)) { var unmarshaller = QueueUnmarshaller.Instance; response.Queue = unmarshaller.Unmarshall(context); continue; } } return(response); }
static async Task Main(string[] args) { string url; var sharedFile = new SharedCredentialsFile(); sharedFile.TryGetProfile("default", out var sourceProfile); var credentials = AWSCredentialsFactory.GetAWSCredentials(sourceProfile, sharedFile); _client = new AmazonSQSClient(credentials, new AmazonSQSConfig() { ServiceURL = "http://192.168.1.57:4566" }); ListQueuesResponse response = await _client.ListQueuesAsync(new ListQueuesRequest()); if (!response.QueueUrls.Any()) { CreateQueueResponse c_response = await _client.CreateQueueAsync("test"); if (c_response.HttpStatusCode == System.Net.HttpStatusCode.OK) { url = c_response.QueueUrl; Console.WriteLine("create queue success"); } else { Console.WriteLine("create queue fail"); return; } } else { url = response.QueueUrls.First(); } //var msg = Console.ReadLine(); Console.WriteLine(url); //SendMessageResponse s_reponse=await _client.SendMessageAsync(url,msg); //Console.WriteLine(response.HttpStatusCode.ToString()); Console.ReadLine(); }
private string createQueue(string queueName) { var createQueueRequest = new CreateQueueRequest(); try { createQueueRequest.QueueName = queueName; var attrs = new Dictionary <string, string>(); attrs.Add(QueueAttributeName.VisibilityTimeout, "60"); attrs.Add(QueueAttributeName.DelaySeconds, "90"); attrs.Add(QueueAttributeName.MessageRetentionPeriod, "1209600"); createQueueRequest.Attributes = attrs; CreateQueueResponse createQueueResponse = amazonSQSClient.CreateQueueAsync(createQueueRequest).Result; return(createQueueResponse.QueueUrl); } catch (Exception e) { throw new Exception(e.Message); } }
private static void EnsureQueue() { if (!string.IsNullOrEmpty(queueUrl)) { return; } EnsureSqs(); lock (lockObject) { CreateQueueRequest sqsRequest = new CreateQueueRequest(); sqsRequest.QueueName = ConfigurationManager.AppSettings["awssqsqueue"]; if (sqsRequest.QueueName == null) { Logger.Info(string.Format("awssqsqueue not configured, configure it first!")); return; } CreateQueueResponse createQueueResponse = sqs.CreateQueue(sqsRequest); queueUrl = createQueueResponse.CreateQueueResult.QueueUrl; } }
public async Task <CreateQueueResponse> CreateQueue(string queueName) { CreateQueueResponse createQueueResponse = null; try { var createQueueRequest = new CreateQueueRequest(); createQueueRequest.QueueName = queueName; var attrs = new Dictionary <string, string>(); attrs.Add(QueueAttributeName.VisibilityTimeout, _amazonConfiguration.VisibilityTimeout); createQueueRequest.Attributes = attrs; createQueueResponse = await _sqsClient.CreateQueueAsync(createQueueRequest); } catch (Exception ex) { } return(createQueueResponse); }
public void AddHandlerResolver() { var expectedQueueName = "TestQueue"; var expectedErrorQueueName = $"{expectedQueueName}_error"; var expectedMessage = new TestMessage { Name = "TestMessage" }; var createQueueResponse = new CreateQueueResponse { QueueUrl = "URL:TestQueue" }; queueNamingStrategyMock.Setup(x => x.GetName(typeof(TestMessage))).Returns(expectedQueueName); sqsServiceMock.Setup(x => x.GetQueueUrl(expectedQueueName)).Returns(createQueueResponse.QueueUrl); sut.Subscribe <TestMessage, IHandlerAsync <TestMessage> >(new TestHandler()); var expected = sut.GetHandler <TestMessage>(); expected.Should().NotBeNull(); }
public async Task <string> CreateQueue(IAmazonSQS sqsClient, string queueName) { try { Console.WriteLine("Creating SQS Queue"); var attrs = new Dictionary <string, string> { { QueueAttributeName.FifoQueue, "true" }, { QueueAttributeName.ContentBasedDeduplication, "false" } }; CreateQueueResponse responseCreate = await sqsClient.CreateQueueAsync( new CreateQueueRequest { QueueName = queueName, Attributes = attrs }); return(responseCreate.QueueUrl); } catch (Exception e) { Console.WriteLine($"SQS Queue creation failed: {e}"); throw; } }
public SubscribedQueue(IAmazonSQS sqsClient, IAmazonSimpleNotificationService snsClient, string topicARN) { _snsClient = snsClient; _sqsClient = sqsClient; //Create Queue CreateQueueRequest createQueueRequest = new CreateQueueRequest(); createQueueRequest.QueueName = "JamieGasMonQueue"; CreateQueueResponse createQueueResponse = _sqsClient.CreateQueueAsync(createQueueRequest).Result; QueueUrl = createQueueResponse.QueueUrl; Console.WriteLine("Queue created with URL:"); Console.WriteLine(QueueUrl); //Subscribe queue to topic _subscriptionArn = _snsClient.SubscribeQueueAsync(topicARN, _sqsClient, QueueUrl).Result; Console.WriteLine("Subscribed to topic."); }
public async Task AmazonSqsService_Should_Receive_Messages_From_A_Queue() { var guid = Guid.NewGuid(); var queueName = $"{guid}.fifo"; var dlQueueName = $"{guid}-DLQ.fifo"; CreateQueueResponse createQueueResponse = await CreateQueue(queueName, dlQueueName); var commentModel = new Fixture().Create <CommentModel>(); string serializedModel = JsonSerializer.Serialize(commentModel); var sendMessageRequest = new SendMessageRequest { QueueUrl = createQueueResponse.QueueUrl, MessageGroupId = commentModel.MovieId.ToString(), MessageDeduplicationId = Guid.NewGuid().ToString(), MessageBody = serializedModel }; await AmazonSqs.SendMessageAsync(sendMessageRequest); var req = new ReceiveMessageRequest { MaxNumberOfMessages = 1, QueueUrl = createQueueResponse.QueueUrl }; ReceiveMessageResponse receiveMessages = await AmazonSqs.ReceiveMessageAsync(req); Assert.Equal(HttpStatusCode.OK, receiveMessages.HttpStatusCode); Message currentMessage = receiveMessages.Messages.FirstOrDefault(); Assert.NotNull(currentMessage); var deserializedComment = JsonSerializer.Deserialize <CommentModel>(currentMessage.Body); Assert.True(commentModel.DeepEquals(deserializedComment)); }
public async Task TestEndToEnd() { // Check if any queue is already created var sqsQueueList = await sqsClient.ListQueuesAsync(prefix); Assert.IsFalse(sqsQueueList.QueueUrls.Count >= 1, "There is something in the queue already"); // Create the queue queueName = setQueueName(); CreateQueueResponse createResponse = await sqsClient.CreateQueueAsync(queueName); // Get the queue list. Assert is added to make sure that the queue is created and make sure that we only create 1 queue sqsQueueList = await sqsClient.ListQueuesAsync(prefix); Assert.IsTrue(sqsQueueList.QueueUrls.Count == 1, "Queue is not created or more than one queue is created"); // Verify the response created from when creating the queue is the same as the one we get from get queue URL var request = new GetQueueUrlRequest(queueName); var responseQueue = sqsClient.GetQueueUrlAsync(request); Assert.AreEqual(createResponse.QueueUrl, responseQueue.Result.QueueUrl, "The queue URL is not the same"); // Send message to the queue var requestMessage = new SendMessageRequest(responseQueue.Result.ToString(), messageBody); // Get the response when sending the message request var responseMessage = await sqsClient.SendMessageAsync(requestMessage); // Verify the message body is correct between the request and the response ValidateMD5(requestMessage.MessageBody, responseMessage.MD5OfMessageBody); // Since we know that we only created 1 queue, we can delete the only one await sqsClient.DeleteQueueAsync(sqsQueueList.QueueUrls[0].ToString()); // Get the list again, and verify that the list count is now 0 sqsQueueList = await sqsClient.ListQueuesAsync(prefix); Assert.IsTrue(sqsQueueList.QueueUrls.Count == 0, "The queue is not deleted"); }
public async Task <CreateQueueResult> CreateQueueAsync(string queueName, int defaultVisibilityTimeout = 30) { if (queueName is null) { throw new ArgumentNullException(nameof(queueName)); } var parameters = new SqsRequest { { "Action", "CreateQueue" }, { "QueueName", queueName }, { "DefaultVisibilityTimeout", defaultVisibilityTimeout } /* in seconds */ }; var httpRequest = new HttpRequestMessage(HttpMethod.Post, Endpoint) { Content = GetPostContent(parameters) }; var responseText = await SendAsync(httpRequest).ConfigureAwait(false); return(CreateQueueResponse.Parse(responseText).CreateQueueResult); }
async Task <CreateQueueResponse> CreateQueueAsync(string queueName, string SubscriptionId) { CreateQueueRequest deadLetterRequest = new CreateQueueRequest(string.Concat(queueName, "-deadletter")); deadLetterRequest.Attributes = new Dictionary <string, string>(); deadLetterRequest.Attributes.Add(QueueAttributeName.ReceiveMessageWaitTimeSeconds, "20"); deadLetterRequest.Attributes.Add(QueueAttributeName.MessageRetentionPeriod, "864000"); string deadLetterArn = null; AmazonSQSClient sqsClient = AwsFactory.CreateClient <AmazonSQSClient>(); var createResponse = await sqsClient.CreateQueueAsync(deadLetterRequest); GetQueueAttributesRequest queueReq = new GetQueueAttributesRequest(); queueReq.QueueUrl = createResponse.QueueUrl; queueReq.AttributeNames.Add(QueueAttributeName.All); var queueAttribs = await sqsClient.GetQueueAttributesAsync(queueReq); deadLetterArn = queueAttribs.QueueARN; string redrivePolicy = $"{{\"deadLetterTargetArn\":\"{deadLetterArn}\",\"maxReceiveCount\":5}}"; CreateQueueRequest createQueueRequest = new CreateQueueRequest(); createQueueRequest.QueueName = queueName; createQueueRequest.Attributes = new Dictionary <string, string>(); createQueueRequest.Attributes.Add(QueueAttributeName.RedrivePolicy, redrivePolicy); createQueueRequest.Attributes.Add(QueueAttributeName.ReceiveMessageWaitTimeSeconds, "20"); //createQueueRequest.Attributes.Add("trigger-id", SubscriptionId); CreateQueueResponse queueResponse = await sqsClient.CreateQueueAsync(createQueueRequest); return(queueResponse); }
public void Test_C_CreateQueue_With_AlreadyExisting_Queue_Name_And_Check_For_Valid_Response() { bool hasCallbackArrived = false; bool actualValue = false; bool expectedValue = true; SQSResponseEventHandler <object, ResponseEventArgs> handler = null; handler = delegate(object sender, ResponseEventArgs args) { ISQSResponse result = args.Response; //Unhook from event. _client.OnSQSResponse -= handler; CreateQueueResponse response = result as CreateQueueResponse; if (null != response) { CreateQueueResult createResult = response.CreateQueueResult; if (null != createResult) { actualValue = true; } } hasCallbackArrived = true; }; //Hook to event _client.OnSQSResponse += handler; //Create request object. _client.CreateQueue(new CreateQueueRequest { QueueName = _queue_UnitTesting_1 }); EnqueueConditional(() => hasCallbackArrived); EnqueueCallback(() => Assert.IsTrue(expectedValue == actualValue)); EnqueueTestComplete(); }
public async Task AmazonSqsService_Should_Send_A_Message_To_A_Queue() { var guid = Guid.NewGuid(); var queueName = $"{guid}.fifo"; var dlQueueName = $"{guid}-DLQ.fifo"; CreateQueueResponse createQueueResponse = await CreateQueue(queueName, dlQueueName); var commentModel = new Fixture().Create <CommentModel>(); string serializedModel = JsonSerializer.Serialize(commentModel); var sendMessageRequest = new SendMessageRequest { QueueUrl = createQueueResponse.QueueUrl, MessageGroupId = commentModel.MovieId.ToString(), MessageDeduplicationId = Guid.NewGuid().ToString(), MessageBody = serializedModel }; SendMessageResponse messageResponse = await AmazonSqs.SendMessageAsync(sendMessageRequest); Assert.Equal(HttpStatusCode.OK, messageResponse.HttpStatusCode); }
public void ReturnMatchingHandler() { var expectedQueueName = "TestQueue"; var expectedErrorQueueName = $"{expectedQueueName}_error"; var expectedMessage = new TestMessage { Name = "TestMessage" }; var expectedQueueUrl = "URL:TestQueue"; var createQueueResponse = new CreateQueueResponse { QueueUrl = expectedQueueUrl }; queueNamingStrategyMock.Setup(x => x.GetName(typeof(TestMessage))).Returns(expectedQueueName); sqsServiceMock.Setup(x => x.GetQueueUrl(expectedQueueName)).Returns(createQueueResponse.QueueUrl); var handlerMock = new Mock <IHandlerAsync <TestMessage> >(); sut.Subscribe <TestMessage, IHandlerAsync <TestMessage> >(handlerMock.Object); var actual = sut.GetHandler <TestMessage>(); actual.Should().NotBeNull(); }
public void AddQueue() { var expectedQueueName = "TestQueue"; var expectedErrorQueueName = $"{expectedQueueName}_error"; var expectedMessage = new TestMessage { Name = "TestMessage" }; var expectedQueueUrl = "URL:TestQueue"; var createQueueResponse = new CreateQueueResponse { QueueUrl = expectedQueueUrl }; queueNamingStrategyMock.Setup(x => x.GetName(typeof(TestMessage))).Returns(expectedQueueName); sqsServiceMock.Setup(x => x.GetQueueUrl(expectedQueueName)).Returns(createQueueResponse.QueueUrl); sut.Subscribe <TestMessage, IHandlerAsync <TestMessage> >(new TestHandler()); var actual = sut.Queues[expectedQueueName]; actual.Should().NotBeNull(); actual.MessageType.Should().Be(expectedMessage.GetType()); actual.Url.Should().Be(expectedQueueUrl); }
public override AmazonWebServiceResponse Unmarshall(XmlUnmarshallerContext context) { CreateQueueResponse response = new CreateQueueResponse(); while (context.Read()) { if (context.IsStartElement) { if (context.TestExpression("CreateQueueResult", 2)) { UnmarshallResult(context, response); continue; } if (context.TestExpression("ResponseMetadata", 2)) { response.ResponseMetadata = ResponseMetadataUnmarshaller.GetInstance().Unmarshall(context); } } } return(response); }
public static bool CreateFIFOQueue(string queueName) { try { if (sqsClient == null) { InitializeSQSClient(); } CreateQueueRequest createQueueRequest = new CreateQueueRequest(); createQueueRequest.Attributes = new Dictionary <string, string>(); createQueueRequest.Attributes.Add("FifoQueue", "true"); createQueueRequest.QueueName = queueName + ".fifo"; // FIFO queue names end with .fifo CreateQueueResponse createQueueResponse = sqsClient.CreateQueue(createQueueRequest); if (createQueueResponse.HttpStatusCode == HttpStatusCode.OK) { return(true); } } catch (AmazonSQSException ex) { Console.WriteLine(ex); } catch (Exception e) { Console.WriteLine(e); } return(false); }
/// <summary> /// Gets a queue to poll from /// </summary> /// <param name="queueName">a name of message queue</param> /// <returns></returns> public string GetQueueUrl <T>(string queueName) { string queueUrl; var internalName = GetInternalQueueName(queueName, typeof(T)); //the Dictionary is used as storage for available queues to have this unique if (!AvailableQueues.TryGetValue(internalName, out queueUrl)) { //Create queue in SQS if queue with such name is not created CreateQueueResponse queue = _sqsClient.CreateQueueAsync(internalName).Result; //something is not right if (queue.HttpStatusCode != HttpStatusCode.OK) { throw new Exception("Unexpected result creating SQS: " + queue.HttpStatusCode); } queueUrl = queue.QueueUrl; //remember the newly created queue AvailableQueues[internalName] = queueUrl; } return(queueUrl); }
public static void Main(string[] args) { IAmazonSQS sqs = AWSClientFactory.CreateAmazonSQSClient(RegionEndpoint.USWest2); try { Console.WriteLine("==========================================="); Console.WriteLine("Getting Started with Amazon SQS"); Console.WriteLine("===========================================\n"); //Creating a queue Console.WriteLine("Create a queue called MyQueue.\n"); CreateQueueRequest sqsRequest = new CreateQueueRequest(); sqsRequest.QueueName = "MyQueue"; CreateQueueResponse createQueueResponse = sqs.CreateQueue(sqsRequest); String myQueueUrl; myQueueUrl = createQueueResponse.QueueUrl; //Confirming the queue exists ListQueuesRequest listQueuesRequest = new ListQueuesRequest(); ListQueuesResponse listQueuesResponse = sqs.ListQueues(listQueuesRequest); Console.WriteLine("Printing list of Amazon SQS queues.\n"); foreach (String queueUrl in listQueuesResponse.QueueUrls) { Console.WriteLine(" QueueUrl: {0}", queueUrl); } Console.WriteLine(); //Sending a message Console.WriteLine("Sending a message to MyQueue.\n"); SendMessageRequest sendMessageRequest = new SendMessageRequest(); sendMessageRequest.QueueUrl = myQueueUrl; //URL from initial queue creation sendMessageRequest.MessageBody = "This is my message text."; sqs.SendMessage(sendMessageRequest); //Receiving a message ReceiveMessageRequest receiveMessageRequest = new ReceiveMessageRequest(); receiveMessageRequest.QueueUrl = myQueueUrl; ReceiveMessageResponse receiveMessageResponse = sqs.ReceiveMessage(receiveMessageRequest); Console.WriteLine("Printing received message.\n"); foreach (Message message in receiveMessageResponse.Messages) { Console.WriteLine(" Message"); Console.WriteLine(" MessageId: {0}", message.MessageId); Console.WriteLine(" ReceiptHandle: {0}", message.ReceiptHandle); Console.WriteLine(" MD5OfBody: {0}", message.MD5OfBody); Console.WriteLine(" Body: {0}", message.Body); foreach (KeyValuePair <string, string> entry in message.Attributes) { Console.WriteLine(" Attribute"); Console.WriteLine(" Name: {0}", entry.Key); Console.WriteLine(" Value: {0}", entry.Value); } } String messageRecieptHandle = receiveMessageResponse.Messages[0].ReceiptHandle; //Deleting a message Console.WriteLine("Deleting the message.\n"); DeleteMessageRequest deleteRequest = new DeleteMessageRequest(); deleteRequest.QueueUrl = myQueueUrl; deleteRequest.ReceiptHandle = messageRecieptHandle; sqs.DeleteMessage(deleteRequest); } catch (AmazonSQSException ex) { Console.WriteLine("Caught Exception: " + ex.Message); Console.WriteLine("Response Status Code: " + ex.StatusCode); Console.WriteLine("Error Code: " + ex.ErrorCode); Console.WriteLine("Error Type: " + ex.ErrorType); Console.WriteLine("Request ID: " + ex.RequestId); } Console.WriteLine("Press Enter to continue..."); Console.Read(); }
/////////////////////////////////////////////////////////////////////// // Methods & Functions // /////////////////////////////////////////////////////////////////////// /// <summary> /// This method initializes the client in order to avoid writing AWS AccessKey and SecretKey for testing zith XUnit /// </summary> /// <param name="regionEndpoint"></param> /// <param name="AWSAcessKey"></param> /// <param name="AWSSecretKey"></param> //private void Initialize (RegionEndpoint regionEndpoint, string AWSAcessKey, string AWSSecretKey) //{ // // Create SQS client // IAmazonSQS queueClient = AWSClientFactory.CreateAmazonSQSClient ( // AWSAcessKey, // AWSSecretKey, // regionEndpoint); //} /// <summary> /// This static method creates an SQS queue to be used later. For parameter definitions beyond error message, /// please check the online documentation (http://docs.aws.amazon.com/AWSSimpleQueueService/latest/APIReference/API_CreateQueue.html) /// </summary> /// <param name="QueueName">Name of the queue to be created</param> /// <param name="RegionEndpoint">Endpoint corresponding to the AWS region where the queue should be created</param> /// <param name="ErrorMessage">String that will receive the error message, if an error occurs</param> /// <returns>Boolean indicating if the queue was created</returns> public static bool CreateSQSQueue(string QueueName, RegionEndpoint RegionEndpoint, out string ErrorMessage, int DelaySeconds = 0, int MaximumMessageSize = AmazonSQSMaxMessageSize, int MessageRetentionPeriod = 345600, int ReceiveMessageWaitTimeSeconds = 0, int VisibilityTimeout = 30, string Policy = "", string AWSAccessKey = "", string AWSSecretKey = "") { bool result = false; ErrorMessage = ""; // Validate and adjust input parameters DelaySeconds = Math.Min(Math.Max(DelaySeconds, 0), 900); MaximumMessageSize = Math.Min(Math.Max(MaximumMessageSize, 1024), AmazonSQSMaxMessageSize); MessageRetentionPeriod = Math.Min(Math.Max(MessageRetentionPeriod, 60), 1209600); ReceiveMessageWaitTimeSeconds = Math.Min(Math.Max(ReceiveMessageWaitTimeSeconds, 0), 20); VisibilityTimeout = Math.Min(Math.Max(VisibilityTimeout, 0), 43200); if (!String.IsNullOrWhiteSpace(QueueName)) { IAmazonSQS queueClient; if (!String.IsNullOrEmpty(AWSAccessKey)) { queueClient = AWSClientFactory.CreateAmazonSQSClient(AWSAccessKey, AWSSecretKey, RegionEndpoint); } else { queueClient = AWSClientFactory.CreateAmazonSQSClient(RegionEndpoint); } try { // Generate the queue creation request CreateQueueRequest createRequest = new CreateQueueRequest(); createRequest.QueueName = QueueName; // Add other creation parameters createRequest.Attributes.Add("DelaySeconds", DelaySeconds.ToString()); createRequest.Attributes.Add("MaximumMessageSize", MaximumMessageSize.ToString()); createRequest.Attributes.Add("MessageRetentionPeriod", MessageRetentionPeriod.ToString()); createRequest.Attributes.Add("ReceiveMessageWaitTimeSeconds", ReceiveMessageWaitTimeSeconds.ToString()); createRequest.Attributes.Add("VisibilityTimeout", VisibilityTimeout.ToString()); // Run the request CreateQueueResponse createResponse = queueClient.CreateQueue(createRequest); // Check for errros if (createResponse.HttpStatusCode != System.Net.HttpStatusCode.OK) { ErrorMessage = "An error occurred while creating the queue. Please try again."; } result = true; } catch (Exception ex) { ErrorMessage = ex.Message; } } else { ErrorMessage = "Invalid Queue Name"; } return(result); }
public static void Main(string[] args) { const string QUEUENAME = "MyQueue"; AmazonSQS sqs = AWSClientFactory.CreateAmazonSQSClient(); try { Console.WriteLine("==========================================="); Console.WriteLine("Getting Started with Amazon SQS"); Console.WriteLine("===========================================\n"); //Creating a queue Console.WriteLine("Create a queue called MyQueue.\n"); CreateQueueRequest sqsRequest = new CreateQueueRequest(); sqsRequest.QueueName = QUEUENAME; CreateQueueResponse createQueueResponse = sqs.CreateQueue(sqsRequest); String myQueueUrl; myQueueUrl = createQueueResponse.CreateQueueResult.QueueUrl; //Confirming the queue exists ListQueuesRequest listQueuesRequest = new ListQueuesRequest(); ListQueuesResponse listQueuesResponse = sqs.ListQueues(listQueuesRequest); var getQueueReq = new GetQueueUrlRequest(); getQueueReq.QueueName = "AppZwitschern"; var getQueueResp = sqs.GetQueueUrl(getQueueReq); Console.WriteLine(":: Url={0}", getQueueResp.GetQueueUrlResult.QueueUrl); Console.WriteLine("Printing list of Amazon SQS queues.\n"); if (listQueuesResponse.IsSetListQueuesResult()) { ListQueuesResult listQueuesResult = listQueuesResponse.ListQueuesResult; foreach (String queueUrl in listQueuesResult.QueueUrl) { Console.WriteLine(" QueueUrl: {0}", queueUrl); } } Console.WriteLine(); //Sending a message Console.WriteLine("Sending a message to MyQueue.\n"); SendMessageRequest sendMessageRequest = new SendMessageRequest(); sendMessageRequest.QueueUrl = myQueueUrl; //URL from initial queue creation sendMessageRequest.MessageBody = "This is my message text."; sqs.SendMessage(sendMessageRequest); //Receiving a message ReceiveMessageRequest receiveMessageRequest = new ReceiveMessageRequest(); receiveMessageRequest.QueueUrl = myQueueUrl; ReceiveMessageResponse receiveMessageResponse = sqs.ReceiveMessage(receiveMessageRequest); if (receiveMessageResponse.IsSetReceiveMessageResult()) { Console.WriteLine("Printing received message.\n"); ReceiveMessageResult receiveMessageResult = receiveMessageResponse.ReceiveMessageResult; foreach (Message message in receiveMessageResult.Message) { Console.WriteLine(" Message"); if (message.IsSetMessageId()) { Console.WriteLine(" MessageId: {0}", message.MessageId); } if (message.IsSetReceiptHandle()) { Console.WriteLine(" ReceiptHandle: {0}", message.ReceiptHandle); } if (message.IsSetMD5OfBody()) { Console.WriteLine(" MD5OfBody: {0}", message.MD5OfBody); } if (message.IsSetBody()) { Console.WriteLine(" Body: {0}", message.Body); } foreach (Amazon.SQS.Model.Attribute attribute in message.Attribute) { Console.WriteLine(" Attribute"); if (attribute.IsSetName()) { Console.WriteLine(" Name: {0}", attribute.Name); } if (attribute.IsSetValue()) { Console.WriteLine(" Value: {0}", attribute.Value); } } } } String messageRecieptHandle = receiveMessageResponse.ReceiveMessageResult.Message[0].ReceiptHandle; //Deleting a message Console.WriteLine("Deleting the message.\n"); DeleteMessageRequest deleteRequest = new DeleteMessageRequest(); deleteRequest.QueueUrl = myQueueUrl; deleteRequest.ReceiptHandle = messageRecieptHandle; sqs.DeleteMessage(deleteRequest); } catch (AmazonSQSException ex) { Console.WriteLine("Caught Exception: " + ex.Message); Console.WriteLine("Response Status Code: " + ex.StatusCode); Console.WriteLine("Error Code: " + ex.ErrorCode); Console.WriteLine("Error Type: " + ex.ErrorType); Console.WriteLine("Request ID: " + ex.RequestId); Console.WriteLine("XML: " + ex.XML); } Console.WriteLine("Press Enter to continue..."); Console.Read(); }
public void MonitorEmail(string emailaddr) { if (Exists(emailaddr) && !monitors.ContainsKey(emailaddr)) { FastEmailMailbox mbx = Mailboxes[emailaddr]; FastEmailMonitor monitor = new FastEmailMonitor(); monitor.mbx = mbx; monitor.sqsqueue_name = mbx.S3Bucket + "-" + Process.GetCurrentProcess().Id + "-" + System.Environment.MachineName; create_sqsclient(); try { // create the queue var sqscreateresponse = sqsclient.CreateQueueAsync(new CreateQueueRequest { QueueName = monitor.sqsqueue_name }); CreateQueueResponse sqsresult = sqscreateresponse.Result; monitor.sqsqueue_url = sqsresult.QueueUrl; } catch (AmazonSQSException e) { Console.WriteLine("Exception while creating SQS Queue for {0}: {1}", emailaddr, e.Message); } // get the queue arn try { List <string> attr = new List <string>() { "QueueArn" }; var sqsattrresponse = sqsclient.GetQueueAttributesAsync(new GetQueueAttributesRequest { QueueUrl = monitor.sqsqueue_url, AttributeNames = attr }); GetQueueAttributesResponse sqsresponse = sqsattrresponse.Result; monitor.sqsqueue_arn = sqsresponse.QueueARN; } catch (AmazonSQSException e) { Console.WriteLine("Exception while getting QueueARN SQS Queue for {0}: {1}", emailaddr, e.Message); } // add permission string perm = @"{ ""Version"":""2012-10-17"", ""Statement"":[ { ""Sid"":""Policy-" + monitor.mbx.TopicArn; perm += @""", ""Effect"":""Allow"", ""Principal"":""*"", ""Action"":""sqs:SendMessage"", ""Resource"":""" + monitor.sqsqueue_arn; perm += @""", ""Condition"":{ ""ArnEquals"":{ ""aws:SourceArn"":""" + monitor.mbx.TopicArn; perm += @""" } } } ] }"; var policy = new Dictionary <string, string>(); policy.Add("Policy", perm); try { var qsattrrequest = sqsclient.SetQueueAttributesAsync(new SetQueueAttributesRequest { QueueUrl = monitor.sqsqueue_url, Attributes = policy }); var qsattrresponse = qsattrrequest.Result; } catch (AmazonSQSException e) { Console.WriteLine("Exception while adding permission policy to queue for {0}: {1}", emailaddr, e.Message); } create_snsclient(); try { var snsresponse = snsclient.SubscribeAsync(new SubscribeRequest { Protocol = "sqs", Endpoint = monitor.sqsqueue_arn, TopicArn = monitor.mbx.TopicArn }); var subresult = snsresponse.Result; monitor.subscription_arn = subresult.SubscriptionArn; } catch (AmazonSimpleNotificationServiceException e) { Console.WriteLine("Exception while subscribing to queue for {0}: {1}", emailaddr, e.Message); } monitors.Add(emailaddr, monitor); } }