

 AWS SDK for .NET V3 がメンテナンスモードになりました。

[AWS SDK for .NET V4](https://docs.aws.amazon.com/sdk-for-net/v4/developer-guide/welcome.html) に移行することをお勧めします。移行方法の詳細と情報については、[メンテナンスモードのお知らせ](https://aws.amazon.com/blogs/developer/aws-sdk-for-net-v3-maintenance-mode-announcement/)を参照してください。

翻訳は機械翻訳により提供されています。提供された翻訳内容と英語版の間で齟齬、不一致または矛盾がある場合、英語版が優先します。

# Amazon SQS を使用したメッセージング
<a name="sqs-apis-intro"></a>

は[、Amazon Simple Queue Service (Amazon SQS)](https://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/) AWS SDK for .NET をサポートします。これは、システム内のコンポーネント間のメッセージまたはワークフローを処理するメッセージキューイングサービスです。

Amazon SQS キューは、マイクロサービス、分散システム、サーバーレスアプリケーションなどのソフトウェアコンポーネント間でメッセージを送信、保存、受信できる仕組みを提供します。その結果、こうしたコンポーネントを切り離すことができるようになり、独自のメッセージングシステムを設計および運用する必要がなくなります。Amazon SQS でのキューとメッセージの仕組みに関する詳細については、[Amazon SQS のチュートリアル](https://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/sqs-other-tutorials.html)および「[Amazon Simple Queue Service デベロッパーガイド](https://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/)」の「[Amazon SQS の基本的なアーキテクチャ](https://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/sqs-basic-architecture.html)」を参照してください。

**重要**  
キューが持つ分散的な性質のため、Amazon SQS ではメッセージを送信された順序で受信することは保証できません。メッセージの順序を保持する必要がある場合は、[Amazon SQS FIFO キュー](https://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/sqs-fifo-queues.html)を使用してください。

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

 AWS SDK for .NET はAPIs Amazon SQS を提供します。API を使用すると、キューやメッセージなどの Amazon SQS 機能を操作できます。このセクションでは、これらの API を操作する際に活用できるパターンを示すいくつかの例を紹介します。API の完全なセットを確認するには、[AWS SDK for .NET API リファレンス](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/)を参照してください (「Amazon.SQS」までスクロールします)。

Amazon SQS API は、[AWSSDK.SQS](https://www.nuget.org/packages/AWSSDK.SQS) NuGet パッケージによって提供されます。

## 前提条件
<a name="w2aac19c15c25c11"></a>

開始する前に、[環境とプロジェクトがセットアップされている](net-dg-config.md)ことを必ず確認してください。また、「[SDK の機能](net-dg-sdk-features.md)」の情報を確認してください。

## トピック
<a name="w2aac19c15c25c13"></a>

**Topics**
+ [API](#w2aac19c15c25b9)
+ [前提条件](#w2aac19c15c25c11)
+ [トピック](#w2aac19c15c25c13)
+ [キューの作成](CreateQueue.md)
+ [キューの更新](UpdateSqsQueue.md)
+ [キューの削除](DeleteSqsQueue.md)
+ [メッセージの送信](SendMessage.md)
+ [メッセージの受信](ReceiveMessage.md)

# Amazon SQS キューの作成
<a name="CreateQueue"></a>

この例では、 AWS SDK for .NET を使用して Amazon SQS キューを作成する方法を示します。ユーザーがデッドレターキューの ARN を指定しない場合、アプリケーションは[デッドレターキュー](https://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/sqs-dead-letter-queues.html)を作成します。次に、デッドレターキュー (ユーザーが指定したもの、または作成されたもの) を含む標準メッセージキューを作成します。

コマンドライン引数を何も指定しない場合、アプリケーションは単に既存のすべてのキューに関する情報を表示します。

以下のセクションでは、この例のスニペットを確認できます。その下には、[この例のコードの全文](#CreateQueue-complete-code)が示されており、そのままビルドして実行できます。

**Topics**
+ [既存のキューの表示](#CreateQueue-show-queues)
+ [キューの作成](#CreateQueue-create-queue)
+ [キューの ARN の取得](#CreateQueue-get-arn)
+ [コード全文](#CreateQueue-complete-code)
+ [その他の考慮事項](#CreateQueue-additional)

## 既存のキューの表示
<a name="CreateQueue-show-queues"></a>

次のスニペットでは、SQS クライアントのリージョンにある既存のキューのリストと、各キューの属性を表示します。

[このトピックの最後](#CreateQueue-complete-code)で、スニペットが実際に使用されている例を確認できます。

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

## キューの作成
<a name="CreateQueue-create-queue"></a>

次のスニペットでは、キューが作成されます。このスニペットにはデッドレターキューの使用が含まれていますが、デッドレターキューは必ずしもキューに必要ではありません。

[このトピックの最後](#CreateQueue-complete-code)で、スニペットが実際に使用されている例を確認できます。

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

## キューの ARN の取得
<a name="CreateQueue-get-arn"></a>

次のスニペットでは、指定されたキュー URL で特定されるキューの ARN を取得します。

[このトピックの最後](#CreateQueue-complete-code)で、スニペットが実際に使用されている例を確認できます。

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

## コード全文
<a name="CreateQueue-complete-code"></a>

このセクションでは、例に関連する参考資料とコードの全文を示します。

### SDK リファレンス
<a name="w2aac19c15c25c17c25b5b1"></a>

NuGet パッケージ:
+ [AWSSDK.SQS](https://www.nuget.org/packages/AWSSDK.SQS)

プログラミング要素:
+ 名前空間 [Amazon.SQS](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/SQS/NSQS.html)

  クラス [AmazonSQSClient](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/SQS/TSQSClient.html)

  クラス [QueueAttributeName](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/SQS/TQueueAttributeName.html)
+ 名前空間 [Amazon.SQS.Model](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/SQS/NSQSModel.html)

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

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

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

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

### コード
<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);
    }
  }

}
```

## その他の考慮事項
<a name="CreateQueue-additional"></a>
+ キュー名は、英数字、ハイフン、およびアンダースコアで構成する必要があります。
+ キュー名とキュー URL では大文字と小文字が区別されます。
+ キュー URL が必要なときにキュー名しかない場合には、`AmazonSQSClient.GetQueueUrlAsync` メソッドのいずれかを使用してください。
+ 設定できるさまざまなキュー属性の詳細については、[AWS SDK for .NET API リファレンス](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/)の「[CreateQueueRequest](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/SQS/TCreateQueueRequest.html)」か、または [Amazon Simple Queue Service API リファレンス](https://docs.aws.amazon.com/AWSSimpleQueueService/latest/APIReference/)の「[SetQueueAttributes](https://docs.aws.amazon.com/AWSSimpleQueueService/latest/APIReference/API_SetQueueAttributes.html)」を参照してください。
+ この例では、作成するキュー上のすべてのメッセージに対してロングポーリングを指定します。これは `ReceiveMessageWaitTimeSeconds` 属性を使用して行われます。

  [AmazonSQSClient](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/SQS/TSQSClient.html) クラスの `ReceiveMessageAsync` メソッドの呼び出し中にロングポーリングを指定することもできます。詳細については、「[Amazon SQS メッセージの受信](ReceiveMessage.md)」を参照してください。

  ショートポーリングとロングポーリングの違いに関する詳細については、*Amazon Simple Queue Service デベロッパーガイド*の「[ショートポーリングとロングポーリング](https://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/sqs-short-and-long-polling.html)」を参照してください。
+ デッドレターキューとは、他の (送信元) キューが正常に処理されないメッセージの送信先として使用できるキューのことです。詳細については、Amazon Simple Queue Service デベロッパーガイドの「[Amazon SQS デッドレターキュー](https://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/sqs-dead-letter-queues.html)」を参照してください。
+ キューのリストとこの例の結果は、[Amazon SQS コンソール](https://console.aws.amazon.com/sqs)でも確認できます。

# Amazon SQS キューの更新
<a name="UpdateSqsQueue"></a>

この例では、 AWS SDK for .NET を使用して Amazon SQS キューを更新する方法を示します。アプリケーションはいくつかのチェックを行った後、指定された属性を指定された値で更新し、キューのすべての属性を表示します。

コマンドライン引数にキュー URL のみを含めた場合、アプリケーションは単にキューのすべての属性を表示します。

以下のセクションでは、この例のスニペットを確認できます。その下には、[この例のコードの全文](#UpdateSqsQueue-complete-code)が示されており、そのままビルドして実行できます。

**Topics**
+ [キュー属性の表示](#UpdateSqsQueue-show-attributes)
+ [属性名の検証](#UpdateSqsQueue-validate-attribute)
+ [キュー属性の更新](#UpdateSqsQueue-update-attribute)
+ [コード全文](#UpdateSqsQueue-complete-code)
+ [その他の考慮事項](#UpdateSqsQueue-additional)

## キュー属性の表示
<a name="UpdateSqsQueue-show-attributes"></a>

次のスニペットでは、指定されたキュー URL で特定されるキューの属性を表示します。

[このトピックの最後](#UpdateSqsQueue-complete-code)で、スニペットが実際に使用されている例を確認できます。

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

## 属性名の検証
<a name="UpdateSqsQueue-validate-attribute"></a>

次のスニペットでは、更新される属性の名前を検証します。

[このトピックの最後](#UpdateSqsQueue-complete-code)で、スニペットが実際に使用されている例を確認できます。

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

## キュー属性の更新
<a name="UpdateSqsQueue-update-attribute"></a>

次のスニペットでは、指定されたキュー URL で特定されるキューの属性を更新します。

[このトピックの最後](#UpdateSqsQueue-complete-code)で、スニペットが実際に使用されている例を確認できます。

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

## コード全文
<a name="UpdateSqsQueue-complete-code"></a>

このセクションでは、例に関連する参考資料とコードの全文を示します。

### SDK リファレンス
<a name="w2aac19c15c25c19c25b5b1"></a>

NuGet パッケージ:
+ [AWSSDK.SQS](https://www.nuget.org/packages/AWSSDK.SQS)

プログラミング要素:
+ 名前空間 [Amazon.SQS](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/SQS/NSQS.html)

  クラス [AmazonSQSClient](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/SQS/TSQSClient.html)

  クラス [QueueAttributeName](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/SQS/TQueueAttributeName.html)
+ 名前空間 [Amazon.SQS.Model](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/SQS/NSQSModel.html)

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

### コード
<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);
    }
  }

}
```

## その他の考慮事項
<a name="UpdateSqsQueue-additional"></a>
+ `RedrivePolicy` 属性を更新するには、値全体を引用符で囲み、キーと値のペアの引用符をお使いのオペレーティングシステムに応じた適切な方法でエスケープする必要があります。

  例えば Windows では、値は次のような形で構成されます。

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

# Amazon SQS キューの削除
<a name="DeleteSqsQueue"></a>

この例では、 AWS SDK for .NET を使用して Amazon SQS キューを削除する方法を示します。アプリケーションはキューを削除し、キューがなくなるまで一定時間待ってから、残っているキューのリストを表示します。

コマンドライン引数を何も指定しない場合、アプリケーションは単に既存のキューのリストを表示します。

以下のセクションでは、この例のスニペットを確認できます。その下には、[この例のコードの全文](#DeleteSqsQueue-complete-code)が示されており、そのままビルドして実行できます。

**Topics**
+ [キューの削除](#DeleteSqsQueue-delete-queue)
+ [キューがなくなるまで待機](#DeleteSqsQueue-wait)
+ [既存のキューのリストの表示](#DeleteSqsQueue-list-queues)
+ [コード全文](#DeleteSqsQueue-complete-code)
+ [その他の考慮事項](#DeleteSqsQueue-additional)

## キューの削除
<a name="DeleteSqsQueue-delete-queue"></a>

次のスニペットでは、指定されたキュー URL で特定されるキューを削除します。

[このトピックの最後](#DeleteSqsQueue-complete-code)で、スニペットが実際に使用されている例を確認できます。

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

## キューがなくなるまで待機
<a name="DeleteSqsQueue-wait"></a>

次のスニペットでは、削除プロセスが完了するまで待機します。この処理には 60 秒かかる場合があります。

[このトピックの最後](#DeleteSqsQueue-complete-code)で、スニペットが実際に使用されている例を確認できます。

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

## 既存のキューのリストの表示
<a name="DeleteSqsQueue-list-queues"></a>

次のスニペットでは、SQS クライアントのリージョンにある既存のキューのリストを表示します。

[このトピックの最後](#DeleteSqsQueue-complete-code)で、スニペットが実際に使用されている例を確認できます。

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

## コード全文
<a name="DeleteSqsQueue-complete-code"></a>

このセクションでは、例に関連する参考資料とコードの全文を示します。

### SDK リファレンス
<a name="w2aac19c15c25c21c25b5b1"></a>

NuGet パッケージ:
+ [AWSSDK.SQS](https://www.nuget.org/packages/AWSSDK.SQS)

プログラミング要素:
+ 名前空間 [Amazon.SQS](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/SQS/NSQS.html)

  クラス [AmazonSQSClient](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/SQS/TSQSClient.html)
+ 名前空間 [Amazon.SQS.Model](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/SQS/NSQSModel.html)

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

### コード
<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}");
    }
  }
}
```

## その他の考慮事項
<a name="DeleteSqsQueue-additional"></a>
+ `DeleteQueueAsync` API コールでは、削除しようとしているキューがデッドレターキューとして使用されているかどうかはチェックされません。チェックするには、より高度な手順が必要になります。
+ キューのリストとこの例の結果は、[Amazon SQS コンソール](https://console.aws.amazon.com/sqs)でも確認できます。

# Amazon SQS メッセージの送信
<a name="SendMessage"></a>

この例では、 を使用して Amazon SQS キューに AWS SDK for .NET メッセージを送信する方法を示します。このキューは、[プログラムで](CreateQueue.md)作成することも、[Amazon SQS コンソール](https://console.aws.amazon.com/sqs)を使用して作成することもできます。アプリケーションは 1 つのメッセージをキューに送信し、次にメッセージのバッチを送信します。その後、アプリケーションはユーザーからの入力を待ちます。入力としては、キューに送信する追加メッセージや、アプリケーションの終了要求などが考えられます。

この例と、[次のメッセージの受信に関する例](ReceiveMessage.md)を一緒に使用して、Amazon SQS のメッセージフローを確認できます。

以下のセクションでは、この例のスニペットを確認できます。その下には、[この例のコードの全文](#SendMessage-complete-code)が示されており、そのままビルドして実行できます。

**Topics**
+ [メッセージの送信](#SendMessage-send-message)
+ [メッセージのバッチの送信](#SendMessage-send-batch)
+ [キューからのすべてのメッセージの削除](#SendMessage-purge-messages)
+ [コード全文](#SendMessage-complete-code)
+ [その他の考慮事項](#SendMessage-additional)

## メッセージの送信
<a name="SendMessage-send-message"></a>

次のスニペットでは、指定されたキュー URL で特定されるキューにメッセージを送信します。

[このトピックの最後](#SendMessage-complete-code)で、スニペットが実際に使用されている例を確認できます。

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

## メッセージのバッチの送信
<a name="SendMessage-send-batch"></a>

次のスニペットでは、指定されたキュー URL で特定されるキューにメッセージのバッチを送信します。

[このトピックの最後](#SendMessage-complete-code)で、スニペットが実際に使用されている例を確認できます。

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

## キューからのすべてのメッセージの削除
<a name="SendMessage-purge-messages"></a>

次のスニペットでは、指定されたキュー URL で特定されるキューからすべてのメッセージを削除します。この操作は、*キューの消去*とも呼ばれます。

[このトピックの最後](#SendMessage-complete-code)で、スニペットが実際に使用されている例を確認できます。

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

## コード全文
<a name="SendMessage-complete-code"></a>

このセクションでは、例に関連する参考資料とコードの全文を示します。

### SDK リファレンス
<a name="w2aac19c15c25c23c25b5b1"></a>

NuGet パッケージ:
+ [AWSSDK.SQS](https://www.nuget.org/packages/AWSSDK.SQS)

プログラミング要素:
+ 名前空間 [Amazon.SQS](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/SQS/NSQS.html)

  クラス [AmazonSQSClient](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/SQS/TSQSClient.html)
+ 名前空間 [Amazon.SQS.Model](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/SQS/NSQSModel.html)

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

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

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

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

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

### コード
<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}");
    }
  }
}
```

## その他の考慮事項
<a name="SendMessage-additional"></a>
+ 許可される文字など、メッセージのさまざまな制限については、[Amazon Simple Queue Service デベロッパーガイド](https://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/)の「[メッセージに関連するクォータ](https://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/sqs-quotas.html#quotas-messages)」を参照してください。
+ メッセージは削除されるか、またはキューが消去されるまでキューに残ります。アプリケーションがメッセージを受信すると、そのメッセージはキュー内にまだ存在していたとしてもキューで表示されなくなります。可視性タイムアウトの詳細については、「[Amazon SQS 可視性タイムアウト](https://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/AboutVT.html)」を参照してください。
+ メッセージ本文に加えて、メッセージに属性を追加することもできます。詳細については、「[メッセージメタデータ](https://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/sqs-message-metadata.html)」を参照してください。

# Amazon SQS メッセージの受信
<a name="ReceiveMessage"></a>

この例では、 を使用して Amazon SQS キューからメッセージ AWS SDK for .NET を受信する方法を示します。このキューは、[プログラムまたは](CreateQueue.md) [Amazon SQS コンソール](https://console.aws.amazon.com/sqs)を使用して作成できます。アプリケーションはキューから 1 つのメッセージを読み取り、メッセージを処理 (この例ではコンソールにメッセージ本文を表示) した後で、キューからメッセージを削除します。アプリケーションは、ユーザーがキーボードでキーを入力するまで、これらの手順を繰り返します。

この例と、[前のメッセージの送信に関する例](SendMessage.md)を一緒に使用して、Amazon SQS のメッセージフローを確認できます。

以下のセクションでは、この例のスニペットを確認できます。その下には、[この例のコードの全文](#ReceiveMessage-complete-code)が示されており、そのままビルドして実行できます。

**Topics**
+ [メッセージの受信](#ReceiveMessage-receive)
+ [メッセージの削除](#ReceiveMessage-delete)
+ [コード全文](#ReceiveMessage-complete-code)
+ [その他の考慮事項](#ReceiveMessage-additional)

## メッセージの受信
<a name="ReceiveMessage-receive"></a>

次のスニペットでは、指定されたキュー URL で特定されるキューからメッセージを受信します。

[このトピックの最後](#ReceiveMessage-complete-code)で、スニペットが実際に使用されている例を確認できます。

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

## メッセージの削除
<a name="ReceiveMessage-delete"></a>

次のスニペットでは、指定されたキュー URL で特定されるキューからメッセージを削除します。

[このトピックの最後](#ReceiveMessage-complete-code)で、スニペットが実際に使用されている例を確認できます。

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

## コード全文
<a name="ReceiveMessage-complete-code"></a>

このセクションでは、例に関連する参考資料とコードの全文を示します。

### SDK リファレンス
<a name="w2aac19c15c25c25c21b5b1"></a>

NuGet パッケージ:
+ [AWSSDK.SQS](https://www.nuget.org/packages/AWSSDK.SQS)

プログラミング要素:
+ 名前空間 [Amazon.SQS](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/SQS/NSQS.html)

  クラス [AmazonSQSClient](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/SQS/TSQSClient.html)
+ 名前空間 [Amazon.SQS.Model](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/SQS/NSQSModel.html)

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

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

### コード
<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);
    }
  }
}
```

## その他の考慮事項
<a name="ReceiveMessage-additional"></a>
+ ロングポーリングを指定するために、この例では `ReceiveMessageAsync` メソッドへの各呼び出しで `WaitTimeSeconds` プロパティを使用しています。

  キューの[作成時](CreateQueue.md)または[更新時](UpdateSqsQueue.md)に `ReceiveMessageWaitTimeSeconds` 属性を使用して、キューのすべてのメッセージにロングポーリングを指定することもできます。

  ショートポーリングとロングポーリングの違いに関する詳細については、*Amazon Simple Queue Service デベロッパーガイド*の「[ショートポーリングとロングポーリング](https://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/sqs-short-and-long-polling.html)」を参照してください。
+ メッセージの処理中に受信ハンドルを使用して、メッセージの可視性タイムアウトを変更できます。その方法については、[AmazonSQSClient](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/SQS/TSQSClient.html) クラスの `ChangeMessageVisibilityAsync` メソッドを参照してください。
+ `DeleteMessageAsync` メソッドを無条件で呼び出すと、可視性タイムアウトの設定にかかわらず、メッセージがキューから削除されます。