Exemplo n.º 1
0
        public static void Main(string[] args)
        {
            LabVariables labVariables = null;
            var          program      = new Program();

            try
            {
                // Start the "prep" mode operations to make sure that the resources are all in the expected state.
                Console.WriteLine("Starting up in \"prep\" mode.");
                labVariables = program.PrepMode_Run();

                Console.WriteLine("\nPrep complete. Transitioning to \"app\" mode.");
                program.AppMode_Run(labVariables);
            }
            catch (Exception ex)
            {
                LabUtility.DumpError(ex);
            }
            finally
            {
                try
                {
                    if (labVariables != null)
                    {
                        Console.Write("\nLab run completed. Cleaning up buckets.");

                        AWSCredentials credentials =
                            new BasicAWSCredentials(ConfigurationManager.AppSettings["prepModeAWSAccessKey"],
                                                    ConfigurationManager.AppSettings["prepModeAWSSecretKey"]);

                        var s3Client = new AmazonS3Client(credentials, RegionEndpoint);

                        OptionalLabCode.RemoveLabBuckets(s3Client, labVariables.BucketNames);
                        Console.WriteLine(" Done.");
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine("\nAttempt to clean up buckets failed. {0}", ex.Message);
                }

                Console.WriteLine("\nPress <enter> to end.");
                Console.ReadLine();
            }
        }
Exemplo n.º 2
0
        private static void Main()
        {
            try
            {
                // Create an S3 client
                var s3Client = new AmazonS3Client(RegionEndpoint);

                // Create a unique bucket name
                var bucketName = "awslab" + Guid.NewGuid().ToString().Substring(0, 8);
                Console.WriteLine("Creating bucket: {0}", bucketName);
                LabCode.CreateBucket(s3Client, bucketName);
                Console.WriteLine("Bucket created.\n");

                // Make sure that our file is here and then call method to upload it to S3
                if (!File.Exists(TEST_IMAGE_PNG))
                {
                    Console.WriteLine("The file {0} was not found in the application directory.", TEST_IMAGE_PNG);
                    Console.WriteLine("Please add it to your project and set its \"Build Action\" property");
                    Console.WriteLine("to \"Content\" and its \"Copy to Output Directory\" property to \"Copy Always.\"");
                    return;
                }
                Console.WriteLine("Uploading object: {0}", TEST_IMAGE_PNG);
                LabCode.PutObject(s3Client, bucketName, TEST_IMAGE_PNG, TEST_IMAGE_PNG);
                Console.WriteLine("Upload complete.\n");

                // Now upload another copy. Later, we'll use this one to demonstrate ACL modification.
                if (!File.Exists(TEST_IMAGE_PNG))
                {
                    Console.WriteLine("The file {0} was not found in the application directory.", TEST_IMAGE2_PNG);
                    Console.WriteLine("Please add it to your project and set its \"Build Action\" property");
                    Console.WriteLine("to \"Content\" and its \"Copy to Output Directory\" property to \"Copy Always.\"");
                    return;
                }
                Console.WriteLine("Uploading a similar object (will be made publicly available later)");
                LabCode.PutObject(s3Client, bucketName, TEST_IMAGE2_PNG, PUBLIC_TEST_IMAGE_PNG);

                Console.WriteLine("Upload complete.\n");

                // List objects in the bucket
                Console.WriteLine("Listing items in bucket: {0}", bucketName);
                LabCode.ListObjects(s3Client, bucketName);
                Console.WriteLine("Listing complete.\n");

                // Change the ACL on one of the objects to make it public
                Console.WriteLine("Changing the ACL to make an object public");
                LabCode.MakeObjectPublic(s3Client, bucketName, PUBLIC_TEST_IMAGE_PNG);
                Console.WriteLine("Done the object should be publicly available now.");
                Console.WriteLine("The URL below has been copied into your clippboard. Test it.");
                string publicUrl = String.Format("http://{0}.s3.amazonaws.com/{1}\n", bucketName, PUBLIC_TEST_IMAGE_PNG);
                Console.WriteLine(publicUrl);
                Clipboard.SetText(publicUrl);

                Console.WriteLine("Press <enter> to continue to the next step.");
                Console.ReadLine();

                // Generate a pre-signed URL for an object to grant temporary access to the file.
                Console.WriteLine("Generating presigned URL.");
                string presignedUrl = LabCode.GeneratePreSignedUrl(s3Client, bucketName, TEST_IMAGE_PNG);
                Console.WriteLine("Done. {0}\n", presignedUrl);
                Console.WriteLine("The URL has been copied into your clippboard. Test it.");
                Clipboard.SetText(presignedUrl);
                Console.WriteLine("Press <enter> to continue to the next step.");
                Console.ReadLine();
                Console.Write("Deleting lab bucket.");
                OptionalLabCode.DeleteBucket(s3Client, bucketName);
                Console.WriteLine(" Done.");
            }
            catch (Exception ex)
            {
                LabUtility.DumpError(ex);
            }
            finally
            {
                Console.WriteLine("\n\nPress <enter> to end.");
                Console.ReadLine();
            }
        }
Exemplo n.º 3
0
        public static void Main(string[] args)
        {
            try
            {
                using (var snsClient = new AmazonSimpleNotificationServiceClient(RegionEndpoint))
                {
                    using (var sqsClient = new AmazonSQSClient(RegionEndpoint))
                    {
                        const string queueName = "Notifications";
                        const string topicName = "ClassroomEvent";

                        // Creating the queue will fail if we've just deleted it and are recreating it
                        // which is a possibility if you're tracking down a code error. If that happens,
                        // pause and retry for up to a minute.
                        Console.WriteLine("Creating {0} queue.", queueName);

                        bool     retry = true, notified = false;
                        DateTime start    = DateTime.Now;
                        string   queueUrl = "";

                        while (retry)
                        {
                            try
                            {
                                // Create an SQS queue
                                queueUrl = LabCode.CreateQueue(sqsClient, queueName);
                                retry    = false;
                            }
                            catch (AmazonSQSException ex)
                            {
                                if (!ex.ErrorCode.Equals("AWS.SimpleQueueService.QueueDeletedRecently"))
                                {
                                    // This is an unexpected error, so waiting and retrying may not help.
                                    // Just rethrow.
                                    throw;
                                }

                                if (DateTime.Now < (start + TimeSpan.FromSeconds(60)))
                                {
                                    if (!notified)
                                    {
                                        Console.WriteLine(
                                            "The attempt to recreate the queue failed because the queue was deleted too\nrecently. Waiting and retrying for up to 1 minute.");
                                        notified = true;
                                    }
                                    // Timeout hasn't expired yet so wait and retry in 5 seconds.
                                    Console.Write(".");
                                    Thread.Sleep(TimeSpan.FromSeconds(5));
                                }
                                else
                                {
                                    Console.WriteLine("Retry timeout expired. Aborting.");
                                    throw;
                                }
                            }
                        }
                        if (notified)
                        {
                            Console.WriteLine("Recovered.");
                        }
                        Console.WriteLine("URL for new queue:\n    {0}", queueUrl);
                        // List SQS queues
                        Console.WriteLine("Getting ARN for {0} queue.", queueName);
                        string queueArn = LabCode.GetQueueArn(sqsClient, queueUrl);
                        Console.WriteLine("ARN for queue: {0}", queueArn);

                        // Create an SNS topic and get ARN
                        Console.WriteLine("Creating {0} topic.", topicName);
                        string topicArn = LabCode.CreateTopic(snsClient, topicName);
                        Console.WriteLine("New topic ARN: {0}", topicArn);

                        Console.WriteLine("Granting the notification topic permission to post in the queue.");
                        OptionalLabCode.GrantNotificationPermission(sqsClient, queueArn, queueUrl, topicArn);
                        Console.WriteLine("Permission granted.");

                        // Create an SNS subscription
                        Console.WriteLine("Creating SNS subscription.");
                        LabCode.CreateSubscription(snsClient, queueArn, topicArn);
                        Console.WriteLine("Subscription created.");

                        // Publish message to topic
                        var messageText    = "This is the SNS topic notification body.";
                        var messageSubject = "SNSTopicNotification";

                        Console.WriteLine("Publishing SNS topic notification.");
                        LabCode.PublishTopicMessage(snsClient, topicArn, messageSubject, messageText);
                        Console.WriteLine("Notification published.");

                        // Send a message to the "Notifications" queue
                        messageText = "This is the message posted to the queue directly.";
                        Console.WriteLine("Posting message to queue directly.");
                        LabCode.PostToQueue(sqsClient, queueUrl, messageText);
                        Console.WriteLine("Message posted.");

                        //Console.WriteLine(">> PAUSING FOR A MOMENT <<");
                        //Thread.Sleep(TimeSpan.FromSeconds(5));

                        // Read messages from queue
                        Console.WriteLine("Reading messages from queue.");

                        List <Message> messages = LabCode.ReadMessages(sqsClient, queueUrl);
                        // We expect two messages here
                        if (messages.Count < 2)
                        {
                            // Try to read again and see if we've picked up the missing message(s).
                            messages.AddRange(LabCode.ReadMessages(sqsClient, queueUrl));
                            if (messages.Count < 2)
                            {
                                Console.WriteLine(
                                    ">>WARNING<< We didn't receive the expected number of messages. Investigate.");
                            }
                            else
                            {
                                Console.WriteLine(
                                    "\n===============================================================================");
                                Console.WriteLine(
                                    "PROBLEM: ReadMessages() had to be called twice to collect all the messages.");
                                Console.WriteLine(
                                    "         Did you remember to set the MaxNumberOfMessages property in the ");
                                Console.WriteLine("         ReceiveMessageRequest object?");
                                Console.WriteLine(
                                    "===============================================================================\n");
                            }
                        }
                        PrintAndRemoveMessagesInResponse(sqsClient, messages, queueUrl);

                        // Locate and delete the SNS subscription
                        Console.WriteLine("Removing provisioned resources.");
                        LabCode.DeleteSubscriptions(snsClient, topicArn);
                        Console.WriteLine("Subscriptions removed.");

                        // Delete the SNS Topic
                        LabCode.DeleteTopic(snsClient, topicArn);
                        Console.WriteLine("Topic deleted.");
                        // Locate the previously created queue and delete
                        LabCode.DeleteQueue(sqsClient, queueUrl);
                        Console.WriteLine("Queue deleted.");
                    }
                }
            }
            catch (Exception ex)
            {
                LabUtility.DumpError(ex);
            }
            finally
            {
                Console.WriteLine("\n\nPress <enter> to end.");
                Console.ReadLine();
            }
        }
Exemplo n.º 4
0
        /// <summary>
        /// Controlling method for the lab.
        /// </summary>
        public static void Main()
        {
            using (var ddbClient = new AmazonDynamoDBClient(RegionEndpoint))
            {
                const string tableName    = "Accounts";
                var          accountItems = new List <Account>
                {
                    new Account
                    {
                        Company = "Amazon.com",
                        Email   = "*****@*****.**",
                        First   = "John",
                        Last    = "Doe",
                        Age     = "33"
                    },
                    new Account
                    {
                        Company = "Asperatus Tech",
                        Email   = "*****@*****.**",
                        First   = "Jane",
                        Last    = "Doe",
                        Age     = "24"
                    },
                    new Account
                    {
                        Company = "Amazon.com",
                        Email   = "*****@*****.**",
                        First   = "Jim",
                        Last    = "Johnson"
                    }
                };

                try
                {
                    // Verify that the table schema is as we expect, and correct any problems we find.
                    if (!ConfirmTableSchema(ddbClient, tableName))
                    {
                        OptionalLabCode.DeleteTable(ddbClient, tableName);
                        OptionalLabCode.BuildTable(ddbClient, tableName);
                    }

                    Console.WriteLine("Adding items to table.");
                    // Create an account item
                    foreach (Account account in accountItems)
                    {
                        LabCode.CreateAccountItem(ddbClient, tableName, account);
                        Console.WriteLine("Added item: {0}/{1}", account.Company, account.Email);
                    }

                    Console.WriteLine("Requesting matches for Company == Amazon.com");
                    QueryResponse response = LabCode.LookupByHashKey(ddbClient, tableName, "Amazon.com");
                    if (response != null && response.Count > 0)
                    {
                        // Record was found
                        foreach (var item in response.Items)
                        {
                            Console.WriteLine("Item Found-");
                            foreach (var attr in item)
                            {
                                Console.WriteLine("    {0} : {1}", attr.Key, attr.Key == "Age" ? attr.Value.N : attr.Value.S);
                            }
                            Console.WriteLine();
                        }
                    }
                    else
                    {
                        Console.WriteLine("No matches found.");
                    }

                    // Conditionally update a record
                    Console.Write("Attempting update. ");
                    LabCode.UpdateIfMatch(ddbClient, tableName, "*****@*****.**", "Amazon.com", "James", "Jim");
                    Console.WriteLine("Done.");
                }
                catch (Exception ex)
                {
                    LabUtility.DumpError(ex);
                }
                finally
                {
                    Console.WriteLine("Press <enter> to end.");
                    Console.ReadLine();
                }
            }
        }