Authentication

Code Sample: Set up Amazon Cognito AWS Credentials
            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))
            {
                //if using .NET Core, make sure to use await keyword and async method
                s3Client.ListBuckets();
            }
Code Sample: Use AWS as an Unauthenticated User
  CognitoAWSCredentials credentials = new CognitoAWSCredentials(
                accountId, identityPoolId,
                unAuthRoleArn,    // Role for unauthenticated users
                authRoleArn,      // Role for authenticated users
                region);
            using (var s3Client = new AmazonS3Client(credentials))
            {
                 //if using .NET Core, make sure to use await keyword and async method
                // 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();
            }
Code Sample: Use Basic Authentication
        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;

        }
Code Sample: Authenticate with Challenges
        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.");
            }
         
        }

Communications

  • Amazon SQS
  • Amazon SNS
  • Amazon SES
  • Amazon SQS
  • Code Sample: Create an Amazon SQS Client
    //config
    AmazonSQSConfig sqsConfig = new AmazonSQSConfig();
    
    sqsConfig.ServiceURL = "http://sqs.us-west-2.amazonaws.com";
    
    //instantiate client
    AmazonSQSClient sqsClient = new AmazonSQSClient(sqsConfig);
    Code Sample: Create an Amazon SQS Queue and Construct an Amazon SQS Queue Url
    //initialize CreateQueueRequest instance
    
    CreateQueueRequest createQueueRequest = new CreateQueueRequest();
    
    createQueueRequest.QueueName = "MySQSQueue";
    Dictionary<string, string> attrs = new Dictionary<string, string>();
    attrs.Add(QueueAttributeName.VisibilityTimeout, "10");
    createQueueRequest.Attributes = attrs;
    
    //if using .NET Core, make sure to use await keyword and async method
    //pass request as a param to CreateQueue method
    CreateQueueResponse createQueueResponse = sqsClient.CreateQueue(createQueueRequest);
    
    //create the sqs queue url to use for sending, receiving, deleting sqs messages
    GetQueueUrlRequest request = new GetQueueUrlRequest
    {
      QueueName = "MyTestQueue",
      QueueOwnerAWSAccountId = "80398EXAMPLE"
    };
    var response = sqsClient.GetQueueUrl(request);
    Console.WriteLine("Queue URL: " + response.QueueUrl);
    Code Sample: Send an Amazon SQS Message or Message Batch
    //send one message
    //step 1 create and initialize a SendMessageRequest instance
    
    SendMessageRequest sendMessageRequest = new SendMessageRequest();
    sendMessageRequest.QueueUrl = myQueueURL; 
    sendMessageRequest.MessageBody = "{YOUR_QUEUE_MESSAGE}";
    
    //step 2 pass your request as a param to the SendMessage method
    
    SendMessageResponse sendMessageResponse = sqsClient.SendMessage(sendMessageRequest);
    
    //send batch of messsages
    //step 1 create and intialize a SendMessageRequestInstance with a list of messages
    
    var sendMessageBatchRequest = new SendMessageBatchRequest
    {
        Entries = new List<SendMessageBatchRequestEntry>
        {
            new SendMessageBatchRequestEntry("message1", "FirstMessageContent"),
            new SendMessageBatchRequestEntry("message2", "SecondMessageContent"),
            new SendMessageBatchRequestEntry("message3", "ThirdMessageContent")
        },
        QueueUrl = "SQS_QUEUE_URL"
    };
    
    //if using .NET Core, make sure to use await keyword and async method
    //step 2 pass the request as a param to the SendMessage method
    
    SendMessageBatchResponse response = client.SendMessageBatch(sendMessageBatchRequest);
    Console.WriteLine("Messages successfully sent:");
    foreach (var success in response.Successful)
    {
        Console.WriteLine("    Message id : {0}", success.MessageId);
        Console.WriteLine("    Message content MD5 : {0}", success.MD5OfMessageBody);
    }
    
    Console.WriteLine("Messages failed to send:");
    foreach (var failed in response.Failed)
    {
        Console.WriteLine("    Message id : {0}", failed.Id);
        Console.WriteLine("    Message content : {0}", failed.Message);
        Console.WriteLine("    Sender's fault? : {0}", failed.SenderFault);
    }
    Code Sample: Receive a message from an Amazon SQS Queue
    //create and initialize a ReceiveMessageRequest instance
    ReceiveMessageRequest receiveMessageRequest = new ReceiveMessageRequest();
    
    receiveMessageRequest.QueueUrl = myQueueURL;
    
    //if using .NET Core, make sure to use await keyword and async method
    //pass the request as a param to the ReceiveMessage method
    var receiveMessageResponse = sqsClient.ReceiveMessage(receiveMessageRequest);
    
    //
    foreach (var message in receiveMessageResponse.Messages)
    {
       // call a method to process messages and pass in message
    }
    Code Sample: Delete a Message from an Amazon SQS Queue
    //create and initialize a DeleteMessageRequest instance
    DeleteMessageRequest deleteMessageRequest = new DeleteMessageRequest();
    
    deleteMessageRequest.QueueUrl = queueUrl;
    deleteMessageRequest.ReceiptHandle = receiptHandle;
    
    //if using .NET Core, make sure to use await keyword and async method
    //pass the request as a param to the DeleteMessage method.
    var response = sqsClient.DeleteMessage(deleteMessageRequest);
  • Amazon SNS
  • Code Sample: List Amazon SNS Topics
    // using Amazon.SimpleNotificationService;
    // using Amazon.SimpleNotificationService.Model;
    
    var client = new AmazonSimpleNotificationServiceClient();
    var request = new ListTopicsRequest();
    var response = new ListTopicsResponse();
    
    do
    {
    //if using .NET Core, make sure to use await keyword and async method
      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));
    Code Sample: Create/Delete Topic
    //if using .NET Core, make sure to use await keyword and async method
    // Create topic
    string topicArn = client.CreateTopic(new CreateTopicRequest
    {
        Name = topicName
    }).CreateTopicResult.TopicArn;
    
    // Delete topic
    client.DeleteTopic(new DeleteTopicRequest
    {
        TopicArn = topicArn
    });
    Code Sample: Subscribe to an Endpoint
    //if using .NET Core, make sure to use await keyword and async method
    client.Subscribe(new SubscribeRequest
    {
        TopicArn = topicArn,
        Protocol = "email",
        Endpoint = "sample@example.com"
    });
    Code Sample: Publish a message
    //if using .NET Core, make sure to use await keyword and async method
    client.Publish(new PublishRequest
    {
        Subject = "Test",
        Message = "Testing testing 1 2 3",
        TopicArn = topicArn
    });
    
  • Amazon SES
  • Code Sample: Send an Email
                // Replace sender@example.com with your "From" address. 
                // This address must be verified with Amazon SES.
                const String FROM = "sender@example.com";
                const String FROMNAME = "Sender Name";
    
                // Replace recipient@example.com with a "To" address. If your account 
                // is still in the sandbox, this address must be verified.
                const String TO = "recipient@example.com";
    
                // Replace smtp_username with your Amazon SES SMTP user name.
                const String SMTP_USERNAME = "smtp_username";
    
                // Replace smtp_password with your Amazon SES SMTP user name.
                const String SMTP_PASSWORD = "smtp_password";
    
                // (Optional) the name of a configuration set to use for this message.
                // If you comment out this line, you also need to remove or comment out
                // the "X-SES-CONFIGURATION-SET" header below.
                const String CONFIGSET = "ConfigSet";
    
                // If you're using Amazon SES in a region other than US West (Oregon), 
                // replace email-smtp.us-west-2.amazonaws.com with the Amazon SES SMTP  
                // endpoint in the appropriate Region.
                const String HOST = "email-smtp.us-west-2.amazonaws.com";
                
                // The port you will connect to on the Amazon SES SMTP endpoint. We
                // are choosing port 587 because we will use STARTTLS to encrypt
                // the connection.
                const int PORT = 587;
    
                // The subject line of the email
                const String SUBJECT =
                    "Amazon SES test (SMTP interface accessed using C#)";
                
                // The body of the email
                const String BODY =
                    "<h1>Amazon SES Test</h1>" +
                    "<p>This email was sent through the "+
                    "<a href='https://aws.amazon.com/ses'>Amazon SES</a> SMTP interface " +
                    "using the .NET System.Net.Mail library.</p>";
    
                // Create and build a new MailMessage object
                MailMessage message = new MailMessage();
                message.IsBodyHtml = true;
                message.From = new MailAddress(FROM,FROMNAME);
                message.To.Add(new MailAddress(TO));
                message.Subject = SUBJECT;
                message.Body = BODY;
                // Comment or delete the next line if you are not using a configuration set
                message.Headers.Add("X-SES-CONFIGURATION-SET", CONFIGSET);
    
                // Create and configure a new SmtpClient
                SmtpClient client =
                    new SmtpClient(HOST, PORT);
                // Pass SMTP credentials
                client.Credentials =
                    new NetworkCredential(SMTP_USERNAME, SMTP_PASSWORD);
                // Enable SSL encryption
                client.EnableSsl = true;
                 
                 //if using .NET Core, make sure to use await keyword and async method
                // Send the email. 
                try
                {
                    Console.WriteLine("Attempting to send email...");
                    client.Send(message);
                    Console.WriteLine("Email sent!");
                }
                catch (Exception ex)
                {
                    Console.WriteLine("The email was not sent.");
                    Console.WriteLine("Error message: " + ex.Message);
                }

Deployment

Code Sample: Launch an Amazon EC2 Instance in EC2-Classic
///create an ec2 client
var ec2Client = new AmazonEC2Client();

//step 1- initialize a RunInstancesRequest
string amiID = "ami-e189c8d1";
string keyPairName = "my-sample-key";

//optional to launch instance with IAM role
var instanceProfile = new IamInstanceProfile();
instanceProfile.Id  = "winapp-instance-role-1";

List<string> groups = new List<string>() { mySG.GroupId };
var launchRequest = new RunInstancesRequest()
{
  ImageId = amiID,
  InstanceType = InstanceType.T1Micro,
  MinCount = 1,
  MaxCount = 1,
  KeyName = keyPairName,
  SecurityGroupIds = groups,
  IamInstanceProfile = instanceProfile //optional property
};

//if using .NET Core, make sure to use await keyword and async method
//step 2 launch the instance by passing the request object to the RunInstances Method

var launchResponse = ec2Client.RunInstances(launchRequest);
var instances = launchResponse.Reservation.Instances;
var instanceIds = new List<string>();
foreach (Instance item in instances)
{
  instanceIds.Add(item.InstanceId);
  Console.WriteLine();
  Console.WriteLine("New instance: " + item.InstanceId);
  Console.WriteLine("Instance state: " + item.State.Name);
}



Code Sample: Launch an Amazon EC2 Instance in a VPC
///create an ec2 client
var ec2Client = new AmazonEC2Client();

//step 1- create and initialize an elastic network interface in a subnet of the VPC

string subnetID = "subnet-cb663da2";

List<string> groups = new List<string>() { mySG.GroupId };
var eni = new InstanceNetworkInterfaceSpecification()
{
  DeviceIndex = 0,
  SubnetId = subnetID,
  Groups = groups,
  AssociatePublicIpAddress = true
};
List<InstanceNetworkInterfaceSpecification> enis = new List<InstanceNetworkInterfaceSpecification>() {eni};

//step 2 create and initialize a RunInstancesRequest object

string amiID = "ami-e189c8d1";
string keyPairName = "my-sample-key";

//optional lines to launch with an IAM role

var instanceProfile = new IamInstanceProfileSpecification();
instanceProfile.Name  = "winapp-instance-role-1";

var launchRequest = new RunInstancesRequest()
{
  ImageId = amiID,
  InstanceType = InstanceType.T1Micro,
  MinCount = 1,
  MaxCount = 1,
  KeyName = keyPairName,
  NetworkInterfaces = enis,
  IamInstanceProfile = instanceProfile //optional property to launch with iam role
};

//if using .NET Core, make sure to use await keyword and async method
//step 3 launch the instance by passing the request object to the RunInstances Method

RunInstancesResponse launchResponse = ec2Client.RunInstances(launchRequest);

List<String> instanceIds = new List<string>();
foreach (Instance instance in launchResponse.Reservation.Instances)
{
  Console.WriteLine(instance.InstanceId);
  instanceIds.Add(instance.InstanceId);
}
Code Sample: Terminate an Amazon EC2 Instance
public static void TerminateInstance(
  AmazonEC2Client ec2Client,
  string instanceId)
{
  //if using .NET Core, make sure to use await keyword and async method
  var request = new TerminateInstancesRequest();
  request.InstanceIds = new List<string>() { instanceId };

  try
  {
    var response = ec2Client.TerminateInstances(request);
    foreach (InstanceStateChange item in response.TerminatingInstances)
    {
      Console.WriteLine("Terminated instance: " + item.InstanceId);
      Console.WriteLine("Instance state: " + item.CurrentState.Name);
    }
  }
  catch(AmazonEC2Exception ex)
  {
    // Check the ErrorCode to see if the instance does not exist.
    if ("InvalidInstanceID.NotFound" == ex.ErrorCode)
    {
      Console.WriteLine("Instance {0} does not exist.", instanceId);
    }
    else
    {
      // The exception was thrown for another reason, so re-throw the exception.
      throw;
    }
  }
}

Storage

  • Amazon DynamoDb
  • Amazon S3
  • Amazon Glacier
  • Amazon DynamoDb
  • Code Samples for Object Persistence Model

    Code Sample: Defining a .NET Class that Represents an Item in a Table
    // using Amazon.DynamoDBv2.DataModel;
    
    [DynamoDBTable("AnimalsInventory")]
    class Item
    {
      [DynamoDBHashKey]
      public int Id { get; set; }
      [DynamoDBRangeKey]
      public string Type { get; set; }
      public string Name { get; set; }
    }
    Using an Instance of the .NET Class to Insert an Item into a Table
    //Insert into DynamoTable using Object Persistence Model
    
    // using Amazon.DynamoDBv2;
    // using Amazon.DynamoDBv2.DataModel;
        
    var client = new AmazonDynamoDBClient();
    var context = new DynamoDBContext(client);
    var item = new Item
    {
      Id = 4,
      Type = "Fish",
      Name = "Goldie"
    };
    
    //if using .NET Core, make sure to use await keyword and async method
    context.Save(item);
    Using an Instance of a .NET Object to Get an Item from a Table
    // using Amazon.DynamoDBv2;
    // using Amazon.DynamoDBv2.DataModel;
    
    var client = new AmazonDynamoDBClient();
    var context = new DynamoDBContext(client);
    //if using .NET Core, make sure to use await keyword and async method of Load
    var item = context.Load<Item>(4, "Fish");
    
    Console.WriteLine("Id = {0}", item.Id);
    Console.WriteLine("Type = {0}", item.Type);
    Console.WriteLine("Name = {0}", item.Name);
  • Amazon S3
  • Code Sample: Create a Bucket
    using Amazon.S3;
    using Amazon.S3.Model;
    using Amazon.S3.Util;
    using System;
    using System.Threading.Tasks;
    
    namespace Amazon.DocSamples.S3
    {
        class CreateBucketTest
        {
            private const string bucketName = "*** bucket name ***";
            // Specify your bucket region (an example region is shown).
            private static readonly RegionEndpoint bucketRegion = RegionEndpoint.USWest2;
            private static IAmazonS3 s3Client;
            public static void Main()
            {
                s3Client = new AmazonS3Client(bucketRegion);
                CreateBucketAsync().Wait();
            }
    
            static async Task CreateBucketAsync()
            {
                try
                {
                    if (!(await AmazonS3Util.DoesS3BucketExistAsync(s3Client, bucketName)))
                    {
                        var putBucketRequest = new PutBucketRequest
                        {
                            BucketName = bucketName,
                            UseClientRegion = true
                        };
    
                        PutBucketResponse putBucketResponse = await s3Client.PutBucketAsync(putBucketRequest);
                    }
                    // Retrieve the bucket location.
                    string bucketLocation = await FindBucketLocationAsync(s3Client);
                }
                catch (AmazonS3Exception e)
                {
                    Console.WriteLine("Error encountered on server. Message:'{0}' when writing an object", e.Message);
                }
                catch (Exception e)
                {
                    Console.WriteLine("Unknown encountered on server. Message:'{0}' when writing an object", e.Message);
                }
            }
            static async Task<string> FindBucketLocationAsync(IAmazonS3 client)
            {
                string bucketLocation;
                var request = new GetBucketLocationRequest()
                {
                    BucketName = bucketName
                };
                GetBucketLocationResponse response = await client.GetBucketLocationAsync(request);
                bucketLocation = response.Location.ToString();
                return bucketLocation;
            }
        }
    }
    Code Sample: Upload Object in a Single Operation
    using Amazon.S3;
    using Amazon.S3.Model;
    using System;
    using System.Threading.Tasks;
    
    namespace Amazon.DocSamples.S3
    {
        class UploadObjectTest
        {
            private const string bucketName = "*** bucket name ***";
            // Example creates two objects (for simplicity, we upload same file twice).
            // You specify key names for these objects.
            private const string keyName1 = "*** key name for first object created ***";
            private const string keyName2 = "*** key name for second object created ***";
            private const string filePath = @"*** file path ***";
            private static readonly RegionEndpoint bucketRegion = RegionEndpoint.EUWest1; 
    
            private static IAmazonS3 client;
    
            public static void Main()
            {
                client = new AmazonS3Client(bucketRegion);
                WritingAnObjectAsync().Wait();
            }
    
            static async Task WritingAnObjectAsync()
            {
                try
                {
                    // 1. Put object-specify only key name for the new object.
                    var putRequest1 = new PutObjectRequest
                    {
                        BucketName = bucketName,
                        Key = keyName1,
                        ContentBody = "sample text"
                    };
    
                    PutObjectResponse response1 = await client.PutObjectAsync(putRequest1);
    
                    // 2. Put the object-set ContentType and add metadata.
                    var putRequest2 = new PutObjectRequest
                    {
                        BucketName = bucketName,
                        Key = keyName2,
                        FilePath = filePath,
                        ContentType = "text/plain"
                    };
                    putRequest2.Metadata.Add("x-amz-meta-title", "someTitle");
                }
                catch (AmazonS3Exception e)
                {
                    Console.WriteLine(
                            "Error encountered ***. Message:'{0}' when writing an object"
                            , e.Message);
                }
                catch (Exception e)
                {
                    Console.WriteLine(
                        "Unknown encountered on server. Message:'{0}' when writing an object"
                        , e.Message);
                }
            }
        }
    }
    Code Sample: Upload Object using Multipart Upload - High Level API
    using Amazon.Runtime;
    using Amazon.S3;
    using Amazon.S3.Model;
    using System;
    using System.Collections.Generic;
    using System.IO;
    using System.Threading.Tasks;
    
    namespace Amazon.DocSamples.S3
    {
        class UploadFileMPULowLevelAPITest
        {
            private const string bucketName = "*** provide bucket name ***";
            private const string keyName = "*** provide a name for the uploaded object ***";
            private const string filePath = "*** provide the full path name of the file to upload ***";
            // Specify your bucket region (an example region is shown).
            private static readonly RegionEndpoint bucketRegion = RegionEndpoint.USWest2;
            private static IAmazonS3 s3Client;
    
            public static void Main()
            {
                s3Client = new AmazonS3Client(bucketRegion);
                Console.WriteLine("Uploading an object");
                UploadObjectAsync().Wait(); 
            }
    
            private static async Task UploadObjectAsync()
            {
                // Create list to store upload part responses.
                List<UploadPartResponse> uploadResponses = new List<UploadPartResponse>();
    
                // Setup information required to initiate the multipart upload.
                InitiateMultipartUploadRequest initiateRequest = new InitiateMultipartUploadRequest
                {
                    BucketName = bucketName,
                    Key = keyName
                };
    
                // Initiate the upload.
                InitiateMultipartUploadResponse initResponse =
                    await s3Client.InitiateMultipartUploadAsync(initiateRequest);
    
                // Upload parts.
                long contentLength = new FileInfo(filePath).Length;
                long partSize = 5 * (long)Math.Pow(2, 20); // 5 MB
    
                try
                {
                    Console.WriteLine("Uploading parts");
            
                    long filePosition = 0;
                    for (int i = 1; filePosition < contentLength; i++)
                    {
                        UploadPartRequest uploadRequest = new UploadPartRequest
                            {
                                BucketName = bucketName,
                                Key = keyName,
                                UploadId = initResponse.UploadId,
                                PartNumber = i,
                                PartSize = partSize,
                                FilePosition = filePosition,
                                FilePath = filePath
                            };
    
                        // Track upload progress.
                        uploadRequest.StreamTransferProgress +=
                            new EventHandler<StreamTransferProgressArgs>(UploadPartProgressEventCallback);
    
                        // Upload a part and add the response to our list.
                        uploadResponses.Add(await s3Client.UploadPartAsync(uploadRequest));
    
                        filePosition += partSize;
                    }
    
                    // Setup to complete the upload.
                    CompleteMultipartUploadRequest completeRequest = new CompleteMultipartUploadRequest
                        {
                            BucketName = bucketName,
                            Key = keyName,
                            UploadId = initResponse.UploadId
                         };
                    completeRequest.AddPartETags(uploadResponses);
    
                    // Complete the upload.
                    CompleteMultipartUploadResponse completeUploadResponse =
                        await s3Client.CompleteMultipartUploadAsync(completeRequest);
                }
                catch (Exception exception)
                {
                    Console.WriteLine("An AmazonS3Exception was thrown: { 0}", exception.Message);
    
                    // Abort the upload.
                    AbortMultipartUploadRequest abortMPURequest = new AbortMultipartUploadRequest
                    {
                        BucketName = bucketName,
                        Key = keyName,
                        UploadId = initResponse.UploadId
                    };
                   await s3Client.AbortMultipartUploadAsync(abortMPURequest);
                }
            }
            public static void UploadPartProgressEventCallback(object sender, StreamTransferProgressArgs e)
            {
                // Process event. 
                Console.WriteLine("{0}/{1}", e.TransferredBytes, e.TotalBytes);
            }
        }
    }
    
    Code Sample: Get Object
    //if using .NET Core, make sure to use await keyword and async method
    GetObjectRequest request = new GetObjectRequest 
    {
        BucketName = bucketName,
        Key = keyName
    };
    
    ResponseHeaderOverrides responseHeaders = new ResponseHeaderOverrides();
    responseHeaders.CacheControl = "No-cache";
    responseHeaders.ContentDisposition = "attachment; filename=testing.txt";
    
    request.ResponseHeaderOverrides = responseHeaders;
    Code Sample: Delete Object from a NonVersioned Bucket
    using Amazon.S3;
    using Amazon.S3.Model;
    using System;
    using System.Threading.Tasks;
    
    namespace Amazon.DocSamples.S3
    {
        class DeleteObjectNonVersionedBucketTest
        {
            private const string bucketName = "*** bucket name ***"; 
            private const string keyName = "*** object key ***";
            // Specify your bucket region (an example region is shown).
            private static readonly RegionEndpoint bucketRegion = RegionEndpoint.USWest2;
            private static IAmazonS3 client;
    
            public static void Main()
            {
                client = new AmazonS3Client(bucketRegion);
                DeleteObjectNonVersionedBucketAsync().Wait();
            }
    
            private static async Task DeleteObjectNonVersionedBucketAsync()
            {
                try
                {
                    var deleteObjectRequest = new DeleteObjectRequest
                    {
                        BucketName = bucketName,
                        Key = keyName
                    };
    
                    Console.WriteLine("Deleting an object");
                    await client.DeleteObjectAsync(deleteObjectRequest);
                }
                catch (AmazonS3Exception e)
                {
                    Console.WriteLine("Error encountered on server. Message:'{0}' when writing an object", e.Message);
                }
                catch (Exception e)
                {
                    Console.WriteLine("Unknown encountered on server. Message:'{0}' when writing an object", e.Message);
                }
            }
        }
    }
  • Amazon Glacier
  • Code Sample: Create/Delete a Vault using High Level API
    using System;
    using Amazon.Glacier;
    using Amazon.Glacier.Transfer;
    using Amazon.Runtime;
    
    namespace glacier.amazon.com.docsamples
    {
      class VaultCreateDescribeListVaultsDeleteHighLevel
      {
        static string vaultName = "*** Provide vault name ***";
    
        public static void Main(string[] args)
        {
          try
          {
              var manager = new ArchiveTransferManager(Amazon.RegionEndpoint.USWest2);
             //if using .NET Core, make sure to use await keyword and async methods
              manager.CreateVault(vaultName);
              Console.WriteLine("Vault created. To delete the vault, press Enter");
              Console.ReadKey();
              manager.DeleteVault(vaultName);
              Console.WriteLine("\nVault deleted. To continue, press Enter");
              Console.ReadKey();
          }
          catch (AmazonGlacierException e) { Console.WriteLine(e.Message); }
          catch (AmazonServiceException e) { Console.WriteLine(e.Message); }
          catch (Exception e) { Console.WriteLine(e.Message); }
          Console.WriteLine("To continue, press Enter");
          Console.ReadKey();
        }
      }
    }
    Code Sample: Retrieve Metadata for a Vault
    AmazonGlacierClient client;
    client = new AmazonGlacierClient(Amazon.RegionEndpoint.USWest2);
    
    DescribeVaultRequest describeVaultRequest = new DescribeVaultRequest()
    {
      VaultName = "*** Provide vault name ***"
    };  
    //if using .NET Core, make sure to use await keyword and async method
    DescribeVaultResponse describeVaultResponse = client.DescribeVault(describeVaultRequest);
    Console.WriteLine("\nVault description...");
    Console.WriteLine(
       "\nVaultName: " + describeVaultResponse.VaultName +
       "\nVaultARN: " + describeVaultResponse.VaultARN +
       "\nVaultCreationDate: " + describeVaultResponse.CreationDate +
       "\nNumberOfArchives: " + describeVaultResponse.NumberOfArchives +
       "\nSizeInBytes: " + describeVaultResponse.SizeInBytes +
       "\nLastInventoryDate: " + describeVaultResponse.LastInventoryDate 
       );
    Code Sample: Upload an Archive
    using System;
    using Amazon.Glacier;
    using Amazon.Glacier.Transfer;
    using Amazon.Runtime;
    
    namespace glacier.amazon.com.docsamples
    {
      class ArchiveUploadHighLevel
      {
        static string vaultName = "examplevault"; 
        static string archiveToUpload = "*** Provide file name (with full path) to upload ***";
    
        public static void Main(string[] args)
        {
           try
          {
             var manager = new ArchiveTransferManager(Amazon.RegionEndpoint.USWest2);
             // Upload an archive.
             //if using .NET Core, make sure to use await keyword and async method
             string archiveId = manager.Upload(vaultName, "upload archive test", archiveToUpload).ArchiveId;
             Console.WriteLine("Archive ID: (Copy and save this ID for use in other examples.) : {0}", archiveId);
             Console.WriteLine("To continue, press Enter"); 
             Console.ReadKey();
          }
          catch (AmazonGlacierException e) { Console.WriteLine(e.Message); }
          catch (AmazonServiceException e) { Console.WriteLine(e.Message); }
          catch (Exception e) { Console.WriteLine(e.Message); }
          Console.WriteLine("To continue, press Enter");
          Console.ReadKey();
        }
      }
    }
    Code Sample: Delete an Archive using High Level API
    using System;
    using Amazon.Glacier;
    using Amazon.Glacier.Transfer;
    using Amazon.Runtime; 
    
    namespace glacier.amazon.com.docsamples
    {
      class ArchiveDeleteHighLevel
      {
        static string vaultName = "examplevault";
        static string archiveId = "*** Provide archive ID ***";
    
        public static void Main(string[] args)
        {
          try
          {
            var manager = new ArchiveTransferManager(Amazon.RegionEndpoint.USWest2);
            //if using .NET Core, make sure to use await keyword and async method
            manager.DeleteArchive(vaultName, archiveId);
            Console.ReadKey();
          }
          catch (AmazonGlacierException e) { Console.WriteLine(e.Message); }
          catch (AmazonServiceException e) { Console.WriteLine(e.Message); }
          catch (Exception e) { Console.WriteLine(e.Message); }
          Console.WriteLine("To continue, press Enter");
          Console.ReadKey();
        }
      }
    }

Join a Virtual .NET Community