

O AWS SDK para .NET V3 entrou no modo de manutenção.

Recomendamos que você migre para a [AWS SDK para .NET V4](https://docs.aws.amazon.com/sdk-for-net/v4/developer-guide/welcome.html). Para obter detalhes e informações adicionais sobre como migrar, consulte nosso [anúncio do modo de manutenção](https://aws.amazon.com/blogs/developer/aws-sdk-for-net-v3-maintenance-mode-announcement/).

As traduções são geradas por tradução automática. Em caso de conflito entre o conteúdo da tradução e da versão original em inglês, a versão em inglês prevalecerá.

# Enviar mensagens usando o Amazon SQS
<a name="sqs-apis-intro"></a>

O AWS SDK para .NET suporta o [Amazon Simple Queue Service (Amazon SQS), que é um serviço](https://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/) de enfileiramento de mensagens que manipula mensagens ou fluxos de trabalho entre componentes em um sistema.

As filas do Amazon SQS fornecem um mecanismo que permite enviar, armazenar e receber mensagens entre componentes de software, como microsserviços, sistemas distribuídos e aplicações sem servidor. Isso permite desacoplar esses componentes e você fica da necessidade de projetar e operar seu próprio sistema de mensagens. Para ter informações sobre como as filas e mensagens funcionam no Amazon SQS, consulte os [tutoriais do Amazon SQS](https://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/sqs-other-tutorials.html) e [Arquitetura básica do Amazon SQS](https://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/sqs-basic-architecture.html) no [Guia do desenvolvedor do Amazon Simple Queue Service](https://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/).

**Importante**  
Devido à natureza distribuída da fila, o Amazon SQS não garante que as mensagens serão recebidas na ordem exata de envio. Se for necessário manter a ordem de mensagens, use uma [fila FIFO do Amazon SQS](https://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/sqs-fifo-queues.html).

## APIs
<a name="w2aac19c15c25b9"></a>

 AWS SDK para .NET Ele fornece APIs para clientes do Amazon SQS. Eles APIs permitem que você trabalhe com recursos do Amazon SQS, como filas e mensagens. Esta seção contém um pequeno número de exemplos que mostram os padrões que você pode seguir ao trabalhar com eles APIs. Para ver o conjunto completo de APIs, consulte a [Referência da AWS SDK para .NET API](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/) (e vá até “Amazon.sqs”).

O Amazon SQS é fornecido pelo APIs [AWSSDK NuGet pacote.SQS](https://www.nuget.org/packages/AWSSDK.SQS).

## Pré-requisitos
<a name="w2aac19c15c25c11"></a>

Antes de começar, assegure-se de ter [configurado o seu ambiente e seu projeto](net-dg-config.md). Revise também as informações em [Atributos do SDK](net-dg-sdk-features.md).

## Tópicos
<a name="w2aac19c15c25c13"></a>

**Topics**
+ [APIs](#w2aac19c15c25b9)
+ [Pré-requisitos](#w2aac19c15c25c11)
+ [Tópicos](#w2aac19c15c25c13)
+ [Criação de filas](CreateQueue.md)
+ [Atualizando filas](UpdateSqsQueue.md)
+ [Excluindo filas](DeleteSqsQueue.md)
+ [Enviar mensagens](SendMessage.md)
+ [Recebimento de mensagens](ReceiveMessage.md)

# Criação de fila no Amazon SQS
<a name="CreateQueue"></a>

Este exemplo mostra como usar o AWS SDK para .NET para criar uma fila do Amazon SQS. O aplicação cria uma [fila de mensagens não entregues](https://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/sqs-dead-letter-queues.html) se você não fornecer o ARN para uma. Em seguida, ele cria uma fila de mensagens padrão, que inclui uma fila de mensagens não entregues (a que você forneceu ou a que foi criada).

Se você não fornecer nenhum argumento de linha de comando, a aplicação simplesmente mostrará informações sobre todas as filas existentes.

As seções a seguir fornecem snippets desse exemplo. O [código completo do exemplo](#CreateQueue-complete-code) é mostrado depois e pode ser criado e executado como está.

**Topics**
+ [Mostrar filas existentes](#CreateQueue-show-queues)
+ [Criação da fila](#CreateQueue-create-queue)
+ [Obtenha o ARN de uma fila](#CreateQueue-get-arn)
+ [Código completo](#CreateQueue-complete-code)
+ [Considerações adicionais](#CreateQueue-additional)

## Mostrar filas existentes
<a name="CreateQueue-show-queues"></a>

O trecho a seguir mostra uma lista das filas existentes na região do cliente SQS e os atributos de cada fila.

O exemplo [no final deste tópico](#CreateQueue-complete-code) mostra o snippet em uso.

```
    //
    // Method to show a list of the existing queues
    private static async Task ShowQueues(IAmazonSQS sqsClient)
    {
      ListQueuesResponse responseList = await sqsClient.ListQueuesAsync("");
      Console.WriteLine();
      foreach(string qUrl in responseList.QueueUrls)
      {
        // Get and show all attributes. Could also get a subset.
        await ShowAllAttributes(sqsClient, qUrl);
      }
    }

    //
    // 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}");
    }
```

## Criação da fila
<a name="CreateQueue-create-queue"></a>

O seguinte snippet cria uma fila. O trecho inclui o uso de uma fila de mensagens não entregues, mas uma fila de mensagens não entregues não é necessariamente necessária para suas filas.

O exemplo [no final deste tópico](#CreateQueue-complete-code) mostra o snippet em uso.

```
    //
    // Method to create a queue. Returns the queue URL.
    private static async Task<string> CreateQueue(
      IAmazonSQS sqsClient, string qName, string deadLetterQueueUrl=null,
      string maxReceiveCount=null, string receiveWaitTime=null)
    {
      var attrs = new Dictionary<string, string>();

      // If a dead-letter queue is given, create a message queue
      if(!string.IsNullOrEmpty(deadLetterQueueUrl))
      {
        attrs.Add(QueueAttributeName.ReceiveMessageWaitTimeSeconds, receiveWaitTime);
        attrs.Add(QueueAttributeName.RedrivePolicy,
          $"{{\"deadLetterTargetArn\":\"{await GetQueueArn(sqsClient, deadLetterQueueUrl)}\"," +
          $"\"maxReceiveCount\":\"{maxReceiveCount}\"}}");
        // Add other attributes for the message queue such as VisibilityTimeout
      }

      // If no dead-letter queue is given, create one of those instead
      //else
      //{
      //  // Add attributes for the dead-letter queue as needed
      //  attrs.Add();
      //}

      // Create the queue
      CreateQueueResponse responseCreate = await sqsClient.CreateQueueAsync(
          new CreateQueueRequest{QueueName = qName, Attributes = attrs});
      return responseCreate.QueueUrl;
    }
```

## Obtenha o ARN de uma fila
<a name="CreateQueue-get-arn"></a>

O snippet a seguir obtém o ARN da fila identificada pelo URL da fila em questão.

O exemplo [no final deste tópico](#CreateQueue-complete-code) mostra o snippet em uso.

```
    //
    // 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;
    }
```

## Código completo
<a name="CreateQueue-complete-code"></a>

Esta seção mostra as referências relevantes e o código completo desse exemplo.

### Referências do SDK
<a name="w2aac19c15c25c17c25b5b1"></a>

NuGet pacotes:
+ [AWSSDK.SQS](https://www.nuget.org/packages/AWSSDK.SQS)

Elementos de programação:
+ Namespace [Amazon.SQS](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/SQS/NSQS.html)

  Classe [Amazon SQSClient](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/SQS/TSQSClient.html)

  Classe [QueueAttributeName](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/SQS/TQueueAttributeName.html)
+ Namespace [Amazon.SQS.Model](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/SQS/NSQSModel.html)

  Classe [CreateQueueRequest](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/SQS/TCreateQueueRequest.html)

  Classe [CreateQueueResponse](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/SQS/TCreateQueueResponse.html)

  Classe [GetQueueAttributesResponse](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/SQS/TGetQueueAttributesResponse.html)

  Classe [ListQueuesResponse](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/SQS/TListQueuesResponse.html)

### O código
<a name="w2aac19c15c25c17c25b7b1"></a>

```
using System;
using System.Threading.Tasks;
using System.Collections.Generic;
using Amazon.SQS;
using Amazon.SQS.Model;

namespace SQSCreateQueue
{
  // = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =
  // Class to create a queue
  class Program
  {
    private const string MaxReceiveCount = "10";
    private const string ReceiveMessageWaitTime = "2";
    private const int MaxArgs = 3;

    static async Task Main(string[] args)
    {
      // Parse the command line and show help if necessary
      var parsedArgs = CommandLine.Parse(args);
      if(parsedArgs.Count > MaxArgs)
        CommandLine.ErrorExit(
          "\nToo many command-line arguments.\nRun the command with no arguments to see help.");

      // Create the Amazon SQS client
      var sqsClient = new AmazonSQSClient();

      // In the case of no command-line arguments, just show help and the existing queues
      if(parsedArgs.Count == 0)
      {
        PrintHelp();
        Console.WriteLine("\nNo arguments specified.");
        Console.Write("Do you want to see a list of the existing queues? ((y) or n): ");
        string response = Console.ReadLine();
        if((string.IsNullOrEmpty(response)) || (response.ToLower() == "y"))
          await ShowQueues(sqsClient);
        return;
      }

      // Get the application arguments from the parsed list
      string queueName =
        CommandLine.GetArgument(parsedArgs, null, "-q", "--queue-name");
      string deadLetterQueueUrl =
        CommandLine.GetArgument(parsedArgs, null, "-d", "--dead-letter-queue");
      string maxReceiveCount =
        CommandLine.GetArgument(parsedArgs, MaxReceiveCount, "-m", "--max-receive-count");
      string receiveWaitTime =
        CommandLine.GetArgument(parsedArgs, ReceiveMessageWaitTime, "-w", "--wait-time");

      if(string.IsNullOrEmpty(queueName))
        CommandLine.ErrorExit(
          "\nYou must supply a queue name.\nRun the command with no arguments to see help.");

      // If a dead-letter queue wasn't given, create one
      if(string.IsNullOrEmpty(deadLetterQueueUrl))
      {
        Console.WriteLine("\nNo dead-letter queue was specified. Creating one...");
        deadLetterQueueUrl = await CreateQueue(sqsClient, queueName + "__dlq");
        Console.WriteLine($"Your new dead-letter queue:");
        await ShowAllAttributes(sqsClient, deadLetterQueueUrl);
      }

      // Create the message queue
      string messageQueueUrl = await CreateQueue(
        sqsClient, queueName, deadLetterQueueUrl, maxReceiveCount, receiveWaitTime);
      Console.WriteLine($"Your new message queue:");
      await ShowAllAttributes(sqsClient, messageQueueUrl);
    }


    //
    // Method to show a list of the existing queues
    private static async Task ShowQueues(IAmazonSQS sqsClient)
    {
      ListQueuesResponse responseList = await sqsClient.ListQueuesAsync("");
      Console.WriteLine();
      foreach(string qUrl in responseList.QueueUrls)
      {
        // Get and show all attributes. Could also get a subset.
        await ShowAllAttributes(sqsClient, qUrl);
      }
    }


    //
    // Method to create a queue. Returns the queue URL.
    private static async Task<string> CreateQueue(
      IAmazonSQS sqsClient, string qName, string deadLetterQueueUrl=null,
      string maxReceiveCount=null, string receiveWaitTime=null)
    {
      var attrs = new Dictionary<string, string>();

      // If a dead-letter queue is given, create a message queue
      if(!string.IsNullOrEmpty(deadLetterQueueUrl))
      {
        attrs.Add(QueueAttributeName.ReceiveMessageWaitTimeSeconds, receiveWaitTime);
        attrs.Add(QueueAttributeName.RedrivePolicy,
          $"{{\"deadLetterTargetArn\":\"{await GetQueueArn(sqsClient, deadLetterQueueUrl)}\"," +
          $"\"maxReceiveCount\":\"{maxReceiveCount}\"}}");
        // Add other attributes for the message queue such as VisibilityTimeout
      }

      // If no dead-letter queue is given, create one of those instead
      //else
      //{
      //  // Add attributes for the dead-letter queue as needed
      //  attrs.Add();
      //}

      // Create the queue
      CreateQueueResponse responseCreate = await sqsClient.CreateQueueAsync(
          new CreateQueueRequest{QueueName = qName, Attributes = attrs});
      return responseCreate.QueueUrl;
    }


    //
    // 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;
    }


    //
    // 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}");
    }


    //
    // Command-line help
    private static void PrintHelp()
    {
      Console.WriteLine(
      "\nUsage: SQSCreateQueue -q <queue-name> [-d <dead-letter-queue>]" +
        " [-m <max-receive-count>] [-w <wait-time>]" +
      "\n  -q, --queue-name: The name of the queue you want to create." +
      "\n  -d, --dead-letter-queue: The URL of an existing queue to be used as the dead-letter queue."+
      "\n      If this argument isn't supplied, a new dead-letter queue will be created." +
      "\n  -m, --max-receive-count: The value for maxReceiveCount in the RedrivePolicy of the queue." +
      $"\n      Default is {MaxReceiveCount}." +
      "\n  -w, --wait-time: The value for ReceiveMessageWaitTimeSeconds of the queue for long polling." +
      $"\n      Default is {ReceiveMessageWaitTime}.");
    }
  }


  // = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =
  // Class that represents a command line on the console or terminal.
  // (This is the same for all examples. When you have seen it once, you can ignore it.)
  static class CommandLine
  {
    //
    // Method to parse a command line of the form: "--key value" or "-k value".
    //
    // Parameters:
    // - args: The command-line arguments passed into the application by the system.
    //
    // Returns:
    // A Dictionary with string Keys and Values.
    //
    // If a key is found without a matching value, Dictionary.Value is set to the key
    //  (including the dashes).
    // If a value is found without a matching key, Dictionary.Key is set to "--NoKeyN",
    //  where "N" represents sequential numbers.
    public static Dictionary<string,string> Parse(string[] args)
    {
      var parsedArgs = new Dictionary<string,string>();
      int i = 0, n = 0;
      while(i < args.Length)
      {
        // If the first argument in this iteration starts with a dash it's an option.
        if(args[i].StartsWith("-"))
        {
          var key = args[i++];
          var value = key;

          // Check to see if there's a value that goes with this option?
          if((i < args.Length) && (!args[i].StartsWith("-"))) value = args[i++];
          parsedArgs.Add(key, value);
        }

        // If the first argument in this iteration doesn't start with a dash, it's a value
        else
        {
          parsedArgs.Add("--NoKey" + n.ToString(), args[i++]);
          n++;
        }
      }

      return parsedArgs;
    }

    //
    // Method to get an argument from the parsed command-line arguments
    //
    // Parameters:
    // - parsedArgs: The Dictionary object returned from the Parse() method (shown above).
    // - defaultValue: The default string to return if the specified key isn't in parsedArgs.
    // - keys: An array of keys to look for in parsedArgs.
    public static string GetArgument(
      Dictionary<string,string> parsedArgs, string defaultReturn, params string[] keys)
    {
      string retval = null;
      foreach(var key in keys)
        if(parsedArgs.TryGetValue(key, out retval)) break;
      return retval ?? defaultReturn;
    }

    //
    // Method to exit the application with an error.
    public static void ErrorExit(string msg, int code=1)
    {
      Console.WriteLine("\nError");
      Console.WriteLine(msg);
      Environment.Exit(code);
    }
  }

}
```

## Considerações adicionais
<a name="CreateQueue-additional"></a>
+ O nome da fila deve ser composto de caracteres alfanuméricos, hifens e sublinhados.
+ Os nomes das filas e as filas diferenciam maiúsculas de URLs minúsculas
+ Se precisar do URL da fila, mas tiver apenas o nome da fila, use um dos `AmazonSQSClient.GetQueueUrlAsync` métodos.
+ Para obter informações sobre os vários atributos de fila que você pode definir, consulte [CreateQueueRequest](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/SQS/TCreateQueueRequest.html)na Referência da [AWS SDK para .NET API ou [SetQueueAttributes](https://docs.aws.amazon.com/AWSSimpleQueueService/latest/APIReference/API_SetQueueAttributes.html)na Referência](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/) da [API do Amazon Simple Queue Service](https://docs.aws.amazon.com/AWSSimpleQueueService/latest/APIReference/).
+ Este exemplo especifica uma sondagem longa para todas as mensagens na fila que você cria. Isto é feito usando o atributo `ReceiveMessageWaitTimeSeconds`.

  Você também pode especificar uma sondagem longa durante uma chamada para os `ReceiveMessageAsync` métodos da SQSClient classe [Amazon](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/SQS/TSQSClient.html). Para obter mais informações, consulte [Recebimento de mensagens do Amazon SQS](ReceiveMessage.md).

  Para obter informações sobre sondagem curta versus sondagem longa, consulte [Sondagem curta e longa](https://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/sqs-short-and-long-polling.html) no *Guia do desenvolvedor do Amazon Simple Queue Service*.
+ Uma fila de mensagens não entregues é aquela fila que outras filas (de origem) podem direcionar para mensagens que não foram processadas com sucesso. Para obter mais informações, consulte [filas de mensagens não entregues do Amazon SQS](https://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/sqs-dead-letter-queues.html) no Guia do desenvolvedor do Amazon Simple Queue Service.
+ Você também pode ver a lista de filas e os resultados desse exemplo no [console do Amazon SQS](https://console.aws.amazon.com/sqs).

# Atualizando filas do Amazon SQS
<a name="UpdateSqsQueue"></a>

Este exemplo mostra como usar o AWS SDK para .NET para atualizar uma fila do Amazon SQS. Depois de algumas verificações, a aplicação atualiza o atributo fornecido com o valor fornecido e, em seguida, mostra todos os atributos da fila.

Se somente o URL da fila estiver incluído nos argumentos da linha de comando, a aplicação simplesmente mostrará todos os atributos da fila.

As seções a seguir fornecem snippets desse exemplo. O [código completo do exemplo](#UpdateSqsQueue-complete-code) é mostrado depois e pode ser criado e executado como está.

**Topics**
+ [Mostrar atributos da fila](#UpdateSqsQueue-show-attributes)
+ [Validar nome do atributo](#UpdateSqsQueue-validate-attribute)
+ [Atualizar atributo de fila](#UpdateSqsQueue-update-attribute)
+ [Código completo](#UpdateSqsQueue-complete-code)
+ [Considerações adicionais](#UpdateSqsQueue-additional)

## Mostrar atributos da fila
<a name="UpdateSqsQueue-show-attributes"></a>

O snippet a seguir mostra os atributos da fila identificados pelo URL da fila em questão.

O exemplo [no final deste tópico](#UpdateSqsQueue-complete-code) mostra o snippet em uso.

```
    //
    // Method to show all attributes of a queue
    private static async Task ShowAllAttributes(IAmazonSQS sqsClient, string qUrl)
    {
      GetQueueAttributesResponse responseGetAtt =
        await sqsClient.GetQueueAttributesAsync(qUrl,
          new List<string>{ QueueAttributeName.All });
      Console.WriteLine($"Queue: {qUrl}");
      foreach(var att in responseGetAtt.Attributes)
        Console.WriteLine($"\t{att.Key}: {att.Value}");
    }
```

## Validar nome do atributo
<a name="UpdateSqsQueue-validate-attribute"></a>

O snippet a seguir valida o nome do atributo que está sendo atualizado.

O exemplo [no final deste tópico](#UpdateSqsQueue-complete-code) mostra o snippet em uso.

```
    //
    // Method to check the name of the attribute
    private static bool ValidAttribute(string attribute)
    {
      var attOk = false;
      var qAttNameType = typeof(QueueAttributeName);
      List<string> qAttNamefields = new List<string>();
      foreach(var field in qAttNameType.GetFields())
       qAttNamefields.Add(field.Name);
      foreach(var name in qAttNamefields)
        if(attribute == name) { attOk = true; break; }
      return attOk;
    }
```

## Atualizar atributo de fila
<a name="UpdateSqsQueue-update-attribute"></a>

O snippet a seguir atualiza um atributo da fila identificado pelo URL da fila em questão.

O exemplo [no final deste tópico](#UpdateSqsQueue-complete-code) mostra o snippet em uso.

```
    //
    // Method to update a queue attribute
    private static async Task UpdateAttribute(
      IAmazonSQS sqsClient, string qUrl, string attribute, string value)
    {
      await sqsClient.SetQueueAttributesAsync(qUrl,
        new Dictionary<string, string>{{attribute, value}});
    }
```

## Código completo
<a name="UpdateSqsQueue-complete-code"></a>

Esta seção mostra as referências relevantes e o código completo desse exemplo.

### Referências do SDK
<a name="w2aac19c15c25c19c25b5b1"></a>

NuGet pacotes:
+ [AWSSDK.SQS](https://www.nuget.org/packages/AWSSDK.SQS)

Elementos de programação:
+ Namespace [Amazon.SQS](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/SQS/NSQS.html)

  Classe [Amazon SQSClient](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/SQS/TSQSClient.html)

  Classe [QueueAttributeName](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/SQS/TQueueAttributeName.html)
+ Namespace [Amazon.SQS.Model](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/SQS/NSQSModel.html)

  Classe [GetQueueAttributesResponse](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/SQS/TGetQueueAttributesResponse.html)

### O código
<a name="w2aac19c15c25c19c25b7b1"></a>

```
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Amazon.SQS;
using Amazon.SQS.Model;

namespace SQSUpdateQueue
{
  // = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =
  // Class to update a queue
  class Program
  {
    private const int MaxArgs = 3;
    private const int InvalidArgCount = 2;

    static async Task Main(string[] args)
    {
      // Parse the command line and show help if necessary
      var parsedArgs = CommandLine.Parse(args);
      if(parsedArgs.Count == 0)
      {
        PrintHelp();
        return;
      }
      if((parsedArgs.Count > MaxArgs) || (parsedArgs.Count == InvalidArgCount))
        CommandLine.ErrorExit("\nThe number of command-line arguments is incorrect." +
          "\nRun the command with no arguments to see help.");

      // Get the application arguments from the parsed list
      var qUrl = CommandLine.GetArgument(parsedArgs, null, "-q");
      var attribute = CommandLine.GetArgument(parsedArgs, null, "-a");
      var value = CommandLine.GetArgument(parsedArgs, null, "-v", "--value");

      if(string.IsNullOrEmpty(qUrl))
        CommandLine.ErrorExit("\nYou must supply at least a queue URL." +
          "\nRun the command with no arguments to see help.");

      // Create the Amazon SQS client
      var sqsClient = new AmazonSQSClient();

      // In the case of one command-line argument, just show the attributes for the queue
      if(parsedArgs.Count == 1)
        await ShowAllAttributes(sqsClient, qUrl);

      // Otherwise, attempt to update the given queue attribute with the given value
      else
      {
        // Check to see if the attribute is valid
        if(ValidAttribute(attribute))
        {
          // Perform the update and then show all the attributes of the queue
          await UpdateAttribute(sqsClient, qUrl, attribute, value);
          await ShowAllAttributes(sqsClient, qUrl);
        }
        else
        {
          Console.WriteLine($"\nThe given attribute name, {attribute}, isn't valid.");
        }
      }
    }


    //
    // Method to show all attributes of a queue
    private static async Task ShowAllAttributes(IAmazonSQS sqsClient, string qUrl)
    {
      GetQueueAttributesResponse responseGetAtt =
        await sqsClient.GetQueueAttributesAsync(qUrl,
          new List<string>{ QueueAttributeName.All });
      Console.WriteLine($"Queue: {qUrl}");
      foreach(var att in responseGetAtt.Attributes)
        Console.WriteLine($"\t{att.Key}: {att.Value}");
    }


    //
    // Method to check the name of the attribute
    private static bool ValidAttribute(string attribute)
    {
      var attOk = false;
      var qAttNameType = typeof(QueueAttributeName);
      List<string> qAttNamefields = new List<string>();
      foreach(var field in qAttNameType.GetFields())
       qAttNamefields.Add(field.Name);
      foreach(var name in qAttNamefields)
        if(attribute == name) { attOk = true; break; }
      return attOk;
    }


    //
    // Method to update a queue attribute
    private static async Task UpdateAttribute(
      IAmazonSQS sqsClient, string qUrl, string attribute, string value)
    {
      await sqsClient.SetQueueAttributesAsync(qUrl,
        new Dictionary<string, string>{{attribute, value}});
    }


    //
    // Command-line help
    private static void PrintHelp()
    {
      Console.WriteLine("\nUsage: SQSUpdateQueue -q queue_url [-a attribute -v value]");
      Console.WriteLine("  -q: The URL of the queue you want to update.");
      Console.WriteLine("  -a: The name of the attribute to update.");
      Console.WriteLine("  -v, --value: The value to assign to the attribute.");
    }
  }


  // = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =
  // Class that represents a command line on the console or terminal.
  // (This is the same for all examples. When you have seen it once, you can ignore it.)
  static class CommandLine
  {
    //
    // Method to parse a command line of the form: "--key value" or "-k value".
    //
    // Parameters:
    // - args: The command-line arguments passed into the application by the system.
    //
    // Returns:
    // A Dictionary with string Keys and Values.
    //
    // If a key is found without a matching value, Dictionary.Value is set to the key
    //  (including the dashes).
    // If a value is found without a matching key, Dictionary.Key is set to "--NoKeyN",
    //  where "N" represents sequential numbers.
    public static Dictionary<string,string> Parse(string[] args)
    {
      var parsedArgs = new Dictionary<string,string>();
      int i = 0, n = 0;
      while(i < args.Length)
      {
        // If the first argument in this iteration starts with a dash it's an option.
        if(args[i].StartsWith("-"))
        {
          var key = args[i++];
          var value = key;

          // Check to see if there's a value that goes with this option?
          if((i < args.Length) && (!args[i].StartsWith("-"))) value = args[i++];
          parsedArgs.Add(key, value);
        }

        // If the first argument in this iteration doesn't start with a dash, it's a value
        else
        {
          parsedArgs.Add("--NoKey" + n.ToString(), args[i++]);
          n++;
        }
      }

      return parsedArgs;
    }

    //
    // Method to get an argument from the parsed command-line arguments
    //
    // Parameters:
    // - parsedArgs: The Dictionary object returned from the Parse() method (shown above).
    // - defaultValue: The default string to return if the specified key isn't in parsedArgs.
    // - keys: An array of keys to look for in parsedArgs.
    public static string GetArgument(
      Dictionary<string,string> parsedArgs, string defaultReturn, params string[] keys)
    {
      string retval = null;
      foreach(var key in keys)
        if(parsedArgs.TryGetValue(key, out retval)) break;
      return retval ?? defaultReturn;
    }

    //
    // Method to exit the application with an error.
    public static void ErrorExit(string msg, int code=1)
    {
      Console.WriteLine("\nError");
      Console.WriteLine(msg);
      Environment.Exit(code);
    }
  }

}
```

## Considerações adicionais
<a name="UpdateSqsQueue-additional"></a>
+ Para atualizar o `RedrivePolicy` atributo, você deve cotar o valor inteiro e escapar das aspas dos key/value pares, conforme apropriado para seu sistema operacional.

  No Windows, por exemplo, o valor é construído de forma semelhante ao seguinte:

  ```
  "{\"deadLetterTargetArn\":\"DEAD_LETTER-QUEUE-ARN\",\"maxReceiveCount\":\"10\"}"
  ```

# Excluindo filas do Amazon SQS
<a name="DeleteSqsQueue"></a>

Este exemplo mostra como usar o AWS SDK para .NET para excluir uma fila do Amazon SQS. A explicação exclui a fila, espera até um determinado período de tempo até que a fila seja excluída e, em seguida, mostra uma lista de filas restantes.

Se você não fornecer nenhum argumento de linha de comando, a aplicação simplesmente mostrará uma lista de filas existentes.

As seções a seguir fornecem snippets desse exemplo. O [código completo do exemplo](#DeleteSqsQueue-complete-code) é mostrado depois e pode ser criado e executado como está.

**Topics**
+ [Excluir a fila](#DeleteSqsQueue-delete-queue)
+ [Aguardar até a fila ser removida](#DeleteSqsQueue-wait)
+ [Mostrar uma lista de filas existentes](#DeleteSqsQueue-list-queues)
+ [Código completo](#DeleteSqsQueue-complete-code)
+ [Considerações adicionais](#DeleteSqsQueue-additional)

## Excluir a fila
<a name="DeleteSqsQueue-delete-queue"></a>

O snippet a seguir exclui a fila identificada pelo URL da fila em questão.

O exemplo [no final deste tópico](#DeleteSqsQueue-complete-code) mostra o snippet em uso.

```
    //
    // Method to delete an SQS queue
    private static async Task DeleteQueue(IAmazonSQS sqsClient, string qUrl)
    {
      Console.WriteLine($"Deleting queue {qUrl}...");
      await sqsClient.DeleteQueueAsync(qUrl);
      Console.WriteLine($"Queue {qUrl} has been deleted.");
    }
```

## Aguardar até a fila ser removida
<a name="DeleteSqsQueue-wait"></a>

O snippet a seguir aguarda a conclusão do processo de exclusão, o que pode levar até 60 segundos.

O exemplo [no final deste tópico](#DeleteSqsQueue-complete-code) mostra o snippet em uso.

```
    //
    // Method to wait up to a given number of seconds
    private static async Task Wait(
      IAmazonSQS sqsClient, int numSeconds, string qUrl)
    {
      Console.WriteLine($"Waiting for up to {numSeconds} seconds.");
      Console.WriteLine("Press any key to stop waiting. (Response might be slightly delayed.)");
      for(int i=0; i<numSeconds; i++)
      {
        Console.Write(".");
        Thread.Sleep(1000);
        if(Console.KeyAvailable) break;

        // Check to see if the queue is gone yet
        var found = false;
        ListQueuesResponse responseList = await sqsClient.ListQueuesAsync("");
        foreach(var url in responseList.QueueUrls)
        {
          if(url == qUrl)
          {
            found = true;
            break;
          }
        }
        if(!found) break;
      }
    }
```

## Mostrar uma lista de filas existentes
<a name="DeleteSqsQueue-list-queues"></a>

O trecho a seguir mostra uma lista das filas existentes na região do cliente SQS.

O exemplo [no final deste tópico](#DeleteSqsQueue-complete-code) mostra o snippet em uso.

```
    //
    // Method to show a list of the existing queues
    private static async Task ListQueues(IAmazonSQS sqsClient)
    {
      ListQueuesResponse responseList = await sqsClient.ListQueuesAsync("");
      Console.WriteLine("\nList of queues:");
      foreach(var qUrl in responseList.QueueUrls)
        Console.WriteLine($"- {qUrl}");
    }
```

## Código completo
<a name="DeleteSqsQueue-complete-code"></a>

Esta seção mostra as referências relevantes e o código completo desse exemplo.

### Referências do SDK
<a name="w2aac19c15c25c21c25b5b1"></a>

NuGet pacotes:
+ [AWSSDK.SQS](https://www.nuget.org/packages/AWSSDK.SQS)

Elementos de programação:
+ Namespace [Amazon.SQS](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/SQS/NSQS.html)

  Classe [Amazon SQSClient](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/SQS/TSQSClient.html)
+ Namespace [Amazon.SQS.Model](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/SQS/NSQSModel.html)

  Classe [ListQueuesResponse](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/SQS/TListQueuesResponse.html)

### O código
<a name="w2aac19c15c25c21c25b7b1"></a>

```
using System;
using System.Threading;
using System.Threading.Tasks;
using Amazon.SQS;
using Amazon.SQS.Model;

namespace SQSDeleteQueue
{
  // = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =
  // Class to update a queue
  class Program
  {
    private const int TimeToWait = 60;

    static async Task Main(string[] args)
    {
      // Create the Amazon SQS client
      var sqsClient = new AmazonSQSClient();

      // If no command-line arguments, just show a list of the queues
      if(args.Length == 0)
      {
        Console.WriteLine("\nUsage: SQSCreateQueue queue_url");
        Console.WriteLine("   queue_url - The URL of the queue you want to delete.");
        Console.WriteLine("\nNo arguments specified.");
        Console.Write("Do you want to see a list of the existing queues? ((y) or n): ");
        var response = Console.ReadLine();
        if((string.IsNullOrEmpty(response)) || (response.ToLower() == "y"))
          await ListQueues(sqsClient);
        return;
      }

      // If given a queue URL, delete that queue
      if(args[0].StartsWith("https://sqs."))
      {
        // Delete the queue
        await DeleteQueue(sqsClient, args[0]);
        // Wait for a little while because it takes a while for the queue to disappear
        await Wait(sqsClient, TimeToWait, args[0]);
        // Show a list of the remaining queues
        await ListQueues(sqsClient);
      }
      else
      {
        Console.WriteLine("The command-line argument isn't a queue URL:");
        Console.WriteLine($"{args[0]}");
      }
    }


    //
    // Method to delete an SQS queue
    private static async Task DeleteQueue(IAmazonSQS sqsClient, string qUrl)
    {
      Console.WriteLine($"Deleting queue {qUrl}...");
      await sqsClient.DeleteQueueAsync(qUrl);
      Console.WriteLine($"Queue {qUrl} has been deleted.");
    }


    //
    // Method to wait up to a given number of seconds
    private static async Task Wait(
      IAmazonSQS sqsClient, int numSeconds, string qUrl)
    {
      Console.WriteLine($"Waiting for up to {numSeconds} seconds.");
      Console.WriteLine("Press any key to stop waiting. (Response might be slightly delayed.)");
      for(int i=0; i<numSeconds; i++)
      {
        Console.Write(".");
        Thread.Sleep(1000);
        if(Console.KeyAvailable) break;

        // Check to see if the queue is gone yet
        var found = false;
        ListQueuesResponse responseList = await sqsClient.ListQueuesAsync("");
        foreach(var url in responseList.QueueUrls)
        {
          if(url == qUrl)
          {
            found = true;
            break;
          }
        }
        if(!found) break;
      }
    }


    //
    // Method to show a list of the existing queues
    private static async Task ListQueues(IAmazonSQS sqsClient)
    {
      ListQueuesResponse responseList = await sqsClient.ListQueuesAsync("");
      Console.WriteLine("\nList of queues:");
      foreach(var qUrl in responseList.QueueUrls)
        Console.WriteLine($"- {qUrl}");
    }
  }
}
```

## Considerações adicionais
<a name="DeleteSqsQueue-additional"></a>
+ A chamada de API `DeleteQueueAsync` não verifica se a fila que você está excluindo está sendo usada como uma fila de mensagens não entregues. Um procedimento mais sofisticado poderia verificar isso.
+ Você também pode ver a lista de filas e os resultados desse exemplo no [console do Amazon SQS](https://console.aws.amazon.com/sqs).

# Enviando mensagens SMS do Amazon
<a name="SendMessage"></a>

[Este exemplo mostra como usar o para enviar mensagens AWS SDK para .NET para uma fila do Amazon SQS, que você pode criar [programaticamente](CreateQueue.md) ou usando o console do Amazon SQS.](https://console.aws.amazon.com/sqs) A aplicação envia uma única mensagem para a fila e, em seguida, um lote de mensagens. Em seguida, a aplicação aguarda a entrada do usuário, que pode ser mensagens adicionais para enviar para a fila ou uma solicitação para sair da aplicação.

Este exemplo e o [próximo exemplo sobre o recebimento de mensagens](ReceiveMessage.md) podem ser usados juntos para ver o fluxo de mensagens no Amazon SQS.

As seções a seguir fornecem snippets desse exemplo. O [código completo do exemplo](#SendMessage-complete-code) é mostrado depois e pode ser criado e executado como está.

**Topics**
+ [Enviar uma mensagem](#SendMessage-send-message)
+ [Enviar um lote de mensagens](#SendMessage-send-batch)
+ [Excluir todas as mensagens da fila](#SendMessage-purge-messages)
+ [Código completo](#SendMessage-complete-code)
+ [Considerações adicionais](#SendMessage-additional)

## Enviar uma mensagem
<a name="SendMessage-send-message"></a>

O snippet a seguir envia uma mensagem para a fila identificada pelo URL da fila em questão.

O exemplo [no final deste tópico](#SendMessage-complete-code) mostra o snippet em uso.

```
    //
    // Method to put a message on a queue
    // Could be expanded to include message attributes, etc., in a SendMessageRequest
    private static async Task SendMessage(
      IAmazonSQS sqsClient, string qUrl, string messageBody)
    {
      SendMessageResponse responseSendMsg =
        await sqsClient.SendMessageAsync(qUrl, messageBody);
      Console.WriteLine($"Message added to queue\n  {qUrl}");
      Console.WriteLine($"HttpStatusCode: {responseSendMsg.HttpStatusCode}");
    }
```

## Enviar um lote de mensagens
<a name="SendMessage-send-batch"></a>

O snippet a seguir envia um lote de mensagens para a fila identificada pelo URL da fila em questão.

O exemplo [no final deste tópico](#SendMessage-complete-code) mostra o snippet em uso.

```
    //
    // Method to put a batch of messages on a queue
    // Could be expanded to include message attributes, etc.,
    // in the SendMessageBatchRequestEntry objects
    private static async Task SendMessageBatch(
      IAmazonSQS sqsClient, string qUrl, List<SendMessageBatchRequestEntry> messages)
    {
      Console.WriteLine($"\nSending a batch of messages to queue\n  {qUrl}");
      SendMessageBatchResponse responseSendBatch =
        await sqsClient.SendMessageBatchAsync(qUrl, messages);
      // Could test responseSendBatch.Failed here
      foreach(SendMessageBatchResultEntry entry in responseSendBatch.Successful)
        Console.WriteLine($"Message {entry.Id} successfully queued.");
    }
```

## Excluir todas as mensagens da fila
<a name="SendMessage-purge-messages"></a>

O snippet a seguir exclui todas as mensagens da fila identificada pelo URL da fila em questão. Isso também é conhecido como *limpando a fila*.

O exemplo [no final deste tópico](#SendMessage-complete-code) mostra o snippet em uso.

```
    //
    // Method to delete all messages from the queue
    private static async Task DeleteAllMessages(IAmazonSQS sqsClient, string qUrl)
    {
      Console.WriteLine($"\nPurging messages from queue\n  {qUrl}...");
      PurgeQueueResponse responsePurge = await sqsClient.PurgeQueueAsync(qUrl);
      Console.WriteLine($"HttpStatusCode: {responsePurge.HttpStatusCode}");
    }
```

## Código completo
<a name="SendMessage-complete-code"></a>

Esta seção mostra as referências relevantes e o código completo desse exemplo.

### Referências do SDK
<a name="w2aac19c15c25c23c25b5b1"></a>

NuGet pacotes:
+ [AWSSDK.SQS](https://www.nuget.org/packages/AWSSDK.SQS)

Elementos de programação:
+ Namespace [Amazon.SQS](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/SQS/NSQS.html)

  Classe [Amazon SQSClient](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/SQS/TSQSClient.html)
+ Namespace [Amazon.SQS.Model](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/SQS/NSQSModel.html)

  Classe [PurgeQueueResponse](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/SQS/TPurgeQueueResponse.html)

  Classe [SendMessageBatchResponse](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/SQS/TSendMessageBatchResponse.html)

  Classe [SendMessageResponse](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/SQS/TSendMessageResponse.html)

  Classe [SendMessageBatchRequestEntry](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/SQS/TSendMessageBatchRequestEntry.html)

  Classe [SendMessageBatchResultEntry](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/SQS/TSendMessageBatchResultEntry.html)

### O código
<a name="w2aac19c15c25c23c25b7b1"></a>

```
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Amazon.SQS;
using Amazon.SQS.Model;

namespace SQSSendMessages
{
  // = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =
  // Class to send messages to a queue
  class Program
  {
    // Some example messages to send to the queue
    private const string JsonMessage = "{\"product\":[{\"name\":\"Product A\",\"price\": \"32\"},{\"name\": \"Product B\",\"price\": \"27\"}]}";
    private const string XmlMessage = "<products><product name=\"Product A\" price=\"32\" /><product name=\"Product B\" price=\"27\" /></products>";
    private const string CustomMessage = "||product|Product A|32||product|Product B|27||";
    private const string TextMessage = "Just a plain text message.";

    static async Task Main(string[] args)
    {
      // Do some checks on the command-line
      if(args.Length == 0)
      {
        Console.WriteLine("\nUsage: SQSSendMessages queue_url");
        Console.WriteLine("   queue_url - The URL of an existing SQS queue.");
        return;
      }
      if(!args[0].StartsWith("https://sqs."))
      {
        Console.WriteLine("\nThe command-line argument isn't a queue URL:");
        Console.WriteLine($"{args[0]}");
        return;
      }

      // Create the Amazon SQS client
      var sqsClient = new AmazonSQSClient();

      // (could verify that the queue exists)
      // Send some example messages to the given queue
      // A single message
      await SendMessage(sqsClient, args[0], JsonMessage);

      // A batch of messages
      var batchMessages = new List<SendMessageBatchRequestEntry>{
        new SendMessageBatchRequestEntry("xmlMsg", XmlMessage),
        new SendMessageBatchRequestEntry("customeMsg", CustomMessage),
        new SendMessageBatchRequestEntry("textMsg", TextMessage)};
      await SendMessageBatch(sqsClient, args[0], batchMessages);

      // Let the user send their own messages or quit
      await InteractWithUser(sqsClient, args[0]);

      // Delete all messages that are still in the queue
      await DeleteAllMessages(sqsClient, args[0]);
    }


    //
    // Method to put a message on a queue
    // Could be expanded to include message attributes, etc., in a SendMessageRequest
    private static async Task SendMessage(
      IAmazonSQS sqsClient, string qUrl, string messageBody)
    {
      SendMessageResponse responseSendMsg =
        await sqsClient.SendMessageAsync(qUrl, messageBody);
      Console.WriteLine($"Message added to queue\n  {qUrl}");
      Console.WriteLine($"HttpStatusCode: {responseSendMsg.HttpStatusCode}");
    }


    //
    // Method to put a batch of messages on a queue
    // Could be expanded to include message attributes, etc.,
    // in the SendMessageBatchRequestEntry objects
    private static async Task SendMessageBatch(
      IAmazonSQS sqsClient, string qUrl, List<SendMessageBatchRequestEntry> messages)
    {
      Console.WriteLine($"\nSending a batch of messages to queue\n  {qUrl}");
      SendMessageBatchResponse responseSendBatch =
        await sqsClient.SendMessageBatchAsync(qUrl, messages);
      // Could test responseSendBatch.Failed here
      foreach(SendMessageBatchResultEntry entry in responseSendBatch.Successful)
        Console.WriteLine($"Message {entry.Id} successfully queued.");
    }


    //
    // Method to get input from the user
    // They can provide messages to put in the queue or exit the application
    private static async Task InteractWithUser(IAmazonSQS sqsClient, string qUrl)
    {
      string response;
      while (true)
      {
        // Get the user's input
        Console.WriteLine("\nType a message for the queue or \"exit\" to quit:");
        response = Console.ReadLine();
        if(response.ToLower() == "exit") break;

        // Put the user's message in the queue
        await SendMessage(sqsClient, qUrl, response);
      }
    }


    //
    // Method to delete all messages from the queue
    private static async Task DeleteAllMessages(IAmazonSQS sqsClient, string qUrl)
    {
      Console.WriteLine($"\nPurging messages from queue\n  {qUrl}...");
      PurgeQueueResponse responsePurge = await sqsClient.PurgeQueueAsync(qUrl);
      Console.WriteLine($"HttpStatusCode: {responsePurge.HttpStatusCode}");
    }
  }
}
```

## Considerações adicionais
<a name="SendMessage-additional"></a>
+ Para obter informações sobre várias limitações nas mensagens, incluindo os caracteres permitidos, consulte [Cotas relacionadas às mensagens](https://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/sqs-quotas.html#quotas-messages) no Guia do [desenvolvedor do Amazon Simple Queue Service](https://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/).
+ As mensagens permanecem nas filas até serem excluídas ou a fila ser removida. Quando uma mensagem for recebida por uma aplicação, ela não ficará visível na fila, mesmo que ainda exista na fila. Para obter mais informações sobre tempos limite de visibilidade, consulte [Tempo limite de visibilidade do Amazon SQS](https://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/AboutVT.html).
+ Além do corpo da mensagem, você também pode adicionar atributos às mensagens. Para obter mais informações, consulte [Mensagem de metadados](https://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/sqs-message-metadata.html).

# Recebimento de mensagens do Amazon SQS
<a name="ReceiveMessage"></a>

[Este exemplo mostra como usar o AWS SDK para .NET para receber mensagens de uma fila do Amazon SQS, que você pode criar [programaticamente](CreateQueue.md) ou usando o console do Amazon SQS.](https://console.aws.amazon.com/sqs) A aplicação lê uma única mensagem da fila, processa a mensagem (nesse caso, exibe o corpo da mensagem no console) e, em seguida, exclui a mensagem da fila. A aplicação repete essas etapas até que o usuário digite uma tecla no teclado.

Este exemplo e o [exemplo anterior sobre envio de mensagens](SendMessage.md), podem ser usados juntos para ver o fluxo de mensagens no Amazon SQS.

As seções a seguir fornecem snippets desse exemplo. O [código completo do exemplo](#ReceiveMessage-complete-code) é mostrado depois e pode ser criado e executado como está.

**Topics**
+ [Recebimento de uma mensagem](#ReceiveMessage-receive)
+ [Excluir uma mensagem](#ReceiveMessage-delete)
+ [Código completo](#ReceiveMessage-complete-code)
+ [Considerações adicionais](#ReceiveMessage-additional)

## Recebimento de uma mensagem
<a name="ReceiveMessage-receive"></a>

O trecho a seguir recebe uma mensagem da fila identificada pelo URL da fila em questão.

O exemplo [no final deste tópico](#ReceiveMessage-complete-code) mostra o snippet em uso.

```
    //
    // Method to read a message from the given queue
    // In this example, it gets one message at a time
    private static async Task<ReceiveMessageResponse> GetMessage(
      IAmazonSQS sqsClient, string qUrl, int waitTime=0)
    {
      return await sqsClient.ReceiveMessageAsync(new ReceiveMessageRequest{
        QueueUrl=qUrl,
        MaxNumberOfMessages=MaxMessages,
        WaitTimeSeconds=waitTime
        // (Could also request attributes, set visibility timeout, etc.)
      });
    }
```

## Excluir uma mensagem
<a name="ReceiveMessage-delete"></a>

O snippet a seguir exclui uma mensagem da fila identificada pelo URL da fila em questão.

O exemplo [no final deste tópico](#ReceiveMessage-complete-code) mostra o snippet em uso.

```
    //
    // Method to delete a message from a queue
    private static async Task DeleteMessage(
      IAmazonSQS sqsClient, Message message, string qUrl)
    {
      Console.WriteLine($"\nDeleting message {message.MessageId} from queue...");
      await sqsClient.DeleteMessageAsync(qUrl, message.ReceiptHandle);
    }
```

## Código completo
<a name="ReceiveMessage-complete-code"></a>

Esta seção mostra as referências relevantes e o código completo desse exemplo.

### Referências do SDK
<a name="w2aac19c15c25c25c21b5b1"></a>

NuGet pacotes:
+ [AWSSDK.SQS](https://www.nuget.org/packages/AWSSDK.SQS)

Elementos de programação:
+ Namespace [Amazon.SQS](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/SQS/NSQS.html)

  Classe [Amazon SQSClient](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/SQS/TSQSClient.html)
+ Namespace [Amazon.SQS.Model](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/SQS/NSQSModel.html)

  Classe [ReceiveMessageRequest](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/SQS/TReceiveMessageRequest.html)

  Classe [ReceiveMessageResponse](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/SQS/TReceiveMessageResponse.html)

### O código
<a name="w2aac19c15c25c25c21b7b1"></a>

```
using System;
using System.Threading.Tasks;
using Amazon.SQS;
using Amazon.SQS.Model;

namespace SQSReceiveMessages
{
  class Program
  {
    private const int MaxMessages = 1;
    private const int WaitTime = 2;
    static async Task Main(string[] args)
    {
      // Do some checks on the command-line
      if(args.Length == 0)
      {
        Console.WriteLine("\nUsage: SQSReceiveMessages queue_url");
        Console.WriteLine("   queue_url - The URL of an existing SQS queue.");
        return;
      }
      if(!args[0].StartsWith("https://sqs."))
      {
        Console.WriteLine("\nThe command-line argument isn't a queue URL:");
        Console.WriteLine($"{args[0]}");
        return;
      }

      // Create the Amazon SQS client
      var sqsClient = new AmazonSQSClient();

      // (could verify that the queue exists)
      // Read messages from the queue and perform appropriate actions
      Console.WriteLine($"Reading messages from queue\n  {args[0]}");
      Console.WriteLine("Press any key to stop. (Response might be slightly delayed.)");
      do
      {
        var msg = await GetMessage(sqsClient, args[0], WaitTime);
        if(msg.Messages.Count != 0)
        {
          if(ProcessMessage(msg.Messages[0]))
            await DeleteMessage(sqsClient, msg.Messages[0], args[0]);
        }
      } while(!Console.KeyAvailable);
    }


    //
    // Method to read a message from the given queue
    // In this example, it gets one message at a time
    private static async Task<ReceiveMessageResponse> GetMessage(
      IAmazonSQS sqsClient, string qUrl, int waitTime=0)
    {
      return await sqsClient.ReceiveMessageAsync(new ReceiveMessageRequest{
        QueueUrl=qUrl,
        MaxNumberOfMessages=MaxMessages,
        WaitTimeSeconds=waitTime
        // (Could also request attributes, set visibility timeout, etc.)
      });
    }


    //
    // Method to process a message
    // In this example, it simply prints the message
    private static bool ProcessMessage(Message message)
    {
      Console.WriteLine($"\nMessage body of {message.MessageId}:");
      Console.WriteLine($"{message.Body}");
      return true;
    }


    //
    // Method to delete a message from a queue
    private static async Task DeleteMessage(
      IAmazonSQS sqsClient, Message message, string qUrl)
    {
      Console.WriteLine($"\nDeleting message {message.MessageId} from queue...");
      await sqsClient.DeleteMessageAsync(qUrl, message.ReceiptHandle);
    }
  }
}
```

## Considerações adicionais
<a name="ReceiveMessage-additional"></a>
+ Para especificar uma sondagem longa, este exemplo usa a propriedade `WaitTimeSeconds` de cada chamada ao método `ReceiveMessageAsync`.

  Você também pode especificar uma sondagem longa para todas as mensagens em uma fila usando o atributo `ReceiveMessageWaitTimeSeconds` ao [criar](CreateQueue.md) ou [atualizar](UpdateSqsQueue.md) a fila.

  Para obter informações sobre sondagem curta versus sondagem longa, consulte [Sondagem curta e longa](https://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/sqs-short-and-long-polling.html) no *Guia do desenvolvedor do Amazon Simple Queue Service*.
+ Durante o processamento da mensagem, você pode usar o identificador de recebimento para alterar o tempo limite de visibilidade da mensagem. Para obter informações sobre como fazer isso, consulte os `ChangeMessageVisibilityAsync` métodos da SQSClient classe [Amazon](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/SQS/TSQSClient.html).
+ Chamar o método `DeleteMessageAsync` remove a mensagem da fila incondicionalmente, qualquer que seja a configuração do tempo limite de visibilidade.