

 AWS SDK untuk .NET V3 telah memasuki mode pemeliharaan.

Kami menyarankan Anda bermigrasi ke [AWS SDK untuk .NET V4](https://docs.aws.amazon.com/sdk-for-net/v4/developer-guide/welcome.html). Untuk detail dan informasi tambahan tentang cara bermigrasi, silakan lihat [pengumuman mode pemeliharaan](https://aws.amazon.com/blogs/developer/aws-sdk-for-net-v3-maintenance-mode-announcement/) kami.

Terjemahan disediakan oleh mesin penerjemah. Jika konten terjemahan yang diberikan bertentangan dengan versi bahasa Inggris aslinya, utamakan versi bahasa Inggris.

# Contoh kode dengan panduan untuk AWS SDK untuk .NET
<a name="tutorials-examples"></a>

Bagian berikut berisi contoh kode dan memberikan panduan untuk contoh. Mereka dapat membantu Anda mempelajari cara menggunakan AWS SDK untuk .NET untuk bekerja dengan AWS layanan.

Jika Anda baru mengenal AWS SDK untuk .NET, Anda mungkin ingin memeriksa [Ikuti tur singkat](quick-start.md) topik terlebih dahulu. Ini memberi Anda pengantar SDK.

Sebelum Anda mulai, pastikan Anda telah [mengatur lingkungan dan proyek Anda](net-dg-config.md). Juga tinjau informasi di[Fitur SDK](net-dg-sdk-features.md).

**Topics**
+ [CloudFormation](cloudformation-apis-intro.md)
+ [Amazon Cognito](cognito-apis-intro.md)
+ [DynamoDB](dynamodb-intro.md)
+ [Amazon EC2](ec2-apis-intro.md)
+ [IAM](iam-apis-intro.md)
+ [Amazon S3](s3-apis-intro.md)
+ [Amazon SNS](sns-apis-intro.md)
+ [Amazon SQS](sqs-apis-intro.md)

# Mengakses CloudFormation dengan AWS SDK untuk .NET
<a name="cloudformation-apis-intro"></a>

 AWS SDK untuk .NET Dukungan [AWS CloudFormation](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/), yang menciptakan dan menyediakan penyebaran AWS infrastruktur dapat diprediksi dan berulang kali.

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

 AWS SDK untuk .NET Menyediakan APIs untuk CloudFormation klien. Ini APIs memungkinkan Anda untuk bekerja dengan CloudFormation fitur seperti template dan tumpukan. Bagian ini berisi sejumlah kecil contoh yang menunjukkan pola yang dapat Anda ikuti saat bekerja dengan ini APIs. Untuk melihat set lengkap APIs, lihat [Referensi AWS SDK untuk .NET API](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/) (dan gulir ke “Amazon. CloudFormation“).

Yang AWS CloudFormation APIs disediakan oleh [AWSSDK. CloudFormation](https://www.nuget.org/packages/AWSSDK.CloudFormation/)paket.

## Prasyarat
<a name="w2aac19c15c11b7"></a>

Sebelum Anda mulai, pastikan Anda telah [mengatur lingkungan dan proyek Anda](net-dg-config.md). Juga tinjau informasi di[Fitur SDK](net-dg-sdk-features.md).

## Topik
<a name="w2aac19c15c11b9"></a>

**Topics**
+ [APIs](#w2aac19c15c11b5)
+ [Prasyarat](#w2aac19c15c11b7)
+ [Topik](#w2aac19c15c11b9)
+ [AWS Sumber daya daftar](cfn-list-resources.md)

# Daftar AWS sumber daya menggunakan AWS CloudFormation
<a name="cfn-list-resources"></a>

Contoh ini menunjukkan cara menggunakan daftar sumber daya dalam CloudFormation tumpukan. AWS SDK untuk .NET Contoh menggunakan API tingkat rendah. Aplikasi tidak mengambil argumen, tetapi hanya mengumpulkan informasi untuk semua tumpukan yang dapat diakses oleh kredensi pengguna dan kemudian menampilkan informasi tentang tumpukan tersebut.

## Referensi SDK
<a name="w2aac19c15c11c13b5b1"></a>

NuGet paket:
+ [AWSSDK.CloudFormation](https://www.nuget.org/packages/AWSSDK.CloudFormation/)

Elemen pemrograman:
+ [Namespace Amazon. CloudFormation](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/CloudFormation/NCloudFormation.html)

  Kelas [AmazonCloudFormationClient](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/CloudFormation/TCloudFormationClient.html)
+ [Namespace Amazon. CloudFormation.Model](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/CloudFormation/NCloudFormationModel.html)

  Kelas [ICloudFormationPaginatorFactory. DescribeStacks](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/CloudFormation/MICloudFormationPaginatorFactoryDescribeStacksDescribeStacksRequest.html)

  Kelas [DescribeStackResourcesRequest](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/CloudFormation/TDescribeStackResourcesRequest.html)

  Kelas [DescribeStackResourcesResponse](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/CloudFormation/TDescribeStackResourcesResponse.html)

  [Stack](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/CloudFormation/TStack.html) Kelas

  Kelas [StackResource](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/CloudFormation/TStackResource.html)

  [Tag](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/CloudFormation/TTag.html) Kelas

```
using Amazon.CloudFormation;
using Amazon.CloudFormation.Model;
using Amazon.Runtime;

namespace CloudFormationActions;

public static class HelloCloudFormation
{
    public static IAmazonCloudFormation _amazonCloudFormation;

    static async Task Main(string[] args)
    {
        // Create the CloudFormation client
        _amazonCloudFormation = new AmazonCloudFormationClient();
        Console.WriteLine($"\nIn Region: {_amazonCloudFormation.Config.RegionEndpoint}");

        // List the resources for each stack
        await ListResources();
    }

    /// <summary>
    /// Method to list stack resources and other information.
    /// </summary>
    /// <returns>True if successful.</returns>
    public static async Task<bool> ListResources()
    {
        try
        {
            Console.WriteLine("Getting CloudFormation stack information...");

            // Get all stacks using the stack paginator.
            var paginatorForDescribeStacks =
                _amazonCloudFormation.Paginators.DescribeStacks(
                    new DescribeStacksRequest());
            await foreach (Stack stack in paginatorForDescribeStacks.Stacks)
            {
                // Basic information for each stack
                Console.WriteLine("\n------------------------------------------------");
                Console.WriteLine($"\nStack: {stack.StackName}");
                Console.WriteLine($"  Status: {stack.StackStatus.Value}");
                Console.WriteLine($"  Created: {stack.CreationTime}");

                // The tags of each stack (etc.)
                if (stack.Tags.Count > 0)
                {
                    Console.WriteLine("  Tags:");
                    foreach (Tag tag in stack.Tags)
                        Console.WriteLine($"    {tag.Key}, {tag.Value}");
                }

                // The resources of each stack
                DescribeStackResourcesResponse responseDescribeResources =
                    await _amazonCloudFormation.DescribeStackResourcesAsync(
                        new DescribeStackResourcesRequest
                        {
                            StackName = stack.StackName
                        });
                if (responseDescribeResources.StackResources.Count > 0)
                {
                    Console.WriteLine("  Resources:");
                    foreach (StackResource resource in responseDescribeResources
                                 .StackResources)
                        Console.WriteLine(
                            $"    {resource.LogicalResourceId}: {resource.ResourceStatus}");
                }
            }

            Console.WriteLine("\n------------------------------------------------");
            return true;
        }
        catch (AmazonCloudFormationException ex)
        {
            Console.WriteLine("Unable to get stack information:\n" + ex.Message);
            return false;
        }
        catch (AmazonServiceException ex)
        {
            if (ex.Message.Contains("Unable to get IAM security credentials"))
            {
                Console.WriteLine(ex.Message);
                Console.WriteLine("If you are usnig SSO, be sure to install" +
                                  " the AWSSDK.SSO and AWSSDK.SSOOIDC packages.");
            }
            else
            {
                Console.WriteLine(ex.Message);
                Console.WriteLine(ex.StackTrace);
            }

            return false;
        }
        catch (ArgumentNullException ex)
        {
            if (ex.Message.Contains("Options property cannot be empty: ClientName"))
            {
                Console.WriteLine(ex.Message);
                Console.WriteLine("If you are using SSO, have you logged in?");
            }
            else
            {
                Console.WriteLine(ex.Message);
                Console.WriteLine(ex.StackTrace);
            }

            return false;
        }
    }
```

# Mengautentikasi pengguna dengan Amazon Cognito
<a name="cognito-apis-intro"></a>

**catatan**  
Informasi dalam topik ini khusus untuk proyek berdasarkan .NET Framework dan AWS SDK untuk .NET versi 3.3 dan sebelumnya.

Menggunakan Amazon Cognito Identity, Anda dapat membuat identitas unik untuk pengguna Anda dan mengautentikasi mereka untuk akses aman ke AWS sumber daya Anda seperti Amazon S3 atau Amazon DynamoDB. Amazon Cognito Identity mendukung penyedia identitas publik seperti Amazon, Facebook, Twitter/Digit, Google, atau penyedia yang kompatibel dengan OpenID Connect serta identitas yang tidak diautentikasi. Amazon Cognito juga mendukung [identitas otentikasi pengembang](https://aws.amazon.com/blogs/mobile/amazon-cognito-announcing-developer-authenticated-identities/), yang memungkinkan Anda mendaftarkan dan mengautentikasi pengguna menggunakan proses otentikasi backend Anda sendiri, sambil tetap menggunakan Amazon Cognito Sync untuk menyinkronkan data pengguna dan mengakses sumber daya. AWS 

Untuk informasi selengkapnya tentang [Amazon Cognito](https://aws.amazon.com/cognito/), lihat Panduan Pengembang [Amazon Cognito](https://docs.aws.amazon.com/cognito/latest/developerguide/).

Contoh kode berikut menunjukkan cara mudah menggunakan Identitas Amazon Cognito. [Penyedia kredensial](cognito-creds-provider.md)Contoh menunjukkan cara membuat dan mengautentikasi identitas pengguna. [CognitoAuthentication pustaka ekstensi](cognito-authentication-extension.md)Contoh menunjukkan cara menggunakan pustaka CognitoAuthentication ekstensi untuk mengautentikasi kumpulan pengguna Amazon Cognito.

**Topics**
+ [Penyedia kredensial](cognito-creds-provider.md)
+ [CognitoAuthentication pustaka ekstensi](cognito-authentication-extension.md)

# Penyedia kredensi Amazon Cognito
<a name="cognito-creds-provider"></a>

**catatan**  
Informasi dalam topik ini khusus untuk proyek berdasarkan .NET Framework dan AWS SDK untuk .NET versi 3.3 dan sebelumnya.

 `Amazon.CognitoIdentity.CognitoAWSCredentials`, ditemukan di [AWSSDK. CognitoIdentity](https://www.nuget.org/packages/AWSSDK.CognitoIdentity/) NuGetpackage, adalah objek kredensial yang menggunakan Amazon Cognito dan AWS Security Token Service AWS STS() untuk mengambil kredensional untuk melakukan panggilan. AWS 

Langkah pertama dalam menyiapkan `CognitoAWSCredentials` adalah membuat “kumpulan identitas”. (Kumpulan identitas adalah penyimpan informasi identitas pengguna yang spesifik untuk akun Anda. Informasi tersebut dapat diambil kembali di seluruh platform klien, perangkat, dan sistem operasi, sehingga jika pengguna mulai menggunakan aplikasi di ponsel dan kemudian beralih ke tablet, informasi aplikasi yang bertahan masih tersedia untuk pengguna tersebut. Anda dapat membuat kumpulan identitas baru dari konsol Amazon Cognito. Jika Anda menggunakan konsol, itu juga akan memberi Anda informasi lain yang Anda butuhkan:
+ Nomor akun Anda - Nomor 12 digit, seperti 123456789012, yang unik untuk akun Anda.
+ Peran yang tidak diautentikasi ARN- Peran yang akan diasumsikan oleh pengguna yang tidak diautentikasi. Misalnya, peran ini dapat memberikan izin hanya-baca ke data Anda.
+ Peran yang diautentikasi ARN- Peran yang akan diasumsikan oleh pengguna yang diautentikasi. Peran ini dapat memberikan izin yang lebih luas untuk data Anda.

## Mengatur Cognito AWSCredentials
<a name="set-up-cognitoawscredentials"></a>

Contoh kode berikut menunjukkan cara mengatur`CognitoAWSCredentials`, yang kemudian dapat Anda gunakan untuk melakukan panggilan ke Amazon S3 sebagai pengguna yang tidak diautentikasi. Ini memungkinkan Anda melakukan panggilan hanya dengan jumlah minimum data yang diperlukan untuk mengautentikasi pengguna. Izin pengguna dikendalikan oleh peran, sehingga Anda dapat mengonfigurasi akses sesuai kebutuhan.

```
CognitoAWSCredentials credentials = new CognitoAWSCredentials(
    accountId,        // Account number
    identityPoolId,   // Identity pool ID
    unAuthRoleArn,    // Role for unauthenticated users
    null,             // Role for authenticated users, not set
    region);
using (var s3Client = new AmazonS3Client(credentials))
{
    s3Client.ListBuckets();
}
```

## Gunakan AWS sebagai pengguna yang tidak diautentikasi
<a name="use-aws-as-an-unauthenticated-user"></a>

Contoh kode berikut menunjukkan bagaimana Anda dapat mulai menggunakan AWS sebagai pengguna yang tidak diautentikasi, kemudian mengautentikasi melalui Facebook dan memperbarui kredensialnya untuk menggunakan kredensi Facebook. Dengan menggunakan pendekatan ini, Anda dapat memberikan kemampuan yang berbeda kepada pengguna yang diautentikasi melalui peran yang diautentikasi. Misalnya, Anda mungkin memiliki aplikasi telepon yang memungkinkan pengguna untuk melihat konten secara anonim, tetapi memungkinkan mereka untuk memposting jika mereka masuk dengan satu atau lebih penyedia yang dikonfigurasi.

```
CognitoAWSCredentials credentials = new CognitoAWSCredentials(
    accountId, identityPoolId,
    unAuthRoleArn,    // Role for unauthenticated users
    authRoleArn,      // Role for authenticated users
    region);
using (var s3Client = new AmazonS3Client(credentials))
{
    // Initial use will be unauthenticated
    s3Client.ListBuckets();

    // Authenticate user through Facebook
    string facebookToken = GetFacebookAuthToken();

    // Add Facebook login to credentials. This clears the current AWS credentials
    // and retrieves new AWS credentials using the authenticated role.
    credentials.AddLogin("graph.facebook.com", facebookAccessToken);

    // This call is performed with the authenticated role and credentials
    s3Client.ListBuckets();
}
```

`CognitoAWSCredentials`Objek menyediakan lebih banyak fungsionalitas jika Anda menggunakannya dengan `AmazonCognitoSyncClient` yang merupakan bagian dari AWS SDK untuk .NET. Jika Anda menggunakan keduanya `AmazonCognitoSyncClient` dan`CognitoAWSCredentials`, Anda tidak perlu menentukan `IdentityId` properti `IdentityPoolId` dan saat melakukan panggilan dengan`AmazonCognitoSyncClient`. Properti ini secara otomatis diisi dari`CognitoAWSCredentials`. Contoh kode berikutnya menggambarkan hal ini, serta peristiwa yang memberi tahu Anda setiap kali ada perubahan`IdentityId`. `CognitoAWSCredentials` `IdentityId`Dapat berubah dalam beberapa kasus, seperti ketika mengubah dari pengguna yang tidak diautentikasi ke yang diautentikasi.

```
CognitoAWSCredentials credentials = GetCognitoAWSCredentials();

// Log identity changes
credentials.IdentityChangedEvent += (sender, args) =>
{
    Console.WriteLine("Identity changed: [{0}] => [{1}]", args.OldIdentityId, args.NewIdentityId);
};

using (var syncClient = new AmazonCognitoSyncClient(credentials))
{
    var result = syncClient.ListRecords(new ListRecordsRequest
    {
        DatasetName = datasetName
        // No need to specify these properties
        //IdentityId = "...",
        //IdentityPoolId = "..."        
    });
}
```

# Contoh pustaka CognitoAuthentication ekstensi Amazon
<a name="cognito-authentication-extension"></a>

**catatan**  
Informasi dalam topik ini khusus untuk proyek berdasarkan .NET Framework dan AWS SDK untuk .NET versi 3.3 dan sebelumnya.

Pustaka CognitoAuthentication ekstensi, ditemukan di [Amazon.Extensions. CognitoAuthentication](https://www.nuget.org/packages/Amazon.Extensions.CognitoAuthentication/) NuGet paket, menyederhanakan proses otentikasi kumpulan pengguna Amazon Cognito untuk pengembang.NET Core dan Xamarin. Pustaka dibangun di atas API penyedia Identitas Amazon Cognito untuk membuat dan mengirim panggilan API otentikasi pengguna.

## Menggunakan pustaka CognitoAuthentication ekstensi
<a name="using-the-cognitoauthentication-extension-library"></a>

Amazon Cognito memiliki beberapa built-in `AuthFlow` dan `ChallengeName` nilai untuk alur otentikasi standar untuk memvalidasi nama pengguna dan kata sandi melalui Secure Remote Password (SRP). Untuk informasi selengkapnya tentang alur autentikasi, lihat Alur Otentikasi [Kumpulan Pengguna Amazon Cognito](https://docs.aws.amazon.com/cognito/latest/developerguide/amazon-cognito-user-pools-authentication-flow.html).

Contoh berikut memerlukan `using` pernyataan ini:

```
// Required for all examples
using System;
using Amazon;
using Amazon.CognitoIdentity;
using Amazon.CognitoIdentityProvider;
using Amazon.Extensions.CognitoAuthentication;
using Amazon.Runtime;
// Required for the GetS3BucketsAsync example
using Amazon.S3;
using Amazon.S3.Model;
```

### Gunakan otentikasi dasar
<a name="use-basic-authentication"></a>

Buat [AmazonCognitoIdentityProviderClient](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/CognitoIdentityProvider/TCognitoIdentityProviderClient.html)menggunakan [Anonymous AWSCredentials](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/Runtime/TAnonymousAWSCredentials.html), yang tidak memerlukan permintaan yang ditandatangani. Anda tidak perlu menyediakan wilayah, kode yang mendasarinya memanggil `FallbackRegionFactory.GetRegionEndpoint()` jika suatu wilayah tidak disediakan. Buat `CognitoUserPool` dan `CognitoUser` objek. Panggil `StartWithSrpAuthAsync` metode dengan `InitiateSrpAuthRequest` yang berisi kata sandi pengguna.

```
public static async void GetCredsAsync()
{
    AmazonCognitoIdentityProviderClient provider =
        new AmazonCognitoIdentityProviderClient(new Amazon.Runtime.AnonymousAWSCredentials());
    CognitoUserPool userPool = new CognitoUserPool("poolID", "clientID", provider);
    CognitoUser user = new CognitoUser("username", "clientID", userPool, provider);
    InitiateSrpAuthRequest authRequest = new InitiateSrpAuthRequest()
    {
        Password = "userPassword"
    };

    AuthFlowResponse authResponse = await user.StartWithSrpAuthAsync(authRequest).ConfigureAwait(false);
    accessToken = authResponse.AuthenticationResult.AccessToken;

}
```

### Otentikasi dengan tantangan
<a name="authenticate-with-challenges"></a>

Melanjutkan alur otentikasi dengan tantangan, seperti dengan NewPasswordRequired dan Multi-Factor Authentication (MFA), juga lebih sederhana. Satu-satunya persyaratan adalah CognitoAuthentication objek, kata sandi pengguna untuk SRP, dan informasi yang diperlukan untuk tantangan berikutnya, yang diperoleh setelah meminta pengguna untuk memasukkannya. Kode berikut menunjukkan satu cara untuk memeriksa jenis tantangan dan mendapatkan respons yang sesuai untuk MFA dan NewPasswordRequired tantangan selama alur otentikasi.

Lakukan permintaan otentikasi dasar seperti sebelumnya, dan`await`. `AuthFlowResponse` Ketika respon diterima loop melalui `AuthenticationResult` objek yang dikembalikan. Jika `ChallengeName` jenisnya`NEW_PASSWORD_REQUIRED`, panggil `RespondToNewPasswordRequiredAsync` metodenya.

```
public static async void GetCredsChallengesAsync()
{
    AmazonCognitoIdentityProviderClient provider = 
        new AmazonCognitoIdentityProviderClient(new Amazon.Runtime.AnonymousAWSCredentials());
    CognitoUserPool userPool = new CognitoUserPool("poolID", "clientID", provider);
    CognitoUser user = new CognitoUser("username", "clientID", userPool, provider);
    InitiateSrpAuthRequest authRequest = new InitiateSrpAuthRequest(){
        Password = "userPassword"
    };

    AuthFlowResponse authResponse = await user.StartWithSrpAuthAsync(authRequest).ConfigureAwait(false);

    while (authResponse.AuthenticationResult == null)
    {
        if (authResponse.ChallengeName == ChallengeNameType.NEW_PASSWORD_REQUIRED)
        {
            Console.WriteLine("Enter your desired new password:");
            string newPassword = Console.ReadLine();

            authResponse = await user.RespondToNewPasswordRequiredAsync(new RespondToNewPasswordRequiredRequest()
            {
                SessionID = authResponse.SessionID,
                NewPassword = newPassword
            });
            accessToken = authResponse.AuthenticationResult.AccessToken;
        }
        else if (authResponse.ChallengeName == ChallengeNameType.SMS_MFA)
        {
            Console.WriteLine("Enter the MFA Code sent to your device:");
            string mfaCode = Console.ReadLine();

            AuthFlowResponse mfaResponse = await user.RespondToSmsMfaAuthAsync(new RespondToSmsMfaRequest()
            {
                SessionID = authResponse.SessionID,
                MfaCode = mfaCode

            }).ConfigureAwait(false);
            accessToken = authResponse.AuthenticationResult.AccessToken;
        }
        else
        {
            Console.WriteLine("Unrecognized authentication challenge.");
            accessToken = "";
            break;
        }
    }

    if (authResponse.AuthenticationResult != null)
    {
        Console.WriteLine("User successfully authenticated.");
    }
    else
    {
        Console.WriteLine("Error in authentication process.");
    }
 
}
```

### Gunakan AWS sumber daya setelah otentikasi
<a name="use-aws-resources-after-authentication"></a>

Setelah pengguna diautentikasi menggunakan CognitoAuthentication perpustakaan, langkah selanjutnya adalah mengizinkan pengguna mengakses AWS sumber daya yang sesuai. Untuk melakukan ini, Anda harus membuat kumpulan identitas melalui konsol Identitas Federasi Amazon Cognito. Dengan menentukan kumpulan pengguna Amazon Cognito yang Anda buat sebagai penyedia, menggunakan PooLid dan ClientID, Anda dapat mengizinkan pengguna kumpulan pengguna Amazon Cognito mengakses sumber daya yang terhubung ke akun Anda. AWS Anda juga dapat menentukan peran yang berbeda untuk memungkinkan pengguna yang tidak diautentikasi dan yang diautentikasi mengakses sumber daya yang berbeda. Anda dapat mengubah aturan ini di konsol IAM, tempat Anda dapat menambahkan atau menghapus izin di bidang **Tindakan** kebijakan terlampir peran. Kemudian, dengan menggunakan kumpulan identitas yang sesuai, kumpulan pengguna, dan informasi pengguna Amazon Cognito, Anda dapat melakukan panggilan ke sumber daya yang berbeda AWS . Contoh berikut menunjukkan pengguna yang diautentikasi dengan SRP yang mengakses bucket Amazon S3 berbeda yang diizinkan oleh peran kumpulan identitas terkait

```
public async void GetS3BucketsAsync()
{
    var provider = new AmazonCognitoIdentityProviderClient(new AnonymousAWSCredentials());
    CognitoUserPool userPool = new CognitoUserPool("poolID", "clientID", provider);
    CognitoUser user = new CognitoUser("username", "clientID", userPool, provider);

    string password = "userPassword";

    AuthFlowResponse context = await user.StartWithSrpAuthAsync(new InitiateSrpAuthRequest()
    {
        Password = password
    }).ConfigureAwait(false);

    CognitoAWSCredentials credentials =
        user.GetCognitoAWSCredentials("identityPoolID", RegionEndpoint.< YourIdentityPoolRegion >);

    using (var client = new AmazonS3Client(credentials))
    {
        ListBucketsResponse response =
            await client.ListBucketsAsync(new ListBucketsRequest()).ConfigureAwait(false);

        foreach (S3Bucket bucket in response.Buckets)
        {
            Console.WriteLine(bucket.BucketName);
        }
    }
}
```

## Opsi otentikasi lainnya
<a name="more-authentication-options"></a>

Selain SRP,, dan MFA NewPasswordRequired, CognitoAuthentication pustaka ekstensi menawarkan aliran otentikasi yang lebih mudah untuk:
+ Kustom - Memulai dengan panggilan ke `StartWithCustomAuthAsync(InitiateCustomAuthRequest customRequest)` 
+ RefreshToken - Memulai dengan panggilan ke `StartWithRefreshTokenAuthAsync(InitiateRefreshTokenAuthRequest refreshTokenRequest)` 
+ RefreshTokenSRP - Memulai dengan panggilan ke `StartWithRefreshTokenAuthAsync(InitiateRefreshTokenAuthRequest refreshTokenRequest)` 
+ AdminNoSRP - Memulai dengan panggilan ke `StartWithAdminNoSrpAuthAsync(InitiateAdminNoSrpAuthRequest adminAuthRequest)` 

Panggil metode yang sesuai tergantung pada aliran yang Anda inginkan. Kemudian lanjutkan meminta pengguna dengan tantangan seperti yang disajikan dalam `AuthFlowResponse` objek dari setiap panggilan metode. Sebut juga metode respons yang sesuai, seperti `RespondToSmsMfaAuthAsync` untuk tantangan MFA dan `RespondToCustomAuthAsync` untuk tantangan khusus.

# Menggunakan database Amazon DynamoDB NoSQL
<a name="dynamodb-intro"></a>

**catatan**  
Model pemrograman dalam topik ini hadir di .NET Framework dan .NET (Core), tetapi konvensi pemanggilan berbeda, apakah sinkron atau asinkron.

 AWS SDK untuk .NET Mendukung Amazon DynamoDB, yang merupakan layanan database NoSQL cepat yang ditawarkan oleh. AWS*SDK menyediakan tiga model pemrograman untuk berkomunikasi dengan DynamoDB: model *tingkat rendah*, model *dokumen*, dan model persistensi objek.*

Informasi berikut memperkenalkan model-model ini dan mereka APIs, memberikan contoh tentang bagaimana dan kapan menggunakannya, dan memberi Anda tautan ke sumber daya pemrograman DynamoDB tambahan di. AWS SDK untuk .NET

## Model Tingkat Rendah
<a name="dynamodb-intro-apis-low-level"></a>

Model pemrograman tingkat rendah membungkus panggilan langsung ke layanan DynamoDB. Anda mengakses model ini melalui namespace [DBv2Amazon.Dynamo](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/DynamoDBv2/NDynamoDBv2.html).

Dari ketiga model tersebut, model tingkat rendah mengharuskan Anda untuk menulis kode paling banyak. Misalnya, Anda harus mengonversi tipe data.NET ke padanannya di DynamoDB. Namun, model ini memberi Anda akses ke sebagian besar fitur.

Contoh berikut menunjukkan cara menggunakan model tingkat rendah untuk membuat tabel, memodifikasi tabel, dan menyisipkan item ke dalam tabel di DynamoDB.

### Membuat Tabel
<a name="dynamodb-intro-apis-low-level-create-table"></a>

Dalam contoh berikut, Anda membuat tabel dengan menggunakan `CreateTable` metode `AmazonDynamoDBClient` kelas. `CreateTable`Metode ini menggunakan instance `CreateTableRequest` kelas yang berisi karakteristik seperti nama atribut item yang diperlukan, definisi kunci primer, dan kapasitas throughput. `CreateTable`Metode mengembalikan sebuah instance dari `CreateTableResponse` kelas.

```
// using Amazon.DynamoDBv2;
// using Amazon.DynamoDBv2.Model;

var client = new AmazonDynamoDBClient();

Console.WriteLine("Getting list of tables");
List<string> currentTables = client.ListTables().TableNames;
Console.WriteLine("Number of tables: " + currentTables.Count);
if (!currentTables.Contains("AnimalsInventory"))
{
    var request = new CreateTableRequest
    {
        TableName = "AnimalsInventory",
        AttributeDefinitions = new List<AttributeDefinition>
      {
        new AttributeDefinition
        {
          AttributeName = "Id",
          // "S" = string, "N" = number, and so on.
          AttributeType = "N"
        },
        new AttributeDefinition
        {
          AttributeName = "Type",
          AttributeType = "S"
        }
      },
        KeySchema = new List<KeySchemaElement>
      {
        new KeySchemaElement
        {
          AttributeName = "Id",
          // "HASH" = hash key, "RANGE" = range key.
          KeyType = "HASH"
        },
        new KeySchemaElement
        {
          AttributeName = "Type",
          KeyType = "RANGE"
        },
      },
        ProvisionedThroughput = new ProvisionedThroughput
        {
            ReadCapacityUnits = 10,
            WriteCapacityUnits = 5
        },
    };

    var response = client.CreateTable(request);

    Console.WriteLine("Table created with request ID: " +
      response.ResponseMetadata.RequestId);
}
```

### Memverifikasi Bahwa Tabel Siap Dimodifikasi
<a name="dynamodb-intro-apis-low-level-verify-table"></a>

Sebelum Anda dapat mengubah atau memodifikasi tabel, tabel harus siap untuk modifikasi. Contoh berikut menunjukkan cara menggunakan model tingkat rendah untuk memverifikasi bahwa tabel di DynamoDB sudah siap. Dalam contoh ini, tabel target untuk memeriksa direferensikan melalui `DescribeTable` metode `AmazonDynamoDBClient` kelas. Setiap lima detik, kode memeriksa nilai `TableStatus` properti tabel. Ketika status diatur ke`ACTIVE`, tabel siap untuk dimodifikasi.

```
// using Amazon.DynamoDBv2;
// using Amazon.DynamoDBv2.Model;

var client = new AmazonDynamoDBClient();      
var status = "";

do
{
  // Wait 5 seconds before checking (again).
  System.Threading.Thread.Sleep(TimeSpan.FromSeconds(5));
        
  try
  {
    var response = client.DescribeTable(new DescribeTableRequest
    {
      TableName = "AnimalsInventory"
    });

    Console.WriteLine("Table = {0}, Status = {1}",
      response.Table.TableName,
      response.Table.TableStatus);

    status = response.Table.TableStatus;
  }
  catch (ResourceNotFoundException)
  {
    // DescribeTable is eventually consistent. So you might
    //   get resource not found. 
  }

} while (status != TableStatus.ACTIVE);
```

### Memasukkan Item ke dalam Tabel
<a name="dynamodb-intro-apis-low-level-insert-item"></a>

Dalam contoh berikut, Anda menggunakan model tingkat rendah untuk menyisipkan dua item ke dalam tabel di DynamoDB. Setiap item dimasukkan melalui `PutItem` metode `AmazonDynamoDBClient` kelas, menggunakan instance `PutItemRequest` kelas. Masing-masing dari dua contoh `PutItemRequest` kelas mengambil nama tabel tempat item akan dimasukkan, dengan serangkaian nilai atribut item.

```
// using Amazon.DynamoDBv2;
// using Amazon.DynamoDBv2.Model;

var client = new AmazonDynamoDBClient();

var request1 = new PutItemRequest
{
  TableName = "AnimalsInventory",
  Item = new Dictionary<string, AttributeValue>
  {
    { "Id", new AttributeValue { N = "1" }},
    { "Type", new AttributeValue { S = "Dog" }},
    { "Name", new AttributeValue { S = "Fido" }}
  }
};

var request2 = new PutItemRequest
{
  TableName = "AnimalsInventory",
  Item = new Dictionary<string, AttributeValue>
  {
    { "Id", new AttributeValue { N = "2" }},
    { "Type", new AttributeValue { S = "Cat" }},
    { "Name", new AttributeValue { S = "Patches" }}
  }
};
        
client.PutItem(request1);
client.PutItem(request2);
```

## Model Dokumen
<a name="dynamodb-intro-apis-document"></a>

Model pemrograman dokumen menyediakan cara yang lebih mudah untuk bekerja dengan data di DynamoDB. Model ini secara khusus ditujukan untuk mengakses tabel dan item dalam tabel. Anda mengakses model ini melalui [DBv2Amazon.Dynamo. DocumentModel](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/DynamoDBv2/NDynamoDBv2DocumentModel.html)namespace.

Dibandingkan dengan model pemrograman tingkat rendah, model dokumen lebih mudah dikodekan terhadap data DynamoDB. Misalnya, Anda tidak perlu mengonversi sebanyak mungkin tipe data.NET ke padanannya di DynamoDB. Namun, model ini tidak menyediakan akses ke banyak fitur seperti model pemrograman tingkat rendah. Misalnya, Anda dapat menggunakan model ini untuk membuat, mengambil, memperbarui, dan menghapus item dalam tabel. Namun, untuk membuat tabel, Anda harus menggunakan model tingkat rendah. Dibandingkan dengan model persistensi objek, model ini mengharuskan Anda untuk menulis lebih banyak kode untuk menyimpan, memuat, dan menanyakan objek.NET.

Untuk informasi selengkapnya tentang model pemrograman dokumen DynamoDB, [lihat .NET: Model dokumen](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/DotNetSDKMidLevel.html) dalam Panduan Pengembang Amazon [DynamoDB](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/).

Bagian berikut memberikan informasi tentang cara membuat representasi tabel DynamoDB yang diinginkan, dan contoh tentang cara menggunakan model dokumen untuk menyisipkan item ke dalam tabel dan mendapatkan item dari tabel.

### Buat representasi tabel
<a name="dynamodb-intro-apis-document-table"></a>

Untuk melakukan operasi data menggunakan model dokumen, Anda harus terlebih dahulu membuat instance `Table` kelas yang mewakili tabel tertentu. Ada dua cara utama untuk melakukan ini.

**LoadTable metode**

Mekanisme pertama adalah menggunakan salah satu `LoadTable` metode statis [https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/DynamoDBv2/TTable.html](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/DynamoDBv2/TTable.html)kelas, mirip dengan contoh berikut:

```
var client = new AmazonDynamoDBClient();
Table table = Table.LoadTable(client, "Reply");
```

**catatan**  
Meskipun mekanisme ini berfungsi, dalam kondisi tertentu, kadang-kadang dapat menyebabkan latensi tambahan atau kebuntuan karena perilaku start dingin dan kumpulan ulir. Untuk informasi lebih lanjut tentang perilaku ini, lihat posting blog [Peningkatan Pola Inisialisasi DynamoDB](https://aws.amazon.com/blogs/developer/improved-dynamodb-initialization-patterns-for-the-aws-sdk-for-net/) untuk. AWS SDK untuk .NET

**TableBuilder**

Mekanisme alternatif, [https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/DynamoDBv2/TTableBuilder.html](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/DynamoDBv2/TTableBuilder.html)kelas, diperkenalkan dalam [versi 3.7.203 dari paket.Dynamo. AWSSDK DBv2 NuGet ](https://www.nuget.org/packages/AWSSDK.DynamoDBv2/3.7.203) Mekanisme ini dapat mengatasi perilaku yang disebutkan di atas dengan menghapus panggilan metode implisit tertentu; khususnya, `DescribeTable` metode. Mekanisme ini digunakan dengan cara yang mirip dengan contoh berikut:

```
var client = new AmazonDynamoDBClient();
var table = new TableBuilder(client, "Reply")
    .AddHashKey("Id", DynamoDBEntryType.String)
    .AddRangeKey("ReplyDateTime", DynamoDBEntryType.String)
    .AddGlobalSecondaryIndex("PostedBy-Message-index", "Author", DynamoDBEntryType.String, "Message", DynamoDBEntryType.String)
    .Build();
```

Untuk informasi lebih lanjut tentang mekanisme alternatif ini, lihat lagi posting blog [Peningkatan Pola Inisialisasi DynamoDB](https://aws.amazon.com/blogs/developer/improved-dynamodb-initialization-patterns-for-the-aws-sdk-for-net/) untuk. AWS SDK untuk .NET

### Memasukkan item ke dalam tabel
<a name="dynamodb-intro-apis-document-insert-item"></a>

Dalam contoh berikut, balasan dimasukkan ke dalam tabel Balas melalui `PutItemAsync` metode `Table` kelas. `PutItemAsync`Metode ini mengambil contoh dari `Document` kelas; `Document` kelas hanyalah kumpulan atribut yang diinisialisasi.

```
using Amazon.DynamoDBv2;
using Amazon.DynamoDBv2.DocumentModel;

// Create a representation of the "Reply" table
//  by using one of the mechanisms described previously.

// Then, add a reply to the table.
var newReply = new Document();
newReply["Id"] = Guid.NewGuid().ToString();
newReply["ReplyDateTime"] = DateTime.UtcNow;
newReply["PostedBy"] = "Author1";
newReply["Message"] = "Thank you!";

await table.PutItemAsync(newReply);
```

### Mendapatkan item dari tabel
<a name="dynamodb-intro-apis-document-get-item"></a>

Dalam contoh berikut, balasan diambil melalui `GetItemAsync` metode `Table` kelas. Untuk menentukan balasan yang akan didapat, `GetItemAsync` metode ini menggunakan kunci hash-and-range utama dari balasan target.

```
using Amazon.DynamoDBv2;
using Amazon.DynamoDBv2.DocumentModel;

// Create a representation of the "Reply" table
//  by using one of the mechanisms described previously.

// Then, get a reply from the table
//  where "guid" is the hash key and "datetime" is the range key.
var reply = await table.GetItemAsync(guid, datetime);
Console.WriteLine("Id = " + reply["Id"]);
Console.WriteLine("ReplyDateTime = " + reply["ReplyDateTime"]);
Console.WriteLine("PostedBy = " + reply["PostedBy"]);
Console.WriteLine("Message = " + reply["Message"]);
```

Contoh sebelumnya secara implisit mengubah nilai tabel menjadi string untuk metode ini. `WriteLine` Anda dapat melakukan konversi eksplisit dengan menggunakan berbagai metode “As [type]” kelas. `DynamoDBEntry` Misalnya, Anda dapat secara eksplisit mengonversi nilai `Id` dari tipe `Primitive` data ke GUID melalui metode: `AsGuid()`

```
var guid = reply["Id"].AsGuid();
```

## Model Kegigihan Objek
<a name="dynamodb-intro-apis-object-persistence"></a>

Model pemrograman persistensi objek dirancang khusus untuk menyimpan, memuat, dan menanyakan objek.NET di DynamoDB. Anda mengakses model ini melalui [DBv2Amazon.Dynamo. DataModel](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/DynamoDBv2/NDynamoDBv2DataModel.html)namespace.

Dari ketiga model tersebut, model persistensi objek adalah yang paling mudah untuk dikodekan setiap kali Anda menyimpan, memuat, atau menanyakan data DynamoDB. Misalnya, Anda bekerja dengan tipe data DynamoDB secara langsung. Namun, model ini hanya menyediakan akses ke operasi yang menyimpan, memuat, dan menanyakan objek.NET di DynamoDB. Misalnya, Anda dapat menggunakan model ini untuk membuat, mengambil, memperbarui, dan menghapus item dalam tabel. Namun, Anda harus terlebih dahulu membuat tabel Anda menggunakan model tingkat rendah, dan kemudian menggunakan model ini untuk memetakan kelas.NET Anda ke tabel.

[Untuk informasi selengkapnya tentang model pemrograman persistensi objek DynamoDB, [lihat .NET: Model persistensi objek di](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/DotNetSDKHighLevel.html) Panduan Pengembang Amazon DynamoDB.](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/)

Contoh berikut menunjukkan kepada Anda bagaimana mendefinisikan kelas.NET yang mewakili item DynamoDB, menggunakan instance dari kelas.NET untuk menyisipkan item ke dalam tabel DynamoDB, dan menggunakan instance dari kelas.NET untuk mendapatkan item dari tabel.

### Mendefinisikan kelas.NET yang mewakili item dalam tabel
<a name="dynamodb-intro-apis-object-persistence-net-class-item"></a>

Dalam contoh berikut dari definisi kelas, `DynamoDBTable` atribut menentukan nama tabel, sedangkan `DynamoDBHashKey` dan `DynamoDBRangeKey` atribut model kunci hash-and-range utama tabel. `DynamoDBGlobalSecondaryIndexHashKey`Atribut didefinisikan sehingga kueri untuk balasan oleh penulis tertentu dapat dibangun.

```
using Amazon.DynamoDBv2;
using Amazon.DynamoDBv2.DataModel;

[DynamoDBTable("Reply")]
public class Reply
{
    [DynamoDBHashKey]
    public string Id { get; set; }

    [DynamoDBRangeKey(StoreAsEpoch = false)]
    public DateTime ReplyDateTime { get; set; }

    [DynamoDBGlobalSecondaryIndexHashKey("PostedBy-Message-Index",
        AttributeName ="PostedBy")]
    public string Author { get; set; }

    [DynamoDBGlobalSecondaryIndexRangeKey("PostedBy-Message-Index")]
    public string Message { get; set; }
}
```

### Membuat konteks untuk model ketekunan objek
<a name="dynamodb-intro-apis-object-persistence-context"></a>

Untuk menggunakan model pemrograman persistensi objek untuk DynamoDB, Anda harus membuat konteks, yang menyediakan koneksi ke DynamoDB dan memungkinkan Anda mengakses tabel, melakukan berbagai operasi, dan menjalankan kueri.

**Konteks dasar**

Contoh berikut menunjukkan cara membuat konteks paling dasar.

```
using Amazon.DynamoDBv2;
using Amazon.DynamoDBv2.DataModel;

var client = new AmazonDynamoDBClient();
var context = new DynamoDBContext(client);
```

**Konteks dengan DisableFetchingTableMetadata properti**

Contoh berikut menunjukkan bagaimana Anda mungkin juga mengatur `DisableFetchingTableMetadata` properti `DynamoDBContextConfig` kelas untuk mencegah panggilan implisit ke `DescribeTable` metode.

```
using Amazon.DynamoDBv2;
using Amazon.DynamoDBv2.DataModel;

var client = new AmazonDynamoDBClient();
var context = new DynamoDBContext(client, new DynamoDBContextConfig
{
    DisableFetchingTableMetadata = true
});
```

Jika `DisableFetchingTableMetadata` properti diatur ke `false` (default), seperti yang ditunjukkan pada contoh pertama, Anda dapat menghilangkan atribut yang menggambarkan kunci dan struktur indeks item tabel dari `Reply` kelas. Atribut ini malah akan disimpulkan melalui panggilan implisit ke metode. `DescribeTable` Jika `DisableFetchingTableMetadata` diatur ke`true`, seperti yang ditunjukkan pada contoh kedua, metode model ketekunan objek seperti `SaveAsync` dan `QueryAsync` bergantung sepenuhnya pada atribut yang didefinisikan di `Reply` kelas. Dalam hal ini, panggilan ke `DescribeTable` metode tidak terjadi.

**catatan**  
Dalam kondisi tertentu, panggilan ke `DescribeTable` metode terkadang dapat menyebabkan latensi tambahan atau kebuntuan karena perilaku cold-start dan thread-pool. Untuk alasan ini, terkadang menguntungkan untuk menghindari panggilan ke metode itu.  
Untuk informasi lebih lanjut tentang perilaku ini, lihat posting blog [Peningkatan Pola Inisialisasi DynamoDB](https://aws.amazon.com/blogs/developer/improved-dynamodb-initialization-patterns-for-the-aws-sdk-for-net/) untuk. AWS SDK untuk .NET

### Menggunakan instance dari kelas.NET untuk menyisipkan item ke dalam tabel
<a name="dynamodb-intro-apis-object-persistence-net-insert-item"></a>

Dalam contoh ini, item dimasukkan melalui `SaveAsync` metode `DynamoDBContext` kelas, yang mengambil instance inisialisasi dari kelas.NET yang mewakili item.

```
using Amazon.DynamoDBv2;
using Amazon.DynamoDBv2.DataModel;

// Create an appropriate context for the object persistence programming model,
//  examples of which have been described earlier.

// Create an object that represents the new item.
var reply = new Reply()
{
    Id = Guid.NewGuid().ToString(),
    ReplyDateTime = DateTime.UtcNow,
    Author = "Author1",
    Message = "Thank you!"
};

// Insert the item into the table.
await context.SaveAsync<Reply>(reply, new DynamoDBOperationConfig
{
    IndexName = "PostedBy-Message-index"
});
```

### Menggunakan instance dari kelas.NET untuk mendapatkan item dari tabel
<a name="dynamodb-intro-apis-object-persistence-net-get-item"></a>

Dalam contoh ini, kueri dibuat untuk menemukan semua catatan “Author1" dengan menggunakan `QueryAsync` metode `DynamoDBContext` kelas. Kemudian, item diambil melalui `GetNextSetAsync` metode query.

```
using Amazon.DynamoDBv2;
using Amazon.DynamoDBv2.DataModel;

// Create an appropriate context for the object persistence programming model,
//  examples of which have been described earlier.

// Construct a query that finds all replies by a specific author.
var query = context.QueryAsync<Reply>("Author1", new DynamoDBOperationConfig
{
    IndexName = "PostedBy-Message-index"
});

// Display the result.
var set = await query.GetNextSetAsync();
foreach (var item in set)
{
    Console.WriteLine("Id = " + item.Id);
    Console.WriteLine("ReplyDateTime = " + item.ReplyDateTime);
    Console.WriteLine("PostedBy = " + item.Author);
    Console.WriteLine("Message = " + item.Message);
}
```

### Informasi tambahan tentang model persistensi objek
<a name="dynamodb-intro-apis-object-persistence-more-into"></a>

Contoh dan penjelasan yang ditunjukkan di atas terkadang menyertakan properti `DynamoDBContext` kelas yang disebut`DisableFetchingTableMetadata`. Properti ini, yang diperkenalkan dalam [DBv2 NuGet paket AWSSDK .Dynamo versi 3.7.203](https://www.nuget.org/packages/AWSSDK.DynamoDBv2/3.7.203), memungkinkan Anda menghindari kondisi tertentu yang dapat menyebabkan latensi tambahan atau kebuntuan karena perilaku cold-start dan thread-pool. Untuk informasi lebih lanjut, lihat posting blog [Peningkatan Pola Inisialisasi DynamoDB](https://aws.amazon.com/blogs/developer/improved-dynamodb-initialization-patterns-for-the-aws-sdk-for-net/) untuk. AWS SDK untuk .NET

Berikut ini adalah beberapa informasi tambahan tentang properti ini.
+ Properti ini dapat diatur secara global dalam `web.config` file Anda `app.config` atau jika Anda menggunakan .NET Framework.
+ Properti ini dapat diatur secara global dengan menggunakan [https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/Amazon/TAWSConfigsDynamoDB.html](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/Amazon/TAWSConfigsDynamoDB.html)kelas, seperti yang ditunjukkan pada contoh berikut.

  ```
  // Set the DisableFetchingTableMetadata property globally
  // before constructing any context objects.
  AWSConfigsDynamoDB.Context.DisableFetchingTableMetadata = true;
  
  var client = new AmazonDynamoDBClient();
  var context = new DynamoDBContext(client);
  ```
+ Dalam beberapa kasus, Anda tidak dapat menambahkan atribut DynamoDB ke kelas.NET; misalnya, jika kelas didefinisikan dalam dependensi. Dalam kasus seperti itu, masih mungkin untuk mengambil keuntungan dari `DisableFetchingTableMetadata` properti. Untuk melakukannya, gunakan [https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/DynamoDBv2/TTableBuilder.html](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/DynamoDBv2/TTableBuilder.html)kelas selain `DisableFetchingTableMetadata` properti. `TableBuilder`Kelas ini juga diperkenalkan dalam [versi 3.7.203 dari paket.Dynamo. AWSSDK DBv2 NuGet ](https://www.nuget.org/packages/AWSSDK.DynamoDBv2/3.7.203)

  ```
  // Set the DisableFetchingTableMetadata property globally
  // before constructing any context objects.
  AWSConfigsDynamoDB.Context.DisableFetchingTableMetadata = true;
  
  var client = new AmazonDynamoDBClient();
  var context = new DynamoDBContext(client);
  
  var table = new TableBuilder(client, "Reply")
      .AddHashKey("Id", DynamoDBEntryType.String)
      .AddRangeKey("ReplyDateTime", DynamoDBEntryType.String)
      .AddGlobalSecondaryIndex("PostedBy-Message-index", "Author", DynamoDBEntryType.String,
          "Message", DynamoDBEntryType.String)
      .Build();
  
  // This registers the "Reply" table we constructed via the builder.
  context.RegisterTableDefinition(table);
  
  // Now operations like this will work,
  // even if the Reply class was not annotated with this index.
  var query = context.QueryAsync<Reply>("Author1", new DynamoDBOperationConfig()
  {
      IndexName = "PostedBy-Message-index"
  });
  ```

## Informasi selengkapnya
<a name="dynamodb-intro-more-info"></a>

 **Menggunakan AWS SDK untuk .NET to program DynamoDB, informasi dan contoh**
+  [DynamoDB APIs](http://blogs.aws.amazon.com/net/post/Tx17SQHVEMW8MXC/DynamoDB-APIs) 
+  [Kickoff Seri DynamoDB](http://blogs.aws.amazon.com/net/post/Tx2XQOCY08QMTKO/DynamoDB-Series-Kickoff) 
+  [DynamoDB Series - Model Dokumen](http://blogs.aws.amazon.com/net/post/Tx2R0WG46GQI1JI/DynamoDB-Series-Document-Model) 
+  [DynamoDB Series - Skema Konversi](http://blogs.aws.amazon.com/net/post/Tx2TCOGWG7ARUH5/DynamoDB-Series-Conversion-Schemas) 
+  [Seri DynamoDB - Model Persistensi Objek](http://blogs.aws.amazon.com/net/post/Tx20L86FLMBW51P/DynamoDB-Series-Object-Persistence-Model) 
+  [Seri DynamoDB - Ekspresi](http://blogs.aws.amazon.com/net/post/TxZQM7VA9AUZ9L/DynamoDB-Series-Expressions) 
+  [Menggunakan Ekspresi dengan Amazon DynamoDB dan AWS SDK untuk .NET](dynamodb-expressions.md) 
+  [Dukungan JSON di Amazon DynamoDB](dynamodb-json.md) 

 **Model, informasi, dan contoh Tingkat Rendah** 
+  [Bekerja dengan Tabel Menggunakan API AWS SDK untuk .NET Tingkat Rendah](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/LowLevelDotNetWorkingWithTables.html) 
+  [Bekerja dengan Item Menggunakan API AWS SDK untuk .NET Tingkat Rendah](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/LowLevelDotNetItemCRUD.html) 
+  [Mengkueri Tabel Menggunakan API Tingkat AWS SDK untuk .NET Rendah](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/LowLevelDotNetQuerying.html) 
+  [Memindai Tabel Menggunakan API AWS SDK untuk .NET Tingkat Rendah](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/LowLevelDotNetScanning.html) 
+  [Bekerja dengan Indeks Sekunder Lokal Menggunakan API Tingkat AWS SDK untuk .NET Rendah](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/LSILowLevelDotNet.html) 
+  [Bekerja dengan Indeks Sekunder Global Menggunakan API Tingkat AWS SDK untuk .NET Rendah](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/GSILowLevelDotNet.html) 

 **Model dokumen, informasi dan contoh** 
+  [Jenis Data DynamoDB](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/DataModel.html#DataModel.DataTypes) 
+  [Dinamo DBEntry](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/TDynamoDBv2DocumentModelDynamoDBEntry.html) 
+  [.NET: Model Dokumen](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/DotNetSDKMidLevel.html) 

 **Model persistensi objek, informasi dan contoh** 
+  [.NET: Model Kegigihan Objek](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/DotNetSDKHighLevel.html) 

 **Informasi bermanfaat lainnya** 
+ Lihat [Integrasi AWS dengan .NET Aspire](aspire-integrations.md) untuk informasi tentang pengembangan dengan Amazon DynamoDB lokal melalui .NET Aspire.

**Topics**
+ [Model Tingkat Rendah](#dynamodb-intro-apis-low-level)
+ [Model Dokumen](#dynamodb-intro-apis-document)
+ [Model Kegigihan Objek](#dynamodb-intro-apis-object-persistence)
+ [Informasi selengkapnya](#dynamodb-intro-more-info)
+ [Menggunakan ekspresi](dynamodb-expressions.md)
+ [Dukungan JSON](dynamodb-json.md)

# Menggunakan Ekspresi dengan Amazon DynamoDB dan AWS SDK untuk .NET
<a name="dynamodb-expressions"></a>

**catatan**  
Informasi dalam topik ini khusus untuk proyek berdasarkan .NET Framework dan AWS SDK untuk .NET versi 3.3 dan sebelumnya.

Contoh kode berikut menunjukkan bagaimana menggunakan AWS SDK untuk .NET untuk program DynamoDB dengan ekspresi. *Ekspresi* menunjukkan atribut yang ingin Anda baca dari item dalam tabel DynamoDB. Anda juga menggunakan ekspresi saat menulis item, untuk menunjukkan kondisi apa pun yang harus dipenuhi (juga dikenal sebagai *pembaruan bersyarat*) dan bagaimana atribut akan diperbarui. Beberapa contoh pembaruan mengganti atribut dengan nilai baru, atau menambahkan data baru ke daftar atau peta. Untuk informasi selengkapnya, lihat [Membaca dan Menulis Item Menggunakan Ekspresi](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Expressions.html).

**Topics**
+ [Sampel Data](#dynamodb-expressions-sample-data)
+ [Dapatkan Item Tunggal dengan Menggunakan Ekspresi dan Kunci Utama Item](#dynamodb-expressions-get-item)
+ [Dapatkan Beberapa Item dengan Menggunakan Ekspresi dan Kunci Utama Tabel](#dynamodb-expressions-query)
+ [Dapatkan Beberapa Item dengan Menggunakan Ekspresi dan Atribut Item Lainnya](#dynamodb-expressions-scan)
+ [Cetak Item](#dynamodb-expressions-print-item)
+ [Membuat atau Mengganti Item dengan Menggunakan Ekspresi](#dynamodb-expressions-put-item)
+ [Memperbarui Item dengan Menggunakan Ekspresi](#dynamodb-expressions-update-item)
+ [Menghapus Item dengan Menggunakan Ekspresi](#dynamodb-expressions-delete-item)
+ [Info Selengkapnya](#dynamodb-expressions-resources)

## Sampel Data
<a name="dynamodb-expressions-sample-data"></a>

Contoh kode dalam topik ini bergantung pada dua item contoh berikut dalam tabel DynamoDB bernama. `ProductCatalog` Barang-barang ini menjelaskan informasi tentang entri produk dalam katalog toko sepeda fiktif. Item ini didasarkan pada contoh yang diberikan dalam [Studi Kasus: ProductCatalog Item](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Expressions.CaseStudy.html). Deskriptor tipe data seperti`BOOL`,,`L`,`M`,`N`, `NS``S`, dan `SS` sesuai dengan yang ada di Format [Data JSON](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/DataFormat.html).

```
{
  "Id": {
    "N": "205"
  },
  "Title": {
    "S": "20-Bicycle 205"
  },
  "Description": {
    "S": "205 description"
  },
  "BicycleType": {
    "S": "Hybrid"
  },
  "Brand": {
    "S": "Brand-Company C"
  },
  "Price": {
    "N": "500"
  },
  "Gender": {
    "S": "B"
  },
  "Color": {
    "SS": [
      "Red",
      "Black"
    ]
  },
  "ProductCategory": {
    "S": "Bike"
  },
  "InStock": {
    "BOOL": true
  },
  "QuantityOnHand": {
    "N": "1"
  },
  "RelatedItems": {
    "NS": [
      "341",
      "472",
      "649"
    ]
  },
  "Pictures": {
    "L": [
      {
        "M": {
          "FrontView": {
            "S": "http://example/products/205_front.jpg"
          }
        }
      },
      {
        "M": {
          "RearView": {
            "S": "http://example/products/205_rear.jpg"
          }
        }
      },
      {
        "M": {
          "SideView": {
            "S": "http://example/products/205_left_side.jpg"
          }
        }
      }
    ]
  },
  "ProductReviews": {
    "M": {
      "FiveStar": {
        "SS": [
          "Excellent! Can't recommend it highly enough! Buy it!",
          "Do yourself a favor and buy this."
        ]
      },
      "OneStar": {
        "SS": [
          "Terrible product! Do not buy this."
        ]
      }
    }
  }
},
{
  "Id": {
    "N": "301"
  },
  "Title": {
    "S": "18-Bicycle 301"
  },
  "Description": {
    "S": "301 description"
  },
  "BicycleType": {
    "S": "Road"
  },
  "Brand": {
    "S": "Brand-Company C"
  },
  "Price": {
    "N": "185"
  },
  "Gender": {
    "S": "F"
  },
  "Color": {
    "SS": [
      "Blue",
      "Silver"
    ]
  },
  "ProductCategory": {
    "S": "Bike"
  },
  "InStock": {
    "BOOL": true
  },
  "QuantityOnHand": {
    "N": "3"
  },
  "RelatedItems": {
    "NS": [
      "801",
      "822",
      "979"
    ]
  },
  "Pictures": {
    "L": [
      {
        "M": {
          "FrontView": {
            "S": "http://example/products/301_front.jpg"
          }
        }
      },
      {
        "M": {
          "RearView": {
            "S": "http://example/products/301_rear.jpg"
          }
        }
      },
      {
        "M": {
          "SideView": {
            "S": "http://example/products/301_left_side.jpg"
          }
        }
      }
    ]
  },
  "ProductReviews": {
    "M": {
      "FiveStar": {
        "SS": [
          "My daughter really enjoyed this bike!"
        ]
      },
      "ThreeStar": {
        "SS": [
          "This bike was okay, but I would have preferred it in my color.",
	      "Fun to ride."
        ]
      }
    }
  }
}
```

## Dapatkan Item Tunggal dengan Menggunakan Ekspresi dan Kunci Utama Item
<a name="dynamodb-expressions-get-item"></a>

Contoh berikut menampilkan `Amazon.DynamoDBv2.AmazonDynamoDBClient.GetItem` metode dan satu set ekspresi untuk mendapatkan dan kemudian mencetak item yang memiliki `Id` dari`205`. Hanya atribut berikut dari item yang dikembalikan:`Id`,`Title`,`Description`, `Color``RelatedItems`,`Pictures`, dan`ProductReviews`.

```
// using Amazon.DynamoDBv2;
// using Amazon.DynamoDBv2.Model;

var client = new AmazonDynamoDBClient();
var request = new GetItemRequest
{
  TableName = "ProductCatalog",
  ProjectionExpression = "Id, Title, Description, Color, #ri, Pictures, #pr",
  ExpressionAttributeNames = new Dictionary<string, string>
  {
    { "#pr", "ProductReviews" },
    { "#ri", "RelatedItems" }
  },
  Key = new Dictionary<string, AttributeValue>
  {
    { "Id", new AttributeValue { N = "205" } }
  },
};
var response = client.GetItem(request);

// PrintItem() is a custom function.
PrintItem(response.Item);
```

Dalam contoh sebelumnya, `ProjectionExpression` properti menentukan atribut yang akan dikembalikan. `ExpressionAttributeNames`Properti menentukan placeholder `#pr` untuk mewakili `ProductReviews` atribut dan placeholder `#ri` untuk mewakili atribut. `RelatedItems` Panggilan untuk `PrintItem` merujuk ke fungsi kustom seperti yang dijelaskan dalam [Cetak Item](#dynamodb-expressions-print-item).

## Dapatkan Beberapa Item dengan Menggunakan Ekspresi dan Kunci Utama Tabel
<a name="dynamodb-expressions-query"></a>

Contoh berikut menampilkan `Amazon.DynamoDBv2.AmazonDynamoDBClient.Query` metode dan satu set ekspresi untuk mendapatkan dan kemudian mencetak item yang memiliki `Id` dari`301`, tetapi hanya jika nilai `Price` lebih besar dari`150`. Hanya atribut berikut dari item yang dikembalikan: `Id``Title`,, dan semua `ThreeStar` atribut di`ProductReviews`.

```
// using Amazon.DynamoDBv2;
// using Amazon.DynamoDBv2.Model;

var client = new AmazonDynamoDBClient();
var request = new QueryRequest
{
  TableName = "ProductCatalog",
  KeyConditions = new Dictionary<string,Condition>
  {
    { "Id", new Condition()
      {
        ComparisonOperator = ComparisonOperator.EQ,
        AttributeValueList = new List<AttributeValue>
        {
          new AttributeValue { N = "301" }
        }
      }
    }
  },
  ProjectionExpression = "Id, Title, #pr.ThreeStar",
  ExpressionAttributeNames = new Dictionary<string, string>
  {
    { "#pr", "ProductReviews" },
    { "#p", "Price" }
  },
  ExpressionAttributeValues = new Dictionary<string,AttributeValue>
  {
    { ":val", new AttributeValue { N = "150" } }
  },
  FilterExpression = "#p > :val"
};
var response = client.Query(request);

foreach (var item in response.Items)
{
  // Write out the first page of an item's attribute keys and values.
  // PrintItem() is a custom function.
  PrintItem(item);
  Console.WriteLine("=====");
}
```

Dalam contoh sebelumnya, `ProjectionExpression` properti menentukan atribut yang akan dikembalikan. `ExpressionAttributeNames`Properti menentukan placeholder `#pr` untuk mewakili `ProductReviews` atribut dan placeholder `#p` untuk mewakili atribut. `Price` `#pr.ThreeStar`menentukan untuk mengembalikan hanya `ThreeStar` atribut. `ExpressionAttributeValues`Properti menentukan placeholder `:val` untuk mewakili nilai. `150` `FilterExpression`Properti menentukan bahwa `#p` (`Price`) harus lebih besar dari `:val` (`150`). Panggilan untuk `PrintItem` merujuk ke fungsi kustom seperti yang dijelaskan dalam [Cetak Item](#dynamodb-expressions-print-item).

## Dapatkan Beberapa Item dengan Menggunakan Ekspresi dan Atribut Item Lainnya
<a name="dynamodb-expressions-scan"></a>

Contoh berikut menampilkan `Amazon.DynamoDBv2.AmazonDynamoDBClient.Scan` metode dan satu set ekspresi untuk mendapatkan dan kemudian mencetak semua item yang memiliki `ProductCategory` dari`Bike`. Hanya atribut berikut dari item yang dikembalikan: `Id``Title`,, dan semua atribut di`ProductReviews`.

```
// using Amazon.DynamoDBv2;
// using Amazon.DynamoDBv2.Model;

var client = new AmazonDynamoDBClient();
var request = new ScanRequest
{
  TableName = "ProductCatalog",
  ProjectionExpression = "Id, Title, #pr",
  ExpressionAttributeValues = new Dictionary<string,AttributeValue>
  {
    { ":catg", new AttributeValue { S = "Bike" } }
  },
  ExpressionAttributeNames = new Dictionary<string, string>
  {
    { "#pr", "ProductReviews" },
    { "#pc", "ProductCategory" }
  },
  FilterExpression = "#pc = :catg",  
};
var response = client.Scan(request);

foreach (var item in response.Items)
{
  // Write out the first page/scan of an item's attribute keys and values.
  // PrintItem() is a custom function.
  PrintItem(item);
  Console.WriteLine("=====");
}
```

Dalam contoh sebelumnya, `ProjectionExpression` properti menentukan atribut yang akan dikembalikan. `ExpressionAttributeNames`Properti menentukan placeholder `#pr` untuk mewakili `ProductReviews` atribut dan placeholder `#pc` untuk mewakili atribut. `ProductCategory` `ExpressionAttributeValues`Properti menentukan placeholder `:catg` untuk mewakili nilai. `Bike` `FilterExpression`Properti menentukan bahwa `#pc` (`ProductCategory`) harus sama dengan `:catg` (`Bike`). Panggilan untuk `PrintItem` merujuk ke fungsi kustom seperti yang dijelaskan dalam [Cetak Item](#dynamodb-expressions-print-item).

## Cetak Item
<a name="dynamodb-expressions-print-item"></a>

Contoh berikut menunjukkan bagaimana untuk mencetak atribut item dan nilai-nilai. Contoh ini digunakan dalam contoh sebelumnya yang menunjukkan cara [Mendapatkan Item Tunggal dengan Menggunakan Ekspresi dan Kunci Utama Item, Dapatkan Beberapa Item dengan Menggunakan Ekspresi dan Kunci](#dynamodb-expressions-get-item) [Utama Tabel, dan](#dynamodb-expressions-query) [Dapatkan Beberapa Item dengan Menggunakan Ekspresi dan Atribut Item Lainnya](#dynamodb-expressions-scan).

```
// using Amazon.DynamoDBv2.Model;

// Writes out an item's attribute keys and values.
public static void PrintItem(Dictionary<string, AttributeValue> attrs)
{
  foreach (KeyValuePair<string, AttributeValue> kvp in attrs)
  {
    Console.Write(kvp.Key + " = ");
    PrintValue(kvp.Value);
  }
}

// Writes out just an attribute's value.
public static void PrintValue(AttributeValue value)
{
  // Binary attribute value.
  if (value.B != null)
  {
    Console.Write("Binary data");
  }
  // Binary set attribute value.
  else if (value.BS.Count > 0)
  {
    foreach (var bValue in value.BS)
    {
      Console.Write("\n  Binary data");
    }
  }
  // List attribute value.
  else if (value.L.Count > 0)
  {
    foreach (AttributeValue attr in value.L)
    {
      PrintValue(attr);
    }
  }
  // Map attribute value.
  else if (value.M.Count > 0)
  {
    Console.Write("\n");
    PrintItem(value.M);
  }
  // Number attribute value.
  else if (value.N != null)
  {
    Console.Write(value.N);
  }
  // Number set attribute value.
  else if (value.NS.Count > 0)
  {
    Console.Write("{0}", string.Join("\n", value.NS.ToArray()));
  }
  // Null attribute value.
  else if (value.NULL)
  {
    Console.Write("Null");
  }
  // String attribute value.
  else if (value.S != null)
  {
    Console.Write(value.S);
  }
  // String set attribute value.
  else if (value.SS.Count > 0)
  {
    Console.Write("{0}", string.Join("\n", value.SS.ToArray()));
  }
  // Otherwise, boolean value.
  else
  {
    Console.Write(value.BOOL);
  }
 
  Console.Write("\n");
}
```

Dalam contoh sebelumnya, setiap nilai atribut memiliki beberapa data-type-specific properti yang dapat dievaluasi untuk menentukan format yang benar untuk mencetak atribut. Properti ini termasuk`B`,`BOOL`,`BS`,`L`,`M`,`N`,`NS`,`NULL`,`S`, dan`SS`, yang sesuai dengan yang ada dalam [Format Data JSON](DataFormat.html). Untuk properti seperti`B`,`N`,`NULL`, dan`S`, jika properti yang sesuai tidak`null`, maka atribut adalah tipe `null` non-data yang sesuai. Untuk properti seperti`BS`,, `L``M`,`NS`, dan`SS`, jika `Count` lebih besar dari nol, maka atributnya adalah tipe non-zero-value data yang sesuai. Jika semua data-type-specific properti atribut adalah salah satu `null` atau `Count` sama dengan nol, maka atribut sesuai dengan tipe `BOOL` data.

## Membuat atau Mengganti Item dengan Menggunakan Ekspresi
<a name="dynamodb-expressions-put-item"></a>

Contoh berikut menampilkan `Amazon.DynamoDBv2.AmazonDynamoDBClient.PutItem` metode dan satu set ekspresi untuk memperbarui item yang memiliki a `Title` of`18-Bicycle 301`. Jika item belum ada, item baru ditambahkan.

```
// using Amazon.DynamoDBv2;
// using Amazon.DynamoDBv2.Model;

var client = new AmazonDynamoDBClient();
var request = new PutItemRequest
{
  TableName = "ProductCatalog",
  ExpressionAttributeNames = new Dictionary<string, string>
  {
    { "#title", "Title" }
  },
  ExpressionAttributeValues = new Dictionary<string, AttributeValue>
  {
    { ":product", new AttributeValue { S = "18-Bicycle 301" } }
  },
  ConditionExpression = "#title = :product", 
  // CreateItemData() is a custom function.
  Item = CreateItemData()
};
client.PutItem(request);
```

Dalam contoh sebelumnya, `ExpressionAttributeNames` properti menentukan placeholder `#title` untuk mewakili atribut. `Title` `ExpressionAttributeValues`Properti menentukan placeholder `:product` untuk mewakili nilai. `18-Bicycle 301` `ConditionExpression`Properti menentukan bahwa `#title` (`Title`) harus sama dengan `:product` (`18-Bicycle 301`). Panggilan untuk `CreateItemData` mengacu pada fungsi kustom berikut:

```
// using Amazon.DynamoDBv2.Model;

// Provides a sample item that can be added to a table.
public static Dictionary<string, AttributeValue> CreateItemData()
{
  var itemData = new Dictionary<string, AttributeValue>
  {
    { "Id", new AttributeValue { N = "301" } },
    { "Title", new AttributeValue { S = "18\" Girl's Bike" } },
    { "BicycleType", new AttributeValue { S = "Road" } },
    { "Brand" , new AttributeValue { S = "Brand-Company C" } },
    { "Color", new AttributeValue { SS = new List<string>{ "Blue", "Silver" } } },
    { "Description", new AttributeValue { S = "301 description" } },
    { "Gender", new AttributeValue { S = "F" } },
    { "InStock", new AttributeValue { BOOL = true } },
    { "Pictures", new AttributeValue { L = new List<AttributeValue>{ 
      { new AttributeValue { M = new Dictionary<string,AttributeValue>{
        { "FrontView", new AttributeValue { S = "http://example/products/301_front.jpg" } } } } },
      { new AttributeValue { M = new Dictionary<string,AttributeValue>{
        { "RearView", new AttributeValue {S = "http://example/products/301_rear.jpg" } } } } },
      { new AttributeValue { M = new Dictionary<string,AttributeValue>{
        { "SideView", new AttributeValue { S = "http://example/products/301_left_side.jpg" } } } } }
    } } },
    { "Price", new AttributeValue { N = "185" } },
    { "ProductCategory", new AttributeValue { S = "Bike" } },
    { "ProductReviews", new AttributeValue { M = new Dictionary<string,AttributeValue>{
      { "FiveStar", new AttributeValue { SS = new List<string>{
        "My daughter really enjoyed this bike!" } } },
      { "OneStar", new AttributeValue { SS = new List<string>{
        "Fun to ride.",
        "This bike was okay, but I would have preferred it in my color." } } }
    } } },
    { "QuantityOnHand", new AttributeValue { N = "3" } },
    { "RelatedItems", new AttributeValue { NS = new List<string>{ "979", "822", "801" } } }
  };

  return itemData;
}
```

Dalam contoh sebelumnya, item contoh dengan data sampel dikembalikan ke pemanggil. Serangkaian atribut dan nilai yang sesuai dibangun, menggunakan tipe data seperti`BOOL`,,`L`,`M`,`N`,`NS`, dan `S``SS`, yang sesuai dengan yang ada dalam [Format Data JSON](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/DataFormat.html).

## Memperbarui Item dengan Menggunakan Ekspresi
<a name="dynamodb-expressions-update-item"></a>

Contoh berikut menampilkan `Amazon.DynamoDBv2.AmazonDynamoDBClient.UpdateItem` metode dan satu set ekspresi untuk mengubah `Title` ke `18" Girl's Bike` untuk item dengan `Id` dari`301`.

```
// using Amazon.DynamoDBv2;
// using Amazon.DynamoDBv2.Model;

var client = new AmazonDynamoDBClient();
var request = new UpdateItemRequest
{
  TableName = "ProductCatalog",
  Key = new Dictionary<string,AttributeValue>
  {
     { "Id", new AttributeValue { N = "301" } }
  },
  ExpressionAttributeNames = new Dictionary<string, string>
  {
    { "#title", "Title" }
  },
  ExpressionAttributeValues = new Dictionary<string, AttributeValue>
  {
    { ":newproduct", new AttributeValue { S = "18\" Girl's Bike" } }
  },
  UpdateExpression = "SET #title = :newproduct"
};
client.UpdateItem(request);
```

Dalam contoh sebelumnya, `ExpressionAttributeNames` properti menentukan placeholder `#title` untuk mewakili atribut. `Title` `ExpressionAttributeValues`Properti menentukan placeholder `:newproduct` untuk mewakili nilai. `18" Girl's Bike` `UpdateExpression`Properti menentukan untuk mengubah `#title` (`Title`) ke `:newproduct` (`18" Girl's Bike`).

## Menghapus Item dengan Menggunakan Ekspresi
<a name="dynamodb-expressions-delete-item"></a>

Contoh berikut menampilkan `Amazon.DynamoDBv2.AmazonDynamoDBClient.DeleteItem` metode dan satu set ekspresi untuk menghapus item dengan `Id` dari`301`, tetapi hanya jika item `Title` tersebut`18-Bicycle 301`.

```
// using Amazon.DynamoDBv2;
// using Amazon.DynamoDBv2.Model;

var client = new AmazonDynamoDBClient();
var request = new DeleteItemRequest
{
  TableName = "ProductCatalog",
  Key = new Dictionary<string,AttributeValue>
  {
     { "Id", new AttributeValue { N = "301" } }
  },
  ExpressionAttributeNames = new Dictionary<string, string>
  {
    { "#title", "Title" }
  },
  ExpressionAttributeValues = new Dictionary<string, AttributeValue>
  {
    { ":product", new AttributeValue { S = "18-Bicycle 301" } }
  },
  ConditionExpression = "#title = :product"
};
client.DeleteItem(request);
```

Dalam contoh sebelumnya, `ExpressionAttributeNames` properti menentukan placeholder `#title` untuk mewakili atribut. `Title` `ExpressionAttributeValues`Properti menentukan placeholder `:product` untuk mewakili nilai. `18-Bicycle 301` `ConditionExpression`Properti menentukan bahwa `#title` (`Title`) harus sama `:product` (`18-Bicycle 301`).

## Info Selengkapnya
<a name="dynamodb-expressions-resources"></a>

Untuk informasi selengkapnya dan contoh kode, lihat:
+  [Seri DynamoDB - Ekspresi](http://blogs.aws.amazon.com/net/post/TxZQM7VA9AUZ9L/DynamoDB-Series-Expressions) 
+  [Mengakses Atribut Item dengan Ekspresi Proyeksi](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Expressions.AccessingItemAttributes.html) 
+  [Menggunakan Placeholder untuk Nama dan Nilai Atribut](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/ExpressionPlaceholders.html) 
+  [Menentukan Kondisi dengan Ekspresi Kondisi](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Expressions.SpecifyingConditions.html) 
+  [Memodifikasi Item dan Atribut dengan Ekspresi Pembaruan](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Expressions.Modifying.html) 
+  [Bekerja dengan Item Menggunakan API AWS SDK untuk .NET Tingkat Rendah](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/LowLevelDotNetItemCRUD.html) 
+  [Mengkueri Tabel Menggunakan API Tingkat AWS SDK untuk .NET Rendah](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/LowLevelDotNetQuerying.html) 
+  [Memindai Tabel Menggunakan API AWS SDK untuk .NET Tingkat Rendah](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/LowLevelDotNetScanning.html) 
+  [Bekerja dengan Indeks Sekunder Lokal Menggunakan API Tingkat AWS SDK untuk .NET Rendah](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/LSILowLevelDotNet.html) 
+  [Bekerja dengan Indeks Sekunder Global Menggunakan API Tingkat AWS SDK untuk .NET Rendah](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/GSILowLevelDotNet.html) 

# Dukungan JSON di Amazon DynamoDB
<a name="dynamodb-json"></a>

**catatan**  
Informasi dalam topik ini khusus untuk proyek berdasarkan .NET Framework dan AWS SDK untuk .NET versi 3.3 dan sebelumnya.

 AWS SDK untuk .NET Mendukung data JSON saat bekerja dengan Amazon DynamoDB. Ini memungkinkan Anda untuk lebih mudah mendapatkan data berformat JSON dari, dan memasukkan dokumen JSON ke dalam, tabel DynamoDB.

**Topics**
+ [Dapatkan Data dari Tabel DynamoDB dalam Format JSON](#dynamodb-json-get-table-data)
+ [Masukkan Data Format JSON ke dalam Tabel DynamoDB](#dynamodb-json-insert-table-data)
+ [DynamoDB Konversi Tipe Data ke JSON](#dynamodb-json-datatypes)
+ [Info Selengkapnya](#dynamodb-json-more-info)

## Dapatkan Data dari Tabel DynamoDB dalam Format JSON
<a name="dynamodb-json-get-table-data"></a>

Contoh berikut menunjukkan bagaimana untuk mendapatkan data dari tabel DynamoDB dalam format JSON:

```
// using Amazon.DynamoDBv2;
// using Amazon.DynamoDBv2.DocumentModel;

var client = new AmazonDynamoDBClient();
var table = Table.LoadTable(client, "AnimalsInventory");
var item = table.GetItem(3, "Horse");

var jsonText = item.ToJson();
Console.Write(jsonText);
      
// Output:
//   {"Name":"Shadow","Type":"Horse","Id":3}

var jsonPrettyText = item.ToJsonPretty();
Console.WriteLine(jsonPrettyText);
      
// Output:
//   {
//     "Name" : "Shadow",
//     "Type" : "Horse",
//     "Id"   : 3
//   }
```

Dalam contoh sebelumnya, `ToJson` metode `Document` kelas mengubah item dari tabel menjadi string berformat JSON. Item diambil melalui `GetItem` metode `Table` kelas. Untuk menentukan item yang akan didapatkan, dalam contoh ini, `GetItem` metode menggunakan kunci hash-and-range utama dari item target. Untuk menentukan tabel untuk mendapatkan item dari, `LoadTable` metode `Table` kelas menggunakan instance dari `AmazonDynamoDBClient` kelas dan nama tabel target di DynamoDB.

## Masukkan Data Format JSON ke dalam Tabel DynamoDB
<a name="dynamodb-json-insert-table-data"></a>

Contoh berikut menunjukkan bagaimana menggunakan format JSON untuk menyisipkan item ke dalam tabel DynamoDB:

```
// using Amazon.DynamoDBv2;
// using Amazon.DynamoDBv2.DocumentModel;

var client = new AmazonDynamoDBClient();
var table = Table.LoadTable(client, "AnimalsInventory");
var jsonText = "{\"Id\":6,\"Type\":\"Bird\",\"Name\":\"Tweety\"}";
var item = Document.FromJson(jsonText);

table.PutItem(item);
```

Dalam contoh sebelumnya, `FromJson` metode `Document` kelas mengkonversi string JSON-diformat menjadi item. Item dimasukkan ke dalam tabel melalui `PutItem` metode `Table` kelas, yang menggunakan instance `Document` kelas yang berisi item. Untuk menentukan tabel untuk memasukkan item ke dalam, `LoadTable` metode `Table` kelas dipanggil, menentukan instance `AmazonDynamoDBClient` kelas dan nama tabel target di DynamoDB.

## DynamoDB Konversi Tipe Data ke JSON
<a name="dynamodb-json-datatypes"></a>

Setiap kali Anda memanggil `ToJson` metode `Document` kelas, dan kemudian pada data JSON yang dihasilkan Anda memanggil `FromJson` metode untuk mengubah data JSON kembali ke instance `Document` kelas, beberapa tipe data DynamoDB tidak akan dikonversi seperti yang diharapkan. Secara khusus:
+ DynamoDB set (`SS``NS`,, `BS` dan jenis) akan dikonversi ke array JSON.
+ Skalar dan set biner DynamoDB (`B``BS`dan tipe) akan dikonversi ke string JSON yang dikodekan base64 atau daftar string.

  Dalam skenario ini, Anda harus memanggil `DecodeBase64Attributes` metode `Document` kelas untuk mengganti data JSON yang dikodekan base64 dengan representasi biner yang benar. Contoh berikut menggantikan atribut item skalar biner berkode base64 dalam contoh `Document` kelas, bernama`Picture`, dengan representasi biner yang benar. Contoh ini juga melakukan hal yang sama untuk atribut item set biner yang dikodekan base64 dalam contoh kelas yang sama, bernama: `Document` `RelatedPictures`

  ```
  item.DecodeBase64Attributes("Picture", "RelatedPictures");
  ```

## Info Selengkapnya
<a name="dynamodb-json-more-info"></a>

Untuk informasi lebih lanjut dan contoh pemrograman JSON dengan DynamoDB dengan, lihat: AWS SDK untuk .NET
+  [Dukungan DynamoDB JSON](https://aws.amazon.com/blogs/developer/dynamodb-json-support/) 
+  [Pembaruan Amazon DynamoDB - JSON, Tingkat Gratis yang Diperluas, Penskalaan Fleksibel, Item Lebih Besar](https://aws.amazon.com/blogs/aws/dynamodb-update-json-and-more/) 

# Bekerja dengan Amazon EC2
<a name="ec2-apis-intro"></a>

Ini AWS SDK untuk .NET mendukung [Amazon EC2](https://docs.aws.amazon.com/ec2/), yang merupakan layanan web yang menyediakan kapasitas komputasi yang dapat diubah ukurannya. Anda menggunakan kapasitas komputasi ini untuk membangun dan meng-host sistem perangkat lunak Anda.

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

 AWS SDK untuk .NET Ini menyediakan API untuk klien Amazon EC2. API memungkinkan Anda untuk bekerja dengan fitur EC2 seperti grup keamanan dan pasangan kunci. API juga memungkinkan Anda mengontrol instans Amazon EC2. Bagian ini berisi sejumlah kecil contoh yang menunjukkan pola yang dapat Anda ikuti saat bekerja dengan ini APIs. Untuk melihat set lengkap APIs, lihat [Referensi AWS SDK untuk .NET API](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/) (dan gulir ke “Amazon.EC2").

Amazon EC2 APIs disediakan oleh [AWSSDK NuGet paket.EC2](https://www.nuget.org/packages/AWSSDK.EC2).

## Prasyarat
<a name="w2aac19c15c17b7"></a>

Sebelum Anda mulai, pastikan Anda telah [mengatur lingkungan dan proyek Anda](net-dg-config.md). Juga tinjau informasi di[Fitur SDK](net-dg-sdk-features.md).

## Tentang contoh
<a name="ec2-apis-intro-about"></a>

Contoh di bagian ini menunjukkan cara bekerja dengan klien Amazon EC2 dan mengelola instans Amazon EC2.

[Tutorial Instans Spot EC2](how-to-spot-instances.md) menunjukkan cara meminta Instans Spot Amazon EC2. Instans Spot memungkinkan Anda mengakses kapasitas EC2 yang tidak digunakan dengan harga kurang dari harga Sesuai Permintaan.

**Topics**
+ [APIs](#w2aac19c15c17b5)
+ [Prasyarat](#w2aac19c15c17b7)
+ [Tentang contoh](#ec2-apis-intro-about)
+ [Grup keamanan](security-groups.md)
+ [Pasangan kunci](key-pairs.md)
+ [Wilayah dan Zona Ketersediaan](using-regions-and-availability-zones.md)
+ [Instans EC2](how-to-ec2.md)
+ [Tutorial Instans Spot](how-to-spot-instances.md)

# Bekerja dengan grup keamanan di Amazon EC2
<a name="security-groups"></a>

Di Amazon EC2, *grup keamanan* bertindak sebagai firewall virtual yang mengontrol lalu lintas jaringan untuk satu atau lebih instans EC2. Secara default, EC2 mengaitkan instans Anda dengan grup keamanan yang tidak mengizinkan lalu lintas masuk. Anda dapat membuat grup keamanan yang memungkinkan instans EC2 Anda menerima lalu lintas tertentu. Misalnya, jika Anda perlu terhubung ke instans EC2 Windows, Anda harus mengkonfigurasi grup keamanan untuk memungkinkan lalu lintas RDP.

Untuk membaca selengkapnya tentang grup keamanan, lihat [grup keamanan Amazon EC2](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-security-groups.html) di Panduan Pengguna [Amazon EC2](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/).

**Awas**  
EC2-Classic sudah tidak digunakan lagi pada 15 Agustus 2022. Kami menyarankan Anda bermigrasi dari EC2-Classic ke VPC. Untuk informasi lebih lanjut, lihat posting blog [EC2-Classic Networking is Retiring - Inilah Cara Mempersiapkan](https://aws.amazon.com/blogs/aws/ec2-classic-is-retiring-heres-how-to-prepare/).

Untuk informasi tentang APIs dan prasyarat, lihat bagian induk (). [Bekerja dengan Amazon EC2](ec2-apis-intro.md)

**Topics**
+ [Menghitung kelompok keamanan](enumerate-security-groups.md)
+ [Membuat grup keamanan](creating-security-group.md)
+ [Memperbarui grup keamanan](authorize-ingress.md)

# Menghitung kelompok keamanan
<a name="enumerate-security-groups"></a>

Contoh ini menunjukkan kepada Anda cara menggunakan AWS SDK untuk .NET untuk menghitung grup keamanan. Jika Anda menyediakan ID [Amazon Virtual Private Cloud](https://docs.aws.amazon.com/vpc/latest/userguide/), aplikasi menghitung grup keamanan untuk VPC tertentu. Jika tidak, aplikasi hanya menampilkan daftar semua grup keamanan yang tersedia.

Bagian berikut menyediakan cuplikan dari contoh ini. [Kode lengkap untuk contoh](#enum-sec-groups-complete-code) ditampilkan setelah itu, dan dapat dibangun dan dijalankan apa adanya.

**Topics**
+ [Menghitung kelompok keamanan](#enum-sec-groups-enum)
+ [Kode lengkap](#enum-sec-groups-complete-code)
+ [Pertimbangan tambahan](#enum-sec-groups-additional)

## Menghitung kelompok keamanan
<a name="enum-sec-groups-enum"></a>

Cuplikan berikut menyebutkan grup keamanan Anda. Ini menghitung semua grup atau grup untuk VPC tertentu jika diberikan.

Contoh [di akhir topik ini](#enum-sec-groups-complete-code) menunjukkan cuplikan ini digunakan.

```
    //
    // Method to enumerate the security groups
    private static async Task EnumerateGroups(IAmazonEC2 ec2Client, string vpcID)
    {
      // A request object, in case we need it.
      var request = new DescribeSecurityGroupsRequest();

      // Put together the properties, if needed
      if(!string.IsNullOrEmpty(vpcID))
      {
        // We have a VPC ID. Find the security groups for just that VPC.
        Console.WriteLine($"\nGetting security groups for VPC {vpcID}...\n");
        request.Filters.Add(new Filter
        {
          Name = "vpc-id",
          Values = new List<string>() { vpcID }
        });
      }

      // Get the list of security groups
      DescribeSecurityGroupsResponse response =
        await ec2Client.DescribeSecurityGroupsAsync(request);

      // Display the list of security groups.
      foreach (SecurityGroup item in response.SecurityGroups)
      {
        Console.WriteLine("Security group: " + item.GroupId);
        Console.WriteLine("\tGroupId: " + item.GroupId);
        Console.WriteLine("\tGroupName: " + item.GroupName);
        Console.WriteLine("\tVpcId: " + item.VpcId);
        Console.WriteLine();
      }
    }
```

## Kode lengkap
<a name="enum-sec-groups-complete-code"></a>

Bagian ini menunjukkan referensi yang relevan dan kode lengkap untuk contoh ini.

### Referensi SDK
<a name="w2aac19c15c17c13c13c15b5b1"></a>

NuGet paket:
+ [AWSSDK.EC2](https://www.nuget.org/packages/AWSSDK.EC2)

Elemen pemrograman:
+ [Namespace Amazon.EC2](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/EC2/NEC2.html)

  [EC2Klien Kelas Amazon](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/EC2/TEC2Client.html)
+ [Namespace Amazon.EC2.Model](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/EC2/NEC2Model.html)

  Kelas [DescribeSecurityGroupsRequest](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/EC2/TDescribeSecurityGroupsRequest.html)

  Kelas [DescribeSecurityGroupsResponse](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/EC2/TDescribeSecurityGroupsResponse.html)

  [Filter](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/EC2/TFilter.html) Kelas

  Kelas [SecurityGroup](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/EC2/TSecurityGroup.html)

### Kode
<a name="w2aac19c15c17c13c13c15b7b1"></a>

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

namespace EC2EnumerateSecGroups
{
  class Program
  {
    static async Task Main(string[] args)
    {
      // Parse the command line
       string vpcID = string.Empty;
      if(args.Length == 0)
      {
        Console.WriteLine("\nEC2EnumerateSecGroups [vpc_id]");
        Console.WriteLine("  vpc_id - The ID of the VPC for which you want to see security groups.");
        Console.WriteLine("\nSince you specified no arguments, showing all available security groups.");
      }
      else
      {
        vpcID = args[0];
      }

      if(vpcID.StartsWith("vpc-") || string.IsNullOrEmpty(vpcID))
      {
        // Create an EC2 client object
        var ec2Client = new AmazonEC2Client();

        // Enumerate the security groups
        await EnumerateGroups(ec2Client, vpcID);
      }
      else
      {
        Console.WriteLine("Could not find a valid VPC ID in the command-line arguments:");
        Console.WriteLine($"{args[0]}");
      }
    }


    //
    // Method to enumerate the security groups
    private static async Task EnumerateGroups(IAmazonEC2 ec2Client, string vpcID)
    {
      // A request object, in case we need it.
      var request = new DescribeSecurityGroupsRequest();

      // Put together the properties, if needed
      if(!string.IsNullOrEmpty(vpcID))
      {
        // We have a VPC ID. Find the security groups for just that VPC.
        Console.WriteLine($"\nGetting security groups for VPC {vpcID}...\n");
        request.Filters.Add(new Filter
        {
          Name = "vpc-id",
          Values = new List<string>() { vpcID }
        });
      }

      // Get the list of security groups
      DescribeSecurityGroupsResponse response =
        await ec2Client.DescribeSecurityGroupsAsync(request);

      // Display the list of security groups.
      foreach (SecurityGroup item in response.SecurityGroups)
      {
        Console.WriteLine("Security group: " + item.GroupId);
        Console.WriteLine("\tGroupId: " + item.GroupId);
        Console.WriteLine("\tGroupName: " + item.GroupName);
        Console.WriteLine("\tVpcId: " + item.VpcId);
        Console.WriteLine();
      }
    }
  }
}
```

## Pertimbangan tambahan
<a name="enum-sec-groups-additional"></a>
+ Perhatikan untuk kasus VPC bahwa filter dibuat dengan `Name` bagian dari pasangan nama-nilai yang disetel ke “vpc-id”. Nama ini berasal dari deskripsi untuk `Filters` properti [DescribeSecurityGroupsRequest](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/EC2/TDescribeSecurityGroupsRequest.html)kelas.
+ Untuk mendapatkan daftar lengkap grup keamanan Anda, Anda juga dapat menggunakan [ DescribeSecurityGroupsAsync tanpa parameter](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/EC2/MEC2DescribeSecurityGroupsAsyncCancellationToken.html).
+ Anda dapat memverifikasi hasilnya dengan memeriksa daftar grup keamanan di konsol [Amazon EC2](https://console.aws.amazon.com/ec2/v2/home#SecurityGroups).

# Membuat grup keamanan
<a name="creating-security-group"></a>

Contoh ini menunjukkan cara menggunakan AWS SDK untuk .NET untuk membuat grup keamanan. Anda dapat memberikan ID VPC yang ada untuk membuat grup keamanan EC2 di VPC. Jika Anda tidak memberikan ID seperti itu, grup keamanan baru akan digunakan untuk EC2-Classic jika AWS akun Anda mendukung ini.

Jika Anda tidak memberikan ID VPC dan AWS akun Anda tidak mendukung EC2-Classic, grup keamanan baru akan menjadi milik VPC default akun Anda.

**Awas**  
EC2-Classic sudah tidak digunakan lagi pada 15 Agustus 2022. Kami menyarankan Anda bermigrasi dari EC2-Classic ke VPC. Untuk informasi lebih lanjut, lihat posting blog [EC2-Classic Networking is Retiring - Inilah Cara Mempersiapkan](https://aws.amazon.com/blogs/aws/ec2-classic-is-retiring-heres-how-to-prepare/).

Bagian berikut menyediakan cuplikan dari contoh ini. [Kode lengkap untuk contoh](#create-sec-groups-complete-code) ditampilkan setelah itu, dan dapat dibangun dan dijalankan apa adanya.

**Topics**
+ [Temukan grup keamanan yang ada](#create-sec-groups-find)
+ [Membuat grup keamanan](#create-sec-groups-enum)
+ [Kode lengkap](#create-sec-groups-complete-code)

## Temukan grup keamanan yang ada
<a name="create-sec-groups-find"></a>

Cuplikan berikut mencari grup keamanan yang ada dengan nama yang diberikan di VPC yang diberikan.

Contoh [di akhir topik ini](#create-sec-groups-complete-code) menunjukkan cuplikan ini digunakan.

```
    //
    // Method to determine if a security group with the specified name
    // already exists in the VPC
    private static async Task<List<SecurityGroup>> FindSecurityGroups(
      IAmazonEC2 ec2Client, string groupName, string vpcID)
    {
      var request = new DescribeSecurityGroupsRequest();
      request.Filters.Add(new Filter{
        Name = "group-name",
        Values = new List<string>() { groupName }
      });
      if(!string.IsNullOrEmpty(vpcID))
        request.Filters.Add(new Filter{
          Name = "vpc-id",
          Values = new List<string>() { vpcID }
        });

      var response = await ec2Client.DescribeSecurityGroupsAsync(request);
      return response.SecurityGroups;
    }
```

## Membuat grup keamanan
<a name="create-sec-groups-enum"></a>

Cuplikan berikut membuat grup keamanan baru jika grup dengan nama itu tidak ada di VPC yang diberikan. Jika tidak ada VPC yang diberikan dan satu atau lebih grup dengan nama itu ada, cuplikan hanya mengembalikan daftar grup.

Contoh [di akhir topik ini](#create-sec-groups-complete-code) menunjukkan cuplikan ini digunakan.

```
    //
    // Method to create a new security group (either EC2-Classic or EC2-VPC)
    // If vpcID is empty, the security group will be for EC2-Classic
    private static async Task<List<SecurityGroup>> CreateSecurityGroup(
      IAmazonEC2 ec2Client, string groupName, string vpcID)
    {
      // See if one or more security groups with that name
      // already exist in the given VPC. If so, return the list of them.
      var securityGroups = await FindSecurityGroups(ec2Client, groupName, vpcID);
      if (securityGroups.Count > 0)
      {
        Console.WriteLine(
          $"\nOne or more security groups with name {groupName} already exist.\n");
        return securityGroups;
      }

      // If the security group doesn't already exists, create it.
      var createRequest = new CreateSecurityGroupRequest{
        GroupName = groupName
      };
      if(string.IsNullOrEmpty(vpcID))
      {
        createRequest.Description = "My .NET example security group for EC2-Classic";
      }
      else
      {
        createRequest.VpcId = vpcID;
        createRequest.Description = "My .NET example security group for EC2-VPC";
      }
      CreateSecurityGroupResponse createResponse =
        await ec2Client.CreateSecurityGroupAsync(createRequest);

      // Return the new security group
      DescribeSecurityGroupsResponse describeResponse =
        await ec2Client.DescribeSecurityGroupsAsync(new DescribeSecurityGroupsRequest{
          GroupIds = new List<string>() { createResponse.GroupId }
        });
      return describeResponse.SecurityGroups;
    }
```

## Kode lengkap
<a name="create-sec-groups-complete-code"></a>

Bagian ini menunjukkan referensi yang relevan dan kode lengkap untuk contoh ini.

### Referensi SDK
<a name="w2aac19c15c17c13c15c23b5b1"></a>

NuGet paket:
+ [AWSSDK.EC2](https://www.nuget.org/packages/AWSSDK.EC2)

Elemen pemrograman:
+ [Namespace Amazon.EC2](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/EC2/NEC2.html)

  [EC2Klien Kelas Amazon](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/EC2/TEC2Client.html)
+ [Namespace Amazon.EC2.Model](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/EC2/NEC2Model.html)

  Kelas [CreateSecurityGroupRequest](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/EC2/TCreateSecurityGroupRequest.html)

  Kelas [CreateSecurityGroupResponse](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/EC2/TCreateSecurityGroupResponse.html)

  Kelas [DescribeSecurityGroupsRequest](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/EC2/TDescribeSecurityGroupsRequest.html)

  Kelas [DescribeSecurityGroupsResponse](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/EC2/TDescribeSecurityGroupsResponse.html)

  [Filter](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/EC2/TFilter.html) Kelas

  Kelas [SecurityGroup](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/EC2/TSecurityGroup.html)

### Kodenya
<a name="w2aac19c15c17c13c15c23b7b1"></a>

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

namespace EC2CreateSecGroup
{
  // = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =
  // Class to create a security group
  class Program
  {
    private const int MaxArgs = 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)
        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 groupName = CommandLine.GetArgument(parsedArgs, null, "-g", "--group-name");
      var vpcID = CommandLine.GetArgument(parsedArgs, null, "-v", "--vpc-id");
      if(string.IsNullOrEmpty(groupName))
        CommandLine.ErrorExit("\nYou must supply a name for the new group." +
          "\nRun the command with no arguments to see help.");
      if(!string.IsNullOrEmpty(vpcID) && !vpcID.StartsWith("vpc-"))
        CommandLine.ErrorExit($"\nNot a valid VPC ID: {vpcID}");

      // groupName has a value and vpcID either has a value or is null (which is fine)
      // Create the new security group and display information about it
      var securityGroups =
        await CreateSecurityGroup(new AmazonEC2Client(), groupName, vpcID);
      Console.WriteLine("Information about the security group(s):");
      foreach(var group in securityGroups)
      {
        Console.WriteLine($"\nGroupName: {group.GroupName}");
        Console.WriteLine($"GroupId: {group.GroupId}");
        Console.WriteLine($"Description: {group.Description}");
        Console.WriteLine($"VpcId (if any): {group.VpcId}");
      }
    }


    //
    // Method to create a new security group (either EC2-Classic or EC2-VPC)
    // If vpcID is empty, the security group will be for EC2-Classic
    private static async Task<List<SecurityGroup>> CreateSecurityGroup(
      IAmazonEC2 ec2Client, string groupName, string vpcID)
    {
      // See if one or more security groups with that name
      // already exist in the given VPC. If so, return the list of them.
      var securityGroups = await FindSecurityGroups(ec2Client, groupName, vpcID);
      if (securityGroups.Count > 0)
      {
        Console.WriteLine(
          $"\nOne or more security groups with name {groupName} already exist.\n");
        return securityGroups;
      }

      // If the security group doesn't already exists, create it.
      var createRequest = new CreateSecurityGroupRequest{
        GroupName = groupName
      };
      if(string.IsNullOrEmpty(vpcID))
      {
        createRequest.Description = "Security group for .NET code example (no VPC specified)";
      }
      else
      {
        createRequest.VpcId = vpcID;
        createRequest.Description = "Security group for .NET code example (VPC: " + vpcID + ")";
      }
      CreateSecurityGroupResponse createResponse =
        await ec2Client.CreateSecurityGroupAsync(createRequest);

      // Return the new security group
      DescribeSecurityGroupsResponse describeResponse =
        await ec2Client.DescribeSecurityGroupsAsync(new DescribeSecurityGroupsRequest{
          GroupIds = new List<string>() { createResponse.GroupId }
        });
      return describeResponse.SecurityGroups;
    }


    //
    // Method to determine if a security group with the specified name
    // already exists in the VPC
    private static async Task<List<SecurityGroup>> FindSecurityGroups(
      IAmazonEC2 ec2Client, string groupName, string vpcID)
    {
      var request = new DescribeSecurityGroupsRequest();
      request.Filters.Add(new Filter{
        Name = "group-name",
        Values = new List<string>() { groupName }
      });
      if(!string.IsNullOrEmpty(vpcID))
        request.Filters.Add(new Filter{
          Name = "vpc-id",
          Values = new List<string>() { vpcID }
        });

      var response = await ec2Client.DescribeSecurityGroupsAsync(request);
      return response.SecurityGroups;
    }


    //
    // Command-line help
    private static void PrintHelp()
    {
      Console.WriteLine(
        "\nUsage: EC2CreateSecGroup -g <group-name> [-v <vpc-id>]" +
        "\n  -g, --group-name: The name you would like the new security group to have." +
        "\n  -v, --vpc-id: The ID of a VPC to which the new security group will belong." +
        "\n     If vpc-id isn't present, the security group will be" +
        "\n     for EC2-Classic (if your AWS account supports this)" +
        "\n     or will use the default VCP for EC2-VPC.");
    }
  }


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

}
```

# Memperbarui grup keamanan
<a name="authorize-ingress"></a>

Contoh ini menunjukkan cara menggunakan aturan AWS SDK untuk .NET untuk menambahkan aturan ke grup keamanan. Secara khusus, contoh menambahkan aturan untuk mengizinkan lalu lintas masuk pada port TCP tertentu, yang dapat digunakan, misalnya, untuk koneksi jarak jauh ke instance EC2. Aplikasi mengambil ID dari grup keamanan yang ada, alamat IP (atau rentang alamat) dalam format CIDR, dan opsional nomor port TCP. Kemudian menambahkan aturan masuk ke grup keamanan yang diberikan.

**catatan**  
Untuk menggunakan contoh ini, Anda memerlukan alamat IP (atau rentang alamat) dalam format CIDR. Lihat **Pertimbangan tambahan** di akhir topik ini untuk metode mendapatkan alamat IP komputer lokal Anda.

Bagian berikut menyediakan cuplikan dari contoh ini. [Kode lengkap untuk contoh](#authorize-ingress-complete-code) ditampilkan setelah itu, dan dapat dibangun dan dijalankan apa adanya.

**Topics**
+ [Tambahkan aturan masuk](#authorize-ingress-add-rule)
+ [Kode lengkap](#authorize-ingress-complete-code)
+ [Pertimbangan tambahan](#authorize-ingress-additional)

## Tambahkan aturan masuk
<a name="authorize-ingress-add-rule"></a>

Cuplikan berikut menambahkan aturan masuk ke grup keamanan untuk alamat IP tertentu (atau rentang) dan port TCP.

Contoh [di akhir topik ini](#authorize-ingress-complete-code) menunjukkan cuplikan ini digunakan.

```
    //
    // Method that adds a TCP ingress rule to a security group
    private static async Task AddIngressRule(
      IAmazonEC2 eC2Client, string groupID, string ipAddress, int port)
    {
      // Create an object to hold the request information for the rule.
      // It uses an IpPermission object to hold the IP information for the rule.
      var ingressRequest = new AuthorizeSecurityGroupIngressRequest{
        GroupId = groupID};
      ingressRequest.IpPermissions.Add(new IpPermission{
        IpProtocol = "tcp",
        FromPort = port,
        ToPort = port,
        Ipv4Ranges = new List<IpRange>() { new IpRange { CidrIp = ipAddress } }
      });

      // Create the inbound rule for the security group
      AuthorizeSecurityGroupIngressResponse responseIngress =
        await eC2Client.AuthorizeSecurityGroupIngressAsync(ingressRequest);
      Console.WriteLine($"\nNew RDP rule was written in {groupID} for {ipAddress}.");
      Console.WriteLine($"Result: {responseIngress.HttpStatusCode}");
    }
```

## Kode lengkap
<a name="authorize-ingress-complete-code"></a>

Bagian ini menunjukkan referensi yang relevan dan kode lengkap untuk contoh ini.

### Referensi SDK
<a name="w2aac19c15c17c13c17c17b5b1"></a>

NuGet paket:
+ [AWSSDK.EC2](https://www.nuget.org/packages/AWSSDK.EC2)

Elemen pemrograman:
+ [Namespace Amazon.EC2](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/EC2/NEC2.html)

  [EC2Klien Kelas Amazon](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/EC2/TEC2Client.html)
+ [Namespace Amazon.EC2.Model](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/EC2/NEC2Model.html)

  Kelas [AuthorizeSecurityGroupIngressRequest](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/EC2/TAuthorizeSecurityGroupIngressRequest.html)

  Kelas [AuthorizeSecurityGroupIngressResponse](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/EC2/TAuthorizeSecurityGroupIngressResponse.html)

  Kelas [IpPermission](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/EC2/TIpPermission.html)

  Kelas [IpRange](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/EC2/TIpRange.html)

### Kodenya
<a name="w2aac19c15c17c13c17c17b7b1"></a>

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

namespace EC2AddRuleForRDP
{
  // = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =
  // Class to add a rule that allows inbound traffic on TCP a port
  class Program
  {
    private const int DefaultPort = 3389;

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

      // Get the application arguments from the parsed list
      var groupID = CommandLine.GetArgument(parsedArgs, null, "-g", "--group-id");
      var ipAddress = CommandLine.GetArgument(parsedArgs, null, "-i", "--ip-address");
      var portStr = CommandLine.GetArgument(parsedArgs, DefaultPort.ToString(), "-p", "--port");
      if(string.IsNullOrEmpty(ipAddress))
        CommandLine.ErrorExit("\nYou must supply an IP address in CIDR format.");
      if(string.IsNullOrEmpty(groupID) || !groupID.StartsWith("sg-"))
        CommandLine.ErrorExit("\nThe ID for a security group is missing or incorrect.");
      if(int.Parse(portStr) == 0)
        CommandLine.ErrorExit($"\nThe given TCP port number, {portStr}, isn't allowed.");

      // Add a rule to the given security group that allows
      // inbound traffic on a TCP port
      await AddIngressRule(
        new AmazonEC2Client(), groupID, ipAddress, int.Parse(portStr));
    }


    //
    // Method that adds a TCP ingress rule to a security group
    private static async Task AddIngressRule(
      IAmazonEC2 eC2Client, string groupID, string ipAddress, int port)
    {
      // Create an object to hold the request information for the rule.
      // It uses an IpPermission object to hold the IP information for the rule.
      var ingressRequest = new AuthorizeSecurityGroupIngressRequest{
        GroupId = groupID};
      ingressRequest.IpPermissions.Add(new IpPermission{
        IpProtocol = "tcp",
        FromPort = port,
        ToPort = port,
        Ipv4Ranges = new List<IpRange>() { new IpRange { CidrIp = ipAddress } }
      });

      // Create the inbound rule for the security group
      AuthorizeSecurityGroupIngressResponse responseIngress =
        await eC2Client.AuthorizeSecurityGroupIngressAsync(ingressRequest);
      Console.WriteLine($"\nNew RDP rule was written in {groupID} for {ipAddress}.");
      Console.WriteLine($"Result: {responseIngress.HttpStatusCode}");
    }


    //
    // Command-line help
    private static void PrintHelp()
    {
      Console.WriteLine(
        "\nUsage: EC2AddRuleForRDP -g <group-id> -i <ip-address> [-p <port>]" +
        "\n  -g, --group-id: The ID of the security group to which you want to add the inbound rule." +
        "\n  -i, --ip-address: An IP address or address range in CIDR format." +
        "\n  -p, --port: The TCP port number. Defaults to 3389.");
    }
  }


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

}
```

## Pertimbangan tambahan
<a name="authorize-ingress-additional"></a>
+ Jika Anda tidak menyediakan nomor port, aplikasi default ke port 3389. Ini adalah port untuk Windows RDP, yang memungkinkan Anda untuk terhubung ke instans EC2 yang menjalankan Windows. Jika Anda meluncurkan instans EC2 yang menjalankan Linux, Anda dapat menggunakan port TCP 22 (SSH) sebagai gantinya.
+ Perhatikan bahwa contoh disetel `IpProtocol` ke “tcp”. Nilai untuk `IpProtocol` dapat ditemukan dalam deskripsi untuk `IpProtocol` properti [IpPermission](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/EC2/TIpPermission.html)kelas.
+ Anda mungkin menginginkan alamat IP komputer lokal Anda saat menggunakan contoh ini. Berikut ini adalah beberapa cara di mana Anda bisa mendapatkan alamat.
  + Jika komputer lokal Anda (dari mana Anda akan terhubung ke instans EC2 Anda) memiliki alamat IP publik statis, Anda dapat menggunakan layanan untuk mendapatkan alamat itu. Salah satu layanan tersebut adalah [http://checkip.amazonaws.com/](http://checkip.amazonaws.com/). Untuk membaca selengkapnya tentang mengotorisasi lalu lintas masuk, lihat [Menambahkan aturan ke grup keamanan](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/working-with-security-groups.html#adding-security-group-rule) dan [Aturan grup keamanan untuk kasus penggunaan yang berbeda](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/security-group-rules-reference.html) di Panduan Pengguna [Amazon EC2](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/).
  + Cara lain untuk mendapatkan alamat IP komputer lokal Anda adalah dengan menggunakan konsol [Amazon EC2](https://console.aws.amazon.com/ec2/v2/home#SecurityGroups).

    Pilih salah satu grup keamanan Anda, pilih tab **Aturan masuk**, dan pilih **Edit aturan masuk**. Dalam aturan masuk, buka menu tarik-turun di kolom **Sumber** dan pilih **IP Saya** untuk melihat alamat IP komputer lokal Anda dalam format CIDR. Pastikan untuk **Membatalkan** operasi.
+ Anda dapat memverifikasi hasil contoh ini dengan memeriksa daftar grup keamanan di konsol [Amazon EC2](https://console.aws.amazon.com/ec2/v2/home#SecurityGroups).

# Bekerja dengan pasangan kunci Amazon EC2
<a name="key-pairs"></a>

Amazon EC2 menggunakan kriptografi kunci publik untuk mengenkripsi dan mendekripsi informasi login. Kriptografi kunci publik menggunakan kunci publik untuk mengenkripsi data, dan kemudian penerima menggunakan kunci pribadi untuk mendekripsi data. Kunci publik dan privat dikenal sebagai pasangan kunci. Jika Anda ingin masuk ke instans EC2, Anda harus menentukan key pair ketika Anda meluncurkannya, dan kemudian memberikan kunci pribadi pasangan ketika Anda terhubung ke sana.

Saat meluncurkan instans EC2, Anda dapat membuat key pair untuknya atau menggunakan salah satu yang sudah Anda gunakan saat meluncurkan instance lain. Untuk membaca selengkapnya tentang pasangan kunci Amazon EC2, lihat [Bekerja dengan pasangan kunci Amazon EC2 di Panduan](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-key-pairs.html) Pengguna Amazon [EC2](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/).

Untuk informasi tentang APIs dan prasyarat, lihat bagian induk (). [Bekerja dengan Amazon EC2](ec2-apis-intro.md)

**Topics**
+ [Membuat dan menampilkan pasangan kunci](create-save-key-pair.md)
+ [Menghapus pasangan kunci](delete-key-pairs.md)

# Membuat dan menampilkan pasangan kunci
<a name="create-save-key-pair"></a>

Contoh ini menunjukkan kepada Anda cara menggunakan AWS SDK untuk .NET to create a key pair. Aplikasi ini mengambil nama untuk key pair baru dan nama file PEM (dengan ekstensi “.pem”). Ini menciptakan keypair, menulis kunci pribadi ke file PEM, dan kemudian menampilkan semua pasangan kunci yang tersedia. Jika Anda tidak memberikan argumen baris perintah, aplikasi hanya menampilkan semua pasangan kunci yang tersedia.

Bagian berikut menyediakan cuplikan dari contoh ini. [Kode lengkap untuk contoh](#create-save-key-pair-complete-code) ditampilkan setelah itu, dan dapat dibangun dan dijalankan apa adanya.

**Topics**
+ [Buat pasangan kunci](#create-save-key-pair-create)
+ [Tampilkan pasangan kunci yang tersedia](#create-save-key-pair-display)
+ [Kode lengkap](#create-save-key-pair-complete-code)
+ [Pertimbangan tambahan](#create-save-key-pair-additional)

## Buat pasangan kunci
<a name="create-save-key-pair-create"></a>

Cuplikan berikut membuat key pair dan kemudian menyimpan kunci pribadi ke file PEM yang diberikan.

Contoh [di akhir topik ini](#create-save-key-pair-complete-code) menunjukkan cuplikan ini digunakan.

```
    //
    // Method to create a key pair and save the key material in a PEM file
    private static async Task CreateKeyPair(
      IAmazonEC2 ec2Client, string keyPairName, string pemFileName)
    {
      // Create the key pair
      CreateKeyPairResponse response =
        await ec2Client.CreateKeyPairAsync(new CreateKeyPairRequest{
          KeyName = keyPairName
        });
      Console.WriteLine($"\nCreated new key pair: {response.KeyPair.KeyName}");

      // Save the private key in a PEM file
      using (var s = new FileStream(pemFileName, FileMode.Create))
      using (var writer = new StreamWriter(s))
      {
        writer.WriteLine(response.KeyPair.KeyMaterial);
      }
    }
```

## Tampilkan pasangan kunci yang tersedia
<a name="create-save-key-pair-display"></a>

Cuplikan berikut menampilkan daftar pasangan kunci yang tersedia.

Contoh [di akhir topik ini](#create-save-key-pair-complete-code) menunjukkan cuplikan ini digunakan.

```
    //
    // Method to show the key pairs that are available
    private static async Task EnumerateKeyPairs(IAmazonEC2 ec2Client)
    {
      DescribeKeyPairsResponse response = await ec2Client.DescribeKeyPairsAsync();
      Console.WriteLine("Available key pairs:");
      foreach (KeyPairInfo item in response.KeyPairs)
        Console.WriteLine($"  {item.KeyName}");
    }
```

## Kode lengkap
<a name="create-save-key-pair-complete-code"></a>

Bagian ini menunjukkan referensi yang relevan dan kode lengkap untuk contoh ini.

### Referensi SDK
<a name="w2aac19c15c17c15c11c19b5b1"></a>

NuGet paket:
+ [AWSSDK.EC2](https://www.nuget.org/packages/AWSSDK.EC2)

Elemen pemrograman:
+ [Namespace Amazon.EC2](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/EC2/NEC2.html)

  [EC2Klien Kelas Amazon](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/EC2/TEC2Client.html)
+ [Namespace Amazon.EC2.Model](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/EC2/NEC2Model.html)

  Kelas [CreateKeyPairRequest](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/EC2/TCreateKeyPairRequest.html)

  Kelas [CreateKeyPairResponse](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/EC2/TCreateKeyPairResponse.html)

  Kelas [DescribeKeyPairsResponse](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/EC2/TDescribeKeyPairsResponse.html)

  Kelas [KeyPairInfo](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/EC2/TKeyPairInfo.html)

### Kodenya
<a name="w2aac19c15c17c15c11c19b7b1"></a>

```
using System;
using System.Threading.Tasks;
using System.IO;
using Amazon.EC2;
using Amazon.EC2.Model;
using System.Collections.Generic;

namespace EC2CreateKeyPair
{
  // = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =
  // Class to create and store a key pair
  class Program
  {
    static async Task Main(string[] args)
    {
      // Create the EC2 client
      var ec2Client = new AmazonEC2Client();

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

      // Get the application arguments from the parsed list
      string keyPairName =
        CommandLine.GetArgument(parsedArgs, null, "-k", "--keypair-name");
      string pemFileName =
        CommandLine.GetArgument(parsedArgs, null, "-p", "--pem-filename");
      if(string.IsNullOrEmpty(keyPairName))
        CommandLine.ErrorExit("\nNo key pair name specified." +
          "\nRun the command with no arguments to see help.");
      if(string.IsNullOrEmpty(pemFileName) || !pemFileName.EndsWith(".pem"))
        CommandLine.ErrorExit("\nThe PEM filename is missing or incorrect." +
          "\nRun the command with no arguments to see help.");

      // Create the key pair
      await CreateKeyPair(ec2Client, keyPairName, pemFileName);
      await EnumerateKeyPairs(ec2Client);
    }


    //
    // Method to create a key pair and save the key material in a PEM file
    private static async Task CreateKeyPair(
      IAmazonEC2 ec2Client, string keyPairName, string pemFileName)
    {
      // Create the key pair
      CreateKeyPairResponse response =
        await ec2Client.CreateKeyPairAsync(new CreateKeyPairRequest{
          KeyName = keyPairName
        });
      Console.WriteLine($"\nCreated new key pair: {response.KeyPair.KeyName}");

      // Save the private key in a PEM file
      using (var s = new FileStream(pemFileName, FileMode.Create))
      using (var writer = new StreamWriter(s))
      {
        writer.WriteLine(response.KeyPair.KeyMaterial);
      }
    }


    //
    // Method to show the key pairs that are available
    private static async Task EnumerateKeyPairs(IAmazonEC2 ec2Client)
    {
      DescribeKeyPairsResponse response = await ec2Client.DescribeKeyPairsAsync();
      Console.WriteLine("Available key pairs:");
      foreach (KeyPairInfo item in response.KeyPairs)
        Console.WriteLine($"  {item.KeyName}");
    }


    //
    // Command-line help
    private static void PrintHelp()
    {
      Console.WriteLine(
        "\nUsage: EC2CreateKeyPair -k <keypair-name> -p <pem-filename>" +
        "\n  -k, --keypair-name: The name you want to assign to the key pair." +
        "\n  -p, --pem-filename: The name of the PEM file to create, with a \".pem\" extension.");
    }
  }


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

}
```

## Pertimbangan tambahan
<a name="create-save-key-pair-additional"></a>
+ Setelah Anda menjalankan contoh, Anda dapat melihat key pair baru di konsol [Amazon EC2](https://console.aws.amazon.com/ec2/#KeyPairs).
+ Ketika Anda membuat key pair, Anda harus menyimpan kunci pribadi yang dikembalikan karena Anda tidak dapat mengambil kunci pribadi nanti.

# Menghapus pasangan kunci
<a name="delete-key-pairs"></a>

Contoh ini menunjukkan kepada Anda cara menggunakan AWS SDK untuk .NET to delete a key pair. Aplikasi ini mengambil nama key pair. Ini menghapus key pair dan kemudian menampilkan semua pasangan kunci yang tersedia. Jika Anda tidak memberikan argumen baris perintah, aplikasi hanya menampilkan semua pasangan kunci yang tersedia.

Bagian berikut menyediakan cuplikan dari contoh ini. [Kode lengkap untuk contoh](#delete-key-pairs-complete-code) ditampilkan setelah itu, dan dapat dibangun dan dijalankan apa adanya.

**Topics**
+ [Hapus key pair](#delete-key-pairs-create)
+ [Tampilkan pasangan kunci yang tersedia](#delete-key-pairs-display)
+ [Kode lengkap](#delete-key-pairs-complete-code)

## Hapus key pair
<a name="delete-key-pairs-create"></a>

Cuplikan berikut menghapus key pair.

Contoh [di akhir topik ini](#delete-key-pairs-complete-code) menunjukkan cuplikan ini digunakan.

```
    //
    // Method to delete a key pair
    private static async Task DeleteKeyPair(IAmazonEC2 ec2Client, string keyName)
    {
      await ec2Client.DeleteKeyPairAsync(new DeleteKeyPairRequest{
        KeyName = keyName});
      Console.WriteLine($"\nKey pair {keyName} has been deleted (if it existed).");
    }
```

## Tampilkan pasangan kunci yang tersedia
<a name="delete-key-pairs-display"></a>

Cuplikan berikut menampilkan daftar pasangan kunci yang tersedia.

Contoh [di akhir topik ini](#delete-key-pairs-complete-code) menunjukkan cuplikan ini digunakan.

```
    //
    // Method to show the key pairs that are available
    private static async Task EnumerateKeyPairs(IAmazonEC2 ec2Client)
    {
      DescribeKeyPairsResponse response = await ec2Client.DescribeKeyPairsAsync();
      Console.WriteLine("Available key pairs:");
      foreach (KeyPairInfo item in response.KeyPairs)
        Console.WriteLine($"  {item.KeyName}");
    }
```

## Kode lengkap
<a name="delete-key-pairs-complete-code"></a>

Bagian ini menunjukkan referensi yang relevan dan kode lengkap untuk contoh ini.

### Referensi SDK
<a name="w2aac19c15c17c15c13c19b5b1"></a>

NuGet paket:
+ [AWSSDK.EC2](https://www.nuget.org/packages/AWSSDK.EC2)

Elemen pemrograman:
+ [Namespace Amazon.EC2](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/EC2/NEC2.html)

  [EC2Klien Kelas Amazon](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/EC2/TEC2Client.html)
+ [Namespace Amazon.EC2.Model](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/EC2/NEC2Model.html)

  Kelas [https://docs.aws.amazon.com/sdkfornet/v3/apidocs/](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/)

  Kelas [DescribeKeyPairsResponse](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/EC2/TDescribeKeyPairsResponse.html)

  Kelas [KeyPairInfo](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/EC2/TKeyPairInfo.html)

### Kodenya
<a name="w2aac19c15c17c15c13c19b7b1"></a>

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

namespace EC2DeleteKeyPair
{
  class Program
  {
    static async Task Main(string[] args)
    {
      // Create the EC2 client
      var ec2Client = new AmazonEC2Client();

      if(args.Length == 1)
      {
        // Delete a key pair (if it exists)
        await DeleteKeyPair(ec2Client, args[0]);

        // Display the key pairs that are left
        await EnumerateKeyPairs(ec2Client);
      }
      else
      {
        Console.WriteLine("\nUsage: EC2DeleteKeyPair keypair-name");
        Console.WriteLine("  keypair-name - The name of the key pair you want to delete.");
        Console.WriteLine("\nNo arguments specified.");
        Console.Write(
          "Do you want to see a list of the existing key pairs? ((y) or n): ");
        string response = Console.ReadLine();
        if((string.IsNullOrEmpty(response)) || (response.ToLower() == "y"))
          await EnumerateKeyPairs(ec2Client);
      }
    }


    //
    // Method to delete a key pair
    private static async Task DeleteKeyPair(IAmazonEC2 ec2Client, string keyName)
    {
      await ec2Client.DeleteKeyPairAsync(new DeleteKeyPairRequest{
        KeyName = keyName});
      Console.WriteLine($"\nKey pair {keyName} has been deleted (if it existed).");
    }


    //
    // Method to show the key pairs that are available
    private static async Task EnumerateKeyPairs(IAmazonEC2 ec2Client)
    {
      DescribeKeyPairsResponse response = await ec2Client.DescribeKeyPairsAsync();
      Console.WriteLine("Available key pairs:");
      foreach (KeyPairInfo item in response.KeyPairs)
        Console.WriteLine($"  {item.KeyName}");
    }
  }
}
```

# Melihat Wilayah Amazon EC2 dan Availability Zone
<a name="using-regions-and-availability-zones"></a>

Amazon EC2 di-host di beberapa lokasi di seluruh dunia. Lokasi ini terdiri dari Wilayah dan Zona Ketersediaan . Setiap Wilayah adalah wilayah geografis terpisah yang memiliki beberapa lokasi terisolasi yang dikenal sebagai Availability Zone.

Untuk membaca lebih lanjut tentang Wilayah dan Availability Zone, lihat [Wilayah dan Zona](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/using-regions-availability-zones.html) di [Panduan Pengguna Amazon EC2](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/).

Contoh ini menunjukkan kepada Anda cara menggunakan AWS SDK untuk .NET untuk mendapatkan detail tentang Wilayah dan Availability Zone yang terkait dengan klien EC2. Aplikasi ini menampilkan daftar Wilayah dan Availability Zone yang tersedia untuk klien EC2.

## Referensi SDK
<a name="w2aac19c15c17c17b9b1"></a>

NuGet paket:
+ [AWSSDK.EC2](https://www.nuget.org/packages/AWSSDK.EC2)

Elemen pemrograman:
+ [Namespace Amazon.EC2](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/EC2/NEC2.html)

  [EC2Klien Kelas Amazon](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/EC2/TEC2Client.html)
+ [Namespace Amazon.EC2.Model](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/EC2/NEC2Model.html)

  Kelas [DescribeAvailabilityZonesResponse](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/EC2/TDescribeAvailabilityZonesResponse.html)

  Kelas [DescribeRegionsResponse](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/EC2/TDescribeRegionsResponse.html)

  Kelas [AvailabilityZone](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/EC2/TAvailabilityZone.html)

  [Wilayah](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/EC2/TRegion.html) Kelas

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

namespace EC2RegionsAndZones
{
  class Program
  {
    static async Task Main(string[] args)
    {
      Console.WriteLine(
        "Finding the Regions and Availability Zones available to an EC2 client...");

      // Create the EC2 client
      var ec2Client = new AmazonEC2Client();

      // Display the Regions and Availability Zones
      await DescribeRegions(ec2Client);
      await DescribeAvailabilityZones(ec2Client);
    }


    //
    // Method to display Regions
    private static async Task DescribeRegions(IAmazonEC2 ec2Client)
    {
      Console.WriteLine("\nRegions that are enabled for the EC2 client:");
      DescribeRegionsResponse response = await ec2Client.DescribeRegionsAsync();
      foreach (Region region in response.Regions)
        Console.WriteLine(region.RegionName);
    }


    //
    // Method to display Availability Zones
    private static async Task DescribeAvailabilityZones(IAmazonEC2 ec2Client)
    {
      Console.WriteLine("\nAvailability Zones for the EC2 client's region:");
      DescribeAvailabilityZonesResponse response =
        await ec2Client.DescribeAvailabilityZonesAsync();
      foreach (AvailabilityZone az in response.AvailabilityZones)
        Console.WriteLine(az.ZoneName);
    }
  }
}
```

# Bekerja dengan instans Amazon EC2
<a name="how-to-ec2"></a>

Anda dapat menggunakan AWS SDK untuk .NET untuk mengontrol instans Amazon EC2 dengan operasi seperti membuat, memulai, dan mengakhiri. Topik di bagian ini memberikan beberapa contoh bagaimana melakukan ini. Untuk membaca selengkapnya tentang instans EC2, lihat instans [Amazon EC2](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Instances.html) di Panduan Pengguna Amazon [EC2](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/).

Untuk informasi tentang APIs dan prasyarat, lihat bagian induk (). [Bekerja dengan Amazon EC2](ec2-apis-intro.md)

**Topics**
+ [Meluncurkan instans EC2](run-instance.md)
+ [Mengakhiri instans EC2](terminate-instance.md)

# Meluncurkan instans Amazon EC2
<a name="run-instance"></a>

Contoh ini menunjukkan kepada Anda cara menggunakan AWS SDK untuk .NET untuk meluncurkan satu atau lebih instans Amazon EC2 yang dikonfigurasi secara identik dari Amazon Machine Image (AMI) yang sama. Menggunakan [beberapa input](#run-instance-gather) yang Anda berikan, aplikasi meluncurkan instans EC2 dan kemudian memonitor instance hingga keluar dari status “Tertunda”.

Saat instans EC2 Anda berjalan, Anda dapat menghubungkannya dari jarak jauh, seperti yang dijelaskan dalam. [(opsional) Connect ke instance](#connect-to-instance)

**Awas**  
EC2-Classic sudah tidak digunakan lagi pada 15 Agustus 2022. Kami menyarankan Anda bermigrasi dari EC2-Classic ke VPC. Untuk informasi lebih lanjut, lihat posting blog [EC2-Classic Networking is Retiring - Inilah Cara Mempersiapkan](https://aws.amazon.com/blogs/aws/ec2-classic-is-retiring-heres-how-to-prepare/).

Bagian berikut menyediakan cuplikan dan informasi lain untuk contoh ini. [Kode lengkap untuk contoh](#run-instance-complete-code) ditampilkan setelah cuplikan, dan dapat dibangun dan dijalankan apa adanya.

**Topics**
+ [Kumpulkan apa yang Anda butuhkan](#run-instance-gather)
+ [Luncurkan sebuah instans](#run-instance-launch)
+ [Pantau instance](#run-instance-monitor)
+ [Kode lengkap](#run-instance-complete-code)
+ [Pertimbangan tambahan](#run-instance-additional)
+ [(opsional) Connect ke instance](#connect-to-instance)
+ [Bersihkan](#run-instance-cleanup)

## Kumpulkan apa yang Anda butuhkan
<a name="run-instance-gather"></a>

Untuk meluncurkan instans EC2, Anda memerlukan beberapa hal.
+ [VPC](https://docs.aws.amazon.com/vpc/latest/userguide/) tempat instance akan diluncurkan. Jika itu adalah instance Windows dan Anda akan menghubungkannya melalui RDP, VPC kemungkinan besar harus memiliki gateway internet yang terpasang padanya, serta entri untuk gateway internet di tabel rute. Untuk informasi lebih lanjut, lihat [Gateway internet](https://docs.aws.amazon.com/vpc/latest/userguide/VPC_Internet_Gateway.html) di *Panduan Pengguna Amazon VPC*.
+ ID subnet yang ada di VPC tempat instance akan diluncurkan. Cara mudah untuk menemukan atau membuat ini adalah dengan masuk ke [konsol VPC Amazon](https://console.aws.amazon.com/vpc/home#subnets), tetapi Anda juga dapat memperolehnya secara terprogram dengan menggunakan metode dan. [CreateSubnetAsync[DescribeSubnetsAsync](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/EC2/MEC2DescribeSubnetsAsyncDescribeSubnetsRequestCancellationToken.html)](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/EC2/MEC2CreateSubnetAsyncCreateSubnetRequestCancellationToken.html)
**catatan**  
Jika Anda tidak menyediakan parameter ini, instance baru akan diluncurkan di VPC default untuk akun Anda.
+ ID grup keamanan yang ada milik VPC tempat instance akan diluncurkan. Untuk informasi selengkapnya, lihat [Bekerja dengan grup keamanan di Amazon EC2](security-groups.md).
+ Jika Anda ingin terhubung ke instance baru, grup keamanan yang disebutkan sebelumnya harus memiliki aturan masuk yang sesuai yang memungkinkan lalu lintas SSH pada port 22 (instance Linux) atau lalu lintas RDP pada port 3389 (instance Windows). Untuk informasi tentang cara melakukan ini[Memperbarui grup keamanan](authorize-ingress.md), lihat, termasuk [Pertimbangan tambahan](authorize-ingress.md#authorize-ingress-additional) mendekati akhir topik itu.
+ Amazon Machine Image (AMI) yang akan digunakan untuk membuat instance. Untuk selengkapnya AMIs, lihat [Gambar Mesin Amazon (AMIs)](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/AMIs.html) di [Panduan Pengguna Amazon EC2](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/). Secara khusus, lihat [Menemukan AMI](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/finding-an-ami.html) dan [Dibagikan AMIs](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/sharing-amis.html).
+ Nama key pair EC2 yang ada, yang digunakan untuk terhubung ke instance baru. Untuk informasi selengkapnya, lihat [Bekerja dengan pasangan kunci Amazon EC2](key-pairs.md).
+ Nama file PEM yang berisi kunci pribadi dari key pair EC2 yang disebutkan sebelumnya. File PEM digunakan saat Anda [terhubung dari jarak jauh](#connect-to-instance) ke instance.

## Luncurkan sebuah instans
<a name="run-instance-launch"></a>

Cuplikan berikut meluncurkan instance EC2.

Contoh di [dekat akhir topik ini](#run-instance-complete-code) menunjukkan cuplikan ini digunakan.

```
    //
    // Method to launch the instances
    // Returns a list with the launched instance IDs
    private static async Task<List<string>> LaunchInstances(
      IAmazonEC2 ec2Client, RunInstancesRequest requestLaunch)
    {
      var instanceIds = new List<string>();
      RunInstancesResponse responseLaunch =
        await ec2Client.RunInstancesAsync(requestLaunch);

      Console.WriteLine("\nNew instances have been created.");
      foreach (Instance item in responseLaunch.Reservation.Instances)
      {
        instanceIds.Add(item.InstanceId);
        Console.WriteLine($"  New instance: {item.InstanceId}");
      }

      return instanceIds;
    }
```

## Pantau instance
<a name="run-instance-monitor"></a>

Cuplikan berikut memonitor instance hingga keluar dari status “Tertunda”.

Contoh di [dekat akhir topik ini](#run-instance-complete-code) menunjukkan cuplikan ini digunakan.

Lihat [InstanceState](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/EC2/TInstanceState.html)kelas untuk nilai valid dari `Instance.State.Code` properti.

```
    //
    // Method to wait until the instances are running (or at least not pending)
    private static async Task CheckState(IAmazonEC2 ec2Client, List<string> instanceIds)
    {
      Console.WriteLine(
        "\nWaiting for the instances to start." +
        "\nPress any key to stop waiting. (Response might be slightly delayed.)");

      int numberRunning;
      DescribeInstancesResponse responseDescribe;
      var requestDescribe = new DescribeInstancesRequest{
        InstanceIds = instanceIds};

      // Check every couple of seconds
      int wait = 2000;
      while(true)
      {
        // Get and check the status for each of the instances to see if it's past pending.
        // Once all instances are past pending, break out.
        // (For this example, we are assuming that there is only one reservation.)
        Console.Write(".");
        numberRunning = 0;
        responseDescribe = await ec2Client.DescribeInstancesAsync(requestDescribe);
        foreach(Instance i in responseDescribe.Reservations[0].Instances)
        {
          // Check the lower byte of State.Code property
          // Code == 0 is the pending state
          if((i.State.Code & 255) > 0) numberRunning++;
        }
        if(numberRunning == responseDescribe.Reservations[0].Instances.Count)
          break;

        // Wait a bit and try again (unless the user wants to stop waiting)
        Thread.Sleep(wait);
        if(Console.KeyAvailable)
          break;
      }

      Console.WriteLine("\nNo more instances are pending.");
      foreach(Instance i in responseDescribe.Reservations[0].Instances)
      {
        Console.WriteLine($"For {i.InstanceId}:");
        Console.WriteLine($"  VPC ID: {i.VpcId}");
        Console.WriteLine($"  Instance state: {i.State.Name}");
        Console.WriteLine($"  Public IP address: {i.PublicIpAddress}");
        Console.WriteLine($"  Public DNS name: {i.PublicDnsName}");
        Console.WriteLine($"  Key pair name: {i.KeyName}");
      }
    }
```

## Kode lengkap
<a name="run-instance-complete-code"></a>

Bagian ini menunjukkan referensi yang relevan dan kode lengkap untuk contoh ini.

### Referensi SDK
<a name="w2aac19c15c17c19b9c27b5b1"></a>

NuGet paket:
+ [AWSSDK.EC2](https://www.nuget.org/packages/AWSSDK.EC2)

Elemen pemrograman:
+ [Namespace Amazon.EC2](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/EC2/NEC2.html)

  [EC2Klien Kelas Amazon](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/EC2/TEC2Client.html)

  Kelas [InstanceType](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/EC2/TInstanceType.html)
+ [Namespace Amazon.EC2.Model](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/EC2/NEC2Model.html)

  Kelas [DescribeInstancesRequest](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/EC2/TDescribeInstancesRequest.html)

  Kelas [DescribeInstancesResponse](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/EC2/TDescribeInstancesResponse.html)

  [Instance](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/EC2/TInstance.html) Kelas

  Kelas [InstanceNetworkInterfaceSpecification](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/EC2/TInstanceNetworkInterfaceSpecification.html)

  Kelas [RunInstancesRequest](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/EC2/TRunInstancesRequest.html)

  Kelas [RunInstancesResponse](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/EC2/TRunInstancesResponse.html)

### Kodenya
<a name="w2aac19c15c17c19b9c27b7b1"></a>

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

namespace EC2LaunchInstance
{
  // = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =
  // Class to launch an EC2 instance
  class Program
  {
    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;
      }

      // Get the application arguments from the parsed list
      string groupID =
        CommandLine.GetArgument(parsedArgs, null, "-g", "--group-id");
      string ami =
        CommandLine.GetArgument(parsedArgs, null, "-a", "--ami-id");
      string keyPairName =
        CommandLine.GetArgument(parsedArgs, null, "-k", "--keypair-name");
      string subnetID =
        CommandLine.GetArgument(parsedArgs, null, "-s", "--subnet-id");
      if(   (string.IsNullOrEmpty(groupID) || !groupID.StartsWith("sg-"))
         || (string.IsNullOrEmpty(ami) || !ami.StartsWith("ami-"))
         || (string.IsNullOrEmpty(keyPairName))
         || (!string.IsNullOrEmpty(subnetID) && !subnetID.StartsWith("subnet-")))
        CommandLine.ErrorExit(
          "\nOne or more of the required arguments is missing or incorrect." +
          "\nRun the command with no arguments to see help.");

      // Create an EC2 client
      var ec2Client = new AmazonEC2Client();

      // Create an object with the necessary properties
      RunInstancesRequest request = GetRequestData(groupID, ami, keyPairName, subnetID);

      // Launch the instances and wait for them to start running
      var instanceIds = await LaunchInstances(ec2Client, request);
      await CheckState(ec2Client, instanceIds);
    }


    //
    // Method to put together the properties needed to launch the instance.
    private static RunInstancesRequest GetRequestData(
      string groupID, string ami, string keyPairName, string subnetID)
    {
      // Common properties
      var groupIDs = new List<string>() { groupID };
      var request = new RunInstancesRequest()
      {
        // The first three of these would be additional command-line arguments or similar.
        InstanceType = InstanceType.T1Micro,
        MinCount = 1,
        MaxCount = 1,
        ImageId = ami,
        KeyName = keyPairName
      };

      // Properties specifically for EC2 in a VPC.
      if(!string.IsNullOrEmpty(subnetID))
      {
        request.NetworkInterfaces =
          new List<InstanceNetworkInterfaceSpecification>() {
            new InstanceNetworkInterfaceSpecification() {
              DeviceIndex = 0,
              SubnetId = subnetID,
              Groups = groupIDs,
              AssociatePublicIpAddress = true
            }
          };
      }

      // Properties specifically for EC2-Classic
      else
      {
        request.SecurityGroupIds = groupIDs;
      }
      return request;
    }


    //
    // Method to launch the instances
    // Returns a list with the launched instance IDs
    private static async Task<List<string>> LaunchInstances(
      IAmazonEC2 ec2Client, RunInstancesRequest requestLaunch)
    {
      var instanceIds = new List<string>();
      RunInstancesResponse responseLaunch =
        await ec2Client.RunInstancesAsync(requestLaunch);

      Console.WriteLine("\nNew instances have been created.");
      foreach (Instance item in responseLaunch.Reservation.Instances)
      {
        instanceIds.Add(item.InstanceId);
        Console.WriteLine($"  New instance: {item.InstanceId}");
      }

      return instanceIds;
    }


    //
    // Method to wait until the instances are running (or at least not pending)
    private static async Task CheckState(IAmazonEC2 ec2Client, List<string> instanceIds)
    {
      Console.WriteLine(
        "\nWaiting for the instances to start." +
        "\nPress any key to stop waiting. (Response might be slightly delayed.)");

      int numberRunning;
      DescribeInstancesResponse responseDescribe;
      var requestDescribe = new DescribeInstancesRequest{
        InstanceIds = instanceIds};

      // Check every couple of seconds
      int wait = 2000;
      while(true)
      {
        // Get and check the status for each of the instances to see if it's past pending.
        // Once all instances are past pending, break out.
        // (For this example, we are assuming that there is only one reservation.)
        Console.Write(".");
        numberRunning = 0;
        responseDescribe = await ec2Client.DescribeInstancesAsync(requestDescribe);
        foreach(Instance i in responseDescribe.Reservations[0].Instances)
        {
          // Check the lower byte of State.Code property
          // Code == 0 is the pending state
          if((i.State.Code & 255) > 0) numberRunning++;
        }
        if(numberRunning == responseDescribe.Reservations[0].Instances.Count)
          break;

        // Wait a bit and try again (unless the user wants to stop waiting)
        Thread.Sleep(wait);
        if(Console.KeyAvailable)
          break;
      }

      Console.WriteLine("\nNo more instances are pending.");
      foreach(Instance i in responseDescribe.Reservations[0].Instances)
      {
        Console.WriteLine($"For {i.InstanceId}:");
        Console.WriteLine($"  VPC ID: {i.VpcId}");
        Console.WriteLine($"  Instance state: {i.State.Name}");
        Console.WriteLine($"  Public IP address: {i.PublicIpAddress}");
        Console.WriteLine($"  Public DNS name: {i.PublicDnsName}");
        Console.WriteLine($"  Key pair name: {i.KeyName}");
      }
    }


    //
    // Command-line help
    private static void PrintHelp()
    {
      Console.WriteLine(
        "\nUsage: EC2LaunchInstance -g <group-id> -a <ami-id> -k <keypair-name> [-s <subnet-id>]" +
        "\n  -g, --group-id: The ID of the security group." +
        "\n  -a, --ami-id: The ID of an Amazon Machine Image." +
        "\n  -k, --keypair-name - The name of a key pair." +
        "\n  -s, --subnet-id: The ID of a subnet. Required only for EC2 in a VPC.");
    }
  }


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

}
```

## Pertimbangan tambahan
<a name="run-instance-additional"></a>
+ Saat memeriksa status instans EC2, Anda dapat menambahkan filter ke `Filter` properti [DescribeInstancesRequest](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/EC2/TDescribeInstancesRequest.html)objek. Dengan menggunakan teknik ini, Anda dapat membatasi permintaan ke instance tertentu; misalnya, instance dengan tag tertentu yang ditentukan pengguna.
+ Untuk singkatnya, beberapa properti diberi nilai tipikal. Salah satu atau semua properti ini dapat ditentukan secara terprogram atau dengan masukan pengguna.
+ Nilai yang dapat Anda gunakan untuk `MaxCount` properti `MinCount` dan [RunInstancesRequest](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/EC2/TRunInstancesRequest.html)objek ditentukan oleh Zona Ketersediaan target dan jumlah maksimum instance yang diizinkan untuk jenis instans. Untuk informasi selengkapnya, lihat [Berapa banyak instans yang dapat saya jalankan di Amazon](https://aws.amazon.com/ec2/faqs/#How_many_instances_can_I_run_in_Amazon_EC2) EC2 di FAQ Umum Amazon EC2.
+ Jika Anda ingin menggunakan jenis instance yang berbeda dari contoh ini, ada beberapa jenis instance untuk dipilih. Untuk informasi selengkapnya, lihat [jenis instans Amazon EC2](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instance-types.html) di Panduan Pengguna [Amazon EC2](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/). Lihat juga [Detail Jenis Instance](https://aws.amazon.com/ec2/instance-types/) [dan Penjelajah Jenis Instance](https://aws.amazon.com/ec2/instance-explorer/).
+ Anda juga dapat melampirkan [peran IAM](net-dg-hosm.md) ke instance saat meluncurkannya. Untuk melakukannya, buat [IamInstanceProfileSpecification](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/EC2/TIamInstanceProfileSpecification.html)objek yang `Name` propertinya disetel ke nama peran IAM. Kemudian tambahkan objek itu ke `IamInstanceProfile` properti [RunInstancesRequest](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/EC2/TRunInstancesRequest.html)objek.
**catatan**  
Untuk meluncurkan instans EC2 yang memiliki peran IAM terpasang, konfigurasi pengguna IAM harus menyertakan izin tertentu. Untuk informasi selengkapnya tentang izin yang diperlukan, lihat [Memberi izin pengguna untuk meneruskan peran IAM ke instans](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/iam-roles-for-amazon-ec2.html#permission-to-pass-iam-roles) di Panduan Pengguna [Amazon EC2](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/).

## (opsional) Connect ke instance
<a name="connect-to-instance"></a>

Setelah sebuah instance berjalan, Anda dapat menghubungkannya dari jarak jauh dengan menggunakan klien jarak jauh yang sesuai. Untuk instance Linux dan Windows, Anda memerlukan alamat IP publik instans atau nama DNS publik. Anda juga membutuhkan yang berikut ini.

**Untuk instance Linux**

Anda dapat menggunakan klien SSH untuk terhubung ke instance Linux Anda. Pastikan bahwa grup keamanan yang Anda gunakan saat meluncurkan instans memungkinkan lalu lintas SSH pada port 22, seperti yang dijelaskan dalam[Memperbarui grup keamanan](authorize-ingress.md).

Anda juga memerlukan bagian pribadi dari key pair yang Anda gunakan untuk meluncurkan instance; yaitu, file PEM.

Untuk informasi selengkapnya, lihat [Connect ke instans Linux Anda](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/connect-to-linux-instance.html) di Panduan Pengguna Amazon EC2.

**Untuk contoh Windows**

Anda dapat menggunakan klien RDP untuk terhubung ke instans Anda. Pastikan bahwa grup keamanan yang Anda gunakan saat meluncurkan instans memungkinkan lalu lintas RDP pada port 3389, seperti yang dijelaskan dalam. [Memperbarui grup keamanan](authorize-ingress.md)

Anda juga memerlukan kata sandi Administrator. Anda dapat memperoleh ini dengan menggunakan kode contoh berikut, yang memerlukan ID instance dan bagian pribadi dari key pair yang digunakan untuk meluncurkan instance; yaitu, file PEM.

Untuk informasi selengkapnya, lihat [Connect ke instans Windows Anda](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/connecting_to_windows_instance.html) di Panduan Pengguna Amazon EC2.

**Awas**  
Kode contoh ini mengembalikan kata sandi Administrator plaintext untuk instance Anda.

### Referensi SDK
<a name="w2aac19c15c17c19b9c35c23b1"></a>

NuGet paket:
+ [AWSSDK.EC2](https://www.nuget.org/packages/AWSSDK.EC2)

Elemen pemrograman:
+ [Namespace Amazon.EC2](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/EC2/NEC2.html)

  [EC2Klien Kelas Amazon](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/EC2/TEC2Client.html)
+ [Namespace Amazon.EC2.Model](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/EC2/NEC2Model.html)

  Kelas [GetPasswordDataRequest](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/EC2/TGetPasswordDataRequest.html)

  Kelas [GetPasswordDataResponse](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/EC2/TGetPasswordDataResponse.html)

### Kodenya
<a name="w2aac19c15c17c19b9c35c25b1"></a>

```
using System;
using System.Collections.Generic;
using System.IO;
using System.Threading.Tasks;
using Amazon.EC2;
using Amazon.EC2.Model;

namespace EC2GetWindowsPassword
{
  // = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =
  // Class to get the Administrator password of a Windows EC2 instance
  class Program
  {
    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;
      }

      // Get the application arguments from the parsed list
      string instanceID =
        CommandLine.GetArgument(parsedArgs, null, "-i", "--instance-id");
      string pemFileName =
        CommandLine.GetArgument(parsedArgs, null, "-p", "--pem-filename");
      if(   (string.IsNullOrEmpty(instanceID) || !instanceID.StartsWith("i-"))
         || (string.IsNullOrEmpty(pemFileName) || !pemFileName.EndsWith(".pem")))
        CommandLine.ErrorExit(
          "\nOne or more of the required arguments is missing or incorrect." +
          "\nRun the command with no arguments to see help.");

      // Create the EC2 client
      var ec2Client = new AmazonEC2Client();

      // Get and display the password
      string password = await GetPassword(ec2Client, instanceID, pemFileName);
      Console.WriteLine($"\nPassword: {password}");
    }


    //
    // Method to get the administrator password of a Windows EC2 instance
    private static async Task<string> GetPassword(
      IAmazonEC2 ec2Client, string instanceID, string pemFilename)
    {
      string password = string.Empty;
      GetPasswordDataResponse response =
        await ec2Client.GetPasswordDataAsync(new GetPasswordDataRequest{
          InstanceId = instanceID});
      if(response.PasswordData != null)
      {
        password = response.GetDecryptedPassword(File.ReadAllText(pemFilename));
      }
      else
      {
        Console.WriteLine($"\nThe password is not available for instance {instanceID}.");
        Console.WriteLine($"If this is a Windows instance, the password might not be ready.");
      }
      return password;
    }


    //
    // Command-line help
    private static void PrintHelp()
    {
      Console.WriteLine(
        "\nUsage: EC2GetWindowsPassword -i <instance-id> -p pem-filename" +
        "\n  -i, --instance-id: The name of the EC2 instance." +
        "\n  -p, --pem-filename: The name of the PEM file with the private key.");
    }
  }

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

}
```

## Bersihkan
<a name="run-instance-cleanup"></a>

Ketika Anda tidak lagi membutuhkan instans EC2 Anda, pastikan untuk menghentikannya, seperti yang dijelaskan dalam. [Mengakhiri instans Amazon EC2](terminate-instance.md)

# Mengakhiri instans Amazon EC2
<a name="terminate-instance"></a>

Jika Anda tidak lagi membutuhkan satu atau lebih instans Amazon EC2, Anda dapat menghentikannya.

Contoh ini menunjukkan cara menggunakan instans AWS SDK untuk .NET untuk mengakhiri EC2. Dibutuhkan contoh ID sebagai input.

## Referensi SDK
<a name="w2aac19c15c17c19c11b7b1"></a>

NuGet paket:
+ [AWSSDK.EC2](https://www.nuget.org/packages/AWSSDK.EC2)

Elemen pemrograman:
+ [Namespace Amazon.EC2](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/EC2/NEC2.html)

  [EC2Klien Kelas Amazon](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/EC2/TEC2Client.html)
+ [Namespace Amazon.EC2.Model](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/EC2/NEC2Model.html)

  Kelas [TerminateInstancesRequest](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/EC2/TTerminateInstancesRequest.html)

  Kelas [TerminateInstancesResponse](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/EC2/TTerminateInstancesResponse.html)

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

namespace EC2TerminateInstance
{
  class Program
  {
    static async Task Main(string[] args)
    {
      if((args.Length == 1) && (args[0].StartsWith("i-")))
      {
        // Terminate the instance
        var ec2Client = new AmazonEC2Client();
        await TerminateInstance(ec2Client, args[0]);
      }
      else
      {
        Console.WriteLine("\nCommand-line argument missing or incorrect.");
        Console.WriteLine("\nUsage: EC2TerminateInstance instance-ID");
        Console.WriteLine("  instance-ID - The EC2 instance you want to terminate.");
        return;
      }
    }

    //
    // Method to terminate an EC2 instance
    private static async Task TerminateInstance(IAmazonEC2 ec2Client, string instanceID)
    {
      var request = new TerminateInstancesRequest{
        InstanceIds = new List<string>() { instanceID }};
      TerminateInstancesResponse response =
        await ec2Client.TerminateInstancesAsync(new TerminateInstancesRequest{
          InstanceIds = new List<string>() { instanceID }
        });
      foreach (InstanceStateChange item in response.TerminatingInstances)
      {
        Console.WriteLine("Terminated instance: " + item.InstanceId);
        Console.WriteLine("Instance state: " + item.CurrentState.Name);
      }
    }
  }
}
```

Setelah Anda menjalankan contoh, sebaiknya masuk ke [konsol Amazon EC2](https://console.aws.amazon.com/ec2/) untuk memverifikasi bahwa [instans EC2 telah dihentikan](https://console.aws.amazon.com/ec2/v2/home#Instances).

# Tutorial Instans Spot Amazon EC2
<a name="how-to-spot-instances"></a>

Tutorial ini menunjukkan cara menggunakan AWS SDK untuk .NET untuk mengelola Instans Spot Amazon EC2.

## Ikhtisar
<a name="tutor-spot-net-overview"></a>

Instans Spot memungkinkan Anda meminta kapasitas Amazon EC2 yang tidak digunakan dengan harga kurang dari harga Sesuai Permintaan. Ini secara signifikan dapat menurunkan biaya EC2 Anda untuk aplikasi yang dapat terganggu.

Berikut ini adalah ringkasan tingkat tinggi tentang bagaimana Instans Spot diminta dan digunakan.

1. Buat permintaan Instans Spot, tentukan harga maksimum yang bersedia Anda bayar.

1. Ketika permintaan terpenuhi, jalankan instance seperti yang Anda lakukan pada instans Amazon EC2 lainnya.

1. Jalankan instance selama yang Anda inginkan dan kemudian hentikan, kecuali jika *Harga Spot* berubah sedemikian rupa sehingga instance dihentikan untuk Anda.

1. Bersihkan permintaan Instans Spot saat Anda tidak lagi membutuhkannya sehingga Instans Spot tidak lagi dibuat.

Ini telah menjadi ikhtisar tingkat yang sangat tinggi dari Instans Spot. Untuk mendapatkan pemahaman yang lebih baik tentang Instans Spot, lihat [Instans Spot](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/using-spot-instances.html) di Panduan Pengguna [Amazon EC2](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/).

## Tentang tutorial ini
<a name="about-spot-instances-tutorial"></a>

Ketika Anda mengikuti tutorial ini, Anda menggunakan AWS SDK untuk .NET untuk melakukan hal berikut:
+ Membuat permintaan Instans Spot
+ Tentukan kapan permintaan Instans Spot telah dipenuhi
+ Batalkan permintaan Instans Spot
+ Mengakhiri instance terkait

Bagian berikut menyediakan cuplikan dan informasi lain untuk contoh ini. [Kode lengkap untuk contoh](#tutor-spot-net-main) ditampilkan setelah cuplikan, dan dapat dibangun dan dijalankan apa adanya.

**Topics**
+ [Ikhtisar](#tutor-spot-net-overview)
+ [Tentang tutorial ini](#about-spot-instances-tutorial)
+ [Prasyarat](#tutor-spot-net-prereq)
+ [Kumpulkan apa yang Anda butuhkan](#tutor-spot-net-gather)
+ [Membuat permintaan Instans Spot](#tutor-spot-net-submit)
+ [Tentukan status permintaan Instans Spot Anda](#tutor-spot-net-request-state)
+ [Bersihkan permintaan Instans Spot Anda](#tutor-spot-net-clean-up-request)
+ [Bersihkan Instans Spot Anda](#tutor-spot-net-clean-up-instance)
+ [Kode lengkap](#tutor-spot-net-main)
+ [Pertimbangan tambahan](#tutor-spot-net-additional)

## Prasyarat
<a name="tutor-spot-net-prereq"></a>

Untuk informasi tentang APIs dan prasyarat, lihat bagian induk (). [Bekerja dengan Amazon EC2](ec2-apis-intro.md)

## Kumpulkan apa yang Anda butuhkan
<a name="tutor-spot-net-gather"></a>

Untuk membuat permintaan Instans Spot, Anda memerlukan beberapa hal. 
+ Jumlah instance dan jenis instance-nya. Ada beberapa jenis contoh untuk dipilih. Untuk informasi selengkapnya, lihat [jenis instans Amazon EC2](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instance-types.html) di Panduan Pengguna [Amazon EC2](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/). Lihat juga [Detail Jenis Instance](https://aws.amazon.com/ec2/instance-types/) [dan Penjelajah Jenis Instance](https://aws.amazon.com/ec2/instance-explorer/).

  Nomor default untuk tutorial ini adalah 1.
+ Amazon Machine Image (AMI) yang akan digunakan untuk membuat instance. Untuk selengkapnya AMIs, lihat [Gambar Mesin Amazon (AMIs)](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/AMIs.html) di [Panduan Pengguna Amazon EC2](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/). Secara khusus, lihat [Menemukan AMI](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/finding-an-ami.html) dan [Dibagikan AMIs](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/sharing-amis.html).
+ Harga maksimum yang bersedia Anda bayar per jam contoh. Anda dapat melihat harga untuk semua jenis instans (untuk Instans Sesuai Permintaan dan Instans Spot) di halaman [harga Amazon](https://aws.amazon.com/ec2/pricing/) EC2. Harga default untuk tutorial ini dijelaskan nanti.
+ Jika Anda ingin terhubung dari jarak jauh ke sebuah instans, grup keamanan dengan konfigurasi dan sumber daya yang sesuai. Ini dijelaskan dalam [Bekerja dengan grup keamanan di Amazon EC2](security-groups.md) dan informasi tentang [mengumpulkan apa yang Anda butuhkan](run-instance.md#run-instance-gather) dan [menghubungkan ke instance](run-instance.md#connect-to-instance) di[Meluncurkan instans Amazon EC2](run-instance.md). Untuk mempermudah, tutorial ini menggunakan grup keamanan bernama **default** yang dimiliki semua AWS akun yang lebih baru.

Ada banyak cara untuk mendekati permintaan Instans Spot. Berikut ini adalah strategi umum:
+ Buat permintaan yang pasti biayanya kurang dari harga sesuai permintaan.
+ Buat permintaan berdasarkan nilai perhitungan yang dihasilkan.
+ Buat permintaan untuk memperoleh kapasitas komputasi secepat mungkin.

Penjelasan berikut mengacu pada [riwayat harga Instans Spot](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/using-spot-instances-history.html) di Panduan Pengguna [Amazon EC2](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/).

### Mengurangi biaya di bawah On-Demand
<a name="reduce-cost"></a>

Anda memiliki pekerjaan pemrosesan batch yang akan memakan waktu beberapa jam atau hari untuk dijalankan. Namun, Anda fleksibel sehubungan dengan kapan dimulai dan berakhir. Anda ingin melihat apakah Anda dapat menyelesaikannya dengan harga kurang dari biaya Instans Sesuai Permintaan.

Anda memeriksa riwayat Harga Spot untuk jenis instans dengan menggunakan konsol Amazon EC2 atau Amazon EC2 API. Setelah menganalisis riwayat harga untuk jenis instans yang diinginkan di Availability Zone tertentu, Anda memiliki dua pendekatan alternatif untuk permintaan Anda:
+ Tentukan permintaan di ujung atas kisaran Harga Spot, yang masih di bawah harga Sesuai Permintaan, mengantisipasi bahwa permintaan Instans Spot satu kali Anda kemungkinan besar akan terpenuhi dan berjalan untuk waktu komputasi yang cukup berturut-turut untuk menyelesaikan pekerjaan.
+ Tentukan permintaan di ujung bawah kisaran harga, dan rencanakan untuk menggabungkan banyak instance yang diluncurkan dari waktu ke waktu melalui permintaan persisten. Contoh akan berjalan cukup lama, secara agregat, untuk menyelesaikan pekerjaan dengan biaya total yang lebih rendah.

### Bayar tidak lebih dari nilai hasilnya
<a name="value-of-result"></a>

Anda memiliki pekerjaan pemrosesan data untuk dijalankan. Anda memahami nilai hasil pekerjaan dengan cukup baik untuk mengetahui berapa nilainya dalam hal biaya komputasi.

Setelah menganalisis riwayat Harga Spot untuk jenis instans Anda, Anda memilih harga di mana biaya waktu komputasi tidak lebih dari nilai hasil pekerjaan. Anda membuat permintaan persisten dan mengizinkannya berjalan sebentar-sebentar karena Harga Spot berfluktuasi pada atau di bawah permintaan Anda.

### Memperoleh kapasitas komputasi dengan cepat
<a name="acquire-quickly"></a>

Anda memiliki kebutuhan jangka pendek yang tidak terduga untuk kapasitas tambahan yang tidak tersedia melalui Instans Sesuai Permintaan. Setelah menganalisis riwayat Harga Spot untuk jenis instans Anda, Anda memilih harga di atas harga historis tertinggi untuk meningkatkan kemungkinan permintaan Anda akan terpenuhi dengan cepat dan terus menghitung hingga selesai.

Setelah Anda mengumpulkan apa yang Anda butuhkan dan memilih strategi, Anda siap untuk meminta Instans Spot. Untuk tutorial ini, harga spot-instance maksimum default ditetapkan sama dengan harga On-Demand (yaitu \$10,003 untuk tutorial ini). Menetapkan harga dengan cara ini memaksimalkan kemungkinan permintaan akan dipenuhi.

## Membuat permintaan Instans Spot
<a name="tutor-spot-net-submit"></a>

Cuplikan berikut menunjukkan cara membuat permintaan Instance Spot dengan elemen yang Anda kumpulkan sebelumnya.

Contoh [di akhir topik ini](#tutor-spot-net-main) menunjukkan cuplikan ini digunakan.

```
    //
    // Method to create a Spot Instance request
    private static async Task<SpotInstanceRequest> CreateSpotInstanceRequest(
      IAmazonEC2 ec2Client, string amiId, string securityGroupName,
      InstanceType instanceType, string spotPrice, int instanceCount)
    {
      var launchSpecification = new LaunchSpecification{
        ImageId = amiId,
        InstanceType = instanceType
      };
      launchSpecification.SecurityGroups.Add(securityGroupName);
      var request = new RequestSpotInstancesRequest{
        SpotPrice = spotPrice,
        InstanceCount = instanceCount,
        LaunchSpecification = launchSpecification
      };

      RequestSpotInstancesResponse result =
        await ec2Client.RequestSpotInstancesAsync(request);
      return result.SpotInstanceRequests[0];
    }
```

Nilai penting yang dikembalikan dari metode ini adalah ID permintaan Instance Spot, yang terkandung dalam `SpotInstanceRequestId` anggota [SpotInstanceRequest](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/EC2/TSpotInstanceRequest.html)objek yang dikembalikan.

**catatan**  
Anda akan dikenakan biaya untuk Instans Spot apa pun yang diluncurkan. Untuk menghindari biaya yang tidak perlu, pastikan untuk [membatalkan permintaan apa pun](#tutor-spot-net-clean-up-request) dan [menghentikan instance apa pun](#tutor-spot-net-clean-up-instance).

## Tentukan status permintaan Instans Spot Anda
<a name="tutor-spot-net-request-state"></a>

Cuplikan berikut menunjukkan cara mendapatkan informasi tentang permintaan Instans Spot Anda. Anda dapat menggunakan informasi tersebut untuk membuat keputusan tertentu dalam kode Anda, seperti apakah akan terus menunggu permintaan Instans Spot dipenuhi.

Contoh [di akhir topik ini](#tutor-spot-net-main) menunjukkan cuplikan ini digunakan.

```
    //
    // Method to get information about a Spot Instance request, including the status,
    // instance ID, etc.
    // It gets the information for a specific request (as opposed to all requests).
    private static async Task<SpotInstanceRequest> GetSpotInstanceRequestInfo(
      IAmazonEC2 ec2Client, string requestId)
    {
      var describeRequest = new DescribeSpotInstanceRequestsRequest();
      describeRequest.SpotInstanceRequestIds.Add(requestId);

      DescribeSpotInstanceRequestsResponse describeResponse =
        await ec2Client.DescribeSpotInstanceRequestsAsync(describeRequest);
      return describeResponse.SpotInstanceRequests[0];
    }
```

Metode ini mengembalikan informasi tentang permintaan Instans Spot seperti ID instance, statusnya, dan kode status. Untuk informasi selengkapnya tentang kode status permintaan Instans Spot, lihat [Status permintaan Spot](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/spot-bid-status.html#spot-instance-bid-status-understand) di [Panduan Pengguna Amazon EC2](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/).

## Bersihkan permintaan Instans Spot Anda
<a name="tutor-spot-net-clean-up-request"></a>

Bila Anda tidak perlu lagi meminta Instans Spot, penting untuk membatalkan permintaan yang belum selesai untuk mencegah permintaan tersebut terpenuhi kembali. Cuplikan berikut menunjukkan cara membatalkan permintaan Instans Spot.

Contoh [di akhir topik ini](#tutor-spot-net-main) menunjukkan cuplikan ini digunakan.

```
    //
    // Method to cancel a Spot Instance request
    private static async Task CancelSpotInstanceRequest(
      IAmazonEC2 ec2Client, string requestId)
    {
      var cancelRequest = new CancelSpotInstanceRequestsRequest();
      cancelRequest.SpotInstanceRequestIds.Add(requestId);

      await ec2Client.CancelSpotInstanceRequestsAsync(cancelRequest);
    }
```

## Bersihkan Instans Spot Anda
<a name="tutor-spot-net-clean-up-instance"></a>

Untuk menghindari biaya yang tidak perlu, penting bagi Anda untuk menghentikan instans apa pun yang dimulai dari permintaan Instans Spot; hanya membatalkan permintaan Instans Spot tidak akan menghentikan instans Anda, yang berarti Anda akan terus dikenakan biaya untuk itu. Cuplikan berikut menunjukkan cara menghentikan instance setelah mendapatkan pengenal instans untuk Instance Spot yang aktif.

Contoh [di akhir topik ini](#tutor-spot-net-main) menunjukkan cuplikan ini digunakan.

```
    //
    // Method to terminate a Spot Instance
    private static async Task TerminateSpotInstance(
      IAmazonEC2 ec2Client, string requestId)
    {
      var describeRequest = new DescribeSpotInstanceRequestsRequest();
      describeRequest.SpotInstanceRequestIds.Add(requestId);

      // Retrieve the Spot Instance request to check for running instances.
      DescribeSpotInstanceRequestsResponse describeResponse =
        await ec2Client.DescribeSpotInstanceRequestsAsync(describeRequest);

      // If there are any running instances, terminate them
      if(   (describeResponse.SpotInstanceRequests[0].Status.Code
              == "request-canceled-and-instance-running")
         || (describeResponse.SpotInstanceRequests[0].State == SpotInstanceState.Active))
      {
        TerminateInstancesResponse response =
          await ec2Client.TerminateInstancesAsync(new TerminateInstancesRequest{
            InstanceIds = new List<string>(){
              describeResponse.SpotInstanceRequests[0].InstanceId } });
        foreach (InstanceStateChange item in response.TerminatingInstances)
        {
          Console.WriteLine($"\n  Terminated instance: {item.InstanceId}");
          Console.WriteLine($"  Instance state: {item.CurrentState.Name}\n");
        }
      }
    }
```

## Kode lengkap
<a name="tutor-spot-net-main"></a>

Contoh kode berikut memanggil metode yang dijelaskan sebelumnya untuk membuat dan membatalkan permintaan Instans Spot dan mengakhiri Instance Spot.

### Referensi SDK
<a name="w2aac19c15c17c21c43b5b1"></a>

NuGet paket:
+ [AWSSDK.EC2](https://www.nuget.org/packages/AWSSDK.EC2)

Elemen pemrograman:
+ [Namespace Amazon.EC2](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/EC2/NEC2.html)

  [EC2Klien Kelas Amazon](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/EC2/TEC2Client.html)

  Kelas [InstanceType](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/EC2/TInstanceType.html)
+ [Namespace Amazon.EC2.Model](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/EC2/NEC2Model.html)

  Kelas [CancelSpotInstanceRequestsRequest](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/EC2/TCancelSpotInstanceRequestsRequest.html)

  Kelas [DescribeSpotInstanceRequestsRequest](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/EC2/TDescribeSpotInstanceRequestsRequest.html)

  Kelas [DescribeSpotInstanceRequestsResponse](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/EC2/TDescribeSpotInstanceRequestsResponse.html)

  Kelas [InstanceStateChange](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/EC2/TInstanceStateChange.html)

  Kelas [LaunchSpecification](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/EC2/TLaunchSpecification.html)

  Kelas [RequestSpotInstancesRequest](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/EC2/TRequestSpotInstancesRequest.html)

  Kelas [RequestSpotInstancesResponse](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/EC2/TRequestSpotInstancesResponse.html)

  Kelas [SpotInstanceRequest](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/EC2/TSpotInstanceRequest.html)

  Kelas [TerminateInstancesRequest](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/EC2/TTerminateInstancesRequest.html)

  Kelas [TerminateInstancesResponse](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/EC2/TTerminateInstancesResponse.html)

### Kodenya
<a name="w2aac19c15c17c21c43b7b1"></a>

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

namespace EC2SpotInstanceRequests
{
  class Program
  {
    static async Task Main(string[] args)
    {
      // Some default values.
      // These could be made into command-line arguments instead.
      var instanceType = InstanceType.T1Micro;
      string securityGroupName = "default";
      string spotPrice = "0.003";
      int instanceCount = 1;

      // Parse the command line arguments
      if((args.Length != 1) || (!args[0].StartsWith("ami-")))
      {
        Console.WriteLine("\nUsage: EC2SpotInstanceRequests ami");
        Console.WriteLine("  ami: the Amazon Machine Image to use for the Spot Instances.");
        return;
      }

      // Create the Amazon EC2 client.
      var ec2Client = new AmazonEC2Client();

      // Create the Spot Instance request and record its ID
      Console.WriteLine("\nCreating spot instance request...");
      var req = await CreateSpotInstanceRequest(
        ec2Client, args[0], securityGroupName, instanceType, spotPrice, instanceCount);
      string requestId = req.SpotInstanceRequestId;

      // Wait for an EC2 Spot Instance to become active
      Console.WriteLine(
        $"Waiting for Spot Instance request with ID {requestId} to become active...");
      int wait = 1;
      var start = DateTime.Now;
      while(true)
      {
        Console.Write(".");

        // Get and check the status to see if the request has been fulfilled.
        var requestInfo = await GetSpotInstanceRequestInfo(ec2Client, requestId);
        if(requestInfo.Status.Code == "fulfilled")
        {
          Console.WriteLine($"\nSpot Instance request {requestId} " +
            $"has been fulfilled by instance {requestInfo.InstanceId}.\n");
          break;
        }

        // Wait a bit and try again, longer each time (1, 2, 4, ...)
        Thread.Sleep(wait);
        wait = wait * 2;
      }

      // Show the user how long it took to fulfill the Spot Instance request.
      TimeSpan span = DateTime.Now.Subtract(start);
      Console.WriteLine($"That took {span.TotalMilliseconds} milliseconds");

      // Perform actions here as needed.
      // For this example, simply wait for the user to hit a key.
      // That gives them a chance to look at the EC2 console to see
      // the running instance if they want to.
      Console.WriteLine("Press any key to start the cleanup...");
      Console.ReadKey(true);

      // Cancel the request.
      // Do this first to make sure that the request can't be re-fulfilled
      // once the Spot Instance has been terminated.
      Console.WriteLine("Canceling Spot Instance request...");
      await CancelSpotInstanceRequest(ec2Client, requestId);

      // Terminate the Spot Instance that's running.
      Console.WriteLine("Terminating the running Spot Instance...");
      await TerminateSpotInstance(ec2Client, requestId);

      Console.WriteLine("Done. Press any key to exit...");
      Console.ReadKey(true);
    }


    //
    // Method to create a Spot Instance request
    private static async Task<SpotInstanceRequest> CreateSpotInstanceRequest(
      IAmazonEC2 ec2Client, string amiId, string securityGroupName,
      InstanceType instanceType, string spotPrice, int instanceCount)
    {
      var launchSpecification = new LaunchSpecification{
        ImageId = amiId,
        InstanceType = instanceType
      };
      launchSpecification.SecurityGroups.Add(securityGroupName);
      var request = new RequestSpotInstancesRequest{
        SpotPrice = spotPrice,
        InstanceCount = instanceCount,
        LaunchSpecification = launchSpecification
      };

      RequestSpotInstancesResponse result =
        await ec2Client.RequestSpotInstancesAsync(request);
      return result.SpotInstanceRequests[0];
    }


    //
    // Method to get information about a Spot Instance request, including the status,
    // instance ID, etc.
    // It gets the information for a specific request (as opposed to all requests).
    private static async Task<SpotInstanceRequest> GetSpotInstanceRequestInfo(
      IAmazonEC2 ec2Client, string requestId)
    {
      var describeRequest = new DescribeSpotInstanceRequestsRequest();
      describeRequest.SpotInstanceRequestIds.Add(requestId);

      DescribeSpotInstanceRequestsResponse describeResponse =
        await ec2Client.DescribeSpotInstanceRequestsAsync(describeRequest);
      return describeResponse.SpotInstanceRequests[0];
    }


    //
    // Method to cancel a Spot Instance request
    private static async Task CancelSpotInstanceRequest(
      IAmazonEC2 ec2Client, string requestId)
    {
      var cancelRequest = new CancelSpotInstanceRequestsRequest();
      cancelRequest.SpotInstanceRequestIds.Add(requestId);

      await ec2Client.CancelSpotInstanceRequestsAsync(cancelRequest);
    }


    //
    // Method to terminate a Spot Instance
    private static async Task TerminateSpotInstance(
      IAmazonEC2 ec2Client, string requestId)
    {
      var describeRequest = new DescribeSpotInstanceRequestsRequest();
      describeRequest.SpotInstanceRequestIds.Add(requestId);

      // Retrieve the Spot Instance request to check for running instances.
      DescribeSpotInstanceRequestsResponse describeResponse =
        await ec2Client.DescribeSpotInstanceRequestsAsync(describeRequest);

      // If there are any running instances, terminate them
      if(   (describeResponse.SpotInstanceRequests[0].Status.Code
              == "request-canceled-and-instance-running")
         || (describeResponse.SpotInstanceRequests[0].State == SpotInstanceState.Active))
      {
        TerminateInstancesResponse response =
          await ec2Client.TerminateInstancesAsync(new TerminateInstancesRequest{
            InstanceIds = new List<string>(){
              describeResponse.SpotInstanceRequests[0].InstanceId } });
        foreach (InstanceStateChange item in response.TerminatingInstances)
        {
          Console.WriteLine($"\n  Terminated instance: {item.InstanceId}");
          Console.WriteLine($"  Instance state: {item.CurrentState.Name}\n");
        }
      }
    }
  }
}
```

## Pertimbangan tambahan
<a name="tutor-spot-net-additional"></a>
+ Setelah Anda menjalankan tutorial, sebaiknya masuk ke [konsol Amazon EC2](https://console.aws.amazon.com/ec2/) untuk memverifikasi bahwa [permintaan Instans Spot](https://console.aws.amazon.com/ec2/home#SpotInstances:) telah dibatalkan dan [Instans Spot telah dihentikan](https://console.aws.amazon.com/ec2/v2/home#Instances).

# Mengakses AWS Identity and Access Management (IAM) dengan AWS SDK untuk .NET
<a name="iam-apis-intro"></a>

 AWS SDK untuk .NET Dukungan [AWS Identity and Access Management](https://docs.aws.amazon.com/IAM/latest/UserGuide/), yang merupakan layanan web yang memungkinkan AWS pelanggan untuk mengelola pengguna dan izin pengguna di AWS.

*Pengguna AWS Identity and Access Management * (IAM) adalah entitas yang Anda buat. AWS Entitas mewakili orang atau aplikasi yang berinteraksi dengannya AWS. Untuk informasi selengkapnya tentang pengguna IAM, lihat Pengguna [IAM dan [Batas IAM dan STS di Panduan](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_iam-limits.html) Pengguna](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_users.html) IAM.

*Anda memberikan izin kepada pengguna dengan membuat kebijakan IAM.* Kebijakan tersebut berisi *dokumen kebijakan* yang mencantumkan tindakan yang dapat dilakukan pengguna dan sumber daya yang dapat memengaruhi tindakan tersebut. Untuk informasi selengkapnya tentang kebijakan IAM, lihat [Kebijakan dan Izin](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies.html) di Panduan Pengguna *IAM*.

**Awas**  
Untuk menghindari risiko keamanan, jangan gunakan pengguna IAM untuk otentikasi saat mengembangkan perangkat lunak yang dibuat khusus atau bekerja dengan data nyata. Sebaliknya, gunakan federasi dengan penyedia identitas seperti [AWS IAM Identity Center](https://docs.aws.amazon.com/singlesignon/latest/userguide/what-is.html).

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

 AWS SDK untuk .NET Menyediakan APIs untuk klien IAM. Ini APIs memungkinkan Anda untuk bekerja dengan fitur IAM seperti pengguna, peran, dan kunci akses.

Bagian ini berisi sejumlah kecil contoh yang menunjukkan pola yang dapat Anda ikuti saat bekerja dengan ini APIs. Untuk melihat set lengkap APIs, lihat [Referensi AWS SDK untuk .NET API](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/) (dan gulir ke “Amazon. IdentityManagement“).

Bagian ini juga berisi [contoh yang](net-dg-hosm.md) menunjukkan kepada Anda cara melampirkan peran IAM ke instans Amazon EC2 untuk mempermudah pengelolaan kredensional.

[IAM APIs disediakan oleh. AWSSDK IdentityManagement](https://www.nuget.org/packages/AWSSDK.IdentityManagement) NuGetpaket.

## Prasyarat
<a name="w2aac19c15c19c15"></a>

Sebelum Anda mulai, pastikan Anda telah [mengatur lingkungan dan proyek Anda](net-dg-config.md). Juga tinjau informasi di[Fitur SDK](net-dg-sdk-features.md).

## Topik
<a name="w2aac19c15c19c17"></a>

**Topics**
+ [APIs](#w2aac19c15c19c13)
+ [Prasyarat](#w2aac19c15c19c15)
+ [Topik](#w2aac19c15c19c17)
+ [Membuat kebijakan terkelola dari JSON](iam-policies-create-json.md)
+ [Menampilkan dokumen kebijakan](iam-policies-display.md)
+ [Memberikan akses dengan peran](net-dg-hosm.md)

# Membuat kebijakan terkelola IAM dari JSON
<a name="iam-policies-create-json"></a>

Contoh ini menunjukkan cara menggunakan AWS SDK untuk .NET untuk membuat kebijakan [terkelola IAM dari dokumen kebijakan](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies_managed-vs-inline.html#aws-managed-policies) yang diberikan di JSON. Aplikasi membuat objek klien IAM, membaca dokumen kebijakan dari file, dan kemudian membuat kebijakan.

**catatan**  
Untuk contoh dokumen kebijakan di JSON, lihat [pertimbangan tambahan](#iam-policies-create-json-additional) di akhir topik ini.

Bagian berikut menyediakan cuplikan dari contoh ini. [Kode lengkap untuk contoh](#iam-policies-create-json-complete-code) ditampilkan setelah itu, dan dapat dibangun dan dijalankan apa adanya.

**Topics**
+ [Buat kebijakan](#iam-policies-create-json-create)
+ [Kode lengkap](#iam-policies-create-json-complete-code)
+ [Pertimbangan tambahan](#iam-policies-create-json-additional)

## Buat kebijakan
<a name="iam-policies-create-json-create"></a>

Cuplikan berikut membuat kebijakan terkelola IAM dengan nama dan dokumen kebijakan yang diberikan.

Contoh [di akhir topik ini](#iam-policies-create-json-complete-code) menunjukkan cuplikan ini digunakan.

```
    //
    // Method to create an IAM policy from a JSON file
    private static async Task<CreatePolicyResponse> CreateManagedPolicy(
      IAmazonIdentityManagementService iamClient, string policyName, string jsonFilename)
    {
      return await iamClient.CreatePolicyAsync(new CreatePolicyRequest{
        PolicyName = policyName,
        PolicyDocument = File.ReadAllText(jsonFilename)});
    }
```

## Kode lengkap
<a name="iam-policies-create-json-complete-code"></a>

Bagian ini menunjukkan referensi yang relevan dan kode lengkap untuk contoh ini.

### Referensi SDK
<a name="w2aac19c15c19c21c17b5b1"></a>

NuGet paket:
+ [AWSSDK.IdentityManagement](https://www.nuget.org/packages/AWSSDK.IdentityManagement)

Elemen pemrograman:
+ [Namespace Amazon. IdentityManagement](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/IAM/NIAM.html)

  Kelas [AmazonIdentityManagementServiceClient](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/IAM/TIAMServiceClient.html)
+ [Namespace Amazon. IdentityManagement.Model](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/IAM/NIAMModel.html)

  Kelas [CreatePolicyRequest](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/IAM/TCreatePolicyRequest.html)

  Kelas [CreatePolicyResponse](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/IAM/TCreatePolicyResponse.html)

### Kodenya
<a name="w2aac19c15c19c21c17b7b1"></a>

```
using System;
using System.Collections.Generic;
using System.IO;
using System.Threading.Tasks;
using Amazon.IdentityManagement;
using Amazon.IdentityManagement.Model;

namespace IamCreatePolicyFromJson
{
  // = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =
  // Class to create an IAM policy with a given policy document
  class Program
  {
    private const int MaxArgs = 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) || (parsedArgs.Count > MaxArgs))
      {
        PrintHelp();
        return;
      }

      // Get the application arguments from the parsed list
      string policyName =
        CommandLine.GetArgument(parsedArgs, null, "-p", "--policy-name");
      string policyFilename =
        CommandLine.GetArgument(parsedArgs, null, "-j", "--json-filename");
      if(   string.IsNullOrEmpty(policyName)
         || (string.IsNullOrEmpty(policyFilename) || !policyFilename.EndsWith(".json")))
        CommandLine.ErrorExit(
          "\nOne or more of the required arguments is missing or incorrect." +
          "\nRun the command with no arguments to see help.");

      // Create an IAM service client
      var iamClient = new AmazonIdentityManagementServiceClient();

      // Create the new policy
      var response = await CreateManagedPolicy(iamClient, policyName, policyFilename);
      Console.WriteLine($"\nPolicy {response.Policy.PolicyName} has been created.");
      Console.WriteLine($"  Arn: {response.Policy.Arn}");
    }


    //
    // Method to create an IAM policy from a JSON file
    private static async Task<CreatePolicyResponse> CreateManagedPolicy(
      IAmazonIdentityManagementService iamClient, string policyName, string jsonFilename)
    {
      return await iamClient.CreatePolicyAsync(new CreatePolicyRequest{
        PolicyName = policyName,
        PolicyDocument = File.ReadAllText(jsonFilename)});
    }


    //
    // Command-line help
    private static void PrintHelp()
    {
      Console.WriteLine(
        "\nUsage: IamCreatePolicyFromJson -p <policy-name> -j <json-filename>" +
        "\n  -p, --policy-name: The name you want the new policy to have." +
        "\n  -j, --json-filename: The name of the JSON file with the policy document.");
    }
  }


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

}
```

## Pertimbangan tambahan
<a name="iam-policies-create-json-additional"></a>
+ Berikut ini adalah contoh dokumen kebijakan yang dapat Anda salin ke dalam file JSON dan gunakan sebagai masukan untuk aplikasi ini:

------
#### [ JSON ]

****  

  ```
  {
    "Version":"2012-10-17",		 	 	 
    "Id"  : "DotnetTutorialPolicy",
    "Statement" : [
      {
        "Sid" : "DotnetTutorialPolicyS3",
        "Effect" : "Allow",
        "Action" : [
          "s3:Get*",
          "s3:List*"
        ],
        "Resource" : "*"
      },
      {
        "Sid" : "DotnetTutorialPolicyPolly",
        "Effect": "Allow",
        "Action": [
          "polly:DescribeVoices",
          "polly:SynthesizeSpeech"
        ],
        "Resource": "*"
      }
    ]
  }
  ```

------
+ Anda dapat memverifikasi bahwa kebijakan telah dibuat dengan melihat di [konsol IAM](https://console.aws.amazon.com/iam/home#/policies). Dalam daftar drop-down **Filter policy**, pilih **Pelanggan dikelola**. Hapus kebijakan saat Anda tidak lagi membutuhkannya.
+  [Untuk informasi selengkapnya tentang pembuatan kebijakan, lihat [Membuat kebijakan IAM](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies_create.html) dan [referensi kebijakan IAM JSON](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies.html) di Panduan Pengguna IAM](https://docs.aws.amazon.com/IAM/latest/UserGuide/)

# Menampilkan dokumen kebijakan kebijakan yang dikelola IAM
<a name="iam-policies-display"></a>

Contoh ini menunjukkan cara menggunakan AWS SDK untuk .NET untuk menampilkan dokumen kebijakan. Aplikasi membuat objek klien IAM, menemukan versi default dari kebijakan terkelola IAM yang diberikan, dan kemudian menampilkan dokumen kebijakan di JSON.

Bagian berikut menyediakan cuplikan dari contoh ini. [Kode lengkap untuk contoh](#iam-policies-display-complete-code) ditampilkan setelah itu, dan dapat dibangun dan dijalankan apa adanya.

**Topics**
+ [Temukan versi default](#iam-policies-display-version)
+ [Menampilkan dokumen kebijakan](#iam-policies-display-doc)
+ [Kode lengkap](#iam-policies-display-complete-code)

## Temukan versi default
<a name="iam-policies-display-version"></a>

Cuplikan berikut menemukan versi default dari kebijakan IAM yang diberikan.

Contoh [di akhir topik ini](#iam-policies-display-complete-code) menunjukkan cuplikan ini digunakan.

```
    //
    // Method to determine the default version of an IAM policy
    // Returns a string with the version
    private static async Task<string> GetDefaultVersion(
      IAmazonIdentityManagementService iamClient, string policyArn)
    {
      // Retrieve all the versions of this policy
      string defaultVersion = string.Empty;
      ListPolicyVersionsResponse reponseVersions =
        await iamClient.ListPolicyVersionsAsync(new ListPolicyVersionsRequest{
          PolicyArn = policyArn});

      // Find the default version
      foreach(PolicyVersion version in reponseVersions.Versions)
      {
        if(version.IsDefaultVersion)
        {
          defaultVersion = version.VersionId;
          break;
        }
      }

      return defaultVersion;
    }
```

## Menampilkan dokumen kebijakan
<a name="iam-policies-display-doc"></a>

Cuplikan berikut menampilkan dokumen kebijakan di JSON dari kebijakan IAM yang diberikan.

Contoh [di akhir topik ini](#iam-policies-display-complete-code) menunjukkan cuplikan ini digunakan.

```
    //
    // Method to retrieve and display the policy document of an IAM policy
    private static async Task ShowPolicyDocument(
      IAmazonIdentityManagementService iamClient, string policyArn, string defaultVersion)
    {
      // Retrieve the policy document of the default version
      GetPolicyVersionResponse responsePolicy =
        await iamClient.GetPolicyVersionAsync(new GetPolicyVersionRequest{
          PolicyArn = policyArn,
          VersionId = defaultVersion});

      // Display the policy document (in JSON)
      Console.WriteLine($"Version {defaultVersion} of the policy (in JSON format):");
      Console.WriteLine(
        $"{HttpUtility.UrlDecode(responsePolicy.PolicyVersion.Document)}");
    }
```

## Kode lengkap
<a name="iam-policies-display-complete-code"></a>

Bagian ini menunjukkan referensi yang relevan dan kode lengkap untuk contoh ini.

### Referensi SDK
<a name="w2aac19c15c19c23c19b5b1"></a>

NuGet paket:
+ [AWSSDK.IdentityManagement](https://www.nuget.org/packages/AWSSDK.IdentityManagement)

Elemen pemrograman:
+ [Namespace Amazon. IdentityManagement](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/IAM/NIAM.html)

  Kelas [AmazonIdentityManagementServiceClient](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/IAM/TIAMServiceClient.html)
+ [Namespace Amazon. IdentityManagement.Model](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/IAM/NIAMModel.html)

  Kelas [GetPolicyVersionRequest](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/IAM/TGetPolicyVersionRequest.html)

  Kelas [GetPolicyVersionResponse](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/IAM/TGetPolicyVersionResponse.html)

  Kelas [ListPolicyVersionsRequest](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/IAM/TListPolicyVersionsRequest.html)

  Kelas [ListPolicyVersionsResponse](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/IAM/TListPolicyVersionsResponse.html)

  Kelas [PolicyVersion](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/IAM/TPolicyVersion.html)

### Kodenya
<a name="w2aac19c15c19c23c19b7b1"></a>

```
using System;
using System.Web;
using System.Threading.Tasks;
using Amazon.IdentityManagement;
using Amazon.IdentityManagement.Model;

namespace IamDisplayPolicyJson
{
  class Program
  {
    static async Task Main(string[] args)
    {
      // Parse the command line and show help if necessary
      if(args.Length != 1)
      {
        Console.WriteLine("\nUsage: IamDisplayPolicyJson policy-arn");
        Console.WriteLine("   policy-arn: The ARN of the policy to retrieve.");
        return;
      }
      if(!args[0].StartsWith("arn:"))
      {
        Console.WriteLine("\nCould not find policy ARN in the command-line arguments:");
        Console.WriteLine($"{args[0]}");
        return;
      }

      // Create an IAM service client
      var iamClient = new AmazonIdentityManagementServiceClient();

      // Retrieve and display the policy document of the given policy
      string defaultVersion = await GetDefaultVersion(iamClient, args[0]);
      if(string.IsNullOrEmpty(defaultVersion))
        Console.WriteLine($"Could not find the default version for policy {args[0]}.");
      else
        await ShowPolicyDocument(iamClient, args[0], defaultVersion);
    }


    //
    // Method to determine the default version of an IAM policy
    // Returns a string with the version
    private static async Task<string> GetDefaultVersion(
      IAmazonIdentityManagementService iamClient, string policyArn)
    {
      // Retrieve all the versions of this policy
      string defaultVersion = string.Empty;
      ListPolicyVersionsResponse reponseVersions =
        await iamClient.ListPolicyVersionsAsync(new ListPolicyVersionsRequest{
          PolicyArn = policyArn});

      // Find the default version
      foreach(PolicyVersion version in reponseVersions.Versions)
      {
        if(version.IsDefaultVersion)
        {
          defaultVersion = version.VersionId;
          break;
        }
      }

      return defaultVersion;
    }


    //
    // Method to retrieve and display the policy document of an IAM policy
    private static async Task ShowPolicyDocument(
      IAmazonIdentityManagementService iamClient, string policyArn, string defaultVersion)
    {
      // Retrieve the policy document of the default version
      GetPolicyVersionResponse responsePolicy =
        await iamClient.GetPolicyVersionAsync(new GetPolicyVersionRequest{
          PolicyArn = policyArn,
          VersionId = defaultVersion});

      // Display the policy document (in JSON)
      Console.WriteLine($"Version {defaultVersion} of the policy (in JSON format):");
      Console.WriteLine(
        $"{HttpUtility.UrlDecode(responsePolicy.PolicyVersion.Document)}");
    }
  }
}
```

# Memberikan akses dengan menggunakan peran IAM
<a name="net-dg-hosm"></a>

Tutorial ini menunjukkan cara menggunakan AWS SDK untuk .NET untuk mengaktifkan peran IAM pada instans Amazon EC2.

## Ikhtisar
<a name="hosm-overview"></a>

Semua permintaan AWS harus ditandatangani secara kriptografi dengan menggunakan kredensil yang dikeluarkan oleh. AWS Oleh karena itu, Anda memerlukan strategi untuk mengelola kredensional untuk aplikasi yang berjalan di instans Amazon EC2. Anda harus mendistribusikan, menyimpan, dan memutar kredensi ini dengan aman, tetapi juga membuatnya dapat diakses oleh aplikasi.

Dengan peran IAM, Anda dapat mengelola kredensil ini secara efektif. Anda membuat peran IAM dan mengonfigurasinya dengan izin yang diperlukan aplikasi, lalu melampirkan peran itu ke instans EC2. Untuk membaca selengkapnya tentang manfaat menggunakan peran IAM, lihat peran [IAM untuk Amazon EC2](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/iam-roles-for-amazon-ec2.html) di Panduan Pengguna Amazon [EC2](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/). Lihat juga informasi tentang [Peran IAM](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles.html) di Panduan Pengguna IAM.

Untuk aplikasi yang dibangun menggunakan AWS SDK untuk .NET, ketika aplikasi membangun objek klien untuk AWS layanan, objek mencari kredensil dari beberapa sumber potensial. Urutan pencarian ditampilkan di[Resolusi kredensi dan profil](creds-assign.md).

Jika objek klien tidak menemukan kredensil dari sumber lain, ia mengambil kredensil sementara yang memiliki izin yang sama dengan yang telah dikonfigurasi ke dalam peran IAM dan berada dalam metadata instans EC2. Kredensial ini digunakan untuk melakukan panggilan ke AWS dari objek klien.

## Tentang tutorial ini
<a name="about-hosm-tutorial"></a>

Saat Anda mengikuti tutorial ini, Anda menggunakan AWS SDK untuk .NET (dan alat lainnya) untuk meluncurkan instans Amazon EC2 dengan peran IAM terlampir, dan kemudian melihat aplikasi pada instance menggunakan izin peran IAM.

**Topics**
+ [Ikhtisar](#hosm-overview)
+ [Tentang tutorial ini](#about-hosm-tutorial)
+ [Buat contoh aplikasi Amazon S3](#net-dg-hosm-sample-s3-app)
+ [Membuat peran IAM](#net-dg-hosm-create-the-role)
+ [Luncurkan instans EC2 dan lampirkan peran IAM](#net-dg-hosm-launch-ec2-instance)
+ [Connect ke instans EC2](#net-dg-hosm-connect)
+ [Jalankan aplikasi sampel pada instans EC2](#net-dg-hosm-run-the-app)
+ [Bersihkan](#net-dg-hosm-cleanup)

## Buat contoh aplikasi Amazon S3
<a name="net-dg-hosm-sample-s3-app"></a>

Contoh aplikasi ini mengambil objek dari Amazon S3. Untuk menjalankan aplikasi, Anda memerlukan yang berikut:
+ Bucket Amazon S3 yang berisi file teks.
+ AWS kredensi pada mesin pengembangan Anda yang memungkinkan Anda mengakses bucket.

Untuk informasi tentang membuat bucket Amazon S3 dan mengunggah objek, lihat Panduan Pengguna [Layanan Penyimpanan Sederhana Amazon](https://docs.aws.amazon.com/AmazonS3/latest/userguide/). Untuk informasi tentang AWS kredensil, lihat. [Konfigurasikan otentikasi SDK dengan AWS](creds-idc.md)

Buat proyek .NET Core dengan kode berikut. Kemudian uji aplikasi pada mesin pengembangan Anda.

**catatan**  
Pada mesin pengembangan Anda, .NET Core Runtime diinstal, yang memungkinkan Anda menjalankan aplikasi tanpa mempublikasikannya. Ketika Anda membuat instans EC2 nanti dalam tutorial ini, Anda dapat memilih untuk menginstal .NET Core Runtime pada instance. Ini memberi Anda pengalaman serupa dan transfer file yang lebih kecil.  
 Namun, Anda juga dapat memilih untuk tidak menginstal .NET Core Runtime pada instance. Jika Anda memilih tindakan ini, Anda harus mempublikasikan aplikasi sehingga semua dependensi disertakan saat Anda mentransfernya ke instance.

### Referensi SDK
<a name="w2aac19c15c19c25c17c13b1"></a>

NuGet paket:
+ [AWSSDK.S3](https://www.nuget.org/packages/AWSSDK.S3)

Elemen pemrograman:
+ [Namespace Amazon.S3](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/S3/NS3.html)

  Kelas [Amazons3Client](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/S3/TS3Client.html)
+ [Namespace Amazon.S3.Model](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/S3/NS3Model.html)

  Kelas [GetObjectResponse](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/S3/TGetObjectResponse.html)

### Kodenya
<a name="w2aac19c15c19c25c17c15b1"></a>

```
using System;
using System.Collections.Generic;
using System.IO;
using System.Threading.Tasks;
using Amazon.S3;
using Amazon.S3.Model;

namespace S3GetTextItem
{
  // = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =
  // Class to retrieve a text file from an S3 bucket and write it to a local file
  class Program
  {
    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;
      }

      // Get the application arguments from the parsed list
      string bucket =
        CommandLine.GetArgument(parsedArgs, null, "-b", "--bucket-name");
      string item =
        CommandLine.GetArgument(parsedArgs, null, "-t", "--text-object");
      string outFile =
        CommandLine.GetArgument(parsedArgs, null, "-o", "--output-filename");
      if(   string.IsNullOrEmpty(bucket)
         || string.IsNullOrEmpty(item)
         || string.IsNullOrEmpty(outFile))
        CommandLine.ErrorExit(
          "\nOne or more of the required arguments is missing or incorrect." +
          "\nRun the command with no arguments to see help.");

      // Create the S3 client object and get the file object from the bucket.
      var response = await GetObject(new AmazonS3Client(), bucket, item);

      // Write the contents of the file object to the given output file.
      var reader = new StreamReader(response.ResponseStream);
      string contents = reader.ReadToEnd();
      using (var s = new FileStream(outFile, FileMode.Create))
      using (var writer = new StreamWriter(s))
        writer.WriteLine(contents);
    }


    //
    // Method to get an object from an S3 bucket.
    private static async Task<GetObjectResponse> GetObject(
      IAmazonS3 s3Client, string bucket, string item)
    {
        Console.WriteLine($"Retrieving {item} from bucket {bucket}.");
        return await s3Client.GetObjectAsync(bucket, item);
    }


    //
    // Command-line help
    private static void PrintHelp()
    {
      Console.WriteLine(
        "\nUsage: S3GetTextItem -b <bucket-name> -t <text-object> -o <output-filename>" +
        "\n  -b, --bucket-name: The name of the S3 bucket." +
        "\n  -t, --text-object: The name of the text object in the bucket." +
        "\n  -o, --output-filename: The name of the file to write the text to.");
    }
  }


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

}
```

Jika mau, Anda dapat menghapus sementara kredensi yang Anda gunakan pada mesin pengembangan Anda untuk melihat bagaimana aplikasi merespons. (Tapi pastikan untuk mengembalikan kredensialnya saat Anda selesai.)

## Membuat peran IAM
<a name="net-dg-hosm-create-the-role"></a>

Buat peran IAM yang memiliki izin yang sesuai untuk mengakses Amazon S3.

1. Buka [konsol IAM](https://console.aws.amazon.com/iam/).

1. Di panel navigasi, pilih **Peran**, lalu pilih **Buat peran**.

1. Pilih **AWS layanan**, temukan dan pilih **EC2**, dan pilih **Berikutnya: Izin**.

1. Di bawah **Lampirkan kebijakan izin**, temukan dan pilih **ReadOnlyAccessAmazonS3**. Tinjau kebijakan jika Anda mau, lalu pilih **Berikutnya: Tag**.

1. Tambahkan tag jika Anda mau dan kemudian pilih **Berikutnya: Tinjau**.

1. Ketik nama dan deskripsi untuk peran tersebut, lalu pilih **Buat peran**. Ingat nama ini karena Anda akan membutuhkannya saat meluncurkan instans EC2 Anda.

## Luncurkan instans EC2 dan lampirkan peran IAM
<a name="net-dg-hosm-launch-ec2-instance"></a>

Luncurkan instans EC2 dengan peran IAM yang Anda buat sebelumnya. Anda dapat melakukannya dengan cara-cara berikut.
+ **Menggunakan konsol EC2**

  Untuk meluncurkan instans menggunakan konsol EC2, lihat [Meluncurkan instance menggunakan wizard instans peluncuran baru di Panduan](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-launch-instance-wizard.html) Pengguna [Amazon EC2](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/).

  Saat Anda melihat melalui halaman peluncuran, Anda setidaknya harus memperluas panel **Detail lanjutan** sehingga Anda dapat menentukan peran IAM yang Anda buat sebelumnya di profil instans **IAM**.
+ **Menggunakan AWS SDK untuk .NET**

  Untuk informasi tentang ini, lihat[Meluncurkan instans Amazon EC2](run-instance.md), termasuk di [Pertimbangan tambahan](run-instance.md#run-instance-additional) dekat akhir topik itu.

Untuk meluncurkan instans EC2 yang memiliki peran IAM terpasang, konfigurasi pengguna IAM harus menyertakan izin tertentu. Untuk informasi selengkapnya tentang izin yang diperlukan, lihat [Memberikan izin kepada pengguna untuk meneruskan peran IAM ke instans](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/iam-roles-for-amazon-ec2.html#permission-to-pass-iam-roles) di Panduan Pengguna [Amazon EC2](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/).

## Connect ke instans EC2
<a name="net-dg-hosm-connect"></a>

Connect ke instans EC2 sehingga Anda dapat mentransfer aplikasi sampel ke sana dan kemudian menjalankan aplikasi. Anda akan memerlukan file yang berisi bagian pribadi dari key pair yang Anda gunakan untuk meluncurkan instance; yaitu, file PEM.

Untuk informasi tentang menghubungkan ke instans, lihat [Connect ke instans Linux](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/connect-to-linux-instance.html) atau [Connect ke instans Windows Anda](https://docs.aws.amazon.com/AWSEC2/latest/WindowsGuide/connecting_to_windows_instance.html) di [Panduan Pengguna Amazon EC2](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/). Ketika Anda terhubung, lakukan sedemikian rupa sehingga Anda dapat mentransfer file dari mesin pengembangan Anda ke instans Anda.

Jika Anda menggunakan Visual Studio di Windows, Anda juga dapat terhubung ke instance dengan menggunakan Toolkit for Visual Studio. Untuk informasi selengkapnya, lihat [Menyambungkan ke Instans Amazon EC2](https://docs.aws.amazon.com/toolkit-for-visual-studio/latest/user-guide/tkv-ec2-ami.html#connect-ec2) di AWS Toolkit for Visual Studio Panduan Pengguna.

## Jalankan aplikasi sampel pada instans EC2
<a name="net-dg-hosm-run-the-app"></a>

1. Salin file aplikasi dari drive lokal Anda ke instans Anda.

   File mana yang Anda transfer tergantung pada bagaimana Anda membangun aplikasi dan apakah instans Anda telah menginstal .NET Core Runtime. Untuk informasi tentang cara mentransfer file ke instans Anda, lihat [Connect ke instans Linux Anda](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/connect-to-linux-instance.html) (lihat sub-bagian yang sesuai) atau [Mentransfer file ke instans Windows](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/connect-to-linux-instanceWindowsFileTransfer.html) di Panduan Pengguna [Amazon EC2](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/).

1. Mulai aplikasi dan verifikasi bahwa itu berjalan dengan hasil yang sama seperti pada mesin pengembangan Anda.

1. Verifikasi bahwa aplikasi menggunakan kredensional yang disediakan oleh peran IAM.

   1. Buka [konsol Amazon EC2](https://console.aws.amazon.com/ec2/).

   1. Pilih instance dan lepaskan peran IAM melalui **Tindakan**, **Pengaturan Instans**, **Lampirkan/Ganti** Peran IAM.

   1. Jalankan aplikasi lagi dan lihat bahwa itu mengembalikan kesalahan otorisasi.

## Bersihkan
<a name="net-dg-hosm-cleanup"></a>

Ketika Anda selesai dengan tutorial ini, dan jika Anda tidak lagi menginginkan instans EC2 yang Anda buat, pastikan untuk menghentikan instance untuk menghindari biaya yang tidak diinginkan. Anda dapat melakukannya di [konsol Amazon EC2](https://console.aws.amazon.com/ec2/) atau secara terprogram, seperti yang dijelaskan dalam. [Mengakhiri instans Amazon EC2](terminate-instance.md) Jika mau, Anda juga dapat menghapus sumber daya lain yang Anda buat untuk tutorial ini. Ini mungkin termasuk peran IAM, keypair EC2 dan file PEM, grup keamanan, dll.

# Menggunakan penyimpanan Internet Amazon Simple Storage Service
<a name="s3-apis-intro"></a>

 AWS SDK untuk .NET Mendukung [Amazon S3](https://aws.amazon.com/s3/), yang merupakan penyimpanan untuk Internet. Ini dirancang untuk membuat komputasi skala web lebih mudah bagi pengembang.

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

 AWS SDK untuk .NET Menyediakan APIs untuk klien Amazon S3. Ini APIs memungkinkan Anda untuk bekerja dengan sumber daya Amazon S3 seperti ember dan item. Untuk melihat set lengkap APIs untuk Amazon S3, lihat yang berikut ini:
+ [AWS SDK untuk .NET Referensi API](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/) (dan gulir ke “Amazon.S3").
+ [Dokumentasi Amazon.Extensions.S3.Encryption](https://aws.github.io/amazon-s3-encryption-client-dotnet/api/Amazon.Extensions.S3.Encryption.html)

Amazon S3 APIs disediakan oleh paket-paket berikut: NuGet 
+ [AWSSDK.S3](https://www.nuget.org/packages/AWSSDK.S3)
+ [Amazon.Extensions.S3.Encryption](https://www.nuget.org/packages/Amazon.Extensions.S3.Encryption)

## Prasyarat
<a name="w2aac19c15c21b7"></a>

Sebelum Anda mulai, pastikan Anda telah [mengatur lingkungan dan proyek Anda](net-dg-config.md). Juga tinjau informasi di[Fitur SDK](net-dg-sdk-features.md).

## Contoh dalam dokumen ini
<a name="s3-apis-examples"></a>

Topik berikut dalam dokumen ini menunjukkan cara menggunakan AWS SDK untuk .NET untuk bekerja dengan Amazon S3.
+ [Menggunakan kunci KMS untuk enkripsi S3](kms-keys-s3-encryption.md)

## Contoh dalam dokumen lain
<a name="s3-apis-examples-other"></a>

Tautan berikut ke [Panduan Pengembang Amazon S3](https://docs.aws.amazon.com/AmazonS3/latest/userguide/) memberikan contoh tambahan tentang cara menggunakan AWS SDK untuk .NET untuk bekerja dengan Amazon S3.

**catatan**  
Meskipun contoh-contoh ini dan pertimbangan pemrograman tambahan dibuat untuk Versi 3 dari AWS SDK untuk .NET menggunakan .NET Framework, mereka juga layak untuk versi yang lebih baru dari AWS SDK untuk .NET menggunakan .NET Core. Penyesuaian kecil dalam kode terkadang diperlukan.

**Contoh pemrograman Amazon S3**
+  [Mengelola ACLs](https://docs.aws.amazon.com/AmazonS3/latest/dev/acl-using-dot-net-sdk.html) 
+  [Membuat Bucket](https://docs.aws.amazon.com/AmazonS3/latest/dev/create-bucket-get-location-example.html#create-bucket-get-location-dotnet) 
+  [Unggah Objek](https://docs.aws.amazon.com/AmazonS3/latest/dev/UploadObjSingleOpNET.html) 
+  [https://docs.aws.amazon.com/AmazonS3/latest/dev/usingHLmpuDotNet.html](https://docs.aws.amazon.com/AmazonS3/latest/dev/usingHLmpuDotNet.html)) 
+  [Unggah Multipart dengan API Tingkat Rendah](https://docs.aws.amazon.com/AmazonS3/latest/dev/usingLLmpuDotNet.html) 
+  [Daftar Objek](https://docs.aws.amazon.com/AmazonS3/latest/dev/list-obj-version-enabled-bucket.html#list-obj-version-enabled-bucket-sdk-examples) 
+  [Listing Keys](https://docs.aws.amazon.com/AmazonS3/latest/dev/ListingObjectKeysUsingNetSDK.html) 
+  [Dapatkan Objek](https://docs.aws.amazon.com/AmazonS3/latest/dev/RetrievingObjectUsingNetSDK.html) 
+  [Salin Objek](https://docs.aws.amazon.com/AmazonS3/latest/dev/CopyingObjectUsingNetSDK.html) 
+  [Salin Objek dengan Multipart Upload API](https://docs.aws.amazon.com/AmazonS3/latest/dev/CopyingObjctsUsingLLNetMPUapi.html) 
+  [Menghapus Objek](https://docs.aws.amazon.com/AmazonS3/latest/dev/DeletingOneObjectUsingNetSDK.html) 
+  [Menghapus Beberapa Objek](https://docs.aws.amazon.com/AmazonS3/latest/dev/DeletingMultipleObjectsUsingNetSDK.html) 
+  [Mengembalikan Objek](https://docs.aws.amazon.com/AmazonS3/latest/dev/restore-object-dotnet.html) 
+  [Konfigurasikan Bucket untuk Pemberitahuan](https://docs.aws.amazon.com/AmazonS3/latest/dev/ways-to-add-notification-config-to-bucket.html) 
+  [Mengelola Siklus Hidup Objek](https://docs.aws.amazon.com/AmazonS3/latest/dev/manage-lifecycle-using-dot-net.html) 
+  [Menghasilkan URL Objek Pra-ditandatangani](https://docs.aws.amazon.com/AmazonS3/latest/dev/ShareObjectPreSignedURLDotNetSDK.html) 
+  [Mengelola Situs Web](https://docs.aws.amazon.com/AmazonS3/latest/dev/ConfigWebSiteDotNet.html) 
+  [Mengaktifkan Berbagi Sumber Daya Lintas Asal (CORS)](https://docs.aws.amazon.com/AmazonS3/latest/dev/ManageCorsUsingDotNet.html) 

**Pertimbangan pemrograman tambahan**
+  [Menggunakan AWS SDK untuk .NET untuk Pemrograman Amazon S3](https://docs.aws.amazon.com/AmazonS3/latest/dev/UsingTheMPDotNetAPI.html) 
+  [Membuat Permintaan Menggunakan Kredensil Sementara Pengguna IAM](https://docs.aws.amazon.com/AmazonS3/latest/dev/AuthUsingTempSessionTokenDotNet.html) 
+  [Membuat Permintaan Menggunakan Kredensial Sementara Pengguna Federasi](https://docs.aws.amazon.com/AmazonS3/latest/dev/AuthUsingTempFederationTokenDotNet.html) 
+  [Menentukan Enkripsi Sisi Server](https://docs.aws.amazon.com/AmazonS3/latest/dev/SSEUsingDotNetSDK.html) 
+  [Menentukan Enkripsi Sisi Server dengan Kunci Enkripsi yang Disediakan Pelanggan](https://docs.aws.amazon.com/AmazonS3/latest/dev/sse-c-using-dot-net-sdk.html) 

# Menggunakan AWS KMS kunci untuk enkripsi Amazon S3 di AWS SDK untuk .NET
<a name="kms-keys-s3-encryption"></a>

Contoh ini menunjukkan cara menggunakan AWS Key Management Service kunci untuk mengenkripsi objek Amazon S3. Aplikasi ini membuat kunci master pelanggan (CMK) dan menggunakannya untuk membuat objek [AmazonS3 EncryptionClient V2](https://aws.github.io/amazon-s3-encryption-client-dotnet/api/Amazon.Extensions.S3.Encryption.AmazonS3EncryptionClientV2.html) untuk enkripsi sisi klien. Aplikasi menggunakan klien tersebut untuk membuat objek terenkripsi dari file teks tertentu di bucket Amazon S3 yang ada. Kemudian mendekripsi objek dan menampilkan isinya.

**Awas**  
Kelas serupa yang `AmazonS3EncryptionClient` disebut tidak digunakan lagi dan kurang aman daripada kelas. `AmazonS3EncryptionClientV2` Untuk memigrasikan kode yang ada yang menggunakan`AmazonS3EncryptionClient`, lihat[Migrasi Klien Enkripsi S3 (V1 ke V2)](s3-encryption-migration-v1-v2.md).

**Topics**
+ [Buat bahan enkripsi](#kms-s3-enc-mat)
+ [Membuat dan mengenkripsi objek Amazon S3](#kms-s3-create-ojbect)
+ [Kode lengkap](#kms-s3-complete-code)
+ [Pertimbangan tambahan](#kms-s3-additional)

## Buat bahan enkripsi
<a name="kms-s3-enc-mat"></a>

Cuplikan berikut membuat `EncryptionMaterials` objek yang berisi ID kunci KMS.

Contoh [di akhir topik ini](#kms-s3-complete-code) menunjukkan cuplikan ini digunakan.

```
      // Create a customer master key (CMK) and store the result
      CreateKeyResponse createKeyResponse =
        await new AmazonKeyManagementServiceClient().CreateKeyAsync(new CreateKeyRequest());
      var kmsEncryptionContext = new Dictionary<string, string>();
      var kmsEncryptionMaterials = new EncryptionMaterialsV2(
        createKeyResponse.KeyMetadata.KeyId, KmsType.KmsContext, kmsEncryptionContext);
```

## Membuat dan mengenkripsi objek Amazon S3
<a name="kms-s3-create-ojbect"></a>

Cuplikan berikut membuat `AmazonS3EncryptionClientV2` objek yang menggunakan bahan enkripsi yang dibuat sebelumnya. Kemudian menggunakan klien untuk membuat dan mengenkripsi objek Amazon S3 baru.

Contoh [di akhir topik ini](#kms-s3-complete-code) menunjukkan cuplikan ini digunakan.

```
    //
    // Method to create and encrypt an object in an S3 bucket
    static async Task<GetObjectResponse> CreateAndRetrieveObjectAsync(
      EncryptionMaterialsV2 materials, string bucketName,
      string fileName, string itemName)
    {
      // CryptoStorageMode.ObjectMetadata is required for KMS EncryptionMaterials
      var config = new AmazonS3CryptoConfigurationV2(SecurityProfile.V2AndLegacy)
      {
        StorageMode = CryptoStorageMode.ObjectMetadata
      };
      var s3EncClient = new AmazonS3EncryptionClientV2(config, materials);

      // Create, encrypt, and put the object
      await s3EncClient.PutObjectAsync(new PutObjectRequest
      {
        BucketName = bucketName,
        Key = itemName,
        ContentBody = File.ReadAllText(fileName)
      });

      // Get, decrypt, and return the object
      return await s3EncClient.GetObjectAsync(new GetObjectRequest
      {
        BucketName = bucketName,
        Key = itemName
      });
    }
```

## Kode lengkap
<a name="kms-s3-complete-code"></a>

Bagian ini menunjukkan referensi yang relevan dan kode lengkap untuk contoh ini.

### Referensi SDK
<a name="w2aac19c15c21c13c15b5b1"></a>

NuGet paket:
+ [Amazon.Extensions.S3.Encryption](https://www.nuget.org/packages/Amazon.Extensions.S3.Encryption)

Elemen pemrograman:
+ [Namespace Amazon.Extensions.S3.Encryption](https://aws.github.io/amazon-s3-encryption-client-dotnet/api/Amazon.Extensions.S3.Encryption.html)

  Kelas [EncryptionClientAmazonS3](https://aws.github.io/amazon-s3-encryption-client-dotnet/api/Amazon.Extensions.S3.Encryption.AmazonS3EncryptionClientV2.html) V2

  Kelas [CryptoConfigurationAmazonS3](https://aws.github.io/amazon-s3-encryption-client-dotnet/api/Amazon.Extensions.S3.Encryption.AmazonS3CryptoConfigurationV2.html) V2

  Kelas [CryptoStorageMode](https://aws.github.io/amazon-s3-encryption-client-dotnet/api/Amazon.Extensions.S3.Encryption.CryptoStorageMode.html)

  Kelas [EncryptionMaterialsV2](https://aws.github.io/amazon-s3-encryption-client-dotnet/api/Amazon.Extensions.S3.Encryption.EncryptionMaterialsV2.html)
+ [Namespace Amazon.Extensions.S3.Encryption.Primitives](https://aws.github.io/amazon-s3-encryption-client-dotnet/api/Amazon.Extensions.S3.Encryption.Primitives.html)

  Kelas [KmsType](https://aws.github.io/amazon-s3-encryption-client-dotnet/api/Amazon.Extensions.S3.Encryption.Primitives.KmsType.html)
+ [Namespace Amazon.S3.Model](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/S3/NS3Model.html)

  Kelas [GetObjectRequest](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/S3/TGetObjectRequest.html)

  Kelas [GetObjectResponse](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/S3/TGetObjectResponse.html)

  Kelas [PutObjectRequest](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/S3/TPutObjectRequest.html)
+ [Namespace Amazon. KeyManagementService](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/KeyManagementService/NKeyManagementService.html)

  Kelas [AmazonKeyManagementServiceClient](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/KeyManagementService/TKeyManagementServiceClient.html)
+ [Namespace Amazon. KeyManagementService.Model](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/KeyManagementService/NKeyManagementServiceModel.html)

  Kelas [CreateKeyRequest](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/KeyManagementService/TCreateKeyRequest.html)

  Kelas [CreateKeyResponse](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/KeyManagementService/TCreateKeyResponse.html)

### Kodenya
<a name="w2aac19c15c21c13c15b7b1"></a>

```
using System;
using System.Collections.Generic;
using System.IO;
using System.Threading.Tasks;
using Amazon.Extensions.S3.Encryption;
using Amazon.Extensions.S3.Encryption.Primitives;
using Amazon.S3.Model;
using Amazon.KeyManagementService;
using Amazon.KeyManagementService.Model;

namespace KmsS3Encryption
{
  // = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =
  // Class to store text in an encrypted S3 object.
  class Program
  {
    private const int MaxArgs = 3;

    public static async Task Main(string[] args)
    {
      // Parse the command line and show help if necessary
      var parsedArgs = CommandLine.Parse(args);
      if((parsedArgs.Count == 0) || (parsedArgs.Count > MaxArgs))
      {
        PrintHelp();
        return;
      }

      // Get the application arguments from the parsed list
      string bucketName =
        CommandLine.GetArgument(parsedArgs, null, "-b", "--bucket-name");
      string fileName =
        CommandLine.GetArgument(parsedArgs, null, "-f", "--file-name");
      string itemName =
        CommandLine.GetArgument(parsedArgs, null, "-i", "--item-name");
      if(string.IsNullOrEmpty(bucketName) || (string.IsNullOrEmpty(fileName)))
        CommandLine.ErrorExit(
          "\nOne or more of the required arguments is missing or incorrect." +
          "\nRun the command with no arguments to see help.");
      if(!File.Exists(fileName))
        CommandLine.ErrorExit($"\nThe given file {fileName} doesn't exist.");
      if(string.IsNullOrEmpty(itemName))
        itemName = Path.GetFileName(fileName);

      // Create a customer master key (CMK) and store the result
      CreateKeyResponse createKeyResponse =
        await new AmazonKeyManagementServiceClient().CreateKeyAsync(new CreateKeyRequest());
      var kmsEncryptionContext = new Dictionary<string, string>();
      var kmsEncryptionMaterials = new EncryptionMaterialsV2(
        createKeyResponse.KeyMetadata.KeyId, KmsType.KmsContext, kmsEncryptionContext);

      // Create the object in the bucket, then display the content of the object
      var putObjectResponse =
        await CreateAndRetrieveObjectAsync(kmsEncryptionMaterials, bucketName, fileName, itemName);
      Stream stream = putObjectResponse.ResponseStream;
      StreamReader reader = new StreamReader(stream);
      Console.WriteLine(reader.ReadToEnd());
    }


    //
    // Method to create and encrypt an object in an S3 bucket
    static async Task<GetObjectResponse> CreateAndRetrieveObjectAsync(
      EncryptionMaterialsV2 materials, string bucketName,
      string fileName, string itemName)
    {
      // CryptoStorageMode.ObjectMetadata is required for KMS EncryptionMaterials
      var config = new AmazonS3CryptoConfigurationV2(SecurityProfile.V2AndLegacy)
      {
        StorageMode = CryptoStorageMode.ObjectMetadata
      };
      var s3EncClient = new AmazonS3EncryptionClientV2(config, materials);

      // Create, encrypt, and put the object
      await s3EncClient.PutObjectAsync(new PutObjectRequest
      {
        BucketName = bucketName,
        Key = itemName,
        ContentBody = File.ReadAllText(fileName)
      });

      // Get, decrypt, and return the object
      return await s3EncClient.GetObjectAsync(new GetObjectRequest
      {
        BucketName = bucketName,
        Key = itemName
      });
    }


    //
    // Command-line help
    private static void PrintHelp()
    {
      Console.WriteLine(
        "\nUsage: KmsS3Encryption -b <bucket-name> -f <file-name> [-i <item-name>]" +
        "\n  -b, --bucket-name: The name of an existing S3 bucket." +
        "\n  -f, --file-name: The name of a text file with content to encrypt and store in S3." +
        "\n  -i, --item-name: The name you want to use for the item." +
        "\n      If item-name isn't given, file-name will be used.");
    }

  }

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

}
```

## Pertimbangan tambahan
<a name="kms-s3-additional"></a>
+ Anda dapat memeriksa hasil dari contoh ini. Untuk melakukannya, buka [konsol Amazon S3](https://console.aws.amazon.com/s3) dan buka ember yang Anda berikan ke aplikasi. Kemudian temukan objek baru, unduh, dan buka di editor teks.
+ Kelas [AmazonS3 EncryptionClient V2](https://aws.github.io/amazon-s3-encryption-client-dotnet/api/Amazon.Extensions.S3.Encryption.AmazonS3EncryptionClientV2.html) mengimplementasikan antarmuka yang sama dengan kelas standar. `AmazonS3Client` Ini membuatnya lebih mudah untuk mem-port kode Anda ke `AmazonS3EncryptionClientV2` kelas sehingga enkripsi dan dekripsi terjadi secara otomatis dan transparan di klien.
+ Salah satu keuntungan menggunakan AWS KMS kunci sebagai kunci utama Anda adalah Anda tidak perlu menyimpan dan mengelola kunci master Anda sendiri; ini dilakukan oleh AWS. Keuntungan kedua adalah bahwa `AmazonS3EncryptionClientV2` kelas interoperable dengan `AmazonS3EncryptionClientV2` kelas. AWS SDK untuk .NET AWS SDK untuk Java Ini berarti Anda dapat mengenkripsi dengan AWS SDK untuk Java dan mendekripsi dengan AWS SDK untuk .NET, dan sebaliknya.
**catatan**  
`AmazonS3EncryptionClientV2`Kelas AWS SDK untuk .NET mendukung kunci master KMS hanya ketika dijalankan dalam mode metadata. Mode file instruksi dari `AmazonS3EncryptionClientV2` kelas tidak AWS SDK untuk .NET kompatibel dengan `AmazonS3EncryptionClientV2` kelas file. AWS SDK untuk Java
+ Untuk informasi selengkapnya tentang enkripsi sisi klien dengan `AmazonS3EncryptionClientV2` kelas, dan cara kerja enkripsi amplop, lihat [Enkripsi Data Sisi Klien dengan dan Amazon AWS SDK untuk .NET S3](https://aws.amazon.com/blogs/developer/client-side-data-encryption-with-aws-sdk-for-net-and-amazon-s3/).

# Mengirim Pemberitahuan Dari Cloud Menggunakan Amazon Simple Notification Service
<a name="sns-apis-intro"></a>

**catatan**  
Informasi dalam topik ini khusus untuk proyek berdasarkan .NET Framework dan AWS SDK untuk .NET versi 3.3 dan sebelumnya.

Ini AWS SDK untuk .NET mendukung Amazon Simple Notification Service (Amazon SNS), yang merupakan layanan web yang memungkinkan aplikasi, pengguna akhir, dan perangkat untuk langsung mengirim notifikasi dari cloud. Untuk informasi selengkapnya, lihat [Amazon SNS](https://aws.amazon.com/sns/).

## Daftar Topik Amazon SNS Anda
<a name="sns-list-example"></a>

Contoh berikut menunjukkan cara mencantumkan topik Amazon SNS Anda, langganan untuk setiap topik, dan atribut untuk setiap topik. Contoh ini menggunakan default [AmazonSimpleNotificationServiceClient](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/SNS/TSNSClient.html).

```
// using Amazon.SimpleNotificationService;
// using Amazon.SimpleNotificationService.Model;

var client = new AmazonSimpleNotificationServiceClient();
var request = new ListTopicsRequest();
var response = new ListTopicsResponse();

do
{
  response = client.ListTopics(request);

  foreach (var topic in response.Topics)
  {
    Console.WriteLine("Topic: {0}", topic.TopicArn);

    var subs = client.ListSubscriptionsByTopic(
      new ListSubscriptionsByTopicRequest
      {
        TopicArn = topic.TopicArn
      });

    var ss = subs.Subscriptions;

    if (ss.Any())
    {
      Console.WriteLine("  Subscriptions:");

      foreach (var sub in ss)
      {
        Console.WriteLine("    {0}", sub.SubscriptionArn);
      }
    }

    var attrs = client.GetTopicAttributes(
      new GetTopicAttributesRequest
      {
        TopicArn = topic.TopicArn
      }).Attributes;

    if (attrs.Any())
    {
      Console.WriteLine("  Attributes:");

      foreach (var attr in attrs)
      {
        Console.WriteLine("    {0} = {1}", attr.Key, attr.Value);
      }
    }

    Console.WriteLine();
  }

  request.NextToken = response.NextToken;

} while (!string.IsNullOrEmpty(response.NextToken));
```

## Mengirim Pesan ke Topik Amazon SNS
<a name="sns-send-message-example"></a>

Contoh berikut menunjukkan cara mengirim pesan ke topik Amazon SNS. Contohnya mengambil satu argumen, ARN dari topik Amazon SNS.

```
using System;
using System.Linq;
using System.Threading.Tasks;

using Amazon;
using Amazon.SimpleNotificationService;
using Amazon.SimpleNotificationService.Model;

namespace SnsSendMessage
{
    class Program
    {
        static void Main(string[] args)
        {
            /* Topic ARNs must be in the correct format:
             *   arn:aws:sns:REGION:ACCOUNT_ID:NAME
             *
             *  where:
             *  REGION     is the region in which the topic is created, such as us-west-2
             *  ACCOUNT_ID is your (typically) 12-character account ID
             *  NAME       is the name of the topic
             */
            string topicArn = args[0];
            string message = "Hello at " + DateTime.Now.ToShortTimeString();

            var client = new AmazonSimpleNotificationServiceClient(region: Amazon.RegionEndpoint.USWest2);

            var request = new PublishRequest
            {
                Message = message,
                TopicArn = topicArn
            };

            try
            {
                var response = client.Publish(request);

                Console.WriteLine("Message sent to topic:");
                Console.WriteLine(message);
            }
            catch (Exception ex)
            {
                Console.WriteLine("Caught exception publishing request:");
                Console.WriteLine(ex.Message);
            }
        }
    }
}
```

Lihat [contoh lengkapnya](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/.dotnet/example_code_legacy/SNS/SnsSendMessage.cs), termasuk informasi tentang cara membuat dan menjalankan contoh dari baris perintah, pada GitHub.

## Mengirim Pesan SMS ke Nomor Telepon
<a name="sns-send-sms-example"></a>

Contoh berikut menunjukkan cara mengirim pesan SMS ke nomor telepon. Contohnya mengambil satu argumen, nomor telepon, yang harus dalam salah satu dari dua format yang dijelaskan dalam komentar.

```
using System;
using System.Linq;
using System.Threading.Tasks;
using Amazon;
using Amazon.SimpleNotificationService;
using Amazon.SimpleNotificationService.Model;

namespace SnsPublish
{
    class Program
    {
        static void Main(string[] args)
        {
            // US phone numbers must be in the correct format:
            // +1 (nnn) nnn-nnnn OR +1nnnnnnnnnn
            string number = args[0];
            string message = "Hello at " + DateTime.Now.ToShortTimeString();

            var client = new AmazonSimpleNotificationServiceClient(region: Amazon.RegionEndpoint.USWest2);
            var request = new PublishRequest
            {
                Message = message,
                PhoneNumber = number
            };

            try
            {
                var response = client.Publish(request);

                Console.WriteLine("Message sent to " + number + ":");
                Console.WriteLine(message);
            }
            catch (Exception ex)
            {
                Console.WriteLine("Caught exception publishing request:");
                Console.WriteLine(ex.Message);
            }
        }
    }
}
```

Lihat [contoh lengkapnya](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/.dotnet/example_code_legacy/SNS/SnsPublish.cs), termasuk informasi tentang cara membuat dan menjalankan contoh dari baris perintah, pada GitHub.

# Perpesanan menggunakan Amazon SQS
<a name="sqs-apis-intro"></a>

 AWS SDK untuk .NET Mendukung [Amazon Simple Queue Service (Amazon Simple Queue Service](https://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/)), yang merupakan layanan antrian pesan yang menangani pesan atau alur kerja antar komponen dalam sistem.

Antrian Amazon SQS menyediakan mekanisme yang memungkinkan Anda mengirim, menyimpan, dan menerima pesan antara komponen perangkat lunak seperti layanan mikro, sistem terdistribusi, dan aplikasi tanpa server. Ini memungkinkan Anda untuk memisahkan komponen tersebut dan membebaskan Anda dari kebutuhan untuk merancang dan mengoperasikan sistem pesan Anda sendiri. [Untuk informasi tentang cara kerja antrian dan pesan di Amazon SQS, lihat tutorial Amazon SQS [dan arsitektur Amazon SQS](https://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/sqs-other-tutorials.html)[Dasar di Panduan Pengembang Layanan Antrian Sederhana Amazon](https://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/sqs-basic-architecture.html).](https://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/)

**penting**  
Karena sifat antrian yang terdistribusi, Amazon SQS tidak dapat menjamin bahwa Anda akan menerima pesan dalam urutan yang tepat yang dikirim. Jika Anda perlu mempertahankan urutan pesan, gunakan antrean [Amazon SQS FIFO](https://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/sqs-fifo-queues.html).

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

 AWS SDK untuk .NET Menyediakan APIs untuk klien Amazon SQS. Ini APIs memungkinkan Anda untuk bekerja dengan fitur Amazon SQS seperti antrian dan pesan. Bagian ini berisi sejumlah kecil contoh yang menunjukkan pola yang dapat Anda ikuti saat bekerja dengan ini APIs. Untuk melihat set lengkap APIs, lihat [Referensi AWS SDK untuk .NET API](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/) (dan gulir ke “Amazon.sqs”).

Amazon SQS APIs disediakan oleh [AWSSDK NuGet paket.SQS](https://www.nuget.org/packages/AWSSDK.SQS).

## Prasyarat
<a name="w2aac19c15c25c11"></a>

Sebelum Anda mulai, pastikan Anda telah [mengatur lingkungan dan proyek Anda](net-dg-config.md). Juga tinjau informasi di[Fitur SDK](net-dg-sdk-features.md).

## Topik
<a name="w2aac19c15c25c13"></a>

**Topics**
+ [APIs](#w2aac19c15c25b9)
+ [Prasyarat](#w2aac19c15c25c11)
+ [Topik](#w2aac19c15c25c13)
+ [Membuat antrian](CreateQueue.md)
+ [Memperbarui antrian](UpdateSqsQueue.md)
+ [Menghapus antrian](DeleteSqsQueue.md)
+ [Mengirim pesan](SendMessage.md)
+ [Menerima pesan](ReceiveMessage.md)

# Membuat antrian Amazon SQS
<a name="CreateQueue"></a>

Contoh ini menunjukkan cara menggunakan antrean Amazon SQS AWS SDK untuk .NET untuk membuat antrean Amazon SQS. Aplikasi membuat [antrian huruf mati](https://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/sqs-dead-letter-queues.html) jika Anda tidak menyediakan ARN untuk satu. Kemudian membuat antrian pesan standar, yang mencakup antrian huruf mati (yang Anda berikan atau yang dibuat).

Jika Anda tidak memberikan argumen baris perintah apa pun, aplikasi hanya menampilkan informasi tentang semua antrian yang ada.

Bagian berikut menyediakan cuplikan dari contoh ini. [Kode lengkap untuk contoh](#CreateQueue-complete-code) ditampilkan setelah itu, dan dapat dibangun dan dijalankan apa adanya.

**Topics**
+ [Tampilkan antrian yang ada](#CreateQueue-show-queues)
+ [Buat antrian](#CreateQueue-create-queue)
+ [Dapatkan ARN antrian](#CreateQueue-get-arn)
+ [Kode lengkap](#CreateQueue-complete-code)
+ [Pertimbangan tambahan](#CreateQueue-additional)

## Tampilkan antrian yang ada
<a name="CreateQueue-show-queues"></a>

Cuplikan berikut menunjukkan daftar antrian yang ada di wilayah klien SQS dan atribut setiap antrian.

Contoh [di akhir topik ini](#CreateQueue-complete-code) menunjukkan cuplikan ini digunakan.

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

## Buat antrian
<a name="CreateQueue-create-queue"></a>

Cuplikan berikut membuat antrian. Cuplikan ini mencakup penggunaan antrian huruf mati, tetapi antrian huruf mati tidak selalu diperlukan untuk antrian Anda.

Contoh [di akhir topik ini](#CreateQueue-complete-code) menunjukkan cuplikan ini digunakan.

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

## Dapatkan ARN antrian
<a name="CreateQueue-get-arn"></a>

Cuplikan berikut mendapatkan ARN dari antrian yang diidentifikasi oleh URL antrian yang diberikan.

Contoh [di akhir topik ini](#CreateQueue-complete-code) menunjukkan cuplikan ini digunakan.

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

## Kode lengkap
<a name="CreateQueue-complete-code"></a>

Bagian ini menunjukkan referensi yang relevan dan kode lengkap untuk contoh ini.

### Referensi SDK
<a name="w2aac19c15c25c17c25b5b1"></a>

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

Elemen pemrograman:
+ [Namespace Amazon.sqs](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/SQS/NSQS.html)

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

  Kelas [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)

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

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

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

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

### Kodenya
<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);
    }
  }

}
```

## Pertimbangan tambahan
<a name="CreateQueue-additional"></a>
+ Nama antrian Anda harus terdiri dari karakter alfanumerik, tanda hubung, dan garis bawah.
+ Nama antrian dan antrian peka huruf URLs besar/kecil
+ Jika Anda memerlukan URL antrian tetapi hanya memiliki nama antrian, gunakan salah satu metode. `AmazonSQSClient.GetQueueUrlAsync`
+ Untuk informasi tentang berbagai atribut antrian yang dapat Anda atur, lihat [CreateQueueRequest](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/SQS/TCreateQueueRequest.html)di [Referensi AWS SDK untuk .NET API atau [SetQueueAttributes](https://docs.aws.amazon.com/AWSSimpleQueueService/latest/APIReference/API_SetQueueAttributes.html)Referensi](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/) [API Layanan Antrian Sederhana Amazon](https://docs.aws.amazon.com/AWSSimpleQueueService/latest/APIReference/).
+ Contoh ini menentukan polling panjang untuk semua pesan pada antrian yang Anda buat. Hal ini dilakukan dengan menggunakan `ReceiveMessageWaitTimeSeconds` atribut.

  Anda juga dapat menentukan polling panjang selama panggilan ke `ReceiveMessageAsync` metode SQSClient kelas [Amazon](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/SQS/TSQSClient.html). Untuk informasi selengkapnya, lihat [Menerima pesan Amazon SQS](ReceiveMessage.md).

  Untuk informasi tentang polling singkat versus polling panjang, lihat Pemungutan suara [pendek dan panjang di Panduan](https://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/sqs-short-and-long-polling.html) Pengembang Layanan *Antrian Sederhana Amazon*.
+ Antrian surat mati adalah antrian yang dapat ditargetkan oleh antrian (sumber) lain untuk pesan yang tidak berhasil diproses. Untuk informasi selengkapnya, lihat [antrian surat mati Amazon SQS di Panduan Pengembang Layanan Antrian](https://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/sqs-dead-letter-queues.html) Sederhana Amazon.
+ Anda juga dapat melihat daftar antrian dan hasil contoh ini di konsol [Amazon SQS](https://console.aws.amazon.com/sqs).

# Memperbarui antrian Amazon SQS
<a name="UpdateSqsQueue"></a>

Contoh ini menunjukkan cara menggunakan AWS SDK untuk .NET untuk memperbarui antrian Amazon SQS. Setelah beberapa pemeriksaan, aplikasi memperbarui atribut yang diberikan dengan nilai yang diberikan, dan kemudian menampilkan semua atribut untuk antrian.

Jika hanya URL antrian yang disertakan dalam argumen baris perintah, aplikasi hanya menampilkan semua atribut untuk antrian.

Bagian berikut menyediakan cuplikan dari contoh ini. [Kode lengkap untuk contoh](#UpdateSqsQueue-complete-code) ditampilkan setelah itu, dan dapat dibangun dan dijalankan apa adanya.

**Topics**
+ [Tampilkan atribut antrian](#UpdateSqsQueue-show-attributes)
+ [Validasi nama atribut](#UpdateSqsQueue-validate-attribute)
+ [Perbarui atribut antrian](#UpdateSqsQueue-update-attribute)
+ [Kode lengkap](#UpdateSqsQueue-complete-code)
+ [Pertimbangan tambahan](#UpdateSqsQueue-additional)

## Tampilkan atribut antrian
<a name="UpdateSqsQueue-show-attributes"></a>

Cuplikan berikut menunjukkan atribut antrian yang diidentifikasi oleh URL antrian yang diberikan.

Contoh [di akhir topik ini](#UpdateSqsQueue-complete-code) menunjukkan cuplikan ini digunakan.

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

## Validasi nama atribut
<a name="UpdateSqsQueue-validate-attribute"></a>

Cuplikan berikut memvalidasi nama atribut yang sedang diperbarui.

Contoh [di akhir topik ini](#UpdateSqsQueue-complete-code) menunjukkan cuplikan ini digunakan.

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

## Perbarui atribut antrian
<a name="UpdateSqsQueue-update-attribute"></a>

Cuplikan berikut memperbarui atribut antrian yang diidentifikasi oleh URL antrian yang diberikan.

Contoh [di akhir topik ini](#UpdateSqsQueue-complete-code) menunjukkan cuplikan ini digunakan.

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

## Kode lengkap
<a name="UpdateSqsQueue-complete-code"></a>

Bagian ini menunjukkan referensi yang relevan dan kode lengkap untuk contoh ini.

### Referensi SDK
<a name="w2aac19c15c25c19c25b5b1"></a>

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

Elemen pemrograman:
+ [Namespace Amazon.sqs](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/SQS/NSQS.html)

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

  Kelas [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)

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

### Kodenya
<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);
    }
  }

}
```

## Pertimbangan tambahan
<a name="UpdateSqsQueue-additional"></a>
+ Untuk memperbarui `RedrivePolicy` atribut, Anda harus mengutip seluruh nilai dan menghindari tanda kutip untuk key/value pasangan, yang sesuai untuk sistem operasi Anda.

  Pada Windows, misalnya, nilainya dibangun dengan cara yang mirip dengan yang berikut ini:

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

# Menghapus antrian Amazon SQS
<a name="DeleteSqsQueue"></a>

Contoh ini menunjukkan cara menggunakan antrean Amazon SQS AWS SDK untuk .NET untuk menghapus. Aplikasi menghapus antrian, menunggu hingga jumlah waktu tertentu untuk antrian hilang, dan kemudian menunjukkan daftar antrian yang tersisa.

Jika Anda tidak memberikan argumen baris perintah apa pun, aplikasi hanya menampilkan daftar antrian yang ada.

Bagian berikut menyediakan cuplikan dari contoh ini. [Kode lengkap untuk contoh](#DeleteSqsQueue-complete-code) ditampilkan setelah itu, dan dapat dibangun dan dijalankan apa adanya.

**Topics**
+ [Hapus antrian](#DeleteSqsQueue-delete-queue)
+ [Tunggu antrian hilang](#DeleteSqsQueue-wait)
+ [Tampilkan daftar antrian yang ada](#DeleteSqsQueue-list-queues)
+ [Kode lengkap](#DeleteSqsQueue-complete-code)
+ [Pertimbangan tambahan](#DeleteSqsQueue-additional)

## Hapus antrian
<a name="DeleteSqsQueue-delete-queue"></a>

Cuplikan berikut menghapus antrian yang diidentifikasi oleh URL antrian yang diberikan.

Contoh [di akhir topik ini](#DeleteSqsQueue-complete-code) menunjukkan cuplikan ini digunakan.

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

## Tunggu antrian hilang
<a name="DeleteSqsQueue-wait"></a>

Cuplikan berikut menunggu proses penghapusan selesai, yang mungkin memakan waktu 60 detik.

Contoh [di akhir topik ini](#DeleteSqsQueue-complete-code) menunjukkan cuplikan ini digunakan.

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

## Tampilkan daftar antrian yang ada
<a name="DeleteSqsQueue-list-queues"></a>

Cuplikan berikut menunjukkan daftar antrian yang ada di wilayah klien SQS.

Contoh [di akhir topik ini](#DeleteSqsQueue-complete-code) menunjukkan cuplikan ini digunakan.

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

## Kode lengkap
<a name="DeleteSqsQueue-complete-code"></a>

Bagian ini menunjukkan referensi yang relevan dan kode lengkap untuk contoh ini.

### Referensi SDK
<a name="w2aac19c15c25c21c25b5b1"></a>

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

Elemen pemrograman:
+ [Namespace Amazon.sqs](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/SQS/NSQS.html)

  Kelas [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)

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

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

## Pertimbangan tambahan
<a name="DeleteSqsQueue-additional"></a>
+ Panggilan `DeleteQueueAsync` API tidak memeriksa untuk melihat apakah antrian yang Anda hapus digunakan sebagai antrian huruf mati. Prosedur yang lebih canggih dapat memeriksa ini.
+ Anda juga dapat melihat daftar antrian dan hasil contoh ini di konsol [Amazon SQS](https://console.aws.amazon.com/sqs).

# Mengirim pesan Amazon SQS
<a name="SendMessage"></a>

[Contoh ini menunjukkan kepada Anda cara menggunakan untuk mengirim pesan AWS SDK untuk .NET ke antrean Amazon SQS, yang dapat Anda buat [secara terprogram atau dengan menggunakan konsol](CreateQueue.md) Amazon SQS.](https://console.aws.amazon.com/sqs) Aplikasi mengirimkan satu pesan ke antrian dan kemudian sekumpulan pesan. Aplikasi kemudian menunggu input pengguna, yang dapat berupa pesan tambahan untuk dikirim ke antrian atau permintaan untuk keluar dari aplikasi.

Contoh ini dan [contoh selanjutnya tentang menerima pesan](ReceiveMessage.md) dapat digunakan bersama untuk melihat aliran pesan di Amazon SQS.

Bagian berikut menyediakan cuplikan dari contoh ini. [Kode lengkap untuk contoh](#SendMessage-complete-code) ditampilkan setelah itu, dan dapat dibangun dan dijalankan apa adanya.

**Topics**
+ [Kirim pesan](#SendMessage-send-message)
+ [Kirim sejumlah pesan](#SendMessage-send-batch)
+ [Hapus semua pesan dari antrian](#SendMessage-purge-messages)
+ [Kode lengkap](#SendMessage-complete-code)
+ [Pertimbangan tambahan](#SendMessage-additional)

## Kirim pesan
<a name="SendMessage-send-message"></a>

Cuplikan berikut mengirimkan pesan ke antrian yang diidentifikasi oleh URL antrian yang diberikan.

Contoh [di akhir topik ini](#SendMessage-complete-code) menunjukkan cuplikan ini digunakan.

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

## Kirim sejumlah pesan
<a name="SendMessage-send-batch"></a>

Cuplikan berikut mengirimkan sekumpulan pesan ke antrian yang diidentifikasi oleh URL antrian yang diberikan.

Contoh [di akhir topik ini](#SendMessage-complete-code) menunjukkan cuplikan ini digunakan.

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

## Hapus semua pesan dari antrian
<a name="SendMessage-purge-messages"></a>

Cuplikan berikut menghapus semua pesan dari antrian yang diidentifikasi oleh URL antrian yang diberikan. Ini juga dikenal sebagai *membersihkan antrian*.

Contoh [di akhir topik ini](#SendMessage-complete-code) menunjukkan cuplikan ini digunakan.

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

## Kode lengkap
<a name="SendMessage-complete-code"></a>

Bagian ini menunjukkan referensi yang relevan dan kode lengkap untuk contoh ini.

### Referensi SDK
<a name="w2aac19c15c25c23c25b5b1"></a>

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

Elemen pemrograman:
+ [Namespace Amazon.sqs](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/SQS/NSQS.html)

  Kelas [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)

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

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

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

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

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

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

## Pertimbangan tambahan
<a name="SendMessage-additional"></a>
+ Untuk informasi tentang berbagai batasan pada pesan, termasuk karakter yang diizinkan, lihat [Kuota yang terkait dengan pesan di Panduan](https://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/sqs-quotas.html#quotas-messages) [Pengembang Layanan Antrian Sederhana Amazon](https://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/).
+ Pesan tetap dalam antrian sampai dihapus atau antrian dibersihkan. Ketika pesan telah diterima oleh aplikasi, itu tidak akan terlihat dalam antrian meskipun masih ada dalam antrian. Untuk informasi selengkapnya tentang batas waktu visibilitas, lihat batas waktu visibilitas [Amazon SQS](https://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/AboutVT.html).
+ Selain isi pesan, Anda juga dapat menambahkan atribut ke pesan. Untuk informasi selengkapnya, lihat [Metadata pesan](https://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/sqs-message-metadata.html).

# Menerima pesan Amazon SQS
<a name="ReceiveMessage"></a>

[Contoh ini menunjukkan cara menggunakan AWS SDK untuk .NET untuk menerima pesan dari antrean Amazon SQS, yang dapat Anda buat [secara terprogram atau menggunakan konsol](CreateQueue.md) Amazon SQS.](https://console.aws.amazon.com/sqs) Aplikasi membaca satu pesan dari antrian, memproses pesan (dalam hal ini, menampilkan badan pesan di konsol), dan kemudian menghapus pesan dari antrian. Aplikasi mengulangi langkah-langkah ini sampai pengguna mengetik tombol pada keyboard.

Contoh ini dan [contoh sebelumnya tentang mengirim pesan](SendMessage.md) dapat digunakan bersama untuk melihat aliran pesan di Amazon SQS.

Bagian berikut menyediakan cuplikan dari contoh ini. [Kode lengkap untuk contoh](#ReceiveMessage-complete-code) ditampilkan setelah itu, dan dapat dibangun dan dijalankan apa adanya.

**Topics**
+ [Menerima pesan](#ReceiveMessage-receive)
+ [Menghapus pesan](#ReceiveMessage-delete)
+ [Kode lengkap](#ReceiveMessage-complete-code)
+ [Pertimbangan tambahan](#ReceiveMessage-additional)

## Menerima pesan
<a name="ReceiveMessage-receive"></a>

Cuplikan berikut menerima pesan dari antrian yang diidentifikasi oleh URL antrian yang diberikan.

Contoh [di akhir topik ini](#ReceiveMessage-complete-code) menunjukkan cuplikan ini digunakan.

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

## Menghapus pesan
<a name="ReceiveMessage-delete"></a>

Cuplikan berikut menghapus pesan dari antrian yang diidentifikasi oleh URL antrian yang diberikan.

Contoh [di akhir topik ini](#ReceiveMessage-complete-code) menunjukkan cuplikan ini digunakan.

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

## Kode lengkap
<a name="ReceiveMessage-complete-code"></a>

Bagian ini menunjukkan referensi yang relevan dan kode lengkap untuk contoh ini.

### Referensi SDK
<a name="w2aac19c15c25c25c21b5b1"></a>

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

Elemen pemrograman:
+ [Namespace Amazon.sqs](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/SQS/NSQS.html)

  Kelas [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)

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

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

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

## Pertimbangan tambahan
<a name="ReceiveMessage-additional"></a>
+ Untuk menentukan polling panjang, contoh ini menggunakan `WaitTimeSeconds` properti untuk setiap panggilan ke `ReceiveMessageAsync` metode.

  Anda juga dapat menentukan polling panjang untuk semua pesan pada antrian dengan menggunakan `ReceiveMessageWaitTimeSeconds` atribut saat [membuat](CreateQueue.md) atau [memperbarui](UpdateSqsQueue.md) antrian.

  Untuk informasi tentang polling singkat versus polling panjang, lihat Pemungutan suara [pendek dan panjang di Panduan](https://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/sqs-short-and-long-polling.html) Pengembang Layanan *Antrian Sederhana Amazon*.
+ Selama pemrosesan pesan, Anda dapat menggunakan tanda terima untuk mengubah batas waktu visibilitas pesan. Untuk informasi tentang cara melakukannya, lihat `ChangeMessageVisibilityAsync` metode SQSClient kelas [Amazon](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/SQS/TSQSClient.html).
+ Memanggil `DeleteMessageAsync` metode tanpa syarat akan menghapus pesan dari antrian, terlepas dari pengaturan batas waktu visibilitas.