public static string Get(string secretName)
        {
            var config = new AmazonSecretsManagerConfig {
                RegionEndpoint = RegionEndpoint.USEast1
            };
            var credentials = new StoredProfileAWSCredentials("getSecretForRdsUser");
            var client      = new AmazonSecretsManagerClient(credentials, config);

            var request = new GetSecretValueRequest
            {
                SecretId = secretName
            };

            GetSecretValueResponse response = null;

            try
            {
                response = client.GetSecretValueAsync(request).Result;
            }
            catch (ResourceNotFoundException)
            {
                Console.WriteLine("The requested secret " + secretName + " was not found");
            }
            catch (InvalidRequestException e)
            {
                Console.WriteLine("The request was invalid due to: " + e.Message);
            }
            catch (InvalidParameterException e)
            {
                Console.WriteLine("The request had invalid params: " + e.Message);
            }

            return(response?.SecretString);
        }
Example #2
0
        public async Task EditR53Record(Amazon.Route53.Model.ResourceRecordSet rrSet,
                                        bool delete = false)
        {
#pragma warning disable 618 // "'StoredProfileCredentials' is obsolete..."
            //var creds = new BasicAWSCredentials(AwsAccessKey, AwsSecretKey);
            var creds = new StoredProfileAWSCredentials("acmesharp-tests");
#pragma warning restore 618
            var reg = RegionEndpoint.GetBySystemName(AwsRegion);
            using (var r53 = new Amazon.Route53.AmazonRoute53Client(creds, reg))
            {
                var rrRequ = new Amazon.Route53.Model.ChangeResourceRecordSetsRequest
                {
                    HostedZoneId = HostedZoneId,
                    ChangeBatch  = new Amazon.Route53.Model.ChangeBatch
                    {
                        Changes = new List <Amazon.Route53.Model.Change>
                        {
                            new Amazon.Route53.Model.Change
                            {
                                Action = delete
                                    ? Amazon.Route53.ChangeAction.DELETE
                                    : Amazon.Route53.ChangeAction.UPSERT,
                                ResourceRecordSet = rrSet
                            }
                        }
                    }
                };

                var rrResp = await r53.ChangeResourceRecordSetsAsync(rrRequ);
            }
        }
Example #3
0
        public static void Main(string[] args)
        {
            var credentials = new StoredProfileAWSCredentials("default");
            var sqsClient   = new AmazonSQSClient(credentials, RegionEndpoint.EUWest1);

            // Create queue

            var createQueueRequest = new CreateQueueRequest
            {
                QueueName = "BFQueue"
            };

            CreateQueueResponse queue = sqsClient.CreateQueueAsync(createQueueRequest).Result;

            Console.WriteLine("Send a message");

            string message = null;

            while ((message = Console.ReadLine()) != "q")
            {
                var sendMessageRequest = new SendMessageRequest(queue.QueueUrl, message)
                {
                };

                sqsClient.SendMessageAsync(sendMessageRequest);
            }
        }
Example #4
0
        /// <summary>
        /// Initilizes the S3 service.
        /// </summary>
        private AmazonS3Client InitialiseClient()
        {
            // CMD line parameter override?
            var profileName = Parameters.Current.AsString("AWSProfileName");

            if (string.IsNullOrEmpty(profileName))
            {
                // App setting
                profileName = ConfigurationManager.AppSettings["AWSProfileName"];
                if (string.IsNullOrEmpty(profileName))
                {
                    profileName = "default";
                }
            }

            // CMD line parameter override?
            var profileLocation = Parameters.Current.AsString("AWSProfilesLocation");

            if (string.IsNullOrEmpty(profileLocation))
            {
                // App setting
                profileLocation = ConfigurationManager.AppSettings["AWSProfilesLocation"];
                if (string.IsNullOrEmpty(profileLocation))
                {
                    profileLocation = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile) + @"\.aws\config";
                }
            }

            var credentials = new StoredProfileAWSCredentials(profileName, profileLocation);

            return(new AmazonS3Client(credentials, RegionEndpoint.EUWest1));
        }
Example #5
0
    //取得目前該金鑰權限下的所有Bucket列表
    public static List <string> GetBucketList()
    {
        var buckets     = new List <string>();
        var credentials = new StoredProfileAWSCredentials("developer"); //若config檔裡有指定profileName屬性,則此段可省略,下面改寫為 var client = new AmazonS3Client()

        using (var client = new AmazonS3Client(credentials))
        {
            try
            {
                ListBucketsResponse response = client.ListBuckets();

                foreach (S3Bucket bucket in response.Buckets)
                {
                    buckets.Add(bucket.BucketName);
                }
            }
            catch (AmazonS3Exception amazonS3Exception)
            {
                if (amazonS3Exception.ErrorCode != null && (amazonS3Exception.ErrorCode.Equals("InvalidAccessKeyId") || amazonS3Exception.ErrorCode.Equals("InvalidSecurity")))
                {
                    LogTools.Error("Please check the provided AWS Credentials. If you haven't signed up for Amazon S3, please visit http://aws.amazon.com/s3");
                }
                else
                {
                    LogTools.Error(string.Format("An Error, number {0}, occurred when listing buckets with the message '{1}", amazonS3Exception.ErrorCode, amazonS3Exception.Message));
                }
            }
        }

        return(buckets);
    }
Example #6
0
        static void Main(string[] args)
        {
            StoredProfileAWSCredentials credentials = new StoredProfileAWSCredentials("development", @"C:\Users\YaligarN\.aws\credentials");

            var dbclient = new AmazonDynamoDBClient(credentials, RegionEndpoint.APSouth1);
            var access   = new AmazonSQSClient(credentials, RegionEndpoint.APSouth1);

            //var Credentials = new Amazon.Runtime.BasicAWSCredentials("AKIAJ3ZHDUXWC4HLNURA", "vVxclYGcoUFSG0Mx0eBYcE7D839Podwboj/BJS4v");
            //var dbclient = new Amazon.DynamoDBv2.AmazonDynamoDBClient(RegionEndpoint.APSouth1);
            //var access = new Amazon.SQS.AmazonSQSClient(Amazon.RegionEndpoint.APSouth1);

            string queueUrl = "https://sqs.ap-south-1.amazonaws.com/068090245287/Employee";

            Console.WriteLine("It is successfully connected to SQS");
            ReceiveMessageRequest request = new ReceiveMessageRequest(queueUrl);

            request.MaxNumberOfMessages = 3;
            ReceiveMessageResponse response = access.ReceiveMessageAsync(request).Result;

            Console.WriteLine("Message is successfully received from SQS");
            foreach (var message in response.Messages)
            {
                string        xml      = message.Body;
                Table         table    = Table.LoadTable(dbclient, "Employee");
                XmlSerializer ser      = new XmlSerializer(typeof(Demo));
                Demo          Employee = (Demo)ser.Deserialize(new StringReader(xml));
                string        json     = JsonConvert.SerializeObject(Employee, Newtonsoft.Json.Formatting.Indented);
                Console.WriteLine(json);
                var item = Document.FromJson(json);
                table.PutItemAsync(item);
            }
            Console.ReadLine();
        }
Example #7
0
        /// <summary>
        /// Initializes the provider by pulling the config info from the web.config and validate/create the DynamoDB table.
        /// If the table is being created this method will block until the table is active.
        /// </summary>
        /// <param name="name"></param>
        /// <param name="config"></param>
        public override void Initialize(string name, NameValueCollection config)
        {
            if (config == null)
            {
                throw new ArgumentNullException("config");
            }

            base.Initialize(name, config);

            GetConfigSettings(config);


            RegionEndpoint region = null;

            if (!string.IsNullOrEmpty(this._regionName))
            {
                region = RegionEndpoint.GetBySystemName(this._regionName);
            }

            AWSCredentials credentials = null;

            if (!string.IsNullOrEmpty(this._accessKey))
            {
                credentials = new BasicAWSCredentials(this._accessKey, this._secretKey);
            }
            else if (!string.IsNullOrEmpty(this._profileName))
            {
                if (string.IsNullOrEmpty(this._profilesLocation))
                {
                    credentials = new StoredProfileAWSCredentials(this._profileName);
                }
                else
                {
                    credentials = new StoredProfileAWSCredentials(this._profileName, this._profilesLocation);
                }
            }

            AmazonDynamoDBConfig ddbConfig = new AmazonDynamoDBConfig();

            if (region != null)
            {
                ddbConfig.RegionEndpoint = region;
            }
            if (!string.IsNullOrEmpty(this._serviceURL))
            {
                ddbConfig.ServiceURL = this._serviceURL;
            }

            if (credentials != null)
            {
                this._ddbClient = new AmazonDynamoDBClient(credentials, ddbConfig);
            }
            else
            {
                this._ddbClient = new AmazonDynamoDBClient(ddbConfig);
            }

            SetupTable();
        }
Example #8
0
        private static DynamoDBContext GetContext()
        {
            AWSCredentials credentials   = new StoredProfileAWSCredentials("rli-dev", "C:/Users/pnpham/.aws/credentials");
            var            Client        = new AmazonDynamoDBClient(credentials, Amazon.RegionEndpoint.USEast1);
            var            contextConfig = new DynamoDBContextConfig();

            return(new DynamoDBContext(Client, contextConfig));
        }
Example #9
0
        public async System.Threading.Tasks.Task <IHttpActionResult> PostUpload(string folder, string filekey)
        {
            if (!Request.Content.IsMimeMultipartContent())
            {
                throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
            }

            var root = HttpContext.Current.Server.MapPath("~/App_Data/Temp/FileUploads");

            if (!Directory.Exists(root))
            {
                Directory.CreateDirectory(root);
            }
            var provider = new MultipartFormDataStreamProvider(root);

            try
            {
                var result = await Request.Content.ReadAsMultipartAsync(provider);
            }
            catch (Exception ex)
            {
            }

            try
            {
                string    bucketName  = "aws-yeon-test-fims-support";
                var       credentials = new StoredProfileAWSCredentials("s3");
                IAmazonS3 client      = new AmazonS3Client(credentials, Amazon.RegionEndpoint.APNortheast2);

                foreach (var file in provider.FileData)
                {
                    PutObjectRequest putRequest = new PutObjectRequest
                    {
                        BucketName = bucketName,
                        Key        = file.Headers.ContentDisposition.FileName.Substring(1, file.Headers.ContentDisposition.FileName.Length - 2),
                        FilePath   = file.LocalFileName
                                     //ContentType = "text/plain"
                    };
                    putRequest.Headers.ContentLength = 168059;
                    PutObjectResponse response = client.PutObject(putRequest);
                }
            }
            catch (AmazonS3Exception amazonS3Exception)
            {
                return(InternalServerError(amazonS3Exception));
            }
            catch (Exception ex)
            {
                return(InternalServerError(ex));
            }
            finally
            {
            }
            return(Ok());
        }
Example #10
0
        public AmazonS3Operations(String profileName, String credentialFileName, String region)
        {
            /*
             * Morea about AWS Access Keys best practices
             * https://docs.aws.amazon.com/general/latest/gr/aws-access-keys-best-practices.html
             *
             */
            var credentials = new StoredProfileAWSCredentials(profileName, credentialFileName);

            client = new AmazonS3Client(credentials, RegionEndpoint.GetBySystemName(region));
        }
Example #11
0
        /// <summary>
        /// Creates the AWSCredentials using either the profile indicated from the AWSOptions object
        /// of the SDK fallback credentials search.
        /// </summary>
        /// <param name="options"></param>
        /// <returns></returns>
        private static AWSCredentials CreateCredentials(AWSOptions options)
        {
            if (options != null &&
                !string.IsNullOrEmpty(options.Profile) &&
                StoredProfileAWSCredentials.IsProfileKnown(options.Profile, options.ProfilesLocation))
            {
                return(new StoredProfileAWSCredentials(options.Profile, options.ProfilesLocation));
            }

            return(FallbackCredentialsFactory.GetCredentials());
        }
Example #12
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            // Add framework services.
            services.AddApplicationInsightsTelemetry(Configuration);

            services.AddMvc(options =>
            {
                // Default profile to cache things for 1 hour
                options.CacheProfiles.Add("Default",
                                          new CacheProfile()
                {
                    Duration = 3600,
                    Location = ResponseCacheLocation.Any
                });

                // Use this profile to get "no-cache" behavior
                options.CacheProfiles.Add("Never",
                                          new CacheProfile()
                {
                    Location = ResponseCacheLocation.None,
                    NoStore  = true
                });

                // Register global exception handling
                options.Filters.Add(typeof(ExceptionLoggingFilter));
            });

            // Swagger
            services.AddSwaggerGen();
            services.ConfigureSwaggerGen(options =>
            {
                // [TO_FILL application information for swagger]
                options.SingleApiVersion(new Info
                {
                    Version        = "v1",
                    Title          = "My Test API",
                    Description    = "The Web API for testing the awesome Asp.Net Core boiler plate",
                    TermsOfService = "None"
                });
                options.IncludeXmlComments(GetXmlCommentsPath(PlatformServices.Default.Application));
                options.DescribeAllEnumsAsStrings();
            });

            // Inject AWS S3 Client
            var awsProfileName = Configuration.GetSection("AWS")["Profile"];
            var awsRegionName  = Configuration.GetSection("AWS")["Region"];
            var credentials    = new StoredProfileAWSCredentials(awsProfileName);
            var awsRegion      = RegionEndpoint.GetBySystemName(awsRegionName);

            services.AddScoped <IAmazonS3, AmazonS3Client>(sp => new AmazonS3Client(credentials, awsRegion));
            services.AddScoped <AwsS3Client, AwsS3Client>();
            services.AddScoped <LambdaCodePackageUploader, LambdaCodePackageUploader>();
        }
        private static AWSCredentials DetermineCredentials(AWSLoggerConfig config)
        {
            if (config.Credentials != null)
            {
                return(config.Credentials);
            }
            if (!string.IsNullOrEmpty(config.Profile) && StoredProfileAWSCredentials.IsProfileKnown(config.Profile, config.ProfilesLocation))
            {
                return(new StoredProfileAWSCredentials(config.Profile, config.ProfilesLocation));
            }

            return(FallbackCredentialsFactory.GetCredentials());
        }
Example #14
0
        private static IAmACommandProcessor GetCommandProcessor()
        {
            var container = new TinyIoCContainer();

            var messageMapperFactory = new TinyIoCMessageMapperFactory(container);


            //create policies
            var retryPolicy = Policy
                              .Handle <Exception>()
                              .WaitAndRetry(new[]
            {
                TimeSpan.FromMilliseconds(50),
                TimeSpan.FromMilliseconds(100),
                TimeSpan.FromMilliseconds(150)
            });

            var circuitBreakerPolicy = Policy
                                       .Handle <Exception>()
                                       .CircuitBreaker(1, TimeSpan.FromMilliseconds(500));

            var policyRegistry = new PolicyRegistry()
            {
                { CommandProcessor.RETRYPOLICY, retryPolicy },
                { CommandProcessor.CIRCUITBREAKER, circuitBreakerPolicy }
            };

            //create message mappers
            var messageMapperRegistry = new MessageMapperRegistry(messageMapperFactory)
            {
                { typeof(FolderCreatedEvent), typeof(FolderCreatedEventMessageMapper) },
                { typeof(DocumentCreatedEvent), typeof(DocumentCreatedEventMessageMapper) },
                { typeof(DocumentUpdatedEvent), typeof(DocumentUpdatedEventMessageMapper) }
            };


            var awsCredentials = new StoredProfileAWSCredentials();

            var sqsMessageProducer = new SqsMessageProducer(awsCredentials);
            var processor          = new CommandProcessor(
                null,
                policyRegistry,
                messageMapperRegistry,
                new FakeMessageStore(),
                sqsMessageProducer
                );

            return(processor);
        }
        string cw_logstream_sequence_token = "token"; // initial token must be longer than 0 chars


        public AwsGameLogic()
        {
            // Making use of profile credentials for workstation here https://docs.aws.amazon.com/sdk-for-net/v2/developer-guide/net-dg-config-creds.html
            aws_credentials = new StoredProfileAWSCredentials("lab");

            rand = new Random();
            Thread t = new Thread(new ThreadStart(PublishPlayerCountLoop));

            t.Start();
            aws_region        = RegionEndpoint.USWest2;
            cw_log_group_name = $"/{environment}/{game_name}";
            Process current_process = Process.GetCurrentProcess();

            cw_log_stream_name = $"{instance_identifier}-{current_process.Id.ToString()}";
        }
Example #16
0
        static Crash()
        {
            string         AWSError;
            AWSCredentials AWSCredentialsForOutput = new StoredProfileAWSCredentials(Settings.Default.AWSS3ProfileName, Settings.Default.AWSCredentialsFilepath);
            AmazonS3Config S3ConfigForOutput       = new AmazonS3Config
            {
                ServiceURL = Settings.Default.AWSS3URL
            };

            AmazonClient = new AmazonClient(AWSCredentialsForOutput, null, S3ConfigForOutput, out AWSError);

            if (!AmazonClient.IsS3Valid)
            {
                System.Diagnostics.Debug.WriteLine("Failed to initailize S3");
            }
        }
Example #17
0
        private async Task PublishEventStubToQueue(string @event)
        {
            var awsProfile   = _configuration.GetSection("AWS").GetSection("Profile").Value;
            var testQueueUrl = _configuration.GetSection("EventStubSubscription").GetSection("QueueUrl").Value;
            var credentials  = new StoredProfileAWSCredentials(awsProfile);
            var sqsClient    = new AmazonSQSClient(new AnonymousAWSCredentials(), new AmazonSQSConfig()
            {
                ServiceURL = _configuration.GetSection("AWS").GetSection("ServiceUrl").Value
            });

            await sqsClient.SendMessageAsync(new SendMessageRequest()
            {
                QueueUrl    = testQueueUrl,
                MessageBody = @event
            });
        }
Example #18
0
    //取得指定目錄之檔案列表
    public static List <string> GetFileList(string bucket, string path = "")
    {
        var files       = new List <string>();
        var credentials = new StoredProfileAWSCredentials("developer");

        using (var client = new AmazonS3Client(credentials))
        {
            try
            {
                ListObjectsRequest request = new ListObjectsRequest();
                request.BucketName = bucket;
                request.Prefix     = path;
                ListObjectsResponse response = client.ListObjects(request);

                do
                {
                    response = client.ListObjects(request);
                    foreach (S3Object entry in response.S3Objects)
                    {
                        files.Add(entry.Key);
                    }

                    if (response.IsTruncated)
                    {
                        request.Marker = response.NextMarker;
                    }
                    else
                    {
                        request = null;
                    }
                } while (request != null);
            }
            catch (AmazonS3Exception amazonS3Exception)
            {
                if (amazonS3Exception.ErrorCode != null && (amazonS3Exception.ErrorCode.Equals("InvalidAccessKeyId") || amazonS3Exception.ErrorCode.Equals("InvalidSecurity")))
                {
                    LogTools.Error("Please check the provided AWS Credentials. If you haven't signed up for Amazon S3, please visit http://aws.amazon.com/s3");
                }
                else
                {
                    LogTools.Error(string.Format("An error occurred with the message '{0}' when listing objects", amazonS3Exception.Message));
                }
            }
        }

        return(files);
    }
Example #19
0
        public static void AmazonGlacierClient(string profileName, string archiveToUpload, string region)
        {
            AmazonGlacierClient client;
            List <string>       partChecksumList = new List <string>();
            var credentials = new StoredProfileAWSCredentials(profileName); // AWS Profile
            var newRegion   = RegionEndpoint.GetBySystemName(region);

            try
            {
                // Connects to Amazon Glacier using your credentials and the specified region
                using (client = new AmazonGlacierClient(credentials, newRegion))
                {
                    Console.WriteLine("Uploading an archive. \n");
                    string uploadId = InitiateMultipartUpload(client, vaultName); // Initiates the multipart upload
                    partChecksumList = UploadParts(uploadId, client, archiveToUpload);
                    string archiveId = CompleteMPU(uploadId, client, partChecksumList, archiveToUpload);
                    Console.WriteLine("Archive ID: {0}", archiveId);
                }

                Console.WriteLine("Operation was successful.");
            }

            // If Glacier times out it will re attempt the upload 5 times
            catch (RequestTimeoutException)
            {
                uploadAttempt = +1;
                Console.WriteLine("Glacier Timed out while receiving the upload \n Upload Attempt " + uploadAttempt + " / 5");

                Console.WriteLine(" Upload Attempt " + uploadAttempt + " / 5");
                if (uploadAttempt < 5)
                {
                    uploadAttempt++;
                    AmazonGlacierClient(profileName, archiveToUpload, region);
                }
                else
                {
                    Console.WriteLine("\n Glacier timed out 5 times while receiving the upload. \n Please Restart the program and try again.");
                    Console.ReadLine();
                    System.Environment.Exit(1);
                }
            }

            catch (AmazonGlacierException e) { Console.WriteLine(e.Message); }
            catch (AmazonServiceException e) { Console.WriteLine(e.Message); }
            catch (Exception e) { Console.WriteLine(e.Message); }
        }
Example #20
0
    //取得檔案內容
    public static string GetFileContent(string bucket, string path)
    {
        var       credentials = new StoredProfileAWSCredentials("developer");
        IAmazonS3 client      = new AmazonS3Client(credentials);

        GetObjectRequest request = new GetObjectRequest()
        {
            BucketName = bucket,
            Key        = path
        };

        using (GetObjectResponse response = client.GetObject(request))
        {
            StreamReader reader = new StreamReader(response.ResponseStream);
            return(reader.ReadToEnd());
        }
    }
Example #21
0
        static Entrypoint()
        {
#if DEBUG
            AWSConfigs.AWSProfileName      = $"{Environment.UserName}-dev";
            AWSConfigs.AWSProfilesLocation = $"{Environment.GetEnvironmentVariable("UserProfile")}\\.aws\\credentials";
            StoredProfileAWSCredentials Creds = new StoredProfileAWSCredentials();

            _S3Client     = new AmazonS3Client(Creds);
            _AthenaClient = new AmazonAthenaClient(Creds);
            _SNSClient    = new AmazonSimpleNotificationServiceClient(Creds);
#else
            _S3Client     = new AmazonS3Client();
            _AthenaClient = new AmazonAthenaClient();
            _SNSClient    = new AmazonSimpleNotificationServiceClient();
#endif

            _SNSTopic = Environment.GetEnvironmentVariable("SNS_TOPIC");
        }
Example #22
0
        /// <summary>
        /// Constructor taking the landing zone
        /// </summary>
        public DataRouterReportQueue(string InQueueName, string InLandingZoneTempPath, int InDecimateWaitingCountStart, int InDecimateWaitingCountEnd)
            : base(InQueueName, InLandingZoneTempPath, InDecimateWaitingCountStart, InDecimateWaitingCountEnd)
        {
            AWSCredentials Credentials = new StoredProfileAWSCredentials(Config.Default.AWSProfileName, Config.Default.AWSCredentialsFilepath);

            AmazonSQSConfig SqsConfig = new AmazonSQSConfig
            {
                ServiceURL = Config.Default.AWSSQSServiceURL
            };

            SqsClient = new AmazonSQSClient(Credentials, SqsConfig);

            AmazonS3Config S3Config = new AmazonS3Config
            {
                ServiceURL = Config.Default.AWSS3ServiceURL
            };

            S3Client = new AmazonS3Client(Credentials, S3Config);
        }
Example #23
0
        public async Task EditFile(string filePath, string contentType, string content)
        {
#pragma warning disable 618 // "'StoredProfileCredentials' is obsolete..."
            var creds = new StoredProfileAWSCredentials("acmesharp-tests");
#pragma warning restore 618
            var reg    = RegionEndpoint.GetBySystemName(AwsRegion);
            var delete = content == null;

            // We need to strip off any leading '/' in the path or
            // else it creates a path with an empty leading segment
            // if (filePath.StartsWith("/"))
            //     filePath = filePath.Substring(1);
            filePath = filePath.Trim('/');

            using (var s3 = new Amazon.S3.AmazonS3Client(creds, reg))
            {
                if (delete)
                {
                    var s3Requ = new Amazon.S3.Model.DeleteObjectRequest
                    {
                        BucketName = BucketName,
                        Key        = filePath,
                    };
                    var s3Resp = await s3.DeleteObjectAsync(s3Requ);
                }
                else
                {
                    using (var ms = new MemoryStream(Encoding.UTF8.GetBytes(content)))
                    {
                        var s3Requ = new Amazon.S3.Model.PutObjectRequest
                        {
                            BucketName  = BucketName,
                            Key         = filePath,
                            ContentType = contentType,
                            InputStream = ms,
                            CannedACL   = S3CannedAcl,
                        };

                        var s3Resp = await s3.PutObjectAsync(s3Requ);
                    }
                }
            }
        }
Example #24
0
        public SqsActor()
        {
            Receive <string> (x => {
                var sqs_url       = Environment.GetEnvironmentVariable("sqs_url", EnvironmentVariableTarget.Process);
                var config        = new AmazonSQSConfig();
                config.ServiceURL = sqs_url;

                var creds  = new StoredProfileAWSCredentials();
                var client = new AmazonSQSClient(creds, config);

                var msg       = x + " and what " + Guid.NewGuid().ToString();
                var queue_url = Environment.GetEnvironmentVariable("queue_url", EnvironmentVariableTarget.Process);

                var request = new Amazon.SQS.Model.SendMessageRequest(queue_url, msg);

                client.SendMessage(request);

                Sender.Tell(string.Format("done  : [{0}]", msg));
            });
        }
Example #25
0
        static async Task MainAsync(string[] args)
        {
            var credentials = new StoredProfileAWSCredentials("LinkLiang");

            using (var client = new AmazonLambdaClient(credentials, RegionEndpoint.USEast1))
            {
                var request = new InvokeRequest
                {
                    FunctionName = "PDF2Raw"
                };
                var response = await client.InvokeAsync(request);

                string result;
                using (var sr = new StreamReader(response.Payload))
                {
                    //Put all tests below
                    result = sr.ReadToEnd();
                }
            }
            Console.WriteLine("Hello World!");
        }
        private static void TestCredentialsFile(ImmutableCredentials ic)
        {
            var profileName      = "testProfile";
            var profilesLocation = WriteCreds(profileName, ic);

#pragma warning disable 618
            var creds = new StoredProfileAWSCredentials(profileName, profilesLocation);
#pragma warning restore 618
            var rc = creds.GetCredentials();
            Assert.AreEqual(ic.SecretKey, rc.SecretKey);
            Assert.AreEqual(ic.AccessKey, rc.AccessKey);
            Assert.AreEqual(ic.UseToken, rc.UseToken);
            Assert.AreEqual(ic.Token, rc.Token);

            for (int i = 0; i < 4; i++)
            {
                var shouldHaveToken = (i % 2 == 1);
#pragma warning disable 618
                creds = new StoredProfileAWSCredentials(profileName + i, profilesLocation);
#pragma warning restore 618
                Assert.IsNotNull(creds);

                rc = creds.GetCredentials();
                Assert.IsNotNull(rc.AccessKey);
                Assert.IsNotNull(rc.SecretKey);
                Assert.AreEqual(shouldHaveToken, rc.UseToken);

                if (rc.UseToken)
                {
                    Assert.AreEqual(sessionCreds.AccessKey, rc.AccessKey);
                    Assert.AreEqual(sessionCreds.SecretKey, rc.SecretKey);
                    Assert.AreEqual(sessionCreds.Token, rc.Token);
                }
                else
                {
                    Assert.AreEqual(basicCreds.AccessKey, rc.AccessKey);
                    Assert.AreEqual(basicCreds.SecretKey, rc.SecretKey);
                }
            }
        }
Example #27
0
        public static void Main(string[] args)
        {
            var configuration = new ConfigurationBuilder()
                                .SetBasePath(Directory.GetCurrentDirectory())
                                .AddJsonFile("appsettings.json", true)
                                .Build();

            Console.Title = configuration["ApplicationName"];


            var profile = configuration["AWSProfile"];

            var credentials = new StoredProfileAWSCredentials(profile);
            var sqsClient   = new AmazonSQSClient(credentials, RegionEndpoint.EUWest1);

            // Create queue if not exist

            GetQueueUrlResponse queue = sqsClient.GetQueueUrlAsync("BFQueue").Result;

            var receiveMessageRequest = new ReceiveMessageRequest
            {
                QueueUrl          = queue.QueueUrl,
                WaitTimeSeconds   = 10,
                VisibilityTimeout = 10
            };

            while (true)
            {
                Console.WriteLine("Polling Queue");
                var messagesResponse = sqsClient.ReceiveMessageAsync(receiveMessageRequest).Result;
                foreach (var message in messagesResponse.Messages)
                {
                    Console.WriteLine($"Message: { message.Body }");

                    var deleteMessageRequest     = new DeleteMessageRequest(queue.QueueUrl, message.ReceiptHandle);
                    DeleteMessageResponse result = sqsClient.DeleteMessageAsync(deleteMessageRequest).Result;
                }
            }
        }
Example #28
0
        public InstanceDetails GetInstanceDetails(string instanceId)
        {
            InstanceDetails instanceDetail = null;

            try
            {
                AWSCredentials credentials = new StoredProfileAWSCredentials("FirstProfile");

                var ec2Client = new AmazonEC2Client(credentials, Amazon.RegionEndpoint.USEast1);

                ////var ec2Client = new AmazonEC2Client(Amazon.RegionEndpoint.USEast1);

                var statusRequest = new DescribeInstanceStatusRequest
                {
                    InstanceIds = { instanceId }
                };



                var status = ec2Client.DescribeInstanceStatus(statusRequest).InstanceStatuses[0];

                instanceDetail = new InstanceDetails();

                instanceDetail.InstanceId      = status.InstanceId;
                instanceDetail.InstanceState   = status.InstanceState.Name;
                instanceDetail.InstanceName    = status.Status.Details[0].Name;
                instanceDetail.InstanceStatus  = status.Status.Details[0].Status;
                instanceDetail.SystemState     = status.Status.Status.Value;
                instanceDetail.SystemName      = status.SystemStatus.Details[0].Name;
                instanceDetail.SystemStatus    = status.SystemStatus.Details[0].Status;
                instanceDetail.AvailablityZone = status.AvailabilityZone;
            }
            catch (Exception ex)
            {
                throw ex;
            }

            return(instanceDetail);
        }
Example #29
0
        public static void Main(string[] args)
        {
            var stash = new Credstash(new CredstashOptions(), new AmazonKeyManagementServiceClient(RegionEndpoint.EUWest1),
                                      new AmazonDynamoDBClient(RegionEndpoint.EUWest1));

            var noneExistingKey1 = stash.GetSecretAsync(Guid.NewGuid().ToString()).Result;
            var noneExistingKey2 = stash.GetSecretAsync(Guid.NewGuid().ToString(), "1").Result;

            //var creds = new StoredProfileAWSCredentials();
            //var stash = new Credstash(new CredstashOptions(), new AmazonKeyManagementServiceClient(creds, RegionEndpoint.EUWest1),
            //    new AmazonDynamoDBClient(creds, RegionEndpoint.EUWest1));
            //var val = stash.GetSecret("redis:host", null, new Dictionary<string, string>()
            //{
            //    { "environment", "beta"}
            //}).Result;
            //Console.WriteLine(val);

            //foreach (var entry in stash.List().Result)
            //{
            //    Console.WriteLine($"{entry.Name} v{entry.Version}");
            //}

            AWSCredentials creds         = new StoredProfileAWSCredentials();
            var            configBuilder = new ConfigurationBuilder();

            configBuilder.AddCredstash(creds, new CredstashConfigurationOptions()
            {
                EncryptionContext = new Dictionary <string, string>()
                {
                    { "environment", "beta" }
                }
            });

            var config = configBuilder.Build();
            var beta   = config.GetSection("beta");

            Print(beta, string.Empty);
        }
Example #30
0
        private static void TestCredentialsFile(ImmutableCredentials ic)
        {
            var profileName      = "testProfile";
            var profilesLocation = WriteCreds(profileName, ic);
            var creds            = new StoredProfileAWSCredentials(profileName, profilesLocation);
            var rc = creds.GetCredentials();

            Assert.AreEqual(ic.SecretKey, rc.SecretKey);
            Assert.AreEqual(ic.AccessKey, rc.AccessKey);
            Assert.AreEqual(ic.UseToken, rc.UseToken);
            Assert.AreEqual(ic.Token, rc.Token);

            for (int i = 0; i < 4; i++)
            {
                creds = new StoredProfileAWSCredentials(profileName + i, profilesLocation);
                Assert.IsNotNull(creds);
                rc = creds.GetCredentials();
                Assert.IsNotNull(rc.AccessKey);
                Assert.IsNotNull(rc.SecretKey);
                var shouldHaveToken = (i % 2 == 1);
                Assert.AreEqual(shouldHaveToken, rc.UseToken);
            }
        }