

È stata rilasciata la versione 4 (V4) di\$1 AWS SDK per .NET 

Per informazioni su come apportare modifiche e migrare le applicazioni, consulta l'argomento sulla [migrazione](https://docs.aws.amazon.com/sdk-for-net/v4/developer-guide/net-dg-v4.html).

 [https://docs.aws.amazon.com/sdk-for-net/v4/developer-guide/net-dg-v4.html](https://docs.aws.amazon.com/sdk-for-net/v4/developer-guide/net-dg-v4.html)

Le traduzioni sono generate tramite traduzione automatica. In caso di conflitto tra il contenuto di una traduzione e la versione originale in Inglese, quest'ultima prevarrà.

# Esempi di codice guidati per AWS SDK per .NET
<a name="tutorials-examples"></a>

Le sezioni seguenti contengono esempi di codice e forniscono indicazioni per gli esempi. Possono aiutarti a imparare a utilizzarli AWS SDK per .NET per lavorare con AWS i servizi. Per ulteriori esempi di codice, vedere[Esempi di codice](csharp_code_examples.md).

**Nota**  
Sono disponibili anche esempi di codice specifici per la AWS SDK per .NET versione 3 di. Per trovarli, consulta [Esempi di codice con indicazioni](https://docs.aws.amazon.com/sdk-for-net/v3/developer-guide/tutorials-examples.html) ed [Esempi di codice](https://docs.aws.amazon.com/sdk-for-net/v3/developer-guide/csharp_code_examples.html) nella AWS SDK per .NET (V3) Developer Guide. Tuttavia, tieni presente che se utilizzi gli esempi di codice specifici per V3 con la versione 4 dell'SDK (la versione più recente), potresti dover apportare modifiche in base alle informazioni contenute. [Migrazione alla versione 4](net-dg-v4.md)

Se non lo conosci AWS SDK per .NET, ti consigliamo di dare prima un'occhiata all'argomento. [Creazione di un'applicazione semplice](quick-start.md) Fornisce un'introduzione all'SDK.

Prima di iniziare, assicuratevi di aver [impostato l'ambiente](net-dg-config.md) e [configurato il progetto](configuring-the-sdk.md). Consulta anche le informazioni contenute in[Utilizzo di 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)
+ [Simple Storage Service (Amazon S3)](s3-apis-intro.md)
+ [Amazon SNS](sns-apis-intro.md)
+ [Amazon SQS](sqs-apis-intro.md)

# Accesso CloudFormation con AWS SDK per .NET
<a name="cloudformation-apis-intro"></a>

I AWS SDK per .NET supporti [AWS CloudFormation](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/), che creano e forniscono implementazioni dell' AWS infrastruttura in modo prevedibile e ripetuto.

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

 AWS SDK per .NET Fornisce ai clienti. APIs CloudFormation Ti APIs consentono di lavorare con CloudFormation funzionalità come modelli e pile. Questa sezione contiene un numero limitato di esempi che mostrano gli schemi che è possibile seguire quando si lavora con questi APIs modelli. Per visualizzare il set completo di APIs, consulta l'[AWS SDK per .NET API Reference](https://docs.aws.amazon.com/sdkfornet/v4/apidocs/) (e scorri fino a «Amazon. CloudFormation«).

 AWS CloudFormation APIs Sono forniti da [AWSSDK. CloudFormation](https://www.nuget.org/packages/AWSSDK.CloudFormation/)pacchetto.

## Prerequisiti
<a name="w2aac19c15c15b7"></a>

Prima di iniziare, assicurati di aver [impostato l'ambiente](net-dg-config.md) e [configurato il progetto](configuring-the-sdk.md). Consulta anche le informazioni contenute in[Utilizzo di SDK](net-dg-sdk-features.md).

## Argomenti
<a name="w2aac19c15c15b9"></a>

**Topics**
+ [APIs](#w2aac19c15c15b5)
+ [Prerequisiti](#w2aac19c15c15b7)
+ [Argomenti](#w2aac19c15c15b9)
+ [Elencare AWS le risorse](cfn-list-resources.md)

# AWS Elencare le risorse utilizzando AWS CloudFormation
<a name="cfn-list-resources"></a>

Questo esempio mostra come usare per AWS SDK per .NET elencare le risorse in CloudFormation pile. L'esempio utilizza l'API di basso livello. L'applicazione non accetta argomenti, ma raccoglie semplicemente informazioni per tutti gli stack accessibili alle credenziali dell'utente e quindi visualizza le informazioni su tali stack.

## Riferimenti SDK
<a name="w2aac19c15c15c13b5b1"></a>

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

Elementi di programmazione:
+ [Namespace Amazon. CloudFormation](https://docs.aws.amazon.com/sdkfornet/v4/apidocs/items/CloudFormation/NCloudFormation.html)

  Classe [AmazonCloudFormationClient](https://docs.aws.amazon.com/sdkfornet/v4/apidocs/items/CloudFormation/TCloudFormationClient.html)
+ [Namespace Amazon. CloudFormation](https://docs.aws.amazon.com/sdkfornet/v4/apidocs/items/CloudFormation/NCloudFormationModel.html).Modello

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

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

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

  [Stack](https://docs.aws.amazon.com/sdkfornet/v4/apidocs/items/CloudFormation/TStack.html) di classi

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

  [Tag](https://docs.aws.amazon.com/sdkfornet/v4/apidocs/items/CloudFormation/TTag.html) di classe

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

# Autenticazione degli utenti con Amazon Cognito
<a name="cognito-apis-intro"></a>

**Nota**  
Le informazioni contenute in questo argomento si riferiscono specificamente ai progetti basati su.NET Framework e alla AWS SDK per .NET versione 3.3 e precedenti.

Utilizzando Amazon Cognito Identity, puoi creare identità uniche per i tuoi utenti e autenticarli per un accesso sicuro alle tue AWS risorse come Amazon S3 o Amazon DynamoDB. Amazon Cognito Identity supporta provider di identità pubblici come Amazon, Facebook, Twitter/Digits, Google o qualsiasi provider compatibile con OpenID Connect, nonché identità non autenticate. Amazon Cognito supporta anche [identità autenticate dagli sviluppatori](https://aws.amazon.com/blogs/mobile/amazon-cognito-announcing-developer-authenticated-identities/), che consentono di registrare e autenticare gli utenti utilizzando il proprio processo di autenticazione back-end, continuando a utilizzare Amazon Cognito Sync per sincronizzare i dati degli utenti e accedere alle risorse. AWS 

Per ulteriori informazioni su [Amazon Cognito, consulta la Amazon Cognito](https://aws.amazon.com/cognito/) [Developer Guide](https://docs.aws.amazon.com/cognito/latest/developerguide/).

I seguenti esempi di codice mostrano come usare facilmente Amazon Cognito Identity. L'[Provider di credenziali](cognito-creds-provider.md)esempio mostra come creare e autenticare le identità degli utenti. L'[CognitoAuthentication libreria di estensioni](cognito-authentication-extension.md)esempio mostra come utilizzare la libreria di CognitoAuthentication estensioni per autenticare i pool di utenti di Amazon Cognito.

**Topics**
+ [Provider di credenziali](cognito-creds-provider.md)
+ [CognitoAuthentication libreria di estensioni](cognito-authentication-extension.md)

# Provider di credenziali Amazon Cognito
<a name="cognito-creds-provider"></a>

**Nota**  
Le informazioni contenute in questo argomento si riferiscono specificamente ai progetti basati su.NET Framework e alla AWS SDK per .NET versione 3.3 e precedenti.

 `Amazon.CognitoIdentity.CognitoAWSCredentials`, disponibile in [AWSSDK. CognitoIdentity](https://www.nuget.org/packages/AWSSDK.CognitoIdentity/) NuGetpackage, è un oggetto di credenziali che utilizza Amazon Cognito e AWS Security Token Service the AWS STS() per recuperare le credenziali per effettuare chiamate. AWS 

Il primo passo per la configurazione di `CognitoAWSCredentials` è creare un "pool di identità". (Un pool di identità è un archivio di informazioni sull'identità dell'utente specifico per il tuo account. Le informazioni sono recuperabili su più piattaforme client, dispositivi e sistemi operativi, in modo tale che, se un utente inizia a usare l'applicazione su un telefono e successivamente su un tablet, le informazioni sull'applicazione restino a disposizione di quell'utente. Puoi creare un nuovo pool di identità dalla console Amazon Cognito. Se stai utilizzando la console, ti verranno fornite le altre informazioni necessarie:
+ Il tuo numero account: un numero di 12 cifre, ad esempio 123456789012, univoco per il tuo account.
+ L'ARN del ruolo non autenticato: un ruolo che verrà assunto dagli utenti non autenticati. Ad esempio, questo ruolo è in grado di fornire le autorizzazioni di sola lettura per i dati.
+ L'ARN del ruolo autenticato: un ruolo che verrà assunto dagli utenti autenticati. Questo ruolo è in grado di fornire autorizzazioni più estese per i dati.

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

Il seguente esempio di codice mostra come eseguire la configurazione`CognitoAWSCredentials`, che puoi quindi utilizzare per effettuare una chiamata ad Amazon S3 come utente non autenticato. In questo modo è possibile effettuare chiamate con solo una quantità minima dei dati richiesti per autenticare l'utente. Le autorizzazioni utente sono controllate dal ruolo, perciò è possibile configurare l'accesso necessario.

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

## Utilizza AWS come utente non autenticato
<a name="use-aws-as-an-unauthenticated-user"></a>

Il seguente esempio di codice mostra come iniziare a utilizzare AWS come utente non autenticato, quindi autenticarsi tramite Facebook e aggiornare le credenziali per utilizzare le credenziali di Facebook. Tramite questo approccio, è possibile concedere diverse funzionalità agli utenti autenticati tramite il ruolo autenticato. Ad esempio, sarebbe possibile avere un'applicazione per telefono che consente agli utenti di visualizzare i contenuti in modo anonimo, ma permette loro di pubblicare se connessi a uno o più provider configurati.

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

L'oggetto `CognitoAWSCredentials` offre anche più funzionalità se utilizzato con il `AmazonCognitoSyncClient` che fa parte di AWS SDK per .NET. Se si utilizzano entrambi `AmazonCognitoSyncClient` e`CognitoAWSCredentials`, non è necessario specificare le `IdentityId` proprietà `IdentityPoolId` e quando si effettuano chiamate con. `AmazonCognitoSyncClient` Queste proprietà vengono automaticamente riempite da `CognitoAWSCredentials`. Il prossimo codice illustra quanto sopra, nonché un evento che notifica ogni modifica dell'`IdentityId` per `CognitoAWSCredentials`. Il codice `IdentityId` può variare in alcuni casi, ad esempio quando si passa da un utente non autenticato a uno autenticato.

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

# Esempi di librerie di CognitoAuthentication estensioni Amazon
<a name="cognito-authentication-extension"></a>

**Nota**  
Le informazioni in questo argomento sono specifiche per i progetti basati su.NET Framework e la AWS SDK per .NET versione 3.3 e precedenti.

La libreria di CognitoAuthentication estensioni, disponibile in [Amazon.Extensions. CognitoAuthentication](https://www.nuget.org/packages/Amazon.Extensions.CognitoAuthentication/) NuGet pacchetto, semplifica il processo di autenticazione dei pool di utenti di Amazon Cognito per gli sviluppatori.NET Core e Xamarin. La libreria si basa sull'API del provider di identità Amazon Cognito per creare e inviare chiamate API di autenticazione degli utenti.

## Utilizzo della libreria di CognitoAuthentication estensioni
<a name="using-the-cognitoauthentication-extension-library"></a>

Amazon Cognito dispone di alcuni `ChallengeName` valori `AuthFlow` e funzionalità integrati per un flusso di autenticazione standard per convalidare nome utente e password tramite Secure Remote Password (SRP). Per ulteriori informazioni sul flusso di autenticazione, consulta [Flusso di autenticazione del pool di utenti Amazon Cognito](https://docs.aws.amazon.com/cognito/latest/developerguide/amazon-cognito-user-pools-authentication-flow.html).

I seguenti esempi richiedono le seguenti istruzioni `using`:

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

### Usa l'autenticazione di base
<a name="use-basic-authentication"></a>

Crea un [AmazonCognitoIdentityProviderClient](https://docs.aws.amazon.com/sdkfornet/v4/apidocs/items/CognitoIdentityProvider/TCognitoIdentityProviderClient.html)account [anonimo](https://docs.aws.amazon.com/sdkfornet/v4/apidocs/items/Runtime/TAnonymousAWSCredentials.html) utilizzandoAWSCredentials, che non richiede richieste firmate. Non è necessario fornire una regione, il codice sottostante chiamerà `FallbackRegionFactory.GetRegionEndpoint()` se non viene fornita una regione. Creare `CognitoUserPool` e oggetti `CognitoUser`. Chiamare il metodo `StartWithSrpAuthAsync` con un codice `InitiateSrpAuthRequest` che contiene le password utente.

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

}
```

### Autentica con sfide
<a name="authenticate-with-challenges"></a>

Inoltre, è più semplice continuare il flusso di autenticazione anche in presenza di problematiche, ad esempio con NewPasswordRequired Multi-Factor Authentication (MFA). Gli unici requisiti sono CognitoAuthentication gli oggetti, la password dell'utente per SRP e le informazioni necessarie per la sfida successiva, che viene acquisita dopo aver richiesto all'utente di inserirla. Il codice seguente mostra un modo per verificare il tipo di sfida e ottenere le risposte appropriate per l'MFA e NewPasswordRequired le sfide durante il flusso di autenticazione.

Effettuare una richiesta di autenticazione di base come in precedenza e `await` una `AuthFlowResponse`. Quando la risposta è ricevuta in loop attraverso l'oggetto restituito `AuthenticationResult`. Se il tipo `ChallengeName` è `NEW_PASSWORD_REQUIRED`, chiamare il metodo `RespondToNewPasswordRequiredAsync`.

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

### Utilizza AWS le risorse dopo l'autenticazione
<a name="use-aws-resources-after-authentication"></a>

Una volta che un utente è autenticato utilizzando la CognitoAuthentication libreria, il passaggio successivo consiste nel consentire all'utente di accedere alle AWS risorse appropriate. A tale scopo è necessario creare un pool di identità tramite la console Amazon Cognito Federated Identities. Specificando il pool di utenti di Amazon Cognito che hai creato come provider, utilizzando i relativi PoolID e ClientID, puoi consentire agli utenti del pool di utenti di Amazon Cognito di accedere alle risorse collegate al tuo account. AWS È anche possibile specificare diversi ruoli per consentire a entrambi gli utenti autenticati e non autenticati di accedere alle diverse risorse. È possibile modificare queste regole nella console IAM, dove è possibile aggiungere o rimuovere le autorizzazioni nel campo**Action (Operazione)** della policy collegata del ruolo. Quindi, utilizzando il pool di identità, il pool di utenti e le informazioni utente di Amazon Cognito appropriati, puoi effettuare chiamate a risorse diverse AWS . L'esempio seguente mostra un utente autenticato con SRP che accede ai diversi bucket Amazon S3 consentiti dal ruolo del pool di identità associato.

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

## Altre opzioni di autenticazione
<a name="more-authentication-options"></a>

Oltre a SRP e MFA NewPasswordRequired, CognitoAuthentication la libreria di estensioni offre un flusso di autenticazione più semplice per:
+ Custom - Iniziare con una chiamata a `StartWithCustomAuthAsync(InitiateCustomAuthRequest customRequest)` 
+ RefreshToken - Inizia con una chiamata a `StartWithRefreshTokenAuthAsync(InitiateRefreshTokenAuthRequest refreshTokenRequest)` 
+ RefreshTokenSRP - Inizia con una chiamata a `StartWithRefreshTokenAuthAsync(InitiateRefreshTokenAuthRequest refreshTokenRequest)` 
+ AdminNoSRP - Inizia con una chiamata a `StartWithAdminNoSrpAuthAsync(InitiateAdminNoSrpAuthRequest adminAuthRequest)` 

Chiamare il metodo appropriato in funzione del flusso desiderato. Quindi continuare a richiedere all'utente le sfide presentate negli oggetti `AuthFlowResponse` di ciascuna chiamata al metodo. Chiamare il metodo di risposta appropriata, ad esempio `RespondToSmsMfaAuthAsync` per le sfide MFA e `RespondToCustomAuthAsync` per le sfide personalizzate.

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

**Nota**  
I modelli di programmazione descritti in questi argomenti sono presenti sia in.NET Framework che in .NET (Core), ma le convenzioni di chiamata sono diverse, siano esse sincrone o asincrone.

 AWS SDK per .NET Supporta Amazon DynamoDB, un servizio di database NoSQL veloce offerto da. AWS*L'SDK fornisce tre modelli di programmazione per comunicare con DynamoDB: il modello di *basso livello*, il modello di *documento* e il modello di persistenza degli oggetti.*

Le seguenti informazioni introducono questi modelli e i relativi modelli APIs, forniscono esempi su come e quando utilizzarli e forniscono collegamenti a risorse di programmazione DynamoDB aggiuntive disponibili in. AWS SDK per .NET

## Modello di basso livello
<a name="dynamodb-intro-apis-low-level"></a>

Il modello di programmazione di basso livello include le chiamate dirette al servizio DynamoDB. [È possibile accedere a questo modello tramite lo spazio dei nomi Amazon.Dynamo. DBv2](https://docs.aws.amazon.com/sdkfornet/v4/apidocs/items/DynamoDBv2/NDynamoDBv2.html)

Dei tre modelli, il modello di basso livello richiede di scrivere la maggior parte del codice. Ad esempio, è necessario convertire i tipi di dati.NET nei loro equivalenti in DynamoDB. Tuttavia, questo modello consente di accedere alla maggior parte delle caratteristiche.

Gli esempi seguenti mostrano come utilizzare il modello di basso livello per creare una tabella, modificare una tabella e inserire elementi in una tabella in DynamoDB.

### Creazione di una tabella
<a name="dynamodb-intro-apis-low-level-create-table"></a>

Nell'esempio seguente, è necessario creare una tabella utilizzando il metodo `CreateTable` della classe `AmazonDynamoDBClient`. Il metodo `CreateTable` utilizza un'istanza della classe `CreateTableRequest` che contiene caratteristiche quali i nomi degli attributi degli item richiesti, la definizione della chiave primaria e la capacità di throughput. Il metodo `CreateTable` restituisce un'istanza della classe `CreateTableResponse`.

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

### Verificare che una tabella sia pronta per la modifica
<a name="dynamodb-intro-apis-low-level-verify-table"></a>

Prima di poterla modificare, una tabella deve essere pronta per la modifica. L'esempio seguente mostra come utilizzare il modello di basso livello per verificare che una tabella in DynamoDB sia pronta. In questo esempio, la tabella di destinazione da verificare viene individuata tramite il metodo `DescribeTable` della classe `AmazonDynamoDBClient`. Ogni cinque secondi, il codice verifica il valore della proprietà `TableStatus` della tabella. Quando lo stato è impostato su `ACTIVE`, la tabella è pronta per essere modificata.

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

### Inserimento di un item in una tabella
<a name="dynamodb-intro-apis-low-level-insert-item"></a>

Nell'esempio seguente, si utilizza il modello di basso livello per inserire due elementi in una tabella in DynamoDB. Ciascun item è inserito tramite il metodo `PutItem` della classe `AmazonDynamoDBClient`, utilizzando un'istanza della classe `PutItemRequest`. Ognuna delle due istanze della classe `PutItemRequest` richiede il nome della tabella in cui gli item verranno inseriti, con una serie di valori degli attributi degli 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);
```

## Modello di documento
<a name="dynamodb-intro-apis-document"></a>

Il modello di programmazione dei documenti offre un modo più semplice per lavorare con i dati in DynamoDB. Questo modello è progettato in modo specifico per l'accesso alle tabelle e agli item nelle tabelle. [È possibile accedere a questo modello tramite Amazon.Dynamo. DBv2 DocumentModel](https://docs.aws.amazon.com/sdkfornet/v4/apidocs/items/DynamoDBv2/NDynamoDBv2DocumentModel.html)namespace.

Rispetto al modello di programmazione di basso livello, il modello documentale è più facile da codificare con i dati DynamoDB. Ad esempio, non è necessario convertire tanti tipi di dati.NET nei rispettivi equivalenti in DynamoDB. Tuttavia, questo modello non consente l'accesso a tutte le caratteristiche del modello di programmazione di basso livello. Ad esempio, è possibile usare questo modello per creare, recuperare, aggiornare ed eliminare gli item nelle tabelle. Tuttavia, per creare le tabelle, è necessario utilizzare il modello di basso livello. Rispetto al modello di persistenza dell'oggetto, questo modello richiede la scrittura di codice supplementare per memorizzare, caricare ed eseguire la query degli oggetti .NET.

Per ulteriori informazioni sul modello di programmazione documentale di DynamoDB, [consulta.NET: Document](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/DotNetSDKMidLevel.html) model nella Amazon [DynamoDB](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/) Developer Guide.

Le sezioni seguenti forniscono informazioni su come creare una rappresentazione della tabella DynamoDB desiderata ed esempi su come utilizzare il modello di documento per inserire elementi nelle tabelle e ottenere elementi dalle tabelle.

### Creare una rappresentazione della tabella
<a name="dynamodb-intro-apis-document-table"></a>

Per eseguire operazioni sui dati utilizzando il modello di documento, dovete prima creare un'istanza della `Table` classe che rappresenti una tabella specifica. Esistono due modi principali per eseguire questa operazione.

**LoadTable metodo**

Il primo meccanismo consiste nell'utilizzare uno dei `LoadTable` metodi statici della [https://docs.aws.amazon.com/sdkfornet/v4/apidocs/items/DynamoDBv2/TTable.html](https://docs.aws.amazon.com/sdkfornet/v4/apidocs/items/DynamoDBv2/TTable.html)classe, simile all'esempio seguente:

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

**Nota**  
Sebbene questo meccanismo funzioni, in determinate condizioni, a volte può portare a latenze o blocchi aggiuntivi dovuti a comportamenti di avvio a freddo e pool di thread. Per ulteriori informazioni su questi comportamenti, consulta il post del blog [Improved DynamoDB Initialization Patterns](https://aws.amazon.com/blogs/developer/improved-dynamodb-initialization-patterns-for-the-aws-sdk-for-net/) for the. AWS SDK per .NET

**TableBuilder**

Un meccanismo alternativo, la [https://docs.aws.amazon.com/sdkfornet/v4/apidocs/items/DynamoDBv2/TTableBuilder.html](https://docs.aws.amazon.com/sdkfornet/v4/apidocs/items/DynamoDBv2/TTableBuilder.html)classe, è stato introdotto nella [versione 3.7.203](https://www.nuget.org/packages/AWSSDK.DynamoDBv2/3.7.203) del pacchetto.Dynamo. AWSSDK DBv2 NuGet Questo meccanismo può risolvere i comportamenti sopra menzionati rimuovendo alcune chiamate implicite al metodo, in particolare il metodo. `DescribeTable` Questo meccanismo viene utilizzato in modo simile all'esempio seguente:

```
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();
```

Per ulteriori informazioni su questo meccanismo alternativo, consulta nuovamente il post sul blog [Improved DynamoDB Initialization Patterns](https://aws.amazon.com/blogs/developer/improved-dynamodb-initialization-patterns-for-the-aws-sdk-for-net/) for the. AWS SDK per .NET

### Inserimento di un elemento in una tabella
<a name="dynamodb-intro-apis-document-insert-item"></a>

Nell'esempio seguente, una risposta viene inserita nella tabella Reply tramite il `PutItemAsync` metodo della `Table` classe. Il metodo `PutItemAsync` richiede un'istanza della classe `Document`; la classe `Document` è semplicemente una raccolta di attributi inizializzati.

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

### Ottenere un elemento da una tabella
<a name="dynamodb-intro-apis-document-get-item"></a>

Nell'esempio seguente, una risposta viene recuperata tramite il `GetItemAsync` metodo della `Table` classe. Per determinare la risposta da ottenere, il `GetItemAsync` metodo utilizza la chiave hash-and-range primaria della risposta di destinazione.

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

L'esempio precedente converte implicitamente i valori della tabella in stringhe per il metodo. `WriteLine` È possibile eseguire conversioni esplicite utilizzando i vari metodi «As [type]» della classe. `DynamoDBEntry` Ad esempio, puoi convertire in modo esplicito il valore di `Id` da un tipo di `Primitive` dati a un GUID tramite il metodo: `AsGuid()`

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

## Modello di persistenza degli oggetti
<a name="dynamodb-intro-apis-object-persistence"></a>

Il modello di programmazione della persistenza degli oggetti è progettato specificamente per l'archiviazione, il caricamento e l'interrogazione di oggetti.NET in DynamoDB. [È possibile accedere a questo modello tramite Amazon.Dynamo. DBv2 DataModel](https://docs.aws.amazon.com/sdkfornet/v4/apidocs/items/DynamoDBv2/NDynamoDBv2DataModel.html)namespace.

Dei tre modelli, il modello di persistenza degli oggetti è il più semplice da utilizzare come codice ogni volta che si archiviano, caricano o interrogano dati DynamoDB. Ad esempio, lavori direttamente con i tipi di dati DynamoDB. Tuttavia, questo modello fornisce l'accesso solo alle operazioni che archiviano, caricano e interrogano oggetti.NET in DynamoDB. Ad esempio, è possibile usare questo modello per creare, recuperare, aggiornare ed eliminare gli item nelle tabelle. Tuttavia, è necessario prima creare le tabelle utilizzando il modello di basso livello e quindi utilizzare questo modello per mappare le classi .NET alle tabelle.

[Per ulteriori informazioni sul modello di programmazione della persistenza degli oggetti DynamoDB, [consulta.NET: Object persistence model nella Amazon DynamoDB Developer](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/DotNetSDKHighLevel.html) Guide.](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/)

Gli esempi seguenti mostrano come definire una classe.NET che rappresenta un elemento di DynamoDB, utilizzare un'istanza della classe.NET per inserire un elemento in una tabella DynamoDB e utilizzare un'istanza della classe.NET per ottenere un elemento dalla tabella.

### Definizione di una classe.NET che rappresenta un elemento in una tabella
<a name="dynamodb-intro-apis-object-persistence-net-class-item"></a>

Nel seguente esempio di definizione di classe, l'`DynamoDBTable`attributo specifica il nome della tabella, mentre gli `DynamoDBRangeKey` attributi `DynamoDBHashKey` e modellano la chiave hash-and-range primaria della tabella. L'`DynamoDBGlobalSecondaryIndexHashKey`attributo è definito in modo da poter creare una query per le risposte di un autore specifico.

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

### Creazione di un contesto per il modello di persistenza degli oggetti
<a name="dynamodb-intro-apis-object-persistence-context"></a>

Per utilizzare il modello di programmazione della persistenza degli oggetti per DynamoDB, è necessario creare un contesto che fornisca una connessione a DynamoDB e consenta di accedere alle tabelle, eseguire varie operazioni ed eseguire query.

**Contesto di base**

L'esempio seguente mostra come creare il contesto più semplice.

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

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

**Contesto con DisableFetchingTableMetadata proprietà**

L'esempio seguente mostra come è possibile impostare ulteriormente la `DisableFetchingTableMetadata` proprietà della `DynamoDBContextConfig` classe per impedire chiamate implicite al `DescribeTable` metodo.

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

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

Se la `DisableFetchingTableMetadata` proprietà è impostata su `false` (impostazione predefinita), come mostrato nel primo esempio, potete omettere dalla classe gli attributi che descrivono la struttura delle chiavi e degli indici degli elementi della tabella. `Reply` Questi attributi verranno invece dedotti tramite una chiamata implicita al metodo. `DescribeTable` If `DisableFetchingTableMetadata` è impostato su`true`, come mostrato nel secondo esempio, sui metodi del modello di persistenza degli oggetti come `SaveAsync` e `QueryAsync` si basa interamente sugli attributi definiti nella classe. `Reply` In questo caso, non viene effettuata una chiamata al `DescribeTable` metodo.

**Nota**  
In determinate condizioni, le chiamate al `DescribeTable` metodo possono talvolta portare a latenze o deadlock aggiuntivi dovuti a comportamenti di avvio a freddo e pool di thread. Per questo motivo, a volte è vantaggioso evitare le chiamate a quel metodo.  
Per ulteriori informazioni su questi comportamenti, consulta il post del blog [Improved DynamoDB Initialization Patterns](https://aws.amazon.com/blogs/developer/improved-dynamodb-initialization-patterns-for-the-aws-sdk-for-net/) for the. AWS SDK per .NET

### Utilizzo di un'istanza della classe.NET per inserire un elemento in una tabella
<a name="dynamodb-intro-apis-object-persistence-net-insert-item"></a>

In questo esempio, un elemento viene inserito tramite il `SaveAsync` metodo della `DynamoDBContext` classe, che utilizza un'istanza inizializzata della classe.NET che rappresenta l'elemento.

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

### Utilizzo di un'istanza di una classe.NET per ottenere elementi da una tabella
<a name="dynamodb-intro-apis-object-persistence-net-get-item"></a>

In questo esempio, viene creata una query per trovare tutti i record di «Author1" utilizzando il `QueryAsync` metodo della `DynamoDBContext` classe. Quindi, gli elementi vengono recuperati tramite il metodo della query. `GetNextSetAsync`

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

### Informazioni aggiuntive sul modello di persistenza degli oggetti
<a name="dynamodb-intro-apis-object-persistence-more-into"></a>

Gli esempi e le spiegazioni mostrati sopra a volte includono una proprietà della `DynamoDBContext` classe chiamata. `DisableFetchingTableMetadata` Questa proprietà, introdotta nella [versione 3.7.203 del DBv2 NuGet pacchetto AWSSDK .Dynamo, consente di](https://www.nuget.org/packages/AWSSDK.DynamoDBv2/3.7.203) evitare determinate condizioni che potrebbero causare latenze o deadlock aggiuntivi dovuti a comportamenti di avvio a freddo e pool di thread. Per ulteriori informazioni, consulta il post sul blog [Improved DynamoDB Initialization Patterns](https://aws.amazon.com/blogs/developer/improved-dynamodb-initialization-patterns-for-the-aws-sdk-for-net/) for the. AWS SDK per .NET

Di seguito sono riportate alcune informazioni aggiuntive su questa proprietà.
+ Questa proprietà può essere impostata globalmente nel tuo `web.config` file `app.config` o se utilizzi .NET Framework.
+ Questa proprietà può essere impostata globalmente utilizzando la [https://docs.aws.amazon.com/sdkfornet/v4/apidocs/items/Amazon/TAWSConfigsDynamoDB.html](https://docs.aws.amazon.com/sdkfornet/v4/apidocs/items/Amazon/TAWSConfigsDynamoDB.html)classe, come illustrato nell'esempio seguente.

  ```
  // Set the DisableFetchingTableMetadata property globally
  // before constructing any context objects.
  AWSConfigsDynamoDB.Context.DisableFetchingTableMetadata = true;
  
  var client = new AmazonDynamoDBClient();
  var context = new DynamoDBContext(client);
  ```
+ In alcuni casi, non è possibile aggiungere attributi DynamoDB a una classe.NET, ad esempio se la classe è definita in una dipendenza. In questi casi, è comunque possibile sfruttare la proprietà. `DisableFetchingTableMetadata` A tale scopo, utilizzate la [https://docs.aws.amazon.com/sdkfornet/v4/apidocs/items/DynamoDBv2/TTableBuilder.html](https://docs.aws.amazon.com/sdkfornet/v4/apidocs/items/DynamoDBv2/TTableBuilder.html)classe in aggiunta alla `DisableFetchingTableMetadata` proprietà. La `TableBuilder` classe è stata introdotta anche nella [versione 3.7.203 del AWSSDK DBv2 NuGet pacchetto.Dynamo](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"
  });
  ```

## Ulteriori informazioni
<a name="dynamodb-intro-more-info"></a>

 **Utilizzo di DynamoDB AWS SDK per .NET per programmare DynamoDB, informazioni ed esempi**
+  [DynamoDB APIs](http://blogs.aws.amazon.com/net/post/Tx17SQHVEMW8MXC/DynamoDB-APIs) 
+  [DynamoDB Series Kickoff](http://blogs.aws.amazon.com/net/post/Tx2XQOCY08QMTKO/DynamoDB-Series-Kickoff) 
+  [DynamoDB Series - Modello di documento](http://blogs.aws.amazon.com/net/post/Tx2R0WG46GQI1JI/DynamoDB-Series-Document-Model) 
+  [DynamoDB Series - Schemi di conversione](http://blogs.aws.amazon.com/net/post/Tx2TCOGWG7ARUH5/DynamoDB-Series-Conversion-Schemas) 
+  [DynamoDB Series - Modello di persistenza degli oggetti](http://blogs.aws.amazon.com/net/post/Tx20L86FLMBW51P/DynamoDB-Series-Object-Persistence-Model) 
+  [DynamoDB Series - Expressions](http://blogs.aws.amazon.com/net/post/TxZQM7VA9AUZ9L/DynamoDB-Series-Expressions) 
+  [Utilizzo di espressioni con Amazon DynamoDB e AWS SDK per .NET](dynamodb-expressions.md) 
+  [Supporto JSON in Amazon DynamoDB](dynamodb-json.md) 

 **Modello di basso livello, informazioni ed esempi** 
+  [Lavorare con le tabelle utilizzando l'API di AWS SDK per .NET basso livello](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/LowLevelDotNetWorkingWithTables.html) 
+  [Lavorare con gli elementi utilizzando l'API di AWS SDK per .NET basso livello](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/LowLevelDotNetItemCRUD.html) 
+  [Interrogazione di tabelle utilizzando l'API di basso livello AWS SDK per .NET](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/LowLevelDotNetQuerying.html) 
+  [Scansione di tabelle utilizzando l'API di basso livello AWS SDK per .NET](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/LowLevelDotNetScanning.html) 
+  [Utilizzo degli indici secondari locali utilizzando l'API di basso livello AWS SDK per .NET](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/LSILowLevelDotNet.html) 
+  [Utilizzo degli indici secondari globali utilizzando l'API di basso livello AWS SDK per .NET](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/GSILowLevelDotNet.html) 

 **Modello di documento, informazioni ed esempi** 
+  [Tipi di dati 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: modello di documento](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/DotNetSDKMidLevel.html) 

 **Modello di persistenza degli oggetti, informazioni ed esempi** 
+  [.NET: modello di persistenza degli oggetti](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/DotNetSDKHighLevel.html) 

 **Altre informazioni utili** 
+ [Integrazione AWS con.NET Aspire](aspire-integrations.md)Per informazioni sullo sviluppo con Amazon DynamoDB locale tramite .NET Aspire, consulta.

**Topics**
+ [Modello di basso livello](#dynamodb-intro-apis-low-level)
+ [Modello di documento](#dynamodb-intro-apis-document)
+ [Modello di persistenza degli oggetti](#dynamodb-intro-apis-object-persistence)
+ [Ulteriori informazioni](#dynamodb-intro-more-info)
+ [Utilizzo di espressioni](dynamodb-expressions.md)
+ [Supporto JSON](dynamodb-json.md)

# Utilizzo di espressioni con Amazon DynamoDB e AWS SDK per .NET
<a name="dynamodb-expressions"></a>

**Nota**  
Le informazioni contenute in questo argomento si riferiscono specificamente ai progetti basati su.NET Framework e alla AWS SDK per .NET versione 3.3 e precedenti.

I seguenti esempi di codice mostrano come utilizzare DynamoDB AWS SDK per .NET per programmare DynamoDB con espressioni. *Le espressioni* indicano gli attributi che si desidera leggere da un elemento in una tabella DynamoDB. Inoltre, puoi usare le espressioni durante la scrittura di un item per indicare qualsiasi condizione che deve essere soddisfatta (operazione detta anche *aggiornamento condizionale*) e per indicare le modalità di aggiornamento degli attributi. Alcuni esempi di aggiornamento sostituiscono l'attributo con un nuovo valore o aggiungono nuovi dati a una lista o una mappa. Per ulteriori informazioni, consulta [Lettura e scrittura di item utilizzando le espressioni](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Expressions.html).

**Topics**
+ [Dati di esempio.](#dynamodb-expressions-sample-data)
+ [Ottenere un singolo item utilizzando le espressioni e la chiave primaria dell'item](#dynamodb-expressions-get-item)
+ [Ottenere più item utilizzando le espressioni e la chiave primaria della tabella](#dynamodb-expressions-query)
+ [Ottenere più item utilizzando le espressioni e altri attributi degli item](#dynamodb-expressions-scan)
+ [Stampare un item](#dynamodb-expressions-print-item)
+ [Creare o sostituire un item utilizzando le espressioni](#dynamodb-expressions-put-item)
+ [Aggiornare un item utilizzando le espressioni](#dynamodb-expressions-update-item)
+ [Eliminare un item utilizzando le espressioni](#dynamodb-expressions-delete-item)
+ [Ulteriori informazioni](#dynamodb-expressions-resources)

## Dati di esempio.
<a name="dynamodb-expressions-sample-data"></a>

Gli esempi di codice in questo argomento si basano sui seguenti due elementi di esempio in una tabella DynamoDB denominata. `ProductCatalog` Questi elementi descrivono le informazioni sulle voci relative ai prodotti in un catalogo di biciclette fittizio. Questi elementi si basano sull'esempio fornito in [Case Study: A ProductCatalog ](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Expressions.CaseStudy.html) Item. I descrittori del tipo di dati come `BOOL`, `L`, `M`, `N`, `NS`, `S` e `SS` corrispondono a quelli nel [Formato di dati 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."
        ]
      }
    }
  }
}
```

## Ottenere un singolo item utilizzando le espressioni e la chiave primaria dell'item
<a name="dynamodb-expressions-get-item"></a>

L'esempio seguente illustra il metodo `Amazon.DynamoDBv2.AmazonDynamoDBClient.GetItem` e un set di espressioni per ottenere e quindi stampare l'item con un codice `Id` di `205`. Solo i seguenti attributi dell'item vengono restituiti: `Id`, `Title`, `Description`, `Color`, `RelatedItems`, `Pictures` e `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);
```

Nell'esempio precedente, la proprietà `ProjectionExpression` specifica gli attributi da restituire. La proprietà `ExpressionAttributeNames` specifica il segnaposto `#pr` per rappresentare l'attributo `ProductReviews` e il segnaposto `#ri` per rappresentare l'attributo `RelatedItems`. La chiamata a `PrintItem` si riferisce a una funzione personalizzata come descritto in [Stampare un item](#dynamodb-expressions-print-item).

## Ottenere più item utilizzando le espressioni e la chiave primaria della tabella
<a name="dynamodb-expressions-query"></a>

L'esempio seguente include il metodo `Amazon.DynamoDBv2.AmazonDynamoDBClient.Query` e un set di espressioni per ottenere e quindi stampare l'item con un codice `Id` di `301`, ma solo se il valore del codice `Price` è maggiore di `150`. Solo i seguenti attributi dell'item vengono restituiti: `Id`, `Title` e tutti gli attributi di `ThreeStar` in `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("=====");
}
```

Nell'esempio precedente, la proprietà `ProjectionExpression` specifica gli attributi da restituire. La proprietà `ExpressionAttributeNames` specifica il segnaposto `#pr` per rappresentare l'attributo `ProductReviews` e il segnaposto `#p` per rappresentare l'attributo `Price`. `#pr.ThreeStar` specifica di restituire solo l'attributo `ThreeStar`. La proprietà `ExpressionAttributeValues` specifica il segnaposto `:val` per rappresentare il valore `150`. La proprietà `FilterExpression` specifica che `#p` (`Price`) deve essere maggiore di `:val` (`150`). La chiamata a `PrintItem` si riferisce a una funzione personalizzata come descritto in [Stampare un item](#dynamodb-expressions-print-item).

## Ottenere più item utilizzando le espressioni e altri attributi degli item
<a name="dynamodb-expressions-scan"></a>

L'esempio seguente include il metodo `Amazon.DynamoDBv2.AmazonDynamoDBClient.Scan` e un set di espressioni per ottenere e quindi stampare tutti gli item con un codice `ProductCategory` di `Bike`. Solo i seguenti attributi dell'item vengono restituiti: `Id`, `Title` e tutti gli attributi in `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("=====");
}
```

Nell'esempio precedente, la proprietà `ProjectionExpression` specifica gli attributi da restituire. La proprietà `ExpressionAttributeNames` specifica il segnaposto `#pr` per rappresentare l'attributo `ProductReviews` e il segnaposto `#pc` per rappresentare l'attributo `ProductCategory`. La proprietà `ExpressionAttributeValues` specifica il segnaposto `:catg` per rappresentare il valore `Bike`. La proprietà `FilterExpression` specifica che `#pc` (`ProductCategory`) deve essere uguale a `:catg` (`Bike`). La chiamata a `PrintItem` si riferisce a una funzione personalizzata come descritto in [Stampare un item](#dynamodb-expressions-print-item).

## Stampare un item
<a name="dynamodb-expressions-print-item"></a>

L'esempio seguente mostra come stampare gli attributi e i valori di un item. Questo esempio viene utilizzato negli esempi precedenti che mostrano come [ottenere un singolo item utilizzando le espressioni e la chiave primaria dell'item](#dynamodb-expressions-get-item), [ottenere più item utilizzando le espressioni e la chiave primaria della tabella](#dynamodb-expressions-query) e [ottenere più item utilizzando le espressioni e altri attributi degli item](#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");
}
```

Nell'esempio precedente, ogni valore di attributo ha diverse data-type-specific proprietà che possono essere valutate per determinare il formato corretto per stampare l'attributo. Queste proprietà includono `B`, `BOOL`, `BS`, `L`, `M`, `N`, `NS`, `NULL`, `S` e `SS`, che corrispondono a quelle nel [Formato di dati JSON](DataFormat.html). Per proprietà come `B`, `N`, `NULL` e `S`, se la proprietà corrispondente non è `null`, l'attributo è del corrispondente tipo di dati non-`null`. Per proprietà quali`BS`,,`L`, e `M` `NS``SS`, se `Count` è maggiore di zero, l'attributo è del tipo di non-zero-value dati corrispondente. Se tutte le data-type-specific proprietà dell'attributo sono `null` o sono `Count` uguali a zero, l'attributo corrisponde al tipo di `BOOL` dati.

## Creare o sostituire un item utilizzando le espressioni
<a name="dynamodb-expressions-put-item"></a>

L'esempio seguente include il metodo `Amazon.DynamoDBv2.AmazonDynamoDBClient.PutItem` e un set di espressioni per aggiornare l'item con un codice `Title` di `18-Bicycle 301`. Se l'item non esiste già, ne viene aggiunto uno nuovo.

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

Nell'esempio precedente, la proprietà `ExpressionAttributeNames` specifica il segnaposto `#title` per rappresentare l'attributo `Title`. La proprietà `ExpressionAttributeValues` specifica il segnaposto `:product` per rappresentare il valore `18-Bicycle 301`. La proprietà `ConditionExpression` specifica che `#title` (`Title`) deve essere uguale a `:product` (`18-Bicycle 301`). La chiamata al codice `CreateItemData` si riferisce alla seguente funzione personalizzata:

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

Nell'esempio precedente, viene restituito all'intermediario un item di esempio con dati campione. Una serie di attributi e valori corrispondenti vengono costruiti utilizzando tipi di dati come `BOOL`, `L`, `M`, `N`, `NS`, `S` e `SS`, che corrispondono a quelli nel [Formato di dati JSON](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/DataFormat.html).

## Aggiornare un item utilizzando le espressioni
<a name="dynamodb-expressions-update-item"></a>

L'esempio seguente include il metodo `Amazon.DynamoDBv2.AmazonDynamoDBClient.UpdateItem` e un set di espressioni per modificare il codice `Title` in `18" Girl's Bike` per l'item con un codice `Id` di `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);
```

Nell'esempio precedente, la proprietà `ExpressionAttributeNames` specifica il segnaposto `#title` per rappresentare l'attributo `Title`. La proprietà `ExpressionAttributeValues` specifica il segnaposto `:newproduct` per rappresentare il valore `18" Girl's Bike`. La proprietà `UpdateExpression` specifica di modificare il codice `#title` (`Title`) in `:newproduct` (`18" Girl's Bike`).

## Eliminare un item utilizzando le espressioni
<a name="dynamodb-expressions-delete-item"></a>

L'esempio seguente include il metodo `Amazon.DynamoDBv2.AmazonDynamoDBClient.DeleteItem` e un set di espressioni per eliminare il codice `Id` di `301` per l'item con un codice `Title` di `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);
```

Nell'esempio precedente, la proprietà `ExpressionAttributeNames` specifica il segnaposto `#title` per rappresentare l'attributo `Title`. La proprietà `ExpressionAttributeValues` specifica il segnaposto `:product` per rappresentare il valore `18-Bicycle 301`. La proprietà `ConditionExpression` specifica che `#title` (`Title`) deve essere uguale a `:product` (`18-Bicycle 301`).

## Ulteriori informazioni
<a name="dynamodb-expressions-resources"></a>

Per maggiori informazioni ed esempi di codice, consulta:
+  [DynamoDB Series - Expressions](http://blogs.aws.amazon.com/net/post/TxZQM7VA9AUZ9L/DynamoDB-Series-Expressions) 
+  [Accesso agli attributi degli item con le espressioni di proiezione](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Expressions.AccessingItemAttributes.html) 
+  [Utilizzo dei segnaposti per i nomi e i valori degli attributi](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/ExpressionPlaceholders.html) 
+  [Specifica delle condizioni con le espressioni di condizione](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Expressions.SpecifyingConditions.html) 
+  [Modifica di item e attributi con le espressioni di aggiornamento](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Expressions.Modifying.html) 
+  [Lavorare con gli elementi utilizzando l'API di basso livello AWS SDK per .NET](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/LowLevelDotNetItemCRUD.html) 
+  [Interrogazione di tabelle utilizzando l'API di basso livello AWS SDK per .NET](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/LowLevelDotNetQuerying.html) 
+  [Scansione di tabelle utilizzando l'API di basso livello AWS SDK per .NET](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/LowLevelDotNetScanning.html) 
+  [Utilizzo degli indici secondari locali utilizzando l'API di basso livello AWS SDK per .NET](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/LSILowLevelDotNet.html) 
+  [Utilizzo degli indici secondari globali utilizzando l'API di basso livello AWS SDK per .NET](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/GSILowLevelDotNet.html) 

# Supporto JSON in Amazon DynamoDB
<a name="dynamodb-json"></a>

**Nota**  
Le informazioni contenute in questo argomento si riferiscono specificamente ai progetti basati su.NET Framework e alla AWS SDK per .NET versione 3.3 e precedenti.

 AWS SDK per .NET Supporta i dati JSON quando si lavora con Amazon DynamoDB. Ciò consente di ottenere più facilmente dati in formato JSON e di inserire documenti JSON nelle tabelle DynamoDB.

**Topics**
+ [Ottieni dati da una tabella DynamoDB in formato JSON](#dynamodb-json-get-table-data)
+ [Inserimento di dati in formato JSON in una tabella DynamoDB](#dynamodb-json-insert-table-data)
+ [Conversioni dei tipi di dati DynamoDB in JSON](#dynamodb-json-datatypes)
+ [Ulteriori informazioni](#dynamodb-json-more-info)

## Ottieni dati da una tabella DynamoDB in formato JSON
<a name="dynamodb-json-get-table-data"></a>

L'esempio seguente mostra come ottenere dati da una tabella DynamoDB in formato 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
//   }
```

Nell'esempio precedente, il metodo `ToJson` della classe `Document` converte un elemento della tabella in una stringa in formato JSON. L'elemento viene recuperato con il metodo `GetItem` della classe `Table`. Per determinare l'elemento da ottenere, in questo esempio, il `GetItem` metodo utilizza la chiave hash-and-range primaria dell'elemento di destinazione. Per determinare la tabella da cui ottenere l'elemento, il `LoadTable` metodo della `Table` classe utilizza un'istanza della `AmazonDynamoDBClient` classe e il nome della tabella di destinazione in DynamoDB.

## Inserimento di dati in formato JSON in una tabella DynamoDB
<a name="dynamodb-json-insert-table-data"></a>

L'esempio seguente mostra come utilizzare il formato JSON per inserire un elemento in una tabella 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);
```

Nell'esempio precedente, il metodo `FromJson` della classe `Document` converte una stringa in formato JSON in un elemento. L'elemento viene inserito nella tabella con il metodo `PutItem` della classe `Table`, che utilizza l'istanza della classe `Document` che contiene l'elemento. Per determinare la tabella in cui inserire l'elemento, viene chiamato il `LoadTable` metodo della `Table` classe, specificando un'istanza della `AmazonDynamoDBClient` classe e il nome della tabella di destinazione in DynamoDB.

## Conversioni dei tipi di dati DynamoDB in JSON
<a name="dynamodb-json-datatypes"></a>

Ogni volta che si chiama il `ToJson` metodo della `Document` classe e quindi sui dati JSON risultanti si chiama il `FromJson` metodo per riconvertire i dati JSON in un'istanza di una `Document` classe, alcuni tipi di dati DynamoDB non verranno convertiti come previsto. Nello specifico:
+ I set DynamoDB (`SS`i tipi`NS`, `BS` e) verranno convertiti in array JSON.
+ Gli scalari e i set binari di DynamoDB (`B`i tipi `BS` and) verranno convertiti in stringhe o elenchi di stringhe JSON con codifica Base64.

  In questo scenario, devi chiamare il metodo `DecodeBase64Attributes` della classe `Document` per sostituire i dati JSON con codifica base64 con la corretta rappresentazione binaria. L'esempio seguente sostituisce un attributo dell'elemento scalare binario con codifica base64 in un'istanza di una classe `Document`, denominato `Picture`, con la corretta rappresentazione binaria. In questo esempio viene eseguita la stessa operazione per un attributo dell'elemento di un set binario con codifica base64 nella stessa istanza della classe `Document`, denominato `RelatedPictures`:

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

## Ulteriori informazioni
<a name="dynamodb-json-more-info"></a>

Per ulteriori informazioni ed esempi di programmazione JSON con DynamoDB con, vedi: AWS SDK per .NET
+  [Supporto JSON in DynamoDB](https://aws.amazon.com/blogs/developer/dynamodb-json-support/) 
+  [Aggiornamento di Amazon DynamoDB - JSON, piano gratuito ampliato, dimensionamento flessibile, elementi più grandi](https://aws.amazon.com/blogs/aws/dynamodb-update-json-and-more/) 

# Utilizzo di Amazon EC2
<a name="ec2-apis-intro"></a>

 AWS SDK per .NET Supporta [Amazon EC2](https://docs.aws.amazon.com/ec2/), un servizio Web che fornisce capacità di calcolo ridimensionabile. Utilizzi questa capacità di calcolo per creare e ospitare i tuoi sistemi software.

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

 AWS SDK per .NET Fornisce API per i client Amazon EC2. Le API consentono di lavorare con funzionalità EC2 come gruppi di sicurezza e coppie di chiavi. Le API consentono inoltre di controllare le istanze Amazon EC2. Questa sezione contiene un piccolo numero di esempi che mostrano i modelli che puoi seguire quando lavori con questi modelli. APIs Per visualizzare il set completo di APIs, consulta l'[AWS SDK per .NET API Reference](https://docs.aws.amazon.com/sdkfornet/v4/apidocs/) (e scorri fino a «Amazon.ec2").

Amazon EC2 è fornito dal APIs [AWSSDK NuGet pacchetto.EC2](https://www.nuget.org/packages/AWSSDK.EC2).

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

Prima di iniziare, assicurati di aver configurato [l'ambiente e [configurato](configuring-the-sdk.md) il](net-dg-config.md) progetto. Consulta anche le informazioni contenute in[Utilizzo di SDK](net-dg-sdk-features.md).

## Informazioni sugli esempi
<a name="ec2-apis-intro-about"></a>

Gli esempi in questa sezione mostrano come lavorare con i client Amazon EC2 e gestire le istanze Amazon EC2.

Il [tutorial sulle istanze Spot di EC2](how-to-spot-instances.md) mostra come richiedere istanze Spot di Amazon EC2. Le istanze Spot ti consentono di accedere alla capacità EC2 inutilizzata a un prezzo inferiore a quello offerto su richiesta.

**Topics**
+ [APIs](#w2aac19c15c21b5)
+ [Prerequisiti](#w2aac19c15c21b7)
+ [Informazioni sugli esempi](#ec2-apis-intro-about)
+ [Gruppi di sicurezza](security-groups.md)
+ [Key pairs (Coppie di chiavi)](key-pairs.md)
+ [Regioni e zone di disponibilità](using-regions-and-availability-zones.md)
+ [Istanze EC2](how-to-ec2.md)
+ [Tutorial sulle istanze Spot](how-to-spot-instances.md)

# Lavorare con i gruppi di sicurezza in Amazon EC2
<a name="security-groups"></a>

In Amazon EC2, un *gruppo di sicurezza* funge da firewall virtuale che controlla il traffico di rete per una o più istanze EC2. Per impostazione predefinita, EC2 associa le istanze a un gruppo di sicurezza che non consente il traffico in entrata. È possibile creare un gruppo di sicurezza che consente alle istanze EC2 di accettare un determinato traffico. Ad esempio, se hai bisogno di connetterti a un'istanza Windows EC2, devi configurare il gruppo di sicurezza per consentire il traffico RDP.

Per ulteriori informazioni sui gruppi di sicurezza, consulta i gruppi di [sicurezza di Amazon EC2](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-security-groups.html) nella [Amazon EC2](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/) User Guide.

**avvertimento**  
EC2-Classic è stato ritirato il 15 agosto 2022. Suggeriamo di effettuare la migrazione da EC2-Classic a un VPC. Per ulteriori informazioni, consulta il post del blog [EC2-Classic Networking is Retiring: ecco](https://aws.amazon.com/blogs/aws/ec2-classic-is-retiring-heres-how-to-prepare/) come prepararsi.

Per informazioni su APIs e prerequisiti, consulta la sezione principale (). [Utilizzo di Amazon EC2](ec2-apis-intro.md)

**Topics**
+ [Enumerazione dei gruppi di sicurezza](enumerate-security-groups.md)
+ [Creazione dei gruppi di sicurezza](creating-security-group.md)
+ [Aggiornamento dei gruppi di sicurezza](authorize-ingress.md)

# Enumerazione dei gruppi di sicurezza
<a name="enumerate-security-groups"></a>

Questo esempio mostra come utilizzare per AWS SDK per .NET enumerare i gruppi di sicurezza. Se fornisci un [Amazon Virtual Private Cloud](https://docs.aws.amazon.com/vpc/latest/userguide/) ID, l'applicazione enumera i gruppi di sicurezza per quel particolare VPC. Altrimenti, l'applicazione visualizza semplicemente un elenco di tutti i gruppi di sicurezza disponibili.

Le sezioni seguenti forniscono frammenti di questo esempio. Successivamente viene mostrato [il codice completo dell'esempio](#enum-sec-groups-complete-code), che può essere creato ed eseguito così com'è.

**Topics**
+ [Enumera i gruppi di sicurezza](#enum-sec-groups-enum)
+ [Codice completo](#enum-sec-groups-complete-code)
+ [Ulteriori considerazioni](#enum-sec-groups-additional)

## Enumera i gruppi di sicurezza
<a name="enum-sec-groups-enum"></a>

Il seguente frammento enumera i tuoi gruppi di sicurezza. Enumera tutti i gruppi o i gruppi per un particolare VPC, se ne viene fornito uno.

L'esempio [alla fine di questo argomento mostra questo frammento](#enum-sec-groups-complete-code) in uso.

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

## Codice completo
<a name="enum-sec-groups-complete-code"></a>

Questa sezione mostra i riferimenti pertinenti e il codice completo per questo esempio.

### Riferimenti SDK
<a name="w2aac19c15c21c13c13c15b5b1"></a>

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

Elementi di programmazione:
+ [Spazio dei nomi Amazon.ec2](https://docs.aws.amazon.com/sdkfornet/v4/apidocs/items/EC2/NEC2.html)

  Classe [Amazon EC2 Client](https://docs.aws.amazon.com/sdkfornet/v4/apidocs/items/EC2/TEC2Client.html)
+ [Spazio dei nomi Amazon.ec2.model](https://docs.aws.amazon.com/sdkfornet/v4/apidocs/items/EC2/NEC2Model.html)

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

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

  [Filtro](https://docs.aws.amazon.com/sdkfornet/v4/apidocs/items/EC2/TFilter.html) di classe

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

### Il codice
<a name="w2aac19c15c21c13c13c15b7b1"></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();
      }
    }
  }
}
```

## Ulteriori considerazioni
<a name="enum-sec-groups-additional"></a>
+ Nota per il caso VPC che il filtro è costruito con la `Name` parte della coppia nome-valore impostata su «vpc-id». Questo nome deriva dalla descrizione della proprietà della classe. `Filters` [DescribeSecurityGroupsRequest](https://docs.aws.amazon.com/sdkfornet/v4/apidocs/items/EC2/TDescribeSecurityGroupsRequest.html)
+ Per ottenere l'elenco completo dei tuoi gruppi di sicurezza, puoi anche utilizzarlo [ DescribeSecurityGroupsAsync senza parametri](https://docs.aws.amazon.com/sdkfornet/v4/apidocs/items/EC2/MEC2DescribeSecurityGroupsAsyncCancellationToken.html).
+ Puoi verificare i risultati controllando l'elenco dei gruppi di sicurezza nella console [Amazon EC2](https://console.aws.amazon.com/ec2/v2/home#SecurityGroups).

# Creazione dei gruppi di sicurezza
<a name="creating-security-group"></a>

Questo esempio mostra come utilizzare il per AWS SDK per .NET creare un gruppo di sicurezza. Puoi fornire l'ID di un VPC esistente per creare un gruppo di sicurezza per EC2 in un VPC. Se non fornisci tale ID, il nuovo gruppo di sicurezza sarà destinato a EC2-Classic, se il tuo account lo supporta. AWS 

Se non fornisci un ID VPC e il tuo AWS account non supporta EC2-Classic, il nuovo gruppo di sicurezza apparterrà al VPC predefinito del tuo account.

**avvertimento**  
EC2-Classic è stato ritirato il 15 agosto 2022. Suggeriamo di effettuare la migrazione da EC2-Classic a un VPC. Per ulteriori informazioni, consulta il post del blog [EC2-Classic Networking is Retiring](https://aws.amazon.com/blogs/aws/ec2-classic-is-retiring-heres-how-to-prepare/) — Ecco come prepararsi.

Le sezioni seguenti forniscono frammenti di questo esempio. Successivamente viene mostrato [il codice completo dell'esempio](#create-sec-groups-complete-code), che può essere creato ed eseguito così com'è.

**Topics**
+ [Trova i gruppi di sicurezza esistenti](#create-sec-groups-find)
+ [Creare un gruppo di sicurezza](#create-sec-groups-enum)
+ [Codice completo](#create-sec-groups-complete-code)

## Trova i gruppi di sicurezza esistenti
<a name="create-sec-groups-find"></a>

Il seguente frammento cerca i gruppi di sicurezza esistenti con il nome specificato nel VPC specificato.

L'esempio [alla fine di questo argomento mostra questo frammento](#create-sec-groups-complete-code) in uso.

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

## Creare un gruppo di sicurezza
<a name="create-sec-groups-enum"></a>

Il seguente frammento di codice crea un nuovo gruppo di sicurezza se un gruppo con quel nome non esiste nel VPC specificato. Se non viene fornito alcun VPC ed esistono uno o più gruppi con quel nome, lo snippet restituisce semplicemente l'elenco dei gruppi.

L'esempio [alla fine di questo argomento mostra questo](#create-sec-groups-complete-code) frammento in uso.

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

## Codice completo
<a name="create-sec-groups-complete-code"></a>

Questa sezione mostra i riferimenti pertinenti e il codice completo per questo esempio.

### Riferimenti SDK
<a name="w2aac19c15c21c13c15c23b5b1"></a>

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

Elementi di programmazione:
+ [Spazio dei nomi Amazon.ec2](https://docs.aws.amazon.com/sdkfornet/v4/apidocs/items/EC2/NEC2.html)

  Classe [Amazon EC2 Client](https://docs.aws.amazon.com/sdkfornet/v4/apidocs/items/EC2/TEC2Client.html)
+ [Spazio dei nomi Amazon.ec2.model](https://docs.aws.amazon.com/sdkfornet/v4/apidocs/items/EC2/NEC2Model.html)

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

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

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

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

  [Filtro](https://docs.aws.amazon.com/sdkfornet/v4/apidocs/items/EC2/TFilter.html) di classe

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

### Il codice
<a name="w2aac19c15c21c13c15c23b7b1"></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);
    }
  }

}
```

# Aggiornamento dei gruppi di sicurezza
<a name="authorize-ingress"></a>

Questo esempio mostra come utilizzare per aggiungere una regola a un gruppo di sicurezza. AWS SDK per .NET In particolare, l'esempio aggiunge una regola per consentire il traffico in entrata su una determinata porta TCP, che può essere utilizzata, ad esempio, per le connessioni remote a un'istanza EC2. L'applicazione richiede l'ID di un gruppo di sicurezza esistente, un indirizzo IP (o intervallo di indirizzi) in formato CIDR e, facoltativamente, un numero di porta TCP. Quindi aggiunge una regola in entrata al gruppo di sicurezza specificato.

**Nota**  
Per utilizzare questo esempio, è necessario un indirizzo IP (o intervallo di indirizzi) in formato CIDR. Per informazioni sui metodi per ottenere l'indirizzo IP del computer locale, vedere **Considerazioni aggiuntive** a questa fine di questo argomento.

Le sezioni seguenti forniscono frammenti di questo esempio. Successivamente viene mostrato [il codice completo dell'esempio](#authorize-ingress-complete-code), che può essere creato ed eseguito così com'è.

**Topics**
+ [Aggiungi una regola in entrata](#authorize-ingress-add-rule)
+ [Codice completo](#authorize-ingress-complete-code)
+ [Ulteriori considerazioni](#authorize-ingress-additional)

## Aggiungi una regola in entrata
<a name="authorize-ingress-add-rule"></a>

Il seguente frammento aggiunge una regola in entrata a un gruppo di sicurezza per un particolare indirizzo IP (o intervallo) e una porta TCP.

L'esempio [alla fine di questo argomento mostra questo frammento](#authorize-ingress-complete-code) in uso.

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

## Codice completo
<a name="authorize-ingress-complete-code"></a>

Questa sezione mostra i riferimenti pertinenti e il codice completo per questo esempio.

### Riferimenti SDK
<a name="w2aac19c15c21c13c17c17b5b1"></a>

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

Elementi di programmazione:
+ [Spazio dei nomi Amazon.ec2](https://docs.aws.amazon.com/sdkfornet/v4/apidocs/items/EC2/NEC2.html)

  Classe [Amazon EC2 Client](https://docs.aws.amazon.com/sdkfornet/v4/apidocs/items/EC2/TEC2Client.html)
+ [Spazio dei nomi Amazon.ec2.model](https://docs.aws.amazon.com/sdkfornet/v4/apidocs/items/EC2/NEC2Model.html)

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

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

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

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

### Il codice
<a name="w2aac19c15c21c13c17c17b7b1"></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);
    }
  }

}
```

## Ulteriori considerazioni
<a name="authorize-ingress-additional"></a>
+ Se non si fornisce un numero di porta, per impostazione predefinita l'applicazione utilizza la porta 3389. Questa è la porta per Windows RDP, che consente di connettersi a un'istanza EC2 che esegue Windows. Se stai avviando un'istanza EC2 che esegue Linux, puoi invece utilizzare la porta TCP 22 (SSH).
+ Nota che l'esempio è impostato su «tcp»`IpProtocol`. I valori di `IpProtocol` possono essere trovati nella descrizione della `IpProtocol` proprietà della [IpPermission](https://docs.aws.amazon.com/sdkfornet/v4/apidocs/items/EC2/TIpPermission.html)classe.
+ Quando usi questo esempio, potresti volere l'indirizzo IP del tuo computer locale. Di seguito sono riportati alcuni dei modi in cui è possibile ottenere l'indirizzo.
  + Se il tuo computer locale (da cui ti connetterai alla tua istanza EC2) ha un indirizzo IP pubblico statico, puoi utilizzare un servizio per ottenere quell'indirizzo. Uno di questi servizi è [http://checkip.amazonaws.com/](http://checkip.amazonaws.com/). Per ulteriori informazioni sull'autorizzazione del traffico in entrata, consulta [Aggiungere regole a un gruppo di sicurezza e Regole del gruppo](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/working-with-security-groups.html#adding-security-group-rule) [di sicurezza per diversi casi d'uso](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/security-group-rules-reference.html) nella Guida per l'utente di [Amazon EC2](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/).
  + Un altro modo per ottenere l'indirizzo IP del computer locale consiste nell'utilizzare la console [Amazon EC2](https://console.aws.amazon.com/ec2/v2/home#SecurityGroups).

    Seleziona uno dei tuoi gruppi di sicurezza, seleziona la scheda **Regole in entrata e scegli Modifica regole** **in** entrata. In una regola in entrata, apri il menu a discesa nella colonna **Origine** e scegli Il **mio IP per visualizzare l'indirizzo IP** del tuo computer locale in formato CIDR. **Assicurati di annullare l'operazione.**
+ Puoi verificare i risultati di questo esempio esaminando l'elenco dei gruppi di sicurezza nella console [Amazon EC2](https://console.aws.amazon.com/ec2/v2/home#SecurityGroups).

# Utilizzo delle coppie di chiavi Amazon EC2
<a name="key-pairs"></a>

Amazon EC2 utilizza la crittografia a chiave pubblica per crittografare e decrittografare le informazioni di accesso. La crittografia a chiave pubblica utilizza una chiave pubblica per crittografare i dati, quindi il destinatario utilizza la chiave privata per decrittografare i dati. La chiave pubblica e quella privata sono note come coppia di chiavi. Se desideri accedere a un'istanza EC2, devi specificare una coppia di chiavi all'avvio e quindi fornire la chiave privata della coppia quando ti connetti ad essa.

Quando avvii un'istanza EC2, puoi creare una key pair per essa o usarne una che hai già usato per lanciare altre istanze. Per ulteriori informazioni sulle coppie di chiavi Amazon EC2, consulta [Working with Amazon EC2 key pairs nella Amazon EC2](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-key-pairs.html) User [Guide](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/).

Per informazioni su APIs e prerequisiti, consulta la sezione principale (). [Utilizzo di Amazon EC2](ec2-apis-intro.md)

**Topics**
+ [Creazione e visualizzazione di coppie di chiavi](create-save-key-pair.md)
+ [Eliminazione di coppie di chiavi](delete-key-pairs.md)

# Creazione e visualizzazione di coppie di chiavi
<a name="create-save-key-pair"></a>

Questo esempio mostra come utilizzare AWS SDK per .NET per creare una key pair. L'applicazione prende il nome per la nuova coppia di chiavi e il nome di un file PEM (con estensione «.pem»). Crea la coppia di chiavi, scrive la chiave privata nel file PEM e quindi visualizza tutte le coppie di chiavi disponibili. Se non si forniscono argomenti della riga di comando, l'applicazione visualizza semplicemente tutte le coppie di chiavi disponibili.

Le sezioni seguenti forniscono frammenti di questo esempio. Successivamente viene mostrato [il codice completo dell'esempio](#create-save-key-pair-complete-code), che può essere creato ed eseguito così com'è.

**Topics**
+ [Creazione della coppia di chiavi](#create-save-key-pair-create)
+ [Visualizza le coppie di chiavi disponibili](#create-save-key-pair-display)
+ [Codice completo](#create-save-key-pair-complete-code)
+ [Ulteriori considerazioni](#create-save-key-pair-additional)

## Creazione della coppia di chiavi
<a name="create-save-key-pair-create"></a>

Il seguente frammento crea una coppia di chiavi e quindi memorizza la chiave privata nel file PEM specificato.

L'esempio [alla fine di questo argomento mostra questo](#create-save-key-pair-complete-code) frammento in uso.

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

## Visualizza le coppie di chiavi disponibili
<a name="create-save-key-pair-display"></a>

Il seguente frammento mostra un elenco delle coppie di chiavi disponibili.

L'esempio [alla fine di questo argomento mostra questo](#create-save-key-pair-complete-code) frammento in uso.

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

## Codice completo
<a name="create-save-key-pair-complete-code"></a>

Questa sezione mostra i riferimenti pertinenti e il codice completo per questo esempio.

### Riferimenti SDK
<a name="w2aac19c15c21c15c11c19b5b1"></a>

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

Elementi di programmazione:
+ [Spazio dei nomi Amazon.ec2](https://docs.aws.amazon.com/sdkfornet/v4/apidocs/items/EC2/NEC2.html)

  Classe [Amazon EC2 Client](https://docs.aws.amazon.com/sdkfornet/v4/apidocs/items/EC2/TEC2Client.html)
+ [Spazio dei nomi Amazon.ec2.model](https://docs.aws.amazon.com/sdkfornet/v4/apidocs/items/EC2/NEC2Model.html)

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

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

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

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

### Il codice
<a name="w2aac19c15c21c15c11c19b7b1"></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);
    }
  }

}
```

## Ulteriori considerazioni
<a name="create-save-key-pair-additional"></a>
+ Dopo aver eseguito l'esempio, puoi vedere la nuova coppia di key nella console [Amazon EC2](https://console.aws.amazon.com/ec2/#KeyPairs).
+ Quando si crea una coppia di chiavi, è necessario salvare la chiave privata restituita perché non è possibile recuperarla in un secondo momento.

# Eliminazione di coppie di chiavi
<a name="delete-key-pairs"></a>

Questo esempio mostra come utilizzare AWS SDK per .NET per eliminare una key pair. L'applicazione prende il nome di una key pair. Elimina la coppia di chiavi e quindi visualizza tutte le coppie di chiavi disponibili. Se non si forniscono argomenti nella riga di comando, l'applicazione visualizza semplicemente tutte le coppie di chiavi disponibili.

Le sezioni seguenti forniscono frammenti di questo esempio. Successivamente viene mostrato [il codice completo dell'esempio](#delete-key-pairs-complete-code), che può essere creato ed eseguito così com'è.

**Topics**
+ [Elimina la coppia di chiavi](#delete-key-pairs-create)
+ [Visualizza le coppie di chiavi disponibili](#delete-key-pairs-display)
+ [Codice completo](#delete-key-pairs-complete-code)

## Elimina la coppia di chiavi
<a name="delete-key-pairs-create"></a>

Il seguente frammento elimina una key pair.

L'esempio [alla fine di questo argomento mostra questo](#delete-key-pairs-complete-code) frammento in uso.

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

## Visualizza le coppie di chiavi disponibili
<a name="delete-key-pairs-display"></a>

Il seguente frammento mostra un elenco delle coppie di chiavi disponibili.

L'esempio [alla fine di questo argomento mostra questo](#delete-key-pairs-complete-code) frammento in uso.

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

## Codice completo
<a name="delete-key-pairs-complete-code"></a>

Questa sezione mostra i riferimenti pertinenti e il codice completo per questo esempio.

### Riferimenti SDK
<a name="w2aac19c15c21c15c13c19b5b1"></a>

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

Elementi di programmazione:
+ [Spazio dei nomi Amazon.ec2](https://docs.aws.amazon.com/sdkfornet/v4/apidocs/items/EC2/NEC2.html)

  Classe [Amazon EC2 Client](https://docs.aws.amazon.com/sdkfornet/v4/apidocs/items/EC2/TEC2Client.html)
+ [Spazio dei nomi Amazon.ec2.model](https://docs.aws.amazon.com/sdkfornet/v4/apidocs/items/EC2/NEC2Model.html)

  Classe [https://docs.aws.amazon.com/sdkfornet/v4/apidocs/](https://docs.aws.amazon.com/sdkfornet/v4/apidocs/)

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

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

### Il codice
<a name="w2aac19c15c21c15c13c19b7b1"></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}");
    }
  }
}
```

# Visualizzazione delle regioni e delle zone di disponibilità di Amazon EC2
<a name="using-regions-and-availability-zones"></a>

Amazon EC2 è ospitato in diverse località in tutto il mondo. Tali località sono composte da regioni e zone di disponibilità. Ogni regione è un'area geografica separata con più località isolate note come zone di disponibilità.

Per ulteriori informazioni su regioni e zone di disponibilità, consulta [Regioni e zone](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/using-regions-availability-zones.html) nella Guida per l'[utente di Amazon EC2](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/).

Questo esempio mostra come utilizzare il per AWS SDK per .NET ottenere dettagli sulle regioni e le zone di disponibilità relative a un client EC2. L'applicazione visualizza gli elenchi delle regioni e delle zone di disponibilità disponibili per un client EC2.

## Riferimenti SDK
<a name="w2aac19c15c21c17b9b1"></a>

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

Elementi di programmazione:
+ [Spazio dei nomi Amazon.ec2](https://docs.aws.amazon.com/sdkfornet/v4/apidocs/items/EC2/NEC2.html)

  Classe [Amazon EC2 Client](https://docs.aws.amazon.com/sdkfornet/v4/apidocs/items/EC2/TEC2Client.html)
+ [Spazio dei nomi Amazon.ec2.model](https://docs.aws.amazon.com/sdkfornet/v4/apidocs/items/EC2/NEC2Model.html)

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

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

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

  [Regione](https://docs.aws.amazon.com/sdkfornet/v4/apidocs/items/EC2/TRegion.html) della classe

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

# Utilizzo delle istanze Amazon EC2
<a name="how-to-ec2"></a>

Puoi utilizzarlo AWS SDK per .NET per controllare le istanze Amazon EC2 con operazioni come creazione, avvio e terminazione. Gli argomenti di questa sezione forniscono alcuni esempi di come eseguire questa operazione. [Per ulteriori informazioni sulle istanze EC2, consulta le istanze Amazon [EC2 nella Amazon EC2](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Instances.html) User Guide.](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/)

Per informazioni su APIs e prerequisiti, consulta la sezione principale (). [Utilizzo di Amazon EC2](ec2-apis-intro.md)

**Topics**
+ [Avvio di un'istanza EC2](run-instance.md)
+ [Terminazione di un'istanza EC2](terminate-instance.md)

# Avvio di un'istanza Amazon EC2
<a name="run-instance"></a>

Questo esempio mostra come utilizzare AWS SDK per .NET per avviare una o più istanze Amazon EC2 configurate in modo identico dalla stessa Amazon Machine Image (AMI). Utilizzando [diversi input forniti](#run-instance-gather), l'applicazione avvia un'istanza EC2 e quindi monitora l'istanza fino a quando non esce dallo stato «In sospeso».

Quando l'istanza EC2 è in esecuzione, puoi connetterti ad essa in remoto, come descritto in. [(opzionale) Connect all'istanza](#connect-to-instance)

**avvertimento**  
EC2-Classic è stato ritirato il 15 agosto 2022. Suggeriamo di effettuare la migrazione da EC2-Classic a un VPC. Per ulteriori informazioni, consulta il post del blog [EC2-Classic Networking is Retiring — Ecco](https://aws.amazon.com/blogs/aws/ec2-classic-is-retiring-heres-how-to-prepare/) come prepararsi.

Le sezioni seguenti forniscono frammenti e altre informazioni per questo esempio. Il [codice completo dell'esempio](#run-instance-complete-code) viene mostrato dopo gli snippet e può essere creato ed eseguito così com'è.

**Topics**
+ [Raccogli ciò di cui hai bisogno](#run-instance-gather)
+ [Avvio di un'istanza](#run-instance-launch)
+ [Monitora l'istanza](#run-instance-monitor)
+ [Codice completo](#run-instance-complete-code)
+ [Ulteriori considerazioni](#run-instance-additional)
+ [(opzionale) Connect all'istanza](#connect-to-instance)
+ [Eliminazione](#run-instance-cleanup)

## Raccogli ciò di cui hai bisogno
<a name="run-instance-gather"></a>

Per avviare un'istanza EC2, avrai bisogno di diversi elementi.
+ Un [VPC](https://docs.aws.amazon.com/vpc/latest/userguide/) in cui verrà avviata l'istanza. Se si tratta di un'istanza Windows e ti connetterai ad essa tramite RDP, molto probabilmente il VPC dovrà avere un gateway Internet collegato, oltre a una voce per il gateway Internet nella tabella delle rotte. Per ulteriori informazioni, consulta [Gateway Internet](https://docs.aws.amazon.com/vpc/latest/userguide/VPC_Internet_Gateway.html) nella *Guida per l’utente di Amazon VPC*.
+ L'ID di una sottorete esistente nel VPC in cui verrà avviata l'istanza. Un modo semplice per trovarlo o crearlo è accedere alla [console Amazon VPC](https://console.aws.amazon.com/vpc/home#subnets), ma puoi anche ottenerlo a livello di codice utilizzando i metodi and. [CreateSubnetAsync[DescribeSubnetsAsync](https://docs.aws.amazon.com/sdkfornet/v4/apidocs/items/EC2/MEC2DescribeSubnetsAsyncDescribeSubnetsRequestCancellationToken.html)](https://docs.aws.amazon.com/sdkfornet/v4/apidocs/items/EC2/MEC2CreateSubnetAsyncCreateSubnetRequestCancellationToken.html)
**Nota**  
Se non fornisci questo parametro, la nuova istanza viene avviata nel VPC predefinito per il tuo account.
+ L'ID di un gruppo di sicurezza esistente che appartiene al VPC in cui verrà avviata l'istanza. Per ulteriori informazioni, consulta [Lavorare con i gruppi di sicurezza in Amazon EC2](security-groups.md).
+ Se desideri connetterti alla nuova istanza, il gruppo di sicurezza menzionato in precedenza deve disporre di una regola in entrata appropriata che consenta il traffico SSH sulla porta 22 (istanza Linux) o il traffico RDP sulla porta 3389 (istanza Windows). Per informazioni su come eseguire questa operazione[Aggiornamento dei gruppi di sicurezza](authorize-ingress.md), consulta anche la parte finale [Ulteriori considerazioni](authorize-ingress.md#authorize-ingress-additional) dell'argomento.
+ L'Amazon Machine Image (AMI) che verrà utilizzata per creare l'istanza. Per informazioni su AMIs, consulta [Amazon Machine Images (AMIs)](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/AMIs.html) nella Guida per l'[utente di Amazon EC2](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/). In particolare, vedi [Find an AMI](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/finding-an-ami.html) and [Shared AMIs](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/sharing-amis.html).
+ Il nome di una coppia di key pair EC2 esistente, utilizzata per connettersi alla nuova istanza. Per ulteriori informazioni, consulta [Utilizzo delle coppie di chiavi Amazon EC2](key-pairs.md).
+ Il nome del file PEM che contiene la chiave privata della coppia di chiavi EC2 menzionata in precedenza. Il file PEM viene utilizzato quando ci si [connette in remoto](#connect-to-instance) all'istanza.

## Avvio di un'istanza
<a name="run-instance-launch"></a>

Il seguente frammento avvia un'istanza EC2.

L'esempio [alla fine di questo argomento mostra questo frammento](#run-instance-complete-code) in uso.

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

## Monitora l'istanza
<a name="run-instance-monitor"></a>

Il seguente frammento monitora l'istanza fino a quando non esce dallo stato «In sospeso».

L'esempio [alla fine di questo argomento mostra questo frammento](#run-instance-complete-code) in uso.

Consultate la [InstanceState](https://docs.aws.amazon.com/sdkfornet/v4/apidocs/items/EC2/TInstanceState.html)classe per i valori validi della `Instance.State.Code` proprietà.

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

## Codice completo
<a name="run-instance-complete-code"></a>

Questa sezione mostra i riferimenti pertinenti e il codice completo per questo esempio.

### Riferimenti SDK
<a name="w2aac19c15c21c19b9c27b5b1"></a>

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

Elementi di programmazione:
+ [Spazio dei nomi Amazon.ec2](https://docs.aws.amazon.com/sdkfornet/v4/apidocs/items/EC2/NEC2.html)

  Classe [Amazon EC2 Client](https://docs.aws.amazon.com/sdkfornet/v4/apidocs/items/EC2/TEC2Client.html)

  Classe [InstanceType](https://docs.aws.amazon.com/sdkfornet/v4/apidocs/items/EC2/TInstanceType.html)
+ [Spazio dei nomi Amazon.ec2.model](https://docs.aws.amazon.com/sdkfornet/v4/apidocs/items/EC2/NEC2Model.html)

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

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

  [Istanza](https://docs.aws.amazon.com/sdkfornet/v4/apidocs/items/EC2/TInstance.html) di classe

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

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

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

### Il codice
<a name="w2aac19c15c21c19b9c27b7b1"></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);
    }
  }

}
```

## Ulteriori considerazioni
<a name="run-instance-additional"></a>
+ Quando controlli lo stato di un'istanza EC2, puoi aggiungere un filtro alla `Filter` proprietà dell'[DescribeInstancesRequest](https://docs.aws.amazon.com/sdkfornet/v4/apidocs/items/EC2/TDescribeInstancesRequest.html)oggetto. Utilizzando questa tecnica, puoi limitare la richiesta a determinate istanze; ad esempio, istanze con un particolare tag specificato dall'utente.
+ Per brevità, ad alcune proprietà sono stati assegnati valori tipici. Alcune o tutte queste proprietà possono invece essere determinate a livello di codice o tramite l'input dell'utente.
+ I valori che è possibile utilizzare per l'[RunInstancesRequest](https://docs.aws.amazon.com/sdkfornet/v4/apidocs/items/EC2/TRunInstancesRequest.html)oggetto `MinCount` e `MaxCount` le proprietà sono determinati dalla zona di disponibilità di destinazione e dal numero massimo di istanze consentite per il tipo di istanza. Per ulteriori informazioni, consulta [Quante istanze posso eseguire in Amazon EC2 nelle](https://aws.amazon.com/ec2/faqs/#How_many_instances_can_I_run_in_Amazon_EC2) Domande frequenti generali di Amazon EC2.
+ Se desideri utilizzare un tipo di istanza diverso da questo esempio, ci sono diversi tipi di istanza tra cui scegliere. Per ulteriori informazioni, consulta i [tipi di istanze di Amazon EC2](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instance-types.html) nella [Amazon EC2](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/) User Guide. Consulta anche [Instance Type Details](https://aws.amazon.com/ec2/instance-types/) e [Instance Type Explorer](https://aws.amazon.com/ec2/instance-explorer/).
+ Puoi anche assegnare un [ruolo IAM](net-dg-hosm.md) a un'istanza al momento del lancio. A tale scopo, crea un [IamInstanceProfileSpecification](https://docs.aws.amazon.com/sdkfornet/v4/apidocs/items/EC2/TIamInstanceProfileSpecification.html)oggetto la cui `Name` proprietà è impostata sul nome di un ruolo IAM. Quindi aggiungi quell'oggetto alla `IamInstanceProfile` proprietà dell'[RunInstancesRequest](https://docs.aws.amazon.com/sdkfornet/v4/apidocs/items/EC2/TRunInstancesRequest.html)oggetto.
**Nota**  
Per avviare un'istanza EC2 a cui è associato un ruolo IAM, la configurazione di un utente IAM deve includere determinate autorizzazioni. Per ulteriori informazioni sulle autorizzazioni richieste, consulta la sezione [Concedere l'autorizzazione a un utente per passare un ruolo IAM a un'istanza](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/iam-roles-for-amazon-ec2.html#permission-to-pass-iam-roles) nella [Amazon EC2](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/) User Guide.

## (opzionale) Connect all'istanza
<a name="connect-to-instance"></a>

Dopo l'esecuzione di un'istanza, puoi connetterti ad essa in remoto utilizzando il client remoto appropriato. Sia per le istanze Linux che per quelle Windows, è necessario l'indirizzo IP pubblico o il nome DNS pubblico dell'istanza. È inoltre necessario quanto segue.

**Per istanze Linux**

Puoi usare un client SSH per connetterti alla tua istanza Linux. Assicurati che il gruppo di sicurezza utilizzato all'avvio dell'istanza consenta il traffico SSH sulla porta 22, come descritto in. [Aggiornamento dei gruppi di sicurezza](authorize-ingress.md)

È inoltre necessaria la parte privata della coppia di chiavi utilizzata per avviare l'istanza, ovvero il file PEM.

Per ulteriori informazioni, consulta [Connect to your Linux istance](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/connect-to-linux-instance.html) nella Amazon EC2 User Guide.

**Per le istanze Windows**

Puoi utilizzare un client RDP per connetterti alla tua istanza. Assicurati che il gruppo di sicurezza utilizzato all'avvio dell'istanza consenta il traffico RDP sulla porta 3389, come descritto in. [Aggiornamento dei gruppi di sicurezza](authorize-ingress.md)

È inoltre necessaria la password dell'amministratore. È possibile ottenere ciò utilizzando il seguente codice di esempio, che richiede l'ID dell'istanza e la parte privata della coppia di chiavi utilizzata per avviare l'istanza, ovvero il file PEM.

Per ulteriori informazioni, consulta [Connect to your Windows nella](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/connecting_to_windows_instance.html) Amazon EC2 User Guide.

**avvertimento**  
Questo codice di esempio restituisce la password di amministratore in testo semplice per l'istanza.

### Riferimenti SDK
<a name="w2aac19c15c21c19b9c35c23b1"></a>

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

Elementi di programmazione:
+ [Spazio dei nomi Amazon.ec2](https://docs.aws.amazon.com/sdkfornet/v4/apidocs/items/EC2/NEC2.html)

  Classe [Amazon EC2 Client](https://docs.aws.amazon.com/sdkfornet/v4/apidocs/items/EC2/TEC2Client.html)
+ [Spazio dei nomi Amazon.ec2.model](https://docs.aws.amazon.com/sdkfornet/v4/apidocs/items/EC2/NEC2Model.html)

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

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

### Il codice
<a name="w2aac19c15c21c19b9c35c25b1"></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);
    }
  }

}
```

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

Quando non hai più bisogno della tua istanza EC2, assicurati di terminarla, come descritto in. [Terminazione di un'istanza Amazon EC2](terminate-instance.md)

# Terminazione di un'istanza Amazon EC2
<a name="terminate-instance"></a>

Quando non hai più bisogno di una o più istanze Amazon EC2, puoi terminarle.

Questo esempio mostra come utilizzare per AWS SDK per .NET terminare le istanze EC2. Richiede un ID di istanza come input.

## Riferimenti SDK
<a name="w2aac19c15c21c19c11b7b1"></a>

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

Elementi di programmazione:
+ [Spazio dei nomi Amazon.ec2](https://docs.aws.amazon.com/sdkfornet/v4/apidocs/items/EC2/NEC2.html)

  Classe [Amazon EC2 Client](https://docs.aws.amazon.com/sdkfornet/v4/apidocs/items/EC2/TEC2Client.html)
+ [Spazio dei nomi Amazon.ec2.model](https://docs.aws.amazon.com/sdkfornet/v4/apidocs/items/EC2/NEC2Model.html)

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

  Classe [TerminateInstancesResponse](https://docs.aws.amazon.com/sdkfornet/v4/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);
      }
    }
  }
}
```

Dopo aver eseguito l'esempio, è consigliabile accedere alla [console Amazon EC2](https://console.aws.amazon.com/ec2/) per verificare che l'[istanza EC2](https://console.aws.amazon.com/ec2/v2/home#Instances) sia stata terminata.

# Tutorial sull'istanza Spot di Amazon EC2
<a name="how-to-spot-instances"></a>

Questo tutorial mostra come utilizzarlo per AWS SDK per .NET gestire le istanze Spot di Amazon EC2.

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

Le istanze Spot consentono di richiedere capacità Amazon EC2 inutilizzata a un prezzo inferiore al prezzo On-Demand. Ciò può ridurre in modo significativo i costi EC2 per le applicazioni che possono essere interrotte.

Di seguito è riportato un riepilogo di alto livello di come le istanze Spot vengono richieste e utilizzate.

1. Crea una richiesta di istanza Spot, specificando il prezzo massimo che sei disposto a pagare.

1. Una volta soddisfatta la richiesta, esegui l'istanza come faresti con qualsiasi altra istanza Amazon EC2.

1. Esegui l'istanza per tutto il tempo che desideri e poi chiudila, a meno che il *prezzo Spot* non cambi in modo tale che l'istanza venga interrotta per te.

1. Pulisci la richiesta dell'istanza Spot quando non è più necessaria, in modo che le istanze Spot non vengano più create.

Questa è stata una panoramica di altissimo livello sulle istanze Spot. Per comprendere meglio le istanze Spot, consulta le istanze [Spot nella Guida](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/using-spot-instances.html) per l'utente di [Amazon EC2](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/).

## Informazioni sul tutorial
<a name="about-spot-instances-tutorial"></a>

Mentre segui questo tutorial, usi il AWS SDK per .NET per fare quanto segue:
+ Creare una richiesta di istanza spot
+ Determina quando la richiesta di istanza Spot è stata soddisfatta
+ Annulla la richiesta di istanza Spot
+ Terminare le istanze associate

Le sezioni seguenti forniscono frammenti e altre informazioni per questo esempio. Il [codice completo dell'esempio](#tutor-spot-net-main) viene mostrato dopo gli snippet e può essere creato ed eseguito così com'è.

**Topics**
+ [Panoramica di](#tutor-spot-net-overview)
+ [Informazioni sul tutorial](#about-spot-instances-tutorial)
+ [Prerequisiti](#tutor-spot-net-prereq)
+ [Raccogli ciò di cui hai bisogno](#tutor-spot-net-gather)
+ [Creazione di una richiesta di istanza Spot](#tutor-spot-net-submit)
+ [Determina lo stato della tua richiesta di istanza Spot](#tutor-spot-net-request-state)
+ [Pulisci le tue richieste di istanze Spot](#tutor-spot-net-clean-up-request)
+ [Pulisci le tue istanze Spot](#tutor-spot-net-clean-up-instance)
+ [Codice completo](#tutor-spot-net-main)
+ [Ulteriori considerazioni](#tutor-spot-net-additional)

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

Per informazioni sui prerequisiti APIs e, consultate la sezione principale (). [Utilizzo di Amazon EC2](ec2-apis-intro.md)

## Raccogli ciò di cui hai bisogno
<a name="tutor-spot-net-gather"></a>

Per creare una richiesta di istanza Spot, avrai bisogno di diversi elementi. 
+ Il numero di istanze e il relativo tipo di istanza. Esistono diversi tipi di istanze tra cui scegliere. Per ulteriori informazioni, consulta i [tipi di istanze di Amazon EC2](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instance-types.html) nella [Amazon EC2](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/) User Guide. Consulta anche [Instance Type Details](https://aws.amazon.com/ec2/instance-types/) e [Instance Type Explorer](https://aws.amazon.com/ec2/instance-explorer/).

  Il numero predefinito per questo tutorial è 1.
+ L'Amazon Machine Image (AMI) che verrà utilizzata per creare l'istanza. Per informazioni su AMIs, consulta [Amazon Machine Images (AMIs)](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/AMIs.html) nella Guida per l'[utente di Amazon EC2](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/). In particolare, vedi [Find an AMI](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/finding-an-ami.html) and [Shared AMIs](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/sharing-amis.html).
+ Il prezzo massimo che sei disposto a pagare per ora di istanza. Puoi vedere i prezzi per tutti i tipi di istanze (sia per le istanze On-Demand che per le istanze Spot) nella pagina dei prezzi di [Amazon](https://aws.amazon.com/ec2/pricing/) EC2. Il prezzo predefinito per questo tutorial viene spiegato più avanti.
+ Se desideri connetterti in remoto a un'istanza, un gruppo di sicurezza con la configurazione e le risorse appropriate. Questo è descritto in [Lavorare con i gruppi di sicurezza in Amazon EC2](security-groups.md) e le informazioni su come [raccogliere ciò di cui hai bisogno](run-instance.md#run-instance-gather) e [connetterti a un'istanza](run-instance.md#connect-to-instance) in[Avvio di un'istanza Amazon EC2](run-instance.md). Per semplicità, questo tutorial utilizza il gruppo di sicurezza denominato **default** di cui dispongono tutti gli AWS account più recenti.

Esistono molti approcci per proporre delle richieste per le istanze Spot. Le seguenti sono strategie comuni:
+ Effettua richieste che sicuramente costeranno meno dei prezzi su richiesta.
+ Effettua richieste in base al valore del calcolo risultante.
+ Effettua richieste in modo da acquisire capacità di calcolo il più rapidamente possibile.

Le seguenti spiegazioni si riferiscono alla [cronologia dei prezzi delle istanze Spot](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/using-spot-instances-history.html) nella Guida per l'[utente di Amazon EC2](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/).

### Riduci i costi al di sotto di quelli di
<a name="reduce-cost"></a>

Hai un processo di elaborazione in batch la cui esecuzione richiede diverse ore o giorni. Tuttavia, hai una certa flessibilità sui tempi di inizio e di fine. Vuoi vedere se riesci a completarlo a un costo inferiore a quello delle istanze on demand.

Puoi esaminare la cronologia dei prezzi Spot per i tipi di istanza utilizzando la console Amazon EC2 o l'API Amazon EC2. Dopo aver analizzato la cronologia dei prezzi per il tipo di istanza desiderato in una determinata zona di disponibilità, hai due alternative per la tua richiesta:
+ Specificate una richiesta all'estremità superiore dell'intervallo di prezzi Spot, che sono ancora inferiori al prezzo on demand, prevedendo che la richiesta effettuata una sola volta sull'istanza Spot venga probabilmente soddisfatta ed eseguita per un tempo di calcolo consecutivo sufficiente a completare il lavoro.
+ Specifica una richiesta nella fascia bassa della gamma di prezzi, pianificando di combinare più istanze avviate in momenti diversi in un'unica richiesta persistente. Le istanze, in forma aggregata, verrebbero eseguite abbastanza a lungo da completare il processo a un costo totale persino inferiore.

### Non paghi più del valore del risultato
<a name="value-of-result"></a>

Hai un processo di elaborazione dei dati da completare. Conosci abbastanza bene il valore dei risultati del lavoro da sapere quanto valgono in termini di costi di elaborazione.

Dopo aver analizzato la cronologia dei prezzi Spot per il tipo di istanza, scegli un prezzo al quale il costo del tempo di elaborazione non sia superiore al valore dei risultati del lavoro. Crea una richiesta persistente e impostane l'esecuzione intermittente quando il prezzo Spot raggiunge o scende sotto la tua richiesta.

### Acquisisci rapidamente capacità di elaborazione
<a name="acquire-quickly"></a>

Hai un bisogno imprevisto, a breve termine, di capacità aggiuntiva che non è disponibile tramite le istanze on demand. Dopo aver analizzato la cronologia dei prezzi Spot per il tipo di istanza, scegli un prezzo superiore al prezzo storico più alto per aumentare notevolmente la probabilità che la tua richiesta venga soddisfatta rapidamente e continui a calcolare fino al completamento.

Dopo aver raccolto ciò di cui hai bisogno e scelto una strategia, sei pronto per richiedere un'istanza Spot. Per questa esercitazione il prezzo massimo di spot-instance predefinito è impostato per essere lo stesso del prezzo su richiesta (che è \$10,003 per questo tutorial). Impostare il prezzo in questo modo massimizza le possibilità che la richiesta venga soddisfatta.

## Creazione di una richiesta di istanza Spot
<a name="tutor-spot-net-submit"></a>

Il seguente frammento mostra come creare una richiesta di istanza Spot con gli elementi raccolti in precedenza.

L'esempio [alla fine di questo argomento mostra questo](#tutor-spot-net-main) frammento in uso.

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

Il valore importante restituito da questo metodo è l'ID della richiesta dell'istanza Spot, contenuto nel `SpotInstanceRequestId` membro dell'oggetto restituito [SpotInstanceRequest](https://docs.aws.amazon.com/sdkfornet/v4/apidocs/items/EC2/TSpotInstanceRequest.html).

**Nota**  
Ti verranno addebitati i costi per ogni istanza Spot lanciata. Per evitare costi inutili, assicurati di [annullare qualsiasi richiesta](#tutor-spot-net-clean-up-request) e [terminare qualsiasi](#tutor-spot-net-clean-up-instance) istanza.

## Determina lo stato della tua richiesta di istanza Spot
<a name="tutor-spot-net-request-state"></a>

Il seguente frammento mostra come ottenere informazioni sulla richiesta di istanza Spot. Puoi utilizzare queste informazioni per prendere determinate decisioni nel codice, ad esempio se continuare ad aspettare che venga soddisfatta una richiesta di istanza Spot.

L'esempio [alla fine di questo argomento mostra questo](#tutor-spot-net-main) frammento in uso.

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

Il metodo restituisce informazioni sulla richiesta dell'istanza Spot, come l'ID dell'istanza, lo stato e il codice di stato. Per ulteriori informazioni sui codici di stato per le richieste di istanze Spot, consulta [lo stato della richiesta Spot](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/spot-bid-status.html#spot-instance-bid-status-understand) nella [Amazon EC2 User Guide](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/).

## Pulisci le tue richieste di istanze Spot
<a name="tutor-spot-net-clean-up-request"></a>

Quando non è più necessario richiedere istanze Spot, è importante annullare le richieste in sospeso per evitare che vengano soddisfatte nuovamente. Il seguente frammento mostra come annullare una richiesta di istanza Spot.

L'esempio [alla fine di questo argomento mostra questo](#tutor-spot-net-main) frammento in uso.

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

## Pulisci le tue istanze Spot
<a name="tutor-spot-net-clean-up-instance"></a>

Per evitare costi inutili, è importante chiudere tutte le istanze avviate dalle richieste di istanze Spot; la semplice cancellazione delle richieste di istanze Spot non comporterà la chiusura delle istanze, il che significa che continueranno a ricevere i relativi costi. Il seguente frammento mostra come terminare un'istanza dopo aver ottenuto l'identificatore di istanza per un'istanza Spot attiva.

L'esempio [alla fine di questo argomento mostra questo frammento](#tutor-spot-net-main) in uso.

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

## Codice completo
<a name="tutor-spot-net-main"></a>

Il seguente esempio di codice richiama i metodi descritti in precedenza per creare e annullare una richiesta di istanza Spot e terminare un'istanza Spot.

### Riferimenti SDK
<a name="w2aac19c15c21c21c43b5b1"></a>

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

Elementi di programmazione:
+ [Spazio dei nomi Amazon.ec2](https://docs.aws.amazon.com/sdkfornet/v4/apidocs/items/EC2/NEC2.html)

  Classe [Amazon EC2 Client](https://docs.aws.amazon.com/sdkfornet/v4/apidocs/items/EC2/TEC2Client.html)

  Classe [InstanceType](https://docs.aws.amazon.com/sdkfornet/v4/apidocs/items/EC2/TInstanceType.html)
+ [Spazio dei nomi Amazon.ec2.model](https://docs.aws.amazon.com/sdkfornet/v4/apidocs/items/EC2/NEC2Model.html)

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

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

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

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

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

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

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

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

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

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

### Il codice
<a name="w2aac19c15c21c21c43b7b1"></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");
        }
      }
    }
  }
}
```

## Ulteriori considerazioni
<a name="tutor-spot-net-additional"></a>
+ Dopo aver eseguito il tutorial, è consigliabile accedere alla [console Amazon EC2](https://console.aws.amazon.com/ec2/) per verificare che la [richiesta dell'istanza Spot sia stata annullata e che l'istanza](https://console.aws.amazon.com/ec2/home#SpotInstances:) [Spot](https://console.aws.amazon.com/ec2/v2/home#Instances) sia stata terminata.

# Accesso AWS Identity and Access Management (IAM) con AWS SDK per .NET
<a name="iam-apis-intro"></a>

I AWS SDK per .NET supporti [AWS Identity and Access Management](https://docs.aws.amazon.com/IAM/latest/UserGuide/), che sono un servizio web che consente AWS ai clienti di gestire gli utenti e le autorizzazioni degli utenti in AWS.

Un *utente AWS Identity and Access Management * (IAM) è un'entità in AWS cui crei. L'entità rappresenta una persona o un'applicazione con AWS cui interagisce. Per ulteriori informazioni sugli utenti IAM, consulta [IAM Users](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_users.html) e [IAM and STS Limits](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_iam-limits.html) nella IAM User Guide.

Concedi le autorizzazioni a un utente creando una *policy* IAM. La policy contiene un *documento di policy* che elenca le azioni che un utente può eseguire e le risorse su cui tali azioni possono influire. Per ulteriori informazioni sulle policy IAM, consulta [Policies and Permissions](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies.html) nella *IAM User Guide*.

**avvertimento**  
Per evitare rischi per la sicurezza, non utilizzare gli utenti IAM per l’autenticazione quando sviluppi software creato ad hoc o lavori con dati reali. Utilizza invece la federazione con un provider di identità come [AWS IAM Identity Center](https://docs.aws.amazon.com/singlesignon/latest/userguide/what-is.html).

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

 AWS SDK per .NET Fornisce APIs per i clienti IAM. Ti APIs consentono di lavorare con funzionalità IAM come utenti, ruoli e chiavi di accesso.

Questa sezione contiene un piccolo numero di esempi che mostrano i modelli che è possibile seguire quando si lavora con questi modelli APIs. Per visualizzare il set completo di APIs, consulta l'[AWS SDK per .NET API Reference](https://docs.aws.amazon.com/sdkfornet/v4/apidocs/) (e scorri fino a «Amazon. IdentityManagement«).

Questa sezione contiene anche [un esempio](net-dg-hosm.md) che mostra come collegare un ruolo IAM alle istanze Amazon EC2 per semplificare la gestione delle credenziali.

[Gli IAM APIs sono forniti da. AWSSDK IdentityManagement](https://www.nuget.org/packages/AWSSDK.IdentityManagement) NuGetpacchetto.

## Prerequisiti
<a name="w2aac19c15c23c15"></a>

Prima di iniziare, assicurati di aver [impostato l'ambiente](net-dg-config.md) e [configurato il progetto](configuring-the-sdk.md). Consulta anche le informazioni contenute in[Utilizzo di SDK](net-dg-sdk-features.md).

## Argomenti
<a name="w2aac19c15c23c17"></a>

**Topics**
+ [APIs](#w2aac19c15c23c13)
+ [Prerequisiti](#w2aac19c15c23c15)
+ [Argomenti](#w2aac19c15c23c17)
+ [Creazione di politiche gestite da JSON](iam-policies-create-json.md)
+ [Visualizzazione dei documenti relativi alle policy](iam-policies-display.md)
+ [Concessione dell'accesso con un ruolo](net-dg-hosm.md)

# Creazione di policy gestite da IAM da JSON
<a name="iam-policies-create-json"></a>

Questo esempio mostra come utilizzare per AWS SDK per .NET creare una [policy gestita da IAM](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies_managed-vs-inline.html#aws-managed-policies) da un determinato documento di policy in JSON. L'applicazione crea un oggetto client IAM, legge il documento di policy da un file e quindi crea la policy.

**Nota**  
Per un documento di policy di esempio in JSON, consulta le [considerazioni aggiuntive](#iam-policies-create-json-additional) alla fine di questo argomento.

Le sezioni seguenti forniscono frammenti di questo esempio. Successivamente viene mostrato [il codice completo dell'esempio](#iam-policies-create-json-complete-code), che può essere creato ed eseguito così com'è.

**Topics**
+ [Creare la policy](#iam-policies-create-json-create)
+ [Codice completo](#iam-policies-create-json-complete-code)
+ [Ulteriori considerazioni](#iam-policies-create-json-additional)

## Creare la policy
<a name="iam-policies-create-json-create"></a>

Il seguente frammento crea una policy gestita da IAM con il nome e il documento di policy specificati.

L'esempio [alla fine di questo argomento mostra questo](#iam-policies-create-json-complete-code) frammento in uso.

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

## Codice completo
<a name="iam-policies-create-json-complete-code"></a>

Questa sezione mostra i riferimenti pertinenti e il codice completo per questo esempio.

### Riferimenti SDK
<a name="w2aac19c15c23c21c17b5b1"></a>

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

Elementi di programmazione:
+ [Namespace Amazon. IdentityManagement](https://docs.aws.amazon.com/sdkfornet/v4/apidocs/items/IAM/NIAM.html)

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

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

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

### Il codice
<a name="w2aac19c15c23c21c17b7b1"></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);
    }
  }

}
```

## Ulteriori considerazioni
<a name="iam-policies-create-json-additional"></a>
+ Di seguito è riportato un esempio di documento di policy che è possibile copiare in un file JSON e utilizzare come input per questa applicazione:

------
#### [ 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": "*"
      }
    ]
  }
  ```

------
+ Puoi verificare che la policy sia stata creata cercando nella [console IAM](https://console.aws.amazon.com/iam/home#/policies). Nell'elenco a discesa **Filtra policy**, seleziona **Customer** managed. Elimina la politica quando non è più necessaria.
+  Per ulteriori informazioni sulla creazione delle policy, consulta [Creating IAM](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies_create.html) Policy e [IAM JSON Policy di riferimento](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies.html) nella [IAM User Guide](https://docs.aws.amazon.com/IAM/latest/UserGuide/)

# Visualizza il documento relativo alla policy di una policy gestita da IAM
<a name="iam-policies-display"></a>

Questo esempio mostra come utilizzare il AWS SDK per .NET per visualizzare un documento di policy. L'applicazione crea un oggetto client IAM, trova la versione predefinita della policy gestita IAM specificata e quindi visualizza il documento relativo alla policy in JSON.

Le sezioni seguenti forniscono frammenti di questo esempio. Successivamente viene mostrato [il codice completo dell'esempio](#iam-policies-display-complete-code), che può essere creato ed eseguito così com'è.

**Topics**
+ [Trova la versione predefinita](#iam-policies-display-version)
+ [Visualizza il documento relativo alla policy](#iam-policies-display-doc)
+ [Codice completo](#iam-policies-display-complete-code)

## Trova la versione predefinita
<a name="iam-policies-display-version"></a>

Il seguente frammento trova la versione predefinita della policy IAM specificata.

L'esempio [alla fine di questo argomento mostra questo](#iam-policies-display-complete-code) frammento in uso.

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

## Visualizza il documento relativo alla policy
<a name="iam-policies-display-doc"></a>

Il seguente frammento mostra il documento di policy in JSON della policy IAM specificata.

L'esempio [alla fine di questo argomento mostra questo](#iam-policies-display-complete-code) frammento in uso.

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

## Codice completo
<a name="iam-policies-display-complete-code"></a>

Questa sezione mostra i riferimenti pertinenti e il codice completo per questo esempio.

### Riferimenti SDK
<a name="w2aac19c15c23c23c19b5b1"></a>

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

Elementi di programmazione:
+ [Namespace Amazon. IdentityManagement](https://docs.aws.amazon.com/sdkfornet/v4/apidocs/items/IAM/NIAM.html)

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

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

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

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

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

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

### Il codice
<a name="w2aac19c15c23c23c19b7b1"></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)}");
    }
  }
}
```

# Concessione dell'accesso utilizzando un ruolo IAM
<a name="net-dg-hosm"></a>

Questo tutorial mostra come utilizzare per AWS SDK per .NET abilitare i ruoli IAM sulle istanze Amazon EC2.

## Panoramica di
<a name="hosm-overview"></a>

Tutte le richieste AWS devono essere firmate crittograficamente utilizzando credenziali emesse da. AWS Pertanto, è necessaria una strategia per gestire le credenziali per le applicazioni eseguite su istanze Amazon EC2. È necessario distribuire, archiviare e ruotare queste credenziali in modo sicuro, ma anche mantenerle accessibili alle applicazioni.

Con i ruoli IAM, puoi gestire efficacemente queste credenziali. Crei un ruolo IAM e lo configuri con le autorizzazioni richieste da un'applicazione, quindi colleghi quel ruolo a un'istanza EC2. Per ulteriori informazioni sui vantaggi dell'utilizzo dei ruoli IAM, consulta [Ruoli IAM per Amazon EC2 nella Amazon EC2](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/iam-roles-for-amazon-ec2.html) [User Guide](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/). Consulta anche le informazioni sui [ruoli IAM nella Guida](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles.html) per l'utente IAM.

Per un'applicazione creata utilizzando AWS SDK per .NET, quando l'applicazione costruisce un oggetto client per un AWS servizio, l'oggetto cerca le credenziali da diverse fonti potenziali. L'ordine in cui esegue la ricerca è mostrato in. [Risoluzione di credenziali e profili](creds-assign.md)

Se l'oggetto client non trova credenziali da nessun'altra fonte, recupera credenziali temporanee con le stesse autorizzazioni di quelle che sono state configurate nel ruolo IAM e che si trovano nei metadati dell'istanza EC2. Queste credenziali vengono utilizzate per effettuare chiamate dall'oggetto client. AWS 

## Informazioni sul tutorial
<a name="about-hosm-tutorial"></a>

Seguendo questo tutorial, usi AWS SDK per .NET (e altri strumenti) per avviare un'istanza Amazon EC2 con un ruolo IAM associato, quindi vedi un'applicazione sull'istanza che utilizza le autorizzazioni del ruolo IAM.

**Topics**
+ [Panoramica di](#hosm-overview)
+ [Informazioni sul tutorial](#about-hosm-tutorial)
+ [Crea un'applicazione Amazon S3 di esempio](#net-dg-hosm-sample-s3-app)
+ [Creazione di un ruolo IAM](#net-dg-hosm-create-the-role)
+ [Avvia un'istanza EC2 e collega il ruolo IAM](#net-dg-hosm-launch-ec2-instance)
+ [Connect all'istanza EC2](#net-dg-hosm-connect)
+ [Esegui l'applicazione di esempio sull'istanza EC2](#net-dg-hosm-run-the-app)
+ [Eliminazione](#net-dg-hosm-cleanup)

## Crea un'applicazione Amazon S3 di esempio
<a name="net-dg-hosm-sample-s3-app"></a>

Questa applicazione di esempio recupera un oggetto da Amazon S3. Per eseguire l'applicazione, è necessario quanto segue:
+ Un bucket Amazon S3 che contiene un file di testo.
+ AWS credenziali sulla tua macchina di sviluppo che ti consentono di accedere al bucket.

Per informazioni sulla creazione di un bucket Amazon S3 e sul caricamento di un oggetto, consulta la [Amazon Simple Storage](https://docs.aws.amazon.com/AmazonS3/latest/userguide/) Service User Guide. Per informazioni sulle AWS credenziali, consulta. [Autenticazione con AWS SDK per .NET AWS](creds-idc.md)

Creare un progetto.NET Core con il codice seguente. Quindi prova l'applicazione sulla tua macchina di sviluppo.

**Nota**  
Sul computer di sviluppo è installato il.NET Core Runtime, che consente di eseguire l'applicazione senza pubblicarla. Quando crei un'istanza EC2 più avanti in questo tutorial, puoi scegliere di installare .NET Core Runtime sull'istanza. Questo ti offre un'esperienza simile e un trasferimento di file più piccolo.  
 Tuttavia, puoi anche scegliere di non installare il.NET Core Runtime sull'istanza. Se scegli questa linea d'azione, devi pubblicare l'applicazione in modo che tutte le dipendenze siano incluse quando la trasferisci sull'istanza.

### Riferimenti SDK
<a name="w2aac19c15c23c25c17c13b1"></a>

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

Elementi di programmazione:
+ [Spazio dei nomi Amazon.S3](https://docs.aws.amazon.com/sdkfornet/v4/apidocs/items/S3/NS3.html)

  Classe [AmazonS3Client](https://docs.aws.amazon.com/sdkfornet/v4/apidocs/items/S3/TS3Client.html)
+ Spazio dei nomi [Amazon.S3.Model](https://docs.aws.amazon.com/sdkfornet/v4/apidocs/items/S3/NS3Model.html)

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

### Il codice
<a name="w2aac19c15c23c25c17c15b1"></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);
    }
  }

}
```

Se lo desideri, puoi rimuovere temporaneamente le credenziali che usi sulla tua macchina di sviluppo per vedere come risponde l'applicazione. (Ma assicuratevi di ripristinare le credenziali quando avete finito.)

## Creazione di un ruolo IAM
<a name="net-dg-hosm-create-the-role"></a>

Crea un ruolo IAM con le autorizzazioni appropriate per accedere ad Amazon S3.

1. Apri la [console IAM](https://console.aws.amazon.com/iam/).

1. Nel riquadro di navigazione, scegli **Ruoli**, quindi scegli **Crea** ruolo.

1. Seleziona **AWS servizio**, trova e scegli **EC2**, quindi scegli **Avanti: Autorizzazioni**.

1. **In **Allega politiche di autorizzazione**, trova e seleziona AmazonS3. ReadOnlyAccess** **Se lo desideri, esamina la politica, quindi scegli Avanti: tag.**

1. Aggiungi i tag se lo desideri, quindi scegli **Avanti: revisione**.

1. Digita un nome e una descrizione per il ruolo e quindi scegli **Create role** (Crea ruolo). Ricorda questo nome perché sarà necessario all'avvio dell'istanza EC2.

## Avvia un'istanza EC2 e collega il ruolo IAM
<a name="net-dg-hosm-launch-ec2-instance"></a>

Avvia un'istanza EC2 con il ruolo IAM creato in precedenza. Puoi farlo nei seguenti modi.
+ **Utilizzo della console EC2**

  Per avviare un'istanza utilizzando la console EC2, consulta [Launch an instance using the new launch instance wizard](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-launch-instance-wizard.html) nella [Amazon EC2](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/) User Guide.

  Mentre consulti la pagina di lancio, dovresti almeno espandere il riquadro dei **dettagli avanzati** in modo da poter specificare il ruolo IAM che hai creato in precedenza nel profilo dell'istanza **IAM**.
+ **Utilizzando il AWS SDK per .NET**

  Per informazioni su questo argomento[Avvio di un'istanza Amazon EC2](run-instance.md), vedere, [Ulteriori considerazioni](run-instance.md#run-instance-additional) inclusa la fine dell'argomento.

Per avviare un'istanza EC2 a cui è associato un ruolo IAM, la configurazione di un utente IAM deve includere determinate autorizzazioni. Per ulteriori informazioni sulle autorizzazioni richieste, consulta [Concedere l'autorizzazione a un utente per passare un ruolo IAM a un'istanza](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/iam-roles-for-amazon-ec2.html#permission-to-pass-iam-roles) nella [Amazon EC2](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/) User Guide.

## Connect all'istanza EC2
<a name="net-dg-hosm-connect"></a>

Connect all'istanza EC2 in modo da poter trasferire l'applicazione di esempio su di essa e quindi eseguire l'applicazione. Avrai bisogno del file che contiene la parte privata della key pair che hai usato per avviare l'istanza, ovvero il file PEM.

Per informazioni sulla connessione a un'istanza, consulta [Connect to your Linux](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/connect-to-linux-instance.html) o [Connect to your Windows](https://docs.aws.amazon.com/AWSEC2/latest/WindowsGuide/connecting_to_windows_instance.html) nella [Amazon EC2 User](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/) Guide. Quando ti connetti, fallo in modo da poter trasferire i file dalla macchina di sviluppo all'istanza.

Se usi Visual Studio su Windows, puoi anche connetterti all'istanza utilizzando Toolkit for Visual Studio. Per ulteriori informazioni, consulta [Connessione a un'istanza Amazon EC2 nella Guida](https://docs.aws.amazon.com/toolkit-for-visual-studio/latest/user-guide/tkv-ec2-ami.html#connect-ec2) per l' AWS Toolkit for Visual Studio utente.

## Esegui l'applicazione di esempio sull'istanza EC2
<a name="net-dg-hosm-run-the-app"></a>

1. Copia i file dell'applicazione dall'unità locale all'istanza.

   I file da trasferire dipendono da come è stata creata l'applicazione e dal fatto che nell'istanza sia installato o meno il.NET Core Runtime. Per informazioni su come trasferire file sulla tua istanza, consulta [Connect to your Linux](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/connect-to-linux-instance.html) (vedi la sottosezione appropriata) o [Transfer files to Windows](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/connect-to-linux-instanceWindowsFileTransfer.html) nella [Amazon EC2](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/) User Guide.

1. Avvia l'applicazione e verifica che funzioni con gli stessi risultati della macchina di sviluppo.

1. Verifica che l'applicazione utilizzi le credenziali fornite dal ruolo IAM.

   1. Aprire la [console di Amazon EC2](https://console.aws.amazon.com/ec2/).

   1. Seleziona l'istanza e scollega il ruolo IAM tramite **Actions**, **Instance Settings**, **Attach/Replace** IAM Role.

   1. Esegui nuovamente l'applicazione e verifica che restituisca un errore di autorizzazione.

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

Quando hai finito con questo tutorial e se non desideri più l'istanza EC2 che hai creato, assicurati di terminare l'istanza per evitare costi indesiderati. Puoi farlo nella [console Amazon EC2](https://console.aws.amazon.com/ec2/) o a livello di codice, come descritto in. [Terminazione di un'istanza Amazon EC2](terminate-instance.md) Se lo desideri, puoi anche eliminare altre risorse che hai creato per questo tutorial. Queste potrebbero includere un ruolo IAM, una coppia di chiavi EC2 e un file PEM, un gruppo di sicurezza, ecc.

# Utilizzo dello storage Internet di Amazon Simple Storage Service
<a name="s3-apis-intro"></a>

 AWS SDK per .NET Supporta [Amazon S3](https://aws.amazon.com/s3/), che è lo storage per Internet. È concepito per rendere più accessibili agli sviluppatori risorse informatiche su grande scala per il Web.

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

 AWS SDK per .NET Fornisce APIs i client Amazon S3. Ti APIs consentono di lavorare con risorse Amazon S3 come bucket e articoli. Per visualizzare il set completo di APIs Amazon S3, consulta quanto segue:
+ [AWS SDK per .NET Riferimento all'API](https://docs.aws.amazon.com/sdkfornet/v4/apidocs/) (e scorri fino a «Amazon.S3").
+ [Documentazione](https://aws.github.io/amazon-s3-encryption-client-dotnet/api/Amazon.Extensions.S3.Encryption.html) sulla crittografia Amazon.Extensions.S3

Amazon S3 APIs è fornito dai seguenti pacchetti: NuGet 
+ [AWSSDK.S3](https://www.nuget.org/packages/AWSSDK.S3)
+ [Crittografia Amazon.Extensions.S3](https://www.nuget.org/packages/Amazon.Extensions.S3.Encryption)

## Prerequisiti
<a name="w2aac19c15c25b7"></a>

[Prima di iniziare, assicurati di aver [configurato l'ambiente e configurato](net-dg-config.md) il progetto.](configuring-the-sdk.md) Consulta anche le informazioni contenute in[Utilizzo di SDK](net-dg-sdk-features.md).

## Esempi in questo documento
<a name="s3-apis-examples"></a>

I seguenti argomenti di questo documento mostrano come utilizzarlo AWS SDK per .NET per lavorare con Amazon S3.
+ [Utilizzo delle chiavi KMS per la crittografia S3](kms-keys-s3-encryption.md)

## Esempi in altri documenti
<a name="s3-apis-examples-other"></a>

I seguenti collegamenti alla [Amazon S3 Developer Guide](https://docs.aws.amazon.com/AmazonS3/latest/userguide/) forniscono ulteriori esempi su come utilizzarla per AWS SDK per .NET lavorare con Amazon S3.

**Nota**  
Sebbene questi esempi e considerazioni aggiuntive sulla programmazione siano stati creati per la versione 3 di Using .NET Framework, sono validi anche per le versioni successive di che AWS SDK per .NET utilizzano .NET Core. AWS SDK per .NET Talvolta sono necessarie piccole modifiche al codice.

**Esempi di programmazione in Amazon S3**
+  [Gestione ACLs](https://docs.aws.amazon.com/AmazonS3/latest/dev/acl-using-dot-net-sdk.html) 
+  [Creazione di un bucket](https://docs.aws.amazon.com/AmazonS3/latest/dev/create-bucket-get-location-example.html#create-bucket-get-location-dotnet) 
+  [Caricamento di un oggetto](https://docs.aws.amazon.com/AmazonS3/latest/dev/UploadObjSingleOpNET.html) 
+  [[Caricamento multiparte con l'API di alto livello (Amazon.S3.Transfer). TransferUtility](https://docs.aws.amazon.com/sdkfornet/v4/apidocs/items/S3/TTransferUtility.html))](https://docs.aws.amazon.com/AmazonS3/latest/dev/usingHLmpuDotNet.html) 
+  [Caricamento in più parti con l'API di basso livello](https://docs.aws.amazon.com/AmazonS3/latest/dev/usingLLmpuDotNet.html) 
+  [Elenco degli oggetti](https://docs.aws.amazon.com/AmazonS3/latest/dev/list-obj-version-enabled-bucket.html#list-obj-version-enabled-bucket-sdk-examples) 
+  [Elenco delle chiavi](https://docs.aws.amazon.com/AmazonS3/latest/dev/ListingObjectKeysUsingNetSDK.html) 
+  [Recupero di un oggetto](https://docs.aws.amazon.com/AmazonS3/latest/dev/RetrievingObjectUsingNetSDK.html) 
+  [Copia di un oggetto](https://docs.aws.amazon.com/AmazonS3/latest/dev/CopyingObjectUsingNetSDK.html) 
+  [Copia di un oggetto con l'API per il caricamento in più parti](https://docs.aws.amazon.com/AmazonS3/latest/dev/CopyingObjctsUsingLLNetMPUapi.html) 
+  [Eliminazione di un oggetto](https://docs.aws.amazon.com/AmazonS3/latest/dev/DeletingOneObjectUsingNetSDK.html) 
+  [Eliminazione di più oggetti](https://docs.aws.amazon.com/AmazonS3/latest/dev/DeletingMultipleObjectsUsingNetSDK.html) 
+  [Ripristino di un oggetto](https://docs.aws.amazon.com/AmazonS3/latest/dev/restore-object-dotnet.html) 
+  [Configurazione di un bucket per le notifiche](https://docs.aws.amazon.com/AmazonS3/latest/dev/ways-to-add-notification-config-to-bucket.html) 
+  [Gestione del ciclo di vita di un oggetto](https://docs.aws.amazon.com/AmazonS3/latest/dev/manage-lifecycle-using-dot-net.html) 
+  [Generazione di un URL prefirmato per un oggetto](https://docs.aws.amazon.com/AmazonS3/latest/dev/ShareObjectPreSignedURLDotNetSDK.html) 
+  [Gestione di siti Web](https://docs.aws.amazon.com/AmazonS3/latest/dev/ConfigWebSiteDotNet.html) 
+  [Abilitazione della condivisione di risorse tra le origini (CORS)](https://docs.aws.amazon.com/AmazonS3/latest/dev/ManageCorsUsingDotNet.html) 

**Considerazioni aggiuntive sulla programmazione**
+  [Utilizzo di AWS SDK per .NET per la programmazione in Amazon S3](https://docs.aws.amazon.com/AmazonS3/latest/dev/UsingTheMPDotNetAPI.html) 
+  [Esecuzione di richieste mediante le credenziali temporanee per gli utenti IAM](https://docs.aws.amazon.com/AmazonS3/latest/dev/AuthUsingTempSessionTokenDotNet.html) 
+  [Esecuzione di richieste mediante le credenziali temporanee per gli utenti federati](https://docs.aws.amazon.com/AmazonS3/latest/dev/AuthUsingTempFederationTokenDotNet.html) 
+  [Specifica della crittografia lato server](https://docs.aws.amazon.com/AmazonS3/latest/dev/SSEUsingDotNetSDK.html) 
+  [Specifica della crittografia lato server con chiavi di crittografia fornite dal cliente](https://docs.aws.amazon.com/AmazonS3/latest/dev/sse-c-using-dot-net-sdk.html) 

# Utilizzo AWS KMS delle chiavi per la crittografia Amazon S3 nel AWS SDK per .NET
<a name="kms-keys-s3-encryption"></a>

Questo esempio mostra come utilizzare AWS Key Management Service le chiavi per crittografare gli oggetti Amazon S3. L'applicazione crea una chiave master del cliente (CMK) e la utilizza per creare un oggetto [AmazonS3 EncryptionClient](https://aws.github.io/amazon-s3-encryption-client-dotnet/api/Amazon.Extensions.S3.Encryption.AmazonS3EncryptionClientV2.html) V2 per la crittografia lato client. L'applicazione utilizza quel client per creare un oggetto crittografato da un determinato file di testo in un bucket Amazon S3 esistente. Quindi decripta l'oggetto e ne visualizza il contenuto.

**avvertimento**  
Una classe simile chiamata `AmazonS3EncryptionClient` è obsoleta ed è meno sicura della classe. `AmazonS3EncryptionClientV2` Per migrare il codice esistente che utilizza, consulta. `AmazonS3EncryptionClient` [Migrazione del client di crittografia S3 (da V1 a V2)](s3-encryption-migration-v1-v2.md)

**Topics**
+ [Creare materiali di crittografia](#kms-s3-enc-mat)
+ [Crea e crittografa un oggetto Amazon S3](#kms-s3-create-ojbect)
+ [Codice completo](#kms-s3-complete-code)
+ [Ulteriori considerazioni](#kms-s3-additional)

## Creare materiali di crittografia
<a name="kms-s3-enc-mat"></a>

Il seguente frammento crea un `EncryptionMaterials` oggetto che contiene un ID di chiave KMS.

L'esempio [alla fine di questo argomento mostra questo](#kms-s3-complete-code) frammento in uso.

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

## Crea e crittografa un oggetto Amazon S3
<a name="kms-s3-create-ojbect"></a>

Il seguente frammento crea un `AmazonS3EncryptionClientV2` oggetto che utilizza i materiali di crittografia creati in precedenza. Utilizza quindi il client per creare e crittografare un nuovo oggetto Amazon S3.

L'esempio [alla fine di questo argomento mostra questo](#kms-s3-complete-code) frammento in uso.

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

## Codice completo
<a name="kms-s3-complete-code"></a>

Questa sezione mostra i riferimenti pertinenti e il codice completo per questo esempio.

### Riferimenti SDK
<a name="w2aac19c15c25c13c15b5b1"></a>

NuGet pacchetti:
+ [Amazon.Extensions.S3.Encryption](https://www.nuget.org/packages/Amazon.Extensions.S3.Encryption)

Elementi di programmazione:
+ [Spazio dei nomi Amazon.Extensions.S3.Encryption](https://aws.github.io/amazon-s3-encryption-client-dotnet/api/Amazon.Extensions.S3.Encryption.html)

  Classe [AmazonS3 V2 EncryptionClient](https://aws.github.io/amazon-s3-encryption-client-dotnet/api/Amazon.Extensions.S3.Encryption.AmazonS3EncryptionClientV2.html)

  Classe [AmazonS3 CryptoConfiguration V2](https://aws.github.io/amazon-s3-encryption-client-dotnet/api/Amazon.Extensions.S3.Encryption.AmazonS3CryptoConfigurationV2.html)

  Classe [CryptoStorageMode](https://aws.github.io/amazon-s3-encryption-client-dotnet/api/Amazon.Extensions.S3.Encryption.CryptoStorageMode.html)

  Classe [EncryptionMaterialsV2](https://aws.github.io/amazon-s3-encryption-client-dotnet/api/Amazon.Extensions.S3.Encryption.EncryptionMaterialsV2.html)
+ [Spazio dei nomi Amazon.Extensions.S3.Encryption.Primitives](https://aws.github.io/amazon-s3-encryption-client-dotnet/api/Amazon.Extensions.S3.Encryption.Primitives.html)

  Classe [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/v4/apidocs/items/S3/NS3Model.html)

  Classe [GetObjectRequest](https://docs.aws.amazon.com/sdkfornet/v4/apidocs/items/S3/TGetObjectRequest.html)

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

  Classe [PutObjectRequest](https://docs.aws.amazon.com/sdkfornet/v4/apidocs/items/S3/TPutObjectRequest.html)
+ [Namespace Amazon. KeyManagementService](https://docs.aws.amazon.com/sdkfornet/v4/apidocs/items/KeyManagementService/NKeyManagementService.html)

  Classe [AmazonKeyManagementServiceClient](https://docs.aws.amazon.com/sdkfornet/v4/apidocs/items/KeyManagementService/TKeyManagementServiceClient.html)
+ [Namespace Amazon. KeyManagementService](https://docs.aws.amazon.com/sdkfornet/v4/apidocs/items/KeyManagementService/NKeyManagementServiceModel.html).Modello

  Classe [CreateKeyRequest](https://docs.aws.amazon.com/sdkfornet/v4/apidocs/items/KeyManagementService/TCreateKeyRequest.html)

  Classe [CreateKeyResponse](https://docs.aws.amazon.com/sdkfornet/v4/apidocs/items/KeyManagementService/TCreateKeyResponse.html)

### Il codice
<a name="w2aac19c15c25c13c15b7b1"></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);
    }
  }

}
```

## Ulteriori considerazioni
<a name="kms-s3-additional"></a>
+ Puoi controllare i risultati di questo esempio. Per farlo, vai alla [console Amazon S3](https://console.aws.amazon.com/s3) e apri il bucket che hai fornito all'applicazione. Quindi trova il nuovo oggetto, scaricalo e aprilo in un editor di testo.
+ La classe [AmazonS3 EncryptionClient V2](https://aws.github.io/amazon-s3-encryption-client-dotnet/api/Amazon.Extensions.S3.Encryption.AmazonS3EncryptionClientV2.html) implementa la stessa interfaccia della classe standard. `AmazonS3Client` Ciò semplifica il trasferimento del codice alla `AmazonS3EncryptionClientV2` classe in modo che la crittografia e la decrittografia avvengano automaticamente e in modo trasparente nel client.
+ Uno dei vantaggi dell'utilizzo di una AWS KMS chiave come chiave principale è che non è necessario archiviare e gestire le proprie chiavi master; questa operazione viene eseguita da. AWS Un secondo vantaggio è che la `AmazonS3EncryptionClientV2` classe di AWS SDK per .NET è interoperabile con la `AmazonS3EncryptionClientV2` classe di. AWS SDK per Java Ciò significa che è possibile crittografare con AWS SDK per Java e decrittografare con, e viceversa. AWS SDK per .NET
**Nota**  
La `AmazonS3EncryptionClientV2` classe di AWS SDK per .NET supporta le chiavi master KMS solo se eseguita in modalità metadati. La modalità del file di istruzioni della `AmazonS3EncryptionClientV2` classe di AWS SDK per .NET è incompatibile con la `AmazonS3EncryptionClientV2` classe di. AWS SDK per Java
+ Per ulteriori informazioni sulla crittografia lato client con la `AmazonS3EncryptionClientV2` classe e su come funziona la crittografia a busta, consulta [Client Side Data Encryption with e Amazon AWS SDK per .NET S3](https://aws.amazon.com/blogs/developer/client-side-data-encryption-with-aws-sdk-for-net-and-amazon-s3/).

# Invio di notifiche dal cloud utilizzando Amazon Simple Notification Service
<a name="sns-apis-intro"></a>

**Nota**  
Le informazioni in questo argomento sono specifiche per i progetti basati su.NET Framework e la AWS SDK per .NET versione 3.3 e precedenti.

 AWS SDK per .NET Supporta Amazon Simple Notification Service (Amazon SNS), un servizio Web che consente ad applicazioni, utenti finali e dispositivi di inviare istantaneamente notifiche dal cloud. Per ulteriori dettagli, consulta la pagina [Amazon SNS](https://aws.amazon.com/sns/).

## Elencare gli argomenti relativi ad Amazon SNS
<a name="sns-list-example"></a>

L'esempio seguente mostra come elencare gli argomenti di Amazon SNS, le sottoscrizioni a ciascun argomento e gli attributi per ogni argomento. Questo esempio utilizza l'impostazione predefinita. [AmazonSimpleNotificationServiceClient](https://docs.aws.amazon.com/sdkfornet/v4/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));
```

## Invio di un messaggio a un argomento Amazon SNS
<a name="sns-send-message-example"></a>

L'esempio seguente mostra come inviare un messaggio a un argomento di Amazon SNS. L'esempio utilizza un argomento, l'ARN dell'argomento 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);
            }
        }
    }
}
```

Guarda l'[esempio completo](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/.dotnet/example_code_legacy/SNS/SnsSendMessage.cs), che include informazioni su come creare ed eseguire l'esempio dalla riga di comando, su. GitHub

## Invio di un messaggio SMS a un numero di telefono
<a name="sns-send-sms-example"></a>

L'esempio seguente mostra come inviare un messaggio SMS a un numero di telefono. L'esempio prende un argomento, il numero di telefono, che deve essere in uno dei due formati descritti nei commenti.

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

Guarda l'[esempio completo](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/.dotnet/example_code_legacy/SNS/SnsPublish.cs), che include informazioni su come creare ed eseguire l'esempio dalla riga di comando, su GitHub.

# Messaggistica tramite Amazon SQS
<a name="sqs-apis-intro"></a>

 AWS SDK per .NET Supporta [Amazon Simple Queue Service (Amazon SQS), un servizio](https://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/) di accodamento dei messaggi che gestisce i messaggi o i flussi di lavoro tra i componenti di un sistema.

Le code Amazon SQS forniscono un meccanismo che consente di inviare, archiviare e ricevere messaggi tra componenti software come microservizi, sistemi distribuiti e applicazioni serverless. Ciò consente di disaccoppiare tali componenti e ti libera dalla necessità di progettare e gestire il tuo sistema di messaggistica. Per informazioni sul funzionamento delle code e dei messaggi in Amazon SQS, consulta i tutorial di Amazon SQS [e l'[architettura [Amazon SQS](https://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/sqs-other-tutorials.html) Basic nella](https://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/) Amazon](https://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/sqs-basic-architecture.html) Simple Queue Service Developer Guide.

**Importante**  
A causa della natura distribuita delle code, Amazon SQS non può garantire che riceverai i messaggi nell'ordine preciso in cui vengono inviati. Se devi mantenere l'ordine dei messaggi, usa una coda [FIFO di Amazon SQS.](https://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/sqs-fifo-queues.html)

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

 AWS SDK per .NET Fornisce APIs per i clienti Amazon SQS. Ti APIs consentono di lavorare con funzionalità di Amazon SQS come code e messaggi. Questa sezione contiene un piccolo numero di esempi che mostrano gli schemi che puoi seguire quando lavori con questi. APIs Per visualizzare il set completo di APIs, consulta l'[AWS SDK per .NET API Reference](https://docs.aws.amazon.com/sdkfornet/v4/apidocs/) (e scorri fino a «Amazon.sqs»).

Amazon SQS è fornito dal APIs [AWSSDK NuGet pacchetto.SQS](https://www.nuget.org/packages/AWSSDK.SQS).

## Prerequisiti
<a name="w2aac19c15c29c11"></a>

Prima di iniziare, assicurati di aver configurato [l'ambiente e [configurato](configuring-the-sdk.md) il](net-dg-config.md) progetto. Consulta anche le informazioni contenute in[Utilizzo di SDK](net-dg-sdk-features.md).

## Argomenti
<a name="w2aac19c15c29c13"></a>

**Topics**
+ [APIs](#w2aac19c15c29b9)
+ [Prerequisiti](#w2aac19c15c29c11)
+ [Argomenti](#w2aac19c15c29c13)
+ [Creazione di code](CreateQueue.md)
+ [Aggiornamento delle code](UpdateSqsQueue.md)
+ [Eliminazione delle code](DeleteSqsQueue.md)
+ [Invio di messaggi](SendMessage.md)
+ [Ricezione di messaggi](ReceiveMessage.md)

# Creazione di code Amazon SQS
<a name="CreateQueue"></a>

Questo esempio mostra come utilizzare per AWS SDK per .NET creare una coda Amazon SQS. L'applicazione crea una [coda di lettere](https://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/sqs-dead-letter-queues.html) non scritte se non viene fornito l'ARN corrispondente. Quindi crea una coda di messaggi standard, che include una coda di lettere non scritte (quella che hai fornito o quella che è stata creata).

Se non fornite alcun argomento della riga di comando, l'applicazione mostra semplicemente le informazioni su tutte le code esistenti.

Le sezioni seguenti forniscono frammenti di questo esempio. Successivamente viene mostrato [il codice completo dell'esempio](#CreateQueue-complete-code), che può essere creato ed eseguito così com'è.

**Topics**
+ [Mostra le code esistenti](#CreateQueue-show-queues)
+ [Crea la coda](#CreateQueue-create-queue)
+ [Ottieni l'ARN di una coda](#CreateQueue-get-arn)
+ [Codice completo](#CreateQueue-complete-code)
+ [Ulteriori considerazioni](#CreateQueue-additional)

## Mostra le code esistenti
<a name="CreateQueue-show-queues"></a>

Il seguente frammento mostra un elenco delle code esistenti nella regione del client SQS e gli attributi di ciascuna coda.

L'esempio [alla fine di questo argomento mostra questo frammento](#CreateQueue-complete-code) in uso.

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

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

## Crea la coda
<a name="CreateQueue-create-queue"></a>

Il seguente frammento crea una coda. Lo snippet include l'uso di una coda di lettere morte, ma una coda di lettere morte non è necessariamente necessaria per le code.

L'esempio alla [fine di questo argomento mostra questo frammento in](#CreateQueue-complete-code) uso.

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

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

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

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

## Ottieni l'ARN di una coda
<a name="CreateQueue-get-arn"></a>

Il seguente frammento ottiene l'ARN della coda identificata dall'URL della coda specificato.

L'esempio [alla fine di questo argomento mostra questo frammento](#CreateQueue-complete-code) in uso.

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

## Codice completo
<a name="CreateQueue-complete-code"></a>

Questa sezione mostra i riferimenti pertinenti e il codice completo per questo esempio.

### Riferimenti SDK
<a name="w2aac19c15c29c17c25b5b1"></a>

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

Elementi di programmazione:
+ [Spazio dei nomi Amazon.sqs](https://docs.aws.amazon.com/sdkfornet/v4/apidocs/items/SQS/NSQS.html)

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

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

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

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

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

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

### Il codice
<a name="w2aac19c15c29c17c25b7b1"></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);
    }
  }

}
```

## Ulteriori considerazioni
<a name="CreateQueue-additional"></a>
+ Il nome della coda deve essere composto da caratteri alfanumerici, trattini e caratteri di sottolineatura.
+ I nomi delle code e la coda fanno distinzione tra maiuscole e minuscole URLs 
+ Se hai bisogno dell'URL della coda ma hai solo il nome della coda, usa uno dei metodi. `AmazonSQSClient.GetQueueUrlAsync`
+ Per informazioni sui vari attributi di coda che puoi impostare, consulta [CreateQueueRequest](https://docs.aws.amazon.com/sdkfornet/v4/apidocs/items/SQS/TCreateQueueRequest.html)l'[AWS SDK per .NET API Reference](https://docs.aws.amazon.com/sdkfornet/v4/apidocs/) o [SetQueueAttributes](https://docs.aws.amazon.com/AWSSimpleQueueService/latest/APIReference/API_SetQueueAttributes.html)il [Amazon Simple Queue Service API](https://docs.aws.amazon.com/AWSSimpleQueueService/latest/APIReference/) Reference.
+ Questo esempio specifica un polling lungo per tutti i messaggi sulla coda che crei. Questa operazione viene eseguita utilizzando l'attributo. `ReceiveMessageWaitTimeSeconds`

  Puoi anche specificare un polling lungo durante una chiamata ai `ReceiveMessageAsync` metodi della SQSClient classe [Amazon](https://docs.aws.amazon.com/sdkfornet/v4/apidocs/items/SQS/TSQSClient.html). Per ulteriori informazioni, consulta [Ricezione di messaggi Amazon SQS](ReceiveMessage.md).

  Per informazioni sul polling breve rispetto al polling lungo, [consulta Short and long polling nella](https://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/sqs-short-and-long-polling.html) *Amazon Simple Queue* Service Developer Guide.
+ Una coda di lettere morte è quella che altre code (di origine) possono indirizzare per i messaggi che non vengono elaborati correttamente. Per ulteriori informazioni, consulta le [code di lettera morta di Amazon SQS nella Guida](https://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/sqs-dead-letter-queues.html) per gli sviluppatori di Amazon Simple Queue Service.
+ Puoi anche visualizzare l'elenco delle code e i risultati di questo esempio nella console [Amazon SQS](https://console.aws.amazon.com/sqs).

# Aggiornamento delle code Amazon SQS
<a name="UpdateSqsQueue"></a>

Questo esempio mostra come utilizzare per AWS SDK per .NET aggiornare una coda Amazon SQS. Dopo alcuni controlli, l'applicazione aggiorna l'attributo specificato con il valore dato, quindi mostra tutti gli attributi per la coda.

Se negli argomenti della riga di comando è incluso solo l'URL della coda, l'applicazione mostra semplicemente tutti gli attributi della coda.

Le sezioni seguenti forniscono frammenti di questo esempio. Successivamente viene mostrato [il codice completo dell'esempio](#UpdateSqsQueue-complete-code), che può essere creato ed eseguito così com'è.

**Topics**
+ [Mostra gli attributi della coda](#UpdateSqsQueue-show-attributes)
+ [Convalida il nome dell'attributo](#UpdateSqsQueue-validate-attribute)
+ [Aggiorna l'attributo della coda](#UpdateSqsQueue-update-attribute)
+ [Codice completo](#UpdateSqsQueue-complete-code)
+ [Ulteriori considerazioni](#UpdateSqsQueue-additional)

## Mostra gli attributi della coda
<a name="UpdateSqsQueue-show-attributes"></a>

Il seguente frammento mostra gli attributi della coda identificata dall'URL della coda specificato.

L'esempio [alla fine di questo argomento mostra questo frammento](#UpdateSqsQueue-complete-code) in uso.

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

## Convalida il nome dell'attributo
<a name="UpdateSqsQueue-validate-attribute"></a>

Il seguente frammento di codice convalida il nome dell'attributo da aggiornare.

L'esempio [alla fine di questo argomento mostra questo](#UpdateSqsQueue-complete-code) frammento in uso.

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

## Aggiorna l'attributo della coda
<a name="UpdateSqsQueue-update-attribute"></a>

Il seguente frammento aggiorna un attributo della coda identificato dall'URL della coda specificato.

L'esempio [alla fine di questo argomento mostra questo frammento](#UpdateSqsQueue-complete-code) in uso.

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

## Codice completo
<a name="UpdateSqsQueue-complete-code"></a>

Questa sezione mostra i riferimenti pertinenti e il codice completo per questo esempio.

### Riferimenti SDK
<a name="w2aac19c15c29c19c25b5b1"></a>

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

Elementi di programmazione:
+ [Spazio dei nomi Amazon.sqs](https://docs.aws.amazon.com/sdkfornet/v4/apidocs/items/SQS/NSQS.html)

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

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

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

### Il codice
<a name="w2aac19c15c29c19c25b7b1"></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);
    }
  }

}
```

## Ulteriori considerazioni
<a name="UpdateSqsQueue-additional"></a>
+ Per aggiornare l'`RedrivePolicy`attributo, è necessario citare l'intero valore ed evitare le virgolette per le key/value coppie, a seconda del sistema operativo in uso.

  In Windows, ad esempio, il valore è costruito in modo simile al seguente:

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

# Eliminazione delle code Amazon SQS
<a name="DeleteSqsQueue"></a>

Questo esempio mostra come utilizzare per AWS SDK per .NET eliminare una coda Amazon SQS. L'applicazione elimina la coda, attende fino a un determinato periodo di tempo che la coda scompaia, quindi mostra un elenco delle code rimanenti.

Se non si fornisce alcun argomento della riga di comando, l'applicazione mostra semplicemente un elenco delle code esistenti.

Le sezioni seguenti forniscono frammenti di questo esempio. Successivamente viene mostrato [il codice completo dell'esempio](#DeleteSqsQueue-complete-code), che può essere creato ed eseguito così com'è.

**Topics**
+ [Eliminare la coda](#DeleteSqsQueue-delete-queue)
+ [Attendi che la coda finisca](#DeleteSqsQueue-wait)
+ [Mostra un elenco di code esistenti](#DeleteSqsQueue-list-queues)
+ [Codice completo](#DeleteSqsQueue-complete-code)
+ [Ulteriori considerazioni](#DeleteSqsQueue-additional)

## Eliminare la coda
<a name="DeleteSqsQueue-delete-queue"></a>

Il seguente frammento elimina la coda identificata dall'URL di coda specificato.

L'esempio [alla fine di questo argomento mostra questo frammento](#DeleteSqsQueue-complete-code) in uso.

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

## Attendi che la coda finisca
<a name="DeleteSqsQueue-wait"></a>

Il seguente frammento attende il completamento del processo di eliminazione, che potrebbe richiedere 60 secondi.

L'esempio [alla fine di questo argomento mostra questo](#DeleteSqsQueue-complete-code) frammento in uso.

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

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

## Mostra un elenco di code esistenti
<a name="DeleteSqsQueue-list-queues"></a>

Il seguente frammento mostra un elenco delle code esistenti nella regione del client SQS.

L'esempio [alla fine di questo argomento mostra questo frammento](#DeleteSqsQueue-complete-code) in uso.

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

## Codice completo
<a name="DeleteSqsQueue-complete-code"></a>

Questa sezione mostra i riferimenti pertinenti e il codice completo per questo esempio.

### Riferimenti SDK
<a name="w2aac19c15c29c21c25b5b1"></a>

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

Elementi di programmazione:
+ [Spazio dei nomi Amazon.sqs](https://docs.aws.amazon.com/sdkfornet/v4/apidocs/items/SQS/NSQS.html)

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

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

### Il codice
<a name="w2aac19c15c29c21c25b7b1"></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}");
    }
  }
}
```

## Ulteriori considerazioni
<a name="DeleteSqsQueue-additional"></a>
+ La chiamata `DeleteQueueAsync` API non verifica se la coda che stai eliminando viene utilizzata come coda di lettere non scritte. Una procedura più sofisticata potrebbe verificarlo.
+ Puoi anche visualizzare l'elenco delle code e i risultati di questo esempio nella console [Amazon SQS](https://console.aws.amazon.com/sqs).

# Invio di messaggi Amazon SQS
<a name="SendMessage"></a>

[Questo esempio mostra come utilizzare per inviare messaggi AWS SDK per .NET a una coda Amazon SQS, che puoi creare a [livello di codice o utilizzando la console](CreateQueue.md) Amazon SQS.](https://console.aws.amazon.com/sqs) L'applicazione invia un singolo messaggio alla coda e poi un batch di messaggi. L'applicazione attende quindi l'input dell'utente, che può essere costituito da messaggi aggiuntivi da inviare alla coda o da una richiesta di uscita dall'applicazione.

Questo esempio e il [prossimo esempio sulla ricezione di messaggi](ReceiveMessage.md) possono essere usati insieme per visualizzare il flusso dei messaggi in Amazon SQS.

Le sezioni seguenti forniscono frammenti di questo esempio. Successivamente viene mostrato [il codice completo dell'esempio](#SendMessage-complete-code), che può essere creato ed eseguito così com'è.

**Topics**
+ [Invio di un messaggio](#SendMessage-send-message)
+ [Inviare un batch di messaggi](#SendMessage-send-batch)
+ [Elimina tutti i messaggi dalla coda](#SendMessage-purge-messages)
+ [Codice completo](#SendMessage-complete-code)
+ [Ulteriori considerazioni](#SendMessage-additional)

## Invio di un messaggio
<a name="SendMessage-send-message"></a>

Il seguente frammento invia un messaggio alla coda identificata dall'URL della coda specificato.

L'esempio [alla fine di questo argomento mostra questo frammento](#SendMessage-complete-code) in uso.

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

## Inviare un batch di messaggi
<a name="SendMessage-send-batch"></a>

Il seguente frammento invia un batch di messaggi alla coda identificata dall'URL di coda specificato.

L'esempio [alla fine di questo argomento mostra questo frammento](#SendMessage-complete-code) in uso.

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

## Elimina tutti i messaggi dalla coda
<a name="SendMessage-purge-messages"></a>

Il seguente frammento elimina tutti i messaggi dalla coda identificata dall'URL di coda specificato. *Questa operazione è nota anche come eliminazione della coda.*

L'esempio [alla fine di questo argomento mostra questo](#SendMessage-complete-code) frammento in uso.

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

## Codice completo
<a name="SendMessage-complete-code"></a>

Questa sezione mostra i riferimenti pertinenti e il codice completo per questo esempio.

### Riferimenti SDK
<a name="w2aac19c15c29c23c25b5b1"></a>

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

Elementi di programmazione:
+ [Spazio dei nomi Amazon.sqs](https://docs.aws.amazon.com/sdkfornet/v4/apidocs/items/SQS/NSQS.html)

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

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

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

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

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

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

### Il codice
<a name="w2aac19c15c29c23c25b7b1"></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}");
    }
  }
}
```

## Ulteriori considerazioni
<a name="SendMessage-additional"></a>
+ Per informazioni sulle varie limitazioni sui messaggi, inclusi i caratteri consentiti, consulta [Quote relative ai messaggi](https://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/sqs-quotas.html#quotas-messages) nella [Amazon Simple Queue Service Developer](https://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/) Guide.
+ I messaggi rimangono in coda finché non vengono eliminati o la coda non viene eliminata. Quando un messaggio viene ricevuto da un'applicazione, non sarà visibile nella coda anche se esiste ancora nella coda. Per ulteriori informazioni sui timeout di visibilità, consulta [Amazon SQS](https://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/AboutVT.html) visibility timeout.
+ Oltre al corpo del messaggio, puoi anche aggiungere attributi ai messaggi. Per ulteriori informazioni, consulta [Metadati dei messaggi](https://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/sqs-message-metadata.html).

# Ricezione di messaggi Amazon SQS
<a name="ReceiveMessage"></a>

[Questo esempio mostra come utilizzare per AWS SDK per .NET ricevere messaggi da una coda Amazon SQS, che puoi creare a [livello di codice o utilizzando la console](CreateQueue.md) Amazon SQS.](https://console.aws.amazon.com/sqs) L'applicazione legge un singolo messaggio dalla coda, elabora il messaggio (in questo caso, visualizza il corpo del messaggio sulla console) e quindi elimina il messaggio dalla coda. L'applicazione ripete questi passaggi finché l'utente non digita un tasto sulla tastiera.

Questo esempio e l'[esempio precedente sull'invio di messaggi](SendMessage.md) possono essere usati insieme per visualizzare il flusso dei messaggi in Amazon SQS.

Le sezioni seguenti forniscono frammenti di questo esempio. Successivamente viene mostrato [il codice completo dell'esempio](#ReceiveMessage-complete-code), che può essere creato ed eseguito così com'è.

**Topics**
+ [Ricevi un messaggio](#ReceiveMessage-receive)
+ [Eliminare un messaggio](#ReceiveMessage-delete)
+ [Codice completo](#ReceiveMessage-complete-code)
+ [Ulteriori considerazioni](#ReceiveMessage-additional)

## Ricevi un messaggio
<a name="ReceiveMessage-receive"></a>

Il seguente frammento riceve un messaggio dalla coda identificata dall'URL di coda specificato.

L'esempio [alla fine di questo argomento mostra questo frammento](#ReceiveMessage-complete-code) in uso.

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

## Eliminare un messaggio
<a name="ReceiveMessage-delete"></a>

Il seguente frammento elimina un messaggio dalla coda identificata dall'URL di coda specificato.

L'esempio [alla fine di questo argomento mostra questo frammento](#ReceiveMessage-complete-code) in uso.

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

## Codice completo
<a name="ReceiveMessage-complete-code"></a>

Questa sezione mostra i riferimenti pertinenti e il codice completo per questo esempio.

### Riferimenti SDK
<a name="w2aac19c15c29c25c21b5b1"></a>

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

Elementi di programmazione:
+ [Spazio dei nomi Amazon.sqs](https://docs.aws.amazon.com/sdkfornet/v4/apidocs/items/SQS/NSQS.html)

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

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

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

### Il codice
<a name="w2aac19c15c29c25c21b7b1"></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);
    }
  }
}
```

## Ulteriori considerazioni
<a name="ReceiveMessage-additional"></a>
+ Per specificare un polling lungo, questo esempio utilizza la `WaitTimeSeconds` proprietà per ogni chiamata al `ReceiveMessageAsync` metodo.

  È inoltre possibile specificare un polling lungo per tutti i messaggi in una coda utilizzando l'`ReceiveMessageWaitTimeSeconds`attributo durante la [creazione](CreateQueue.md) o l'[aggiornamento](UpdateSqsQueue.md) della coda.

  Per informazioni sul polling breve rispetto al polling lungo, [consulta Short and long polling nella](https://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/sqs-short-and-long-polling.html) *Amazon Simple Queue* Service Developer Guide.
+ Durante l'elaborazione dei messaggi, puoi utilizzare la maniglia di ricezione per modificare il timeout di visibilità dei messaggi. Per informazioni su come eseguire questa operazione, consulta i `ChangeMessageVisibilityAsync` metodi della SQSClient classe [Amazon](https://docs.aws.amazon.com/sdkfornet/v4/apidocs/items/SQS/TSQSClient.html).
+ La chiamata al `DeleteMessageAsync` metodo rimuove incondizionatamente il messaggio dalla coda, indipendentemente dall'impostazione del timeout di visibilità.