Пример #1
0
        /// <summary>
        ///     Uploads the file asynchronous.
        /// </summary>
        /// <param name="fileToUpload">The file to upload.</param>
        /// <param name="keyname">The keyname.</param>
        /// <returns></returns>
        private static async Task UploadFileAsync(Stream fileToUpload, string keyname)
        {
            try
            {
                var sw = Stopwatch.StartNew();
                var credentialProfileStoreChain = new CredentialProfileStoreChain();
                credentialProfileStoreChain.TryGetAWSCredentials("basic_profile", out var defaultCredentials);

                IAmazonS3 s3Client = new AmazonS3Client(defaultCredentials, BucketRegion);

                var fileTransferUtility = new TransferUtility(s3Client);

                // Option 3. Upload data from a type of System.IO.Stream.
                await fileTransferUtility.UploadAsync(fileToUpload,
                                                      BucketName, keyname);

                sw.Stop();

                Console.WriteLine("UploadWithFileStream completed in {0}seconds", sw.Elapsed.TotalSeconds);
            }
            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);
            }
        }
Пример #2
0
        /// <summary>
        ///     Uploads the file asynchronous.
        /// </summary>
        /// <returns></returns>
        private static async Task UploadFileAsync()
        {
            try
            {
                var sw = Stopwatch.StartNew();
                var credentialProfileStoreChain = new CredentialProfileStoreChain();
                credentialProfileStoreChain.TryGetAWSCredentials("basic_profile", out var defaultCredentials);

                IAmazonS3 s3Client = new AmazonS3Client(defaultCredentials, BucketRegion);

                var fileTransferUtility = new TransferUtility(s3Client);
                // Option 1. Upload a file. The file name is used as the object key name.
                await fileTransferUtility.UploadAsync(FilePath, BucketName);

                sw.Stop();

                Console.WriteLine("Upload completed in {0} seconds", sw.Elapsed.TotalSeconds);
            }
            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);
            }
        }
Пример #3
0
        private static (AWSCredentials Creds, RegionEndpoint Region) GetAWSConfig(string profileName = null)
        {
            if (!string.IsNullOrEmpty(profileName))
            {
                var            chain = new CredentialProfileStoreChain();
                AWSCredentials creds;
                RegionEndpoint region;
                if (chain.TryGetProfile(profileName, out var profile))
                {
                    region = profile.Region;
                }
                else
                {
                    throw new ArgumentException($"No region profile with the name '{profileName}' was found.");
                }

                if (chain.TryGetAWSCredentials(profileName, out var credentials))
                {
                    creds = credentials;
                }
                else
                {
                    throw new ArgumentException($"No credential profile with credentials found with the name '{profileName}'.");
                }
            }

            return(FallbackCredentialsFactory.GetCredentials(), FallbackRegionFactory.GetRegionEndpoint());
        }
Пример #4
0
        static Context GetContext(Config config, bool login = true)
        {
            var store = new CredentialProfileStoreChain();

            if (!store.TryGetProfile(config.Profile, out var profile))
            {
                throw new Exception($"Unable to find '{config.Profile}' AWS profile");
            }

            var credentials = profile.GetAWSCredentials(store);
            var region      = RegionEndpoint.GetBySystemName(config.Region);

            var result = new Context
            {
                Config              = config,
                Region              = region,
                AwsCredentials      = credentials,
                JsonStackSerializer = new JsonStackSerializer()
            };

            if (login)
            {
                result.Cloudformation = new AmazonCloudFormationClient(credentials, region);
                result.S3             = new AmazonS3Client(credentials, region);
                result.SSM            = new AmazonSimpleSystemsManagementClient(credentials, region);
                result.Lambda         = new AmazonLambdaClient(credentials, region);
            }

            return(result);
        }
        /// <summary>
        /// Creates a new profile in the AWS SDK Store for storing credentials in encrypted form.
        /// </summary>
        /// <remarks>
        /// The encrypted credentials in the SDK Store are located in the'%LOCALAPPDATA%\AWSToolkit'
        /// folder in the RegisteredAccounts.json file.
        /// </remarks>
        /// <param name="profileName">Profile name to associate with credentials.</param>
        /// <param name="accessKey">The access key to store with <paramref name="profileName"/>.</param>
        /// <param name="secretKey">The secret key to store with <paramref name="profileName"/>.</param>
        /// <param name="region">The AWS region to associate with <paramref name="profileName"/>.</param>
        /// <returns>Successful or not result.</returns>
        private static bool RegisterAccount(string profileName, string accessKey, string secretKey, string region)
        {
            var chain = new CredentialProfileStoreChain();

            if (chain.ListProfiles().Any(p => p.Name.Equals(profileName,
                                                            StringComparison.InvariantCultureIgnoreCase)))
            {
                MessageBox.Show("The profile name already exists in one or more locations.",
                                Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return(false);
            }

            var options = new CredentialProfileOptions
            {
                AccessKey = accessKey,
                SecretKey = secretKey
            };

            var profile    = new CredentialProfile(profileName, options);
            var netSdkFile = new NetSDKCredentialsFile();

            profile.Region = RegionEndpoint.GetBySystemName(region);
            netSdkFile.RegisterProfile(profile);

            MessageBox.Show("AWS account was stored successfully.",
                            Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Information);
            return(true);
        }
Пример #6
0
        public static async void UploadCompressedFile(string archiveFileName)
        {
            var keyName = Path.GetFileName(archiveFileName);

            try
            {
                var            chain = new CredentialProfileStoreChain();
                AWSCredentials awsCredentials;
                if (chain.TryGetAWSCredentials("playpen", out awsCredentials))
                {
                    var amazonS3Client             = new AmazonS3Client(awsCredentials, bucketRegion);
                    var fileTransferUtility        = new TransferUtility(amazonS3Client);
                    var fileTransferUtilityRequest = new TransferUtilityUploadRequest
                    {
                        BucketName = bucketName,
                        Key        = keyNamePrefix + keyName,
                        FilePath   = archiveFileName
                    };
                    await fileTransferUtility.UploadAsync(fileTransferUtilityRequest);
                }
            }
            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);
            }
        }
Пример #7
0
        static async Task Main(string[] args)
        {
            var source = new CredentialProfileStoreChain();
            var creds  = source.TryGetProfile("personal", out var c) ? AWSCredentialsFactory.GetAWSCredentials(c, source) : null;
            var s3     = new AmazonS3Client(creds, RegionEndpoint.EUWest2);

            var resultsStorage = new S3ResultStorage(s3, "selectquery-dev-resultsbucket-cmlezfu231g");

            var underlyingExecutor = new S3SelectExecutor(s3, new InputSerialization
            {
                JSON = new JSONInput {
                    JsonType = JsonType.Lines
                },
                CompressionType = CompressionType.Gzip
            });
            var worker = new Worker(underlyingExecutor, resultsStorage);

            var sourceResolver = new S3SourceResolver(s3);
            var workerExecutor = new LocalWorkerExecutor(worker);

            var distributor = new Distributor(sourceResolver, workerExecutor, resultsStorage, resultsStorage);

            await distributor.QueryAsync(new DistributorInput(
                                             ParseQuery("SELECT * FROM s3object s LIMIT 100"),
                                             new DataSource.List(new[]
            {
                new Uri("s3://selectquery-data/0ECr0RR7ADAmZ7B6.gz"),
            })
                                             ));
        }
Пример #8
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.Configure <CookiePolicyOptions>(options =>
            {
                // This lambda determines whether user consent for non-essential cookies is needed for a given request.
                options.CheckConsentNeeded    = context => true;
                options.MinimumSameSitePolicy = SameSiteMode.None;
            });


            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
            services.AddDefaultAWSOptions(this.Configuration.GetAWSOptions());

            AWSOptions awsOptions             = Configuration.GetAWSOptions();
            CredentialProfileStoreChain chain = new CredentialProfileStoreChain(awsOptions.ProfilesLocation);

            if (chain.TryGetAWSCredentials(awsOptions.Profile, out AWSCredentials result))
            {
                ImmutableCredentials credentials = result.GetCredentials();

                Environment.SetEnvironmentVariable("AWS_ACCESS_KEY_ID", credentials.AccessKey);
                Environment.SetEnvironmentVariable("AWS_SECRET_ACCESS_KEY", credentials.SecretKey);
            }
            else
            {
                throw new Exception("Could not get Amazon credentials");
            }

            Environment.SetEnvironmentVariable("AWS_REGION", awsOptions.Region.SystemName);

            services.AddAWSService <IAmazonS3>();
        }
Пример #9
0
		string mWSAuthToken = "amzn.mws.10b0d30f-3c9c-fa00-c792-e9142f66a94c"; // me
																			   //string mWSAuthToken = "amzn.mws.c2b0d4ad-e73e-b729-d3a1-b0998fcd6a9f"; // RC
		public FeedsTests()
		{
			var chain = new CredentialProfileStoreChain();
			AWSCredentials awsCredentials;
			chain.TryGetAWSCredentials("DD MWS", out awsCredentials);
			creds = awsCredentials.GetCredentials();
		}
Пример #10
0
        public SqsMessageProducerRequeueTests()
        {
            _myCommand = new MyCommand {
                Value = "Test"
            };
            _correlationId = Guid.NewGuid();
            _replyTo       = "http:\\queueUrl";
            _contentType   = "text\\plain";
            var channelName = $"Producer-Requeue-Tests-{Guid.NewGuid().ToString()}".Truncate(45);

            _topicName  = $"Producer-Requeue-Tests-{Guid.NewGuid().ToString()}".Truncate(45);
            _connection = new Connection <MyCommand>(
                name: new ConnectionName(channelName),
                channelName: new ChannelName(channelName),
                routingKey: new RoutingKey(_topicName)
                );

            _message = new Message(
                new MessageHeader(_myCommand.Id, _topicName, MessageType.MT_COMMAND, _correlationId, _replyTo, _contentType),
                new MessageBody(JsonConvert.SerializeObject((object)_myCommand))
                );

            //Must have credentials stored in the SDK Credentials store or shared credentials file
            var credentialChain = new CredentialProfileStoreChain();

            (AWSCredentials credentials, RegionEndpoint region) = CredentialsChain.GetAwsCredentials();
            var awsConnection = new AWSMessagingGatewayConnection(credentials, region);

            _sender         = new SqsMessageProducer(awsConnection);
            _channelFactory = new ChannelFactory(awsConnection, new SqsMessageConsumerFactory(awsConnection));
            _channel        = _channelFactory.CreateChannel(_connection);
        }
Пример #11
0
 public DynamoDBHelper(ILambdaContext mContext, bool isLocalDebug)
 {
     try
     {
         this.context      = mContext;
         this.isLocalDebug = isLocalDebug;
         if (isLocalDebug)
         {
             var            chain = new CredentialProfileStoreChain();
             AWSCredentials awsCredentials;
             if (chain.TryGetAWSCredentials(Constants.AWSProfileName, out awsCredentials))
             {
                 // use awsCredentials
                 client = new AmazonDynamoDBClient(awsCredentials, Amazon.RegionEndpoint.USEast1);
             }
         }
         else
         {
             client = new AmazonDynamoDBClient();
         }
     }
     catch (Exception ex)
     {
         context.Logger.LogLine("DynamoDBHelper  => " + ex.StackTrace);
     }
 }
        protected AWSCredentials DetermineAWSCredentials()
        {
            AWSCredentials credentials;

            if (this.Credentials != null)
            {
                credentials = this.Credentials;
            }
            else
            {
                var profile = this.Profile;
                if (string.IsNullOrEmpty(profile))
                {
                    profile = DefaultConfig[CommonDefinedCommandOptions.ARGUMENT_AWS_PROFILE.Switch] as string;
                }

                if (!string.IsNullOrEmpty(profile))
                {
                    var chain = new CredentialProfileStoreChain(this.ProfileLocation);
                    if (!chain.TryGetAWSCredentials(profile, out credentials))
                    {
                        throw new ToolsException($"Credentials for profile {profile} cannot be found", ToolsException.CommonErrorCode.ProfileNotFound);
                    }
                }
                else
                {
                    credentials = FallbackCredentialsFactory.GetCredentials();
                }
            }

            return(credentials);
        }
        public SQSBufferedConsumerTests()
        {
            //Must have credentials stored in the SDK Credentials store or shared credentials file
            var credentialChain = new CredentialProfileStoreChain();

            if (credentialChain.TryGetAWSCredentials("default", out var credentials) && credentialChain.TryGetProfile("default", out var profile))
            {
                var awsConnection = new AWSMessagingGatewayConnection(credentials, profile.Region);

                ChannelFactory channelFactory = new ChannelFactory(awsConnection, new SqsMessageConsumerFactory(awsConnection));
                var            name           = Guid.NewGuid().ToString();

                //we need the channel to create the queues and notifications
                channelFactory.CreateChannel(new Connection <MyCommand>(
                                                 name: new ConnectionName(name),
                                                 channelName: new ChannelName(name),
                                                 routingKey: new RoutingKey(_topicName),
                                                 bufferSize: BUFFER_SIZE
                                                 ));

                //we want to access via a consumer, to receive multiple messages - we don't want to expose on channel
                //just for the tests, so create a new consumer from the properties
                _consumer = new SqsMessageConsumer(awsConnection, new ChannelName(name).ToValidSQSQueueName(), BUFFER_SIZE);

                _messageProducer = new SqsMessageProducer(awsConnection);
            }
        }
Пример #14
0
            public FallbackFactoryTestFixture(string sharedCredsFileContent, string awsProfileValue, string enableEndpointDiscoveryValue = null)
            {
                sharedFixture = new SharedCredentialsFileTestFixture(sharedCredsFileContent);
                netSdkFixture = new NetSDKCredentialsFileTestFixture();

                originalCredsChain = (CredentialProfileStoreChain)ReflectionHelpers.Invoke(typeof(FallbackCredentialsFactory), "credentialProfileChain");
                ReflectionHelpers.Invoke(typeof(FallbackCredentialsFactory), "credentialProfileChain", new CredentialProfileStoreChain(sharedFixture.CredentialsFilePath));

                originalRegionChain = (CredentialProfileStoreChain)ReflectionHelpers.Invoke(typeof(FallbackRegionFactory), "credentialProfileChain");
                ReflectionHelpers.Invoke(typeof(FallbackRegionFactory), "credentialProfileChain", new CredentialProfileStoreChain(sharedFixture.CredentialsFilePath));

                originalEndpointDiscoveryEnabledChain = (CredentialProfileStoreChain)ReflectionHelpers.Invoke(typeof(FallbackEndpointDiscoveryEnabledFactory), "credentialProfileChain");
                ReflectionHelpers.Invoke(typeof(FallbackEndpointDiscoveryEnabledFactory), "credentialProfileChain", new CredentialProfileStoreChain(sharedFixture.CredentialsFilePath));

                originalAWSProfileValue = Environment.GetEnvironmentVariable(AWS_PROFILE_ENVIRONMENT_VARIABLE);
                Environment.SetEnvironmentVariable(AWS_PROFILE_ENVIRONMENT_VARIABLE, awsProfileValue);

                originalAWSEnableEndpointDiscoveryValue = Environment.GetEnvironmentVariable(AWS_ENABLE_ENDPOINT_DISCOVERY_ENVIRONMENT_VARIABLE);
                Environment.SetEnvironmentVariable(AWS_ENABLE_ENDPOINT_DISCOVERY_ENVIRONMENT_VARIABLE, enableEndpointDiscoveryValue);

                // reset before use to ensure the new credentialProfileChains are used.
                FallbackCredentialsFactory.Reset();
                FallbackRegionFactory.Reset();
                FallbackEndpointDiscoveryEnabledFactory.Reset();
            }
Пример #15
0
        private static CloudConfig CreateCloudConfig()
        {
            AWSCredentials credentials;
            bool           isInAws = false;

            var            chain = new CredentialProfileStoreChain();
            AWSCredentials awsCredentials;

            if (chain.TryGetAWSCredentials("chessdb-prod", out awsCredentials))
            {
                credentials = awsCredentials;
            }
            else
            {
                credentials = FallbackCredentialsFactory.GetCredentials();
                isInAws     = true;
            }

            var options = new AWSOptions()
            {
                Credentials = credentials,
                Region      = RegionEndpoint.USEast2,
            };

            string stage = Environment.GetEnvironmentVariable("JANUS_STAGE") ?? "prod";

            return(new CloudConfig()
            {
                Stage = stage,
                Options = options,
                IsInCloud = isInAws,
            });
        }
Пример #16
0
        private AWSCredentials GetAwsCredentials(AWSS3Labs.Web.Configuration.AmazonS3Config config)
        {
            if (!string.IsNullOrWhiteSpace(config.Profile))
            {
                var credentialProfileStoreChain = new CredentialProfileStoreChain();

                if (credentialProfileStoreChain.TryGetAWSCredentials(config.Profile, out AWSCredentials profileCredentials))
                {
                    return(profileCredentials);
                }
                else
                {
                    throw new AmazonClientException($"Failed to find AWS credentials for the profile {config.Profile}");
                }
            }

            if (!string.IsNullOrEmpty(config.AccessKeyId) && !string.IsNullOrWhiteSpace(config.SecretAccessKey))
            {
                return(new BasicAWSCredentials(config.AccessKeyId, config.SecretAccessKey));
            }

            var credentials = FallbackCredentialsFactory.GetCredentials();

            if (credentials == null)
            {
                throw new AmazonClientException("Failed to find AWS Credentials for constructing AWS service client");
            }

            return(credentials);
        }
Пример #17
0
        private static void LocalProfileTest()
        {
            var chain          = new CredentialProfileStoreChain();
            var awsCredentials = default(AWSCredentials);

            if (chain.TryGetAWSCredentials("default", out awsCredentials))
            {
                var aws = awsCredentials.GetCredentials();

                var request = new AwsApiGatewayRequest()
                {
                    RegionName    = "ap-southeast-2",
                    Host          = apiEndpoint,
                    AccessKey     = aws.AccessKey,
                    SecretKey     = aws.SecretKey,
                    AbsolutePath  = apiEndpointStaging,
                    JsonData      = "245",
                    RequestMethod = HttpMethod.Post
                };
                var apiRequest = new ApiRequest(request);
                var response   = apiRequest.GetResponse();

                Console.WriteLine(response.ContentLength);
            }
        }
        public SQSBufferedConsumerTests()
        {
            //Must have credentials stored in the SDK Credentials store or shared credentials file
            var credentialChain = new CredentialProfileStoreChain();

            (AWSCredentials credentials, RegionEndpoint region) = CredentialsChain.GetAwsCredentials();
            var awsConnection = new AWSMessagingGatewayConnection(credentials, region);

            _channelFactory = new ChannelFactory(awsConnection, new SqsMessageConsumerFactory(awsConnection));
            var channelName = $"Buffered-Consumer-Tests-{Guid.NewGuid().ToString()}".Truncate(45);

            _topicName = $"Buffered-Consumer-Tests-{Guid.NewGuid().ToString()}".Truncate(45);

            //we need the channel to create the queues and notifications
            _channelFactory.CreateChannel(new Connection <MyCommand>(
                                              name: new ConnectionName(channelName),
                                              channelName: new ChannelName(channelName),
                                              routingKey: new RoutingKey(_topicName),
                                              bufferSize: BUFFER_SIZE
                                              ));

            //we want to access via a consumer, to receive multiple messages - we don't want to expose on channel
            //just for the tests, so create a new consumer from the properties
            var sqsQueueName = new ChannelName(channelName).ToValidSQSQueueName();

            _consumer        = new SqsMessageConsumer(awsConnection, sqsQueueName, BUFFER_SIZE);
            _messageProducer = new SqsMessageProducer(awsConnection);
        }
        public AppConfigAWSCredentials()
        {
            NameValueCollection appConfig = ConfigurationManager.AppSettings;
            var logger = Logger.GetLogger(typeof(AppConfigAWSCredentials));

            // Attempt hardcoded key credentials first, then look for an explicit profile name
            // in either the SDK credential store or the shared credentials file. When using a profile
            // name, if a location is not given the search will use the default locations and name for
            // the credential file (assuming the profile is not found in the SDK store first)
            if (!string.IsNullOrEmpty(appConfig[ACCESSKEY]) && !string.IsNullOrEmpty(appConfig[SECRETKEY]))
            {
                var accessKey = appConfig[ACCESSKEY];
                var secretKey = appConfig[SECRETKEY];
                this._wrappedCredentials = new BasicAWSCredentials(accessKey, secretKey);
                logger.InfoFormat("Credentials found with {0} and {1} app settings", ACCESSKEY, SECRETKEY);
            }
            else if (!string.IsNullOrEmpty(AWSConfigs.AWSProfileName))
            {
                CredentialProfileStoreChain chain = new CredentialProfileStoreChain(AWSConfigs.AWSProfilesLocation);
                CredentialProfile           profile;
                if (chain.TryGetProfile(AWSConfigs.AWSProfileName, out profile))
                {
                    // Will throw a descriptive exception if profile.CanCreateAWSCredentials is false.
                    _wrappedCredentials = profile.GetAWSCredentials(profile.CredentialProfileStore, true);
                }
            }

            if (this._wrappedCredentials == null)
            {
                throw new InvalidOperationException(string.Format(CultureInfo.InvariantCulture,
                                                                  "The app.config/web.config files for the application did not contain credential information"));
            }
        }
Пример #20
0
        public SqsMessageProducerSendTests()
        {
            _myCommand = new MyCommand {
                Value = "Test"
            };
            _correlationId = Guid.NewGuid();
            _replyTo       = "http:\\queueUrl";
            _contentType   = "text\\plain";
            _topicName     = _myCommand.GetType().FullName.ToValidSNSTopicName();

            _message = new Message(
                new MessageHeader(_myCommand.Id, _topicName, MessageType.MT_COMMAND, _correlationId, _replyTo, _contentType),
                new MessageBody(JsonConvert.SerializeObject((object)_myCommand))
                );

            //Must have credentials stored in the SDK Credentials store or shared credentials file
            var credentialChain = new CredentialProfileStoreChain();

            if (credentialChain.TryGetAWSCredentials("default", out var credentials) && credentialChain.TryGetProfile("default", out var profile))
            {
                var awsConnection = new AWSMessagingGatewayConnection(credentials, profile.Region);

                _channelFactory = new ChannelFactory(awsConnection, new SqsMessageConsumerFactory(awsConnection));

                _channel = _channelFactory.CreateChannel(_connection);

                _messageProducer = new SqsMessageProducer(awsConnection);
            }
        }
Пример #21
0
        public config(string aws_credential_profile_name)
        {
            this.aws_credential_profile_name = aws_credential_profile_name;

            InitializeComponent();

            //大きさ固定
            this.FormBorderStyle = FormBorderStyle.FixedSingle;
            //フォームが最大化されないようにする
            this.MaximizeBox = false;
            //フォームが最小化されないようにする
            this.MinimizeBox = false;

            // 参考:http://docs.aws.amazon.com/sdk-for-net/v3/developer-guide/net-dg-config-creds.html
            // プロファイルを読み込む
            var            chain = new CredentialProfileStoreChain();
            AWSCredentials awsCredentials;

            if (chain.TryGetAWSCredentials(aws_credential_profile_name, out awsCredentials))
            {
                //読めたのでセット
                var cretiential = awsCredentials.GetCredentials();
                Txt_AWS_AccessKey.Text = cretiential.AccessKey;
                Txt_AWS_SecretKey.Text = cretiential.SecretKey;
            }
            else
            {
                //読めなかったのでクリア
                Txt_AWS_AccessKey.Text = "";
                Txt_AWS_SecretKey.Text = "";
            }
        }
Пример #22
0
        public async Task <AWSCredentials> ResolveAWSCredentials(string profileName, string lastUsedProfileName)
        {
            AWSCredentials credentials;

            var chain = new CredentialProfileStoreChain();

            if (!string.IsNullOrEmpty(profileName))
            {
                if (chain.TryGetAWSCredentials(profileName, out credentials) &&
                    await CanLoadCredentials(credentials))
                {
                    _toolInteractiveService.WriteLine($"Configuring AWS Credentials from Profile {profileName}.");
                    return(credentials);
                }
            }

            if (!string.IsNullOrEmpty(lastUsedProfileName) &&
                chain.TryGetAWSCredentials(lastUsedProfileName, out credentials) &&
                await CanLoadCredentials(credentials))
            {
                _toolInteractiveService.WriteLine($"Configuring AWS Credentials with previous configured profile value {lastUsedProfileName}.");
                return(credentials);
            }

            try
            {
                credentials = FallbackCredentialsFactory.GetCredentials();

                if (await CanLoadCredentials(credentials))
                {
                    _toolInteractiveService.WriteLine("Configuring AWS Credentials using AWS SDK credential search.");
                    return(credentials);
                }
            }
            catch (AmazonServiceException)
            {
                // FallbackCredentialsFactory throws an exception if no credentials are found. Burying exception because if no credentials are found
                // we want to continue and ask the user to select a profile.
            }

            var sharedCredentials = new SharedCredentialsFile();

            if (sharedCredentials.ListProfileNames().Count == 0)
            {
                _toolInteractiveService.WriteErrorLine("Unable to resolve AWS credentials to access AWS.");
                throw new NoAWSCredentialsFoundException();
            }

            var consoleUtilities    = new ConsoleUtilities(_toolInteractiveService);
            var selectedProfileName = consoleUtilities.AskUserToChoose(sharedCredentials.ListProfileNames(), "Select AWS Credentials Profile", null);

            if (!chain.TryGetAWSCredentials(selectedProfileName, out credentials) ||
                !(await CanLoadCredentials(credentials)))
            {
                _toolInteractiveService.WriteErrorLine($"Unable to create AWS credentials for profile {selectedProfileName}.");
                throw new NoAWSCredentialsFoundException();
            }

            return(credentials);
        }
Пример #23
0
        public async Task <string> UploadFile(string fileName, Stream fileStream)
        {
            var chain = new CredentialProfileStoreChain();

            if (!chain.TryGetAWSCredentials("top_trumps", out var awsCredentials))
            {
                throw new Exception("AWS CREDENTIALS NOT FOUND");
            }

            var key = $"{Guid.NewGuid()}.{fileName}";

            using var client = new AmazonS3Client(awsCredentials);

            var uploadRequest = new TransferUtilityUploadRequest
            {
                InputStream = fileStream,
                Key         = key,
                BucketName  = _configuration["AWS:S3BucketName"],
                CannedACL   = S3CannedACL.PublicRead
            };

            var fileTransferUtility = new TransferUtility(client);
            await fileTransferUtility.UploadAsync(uploadRequest);

            return(GetUrl(key));
        }
Пример #24
0
        public static void Main()
        {
#if RUN_LOCAL
            var config = new AmazonSQSConfig();
            config.ServiceURL = "http://127.0.0.1:4100";
            var sqs = new AmazonSQSClient(config);
#else
            var chain = new CredentialProfileStoreChain();
            // TODO: fill your credentials!
            if (!chain.TryGetAWSCredentials("DevDaysEurope2019", out var awsCredentials))
            {
                Console.WriteLine("Can't find profile, configure profile and try again");

                return;
            }

            var sqs = new AmazonSQSClient(awsCredentials, RegionEndpoint.EUCentral1);
#endif
            var wrapper = new QueueWrapper(sqs);

            var queueUrl = wrapper.GetQueueUrl(QueueName).Result;
            Console.WriteLine($"Listening for messages, queue url: {queueUrl}");

            do
            {
                var message = wrapper.GetNextMessage(queueUrl).Result;

                Console.WriteLine(message);
                Console.WriteLine("-----------------");
            } while (true);
        }
Пример #25
0
        public static bool TryGetClient(string profile, TelemetryConfiguration config, out ITelemetryClient client, bool enabledDefaultCredentials = false)
        {
            client = null;
            var            chain = new CredentialProfileStoreChain();
            AWSCredentials awsCredentials;

            if (enabledDefaultCredentials)
            {
                awsCredentials = FallbackCredentialsFactory.GetCredentials();
                if (awsCredentials == null)
                {
                    return(false);
                }
            }
            else
            {
                if (!chain.TryGetAWSCredentials(profile, out awsCredentials))
                {
                    return(false);
                }
            }
            if (awsCredentials != null)
            {
                client = new TelemetryClient(awsCredentials, new TelemetryClientConfig
                {
                    RegionEndpoint = RegionEndpoint.GetBySystemName(config.Region),
                    MaxErrorRetry  = 2,
                    ServiceURL     = config.InvokeUrl,
                });
                return(true);
            }
            return(false);
        }
Пример #26
0
        public Form1()
        {
            InitializeComponent();

            var            chain = new CredentialProfileStoreChain();
            AWSCredentials awsCredentials;

            if (chain.TryGetAWSCredentials("default", out awsCredentials))
            {
                var keys = awsCredentials.GetCredentials();
                client      = new AmazonSimpleNotificationServiceClient(region: region, awsAccessKeyId: keys.AccessKey, awsSecretAccessKey: keys.SecretKey);
                soundWriter = new SoundS3Writer(keys.AccessKey, keys.SecretKey, region);
                //soundWriter = new SoundFileWriter();
            }
            request = new PublishRequest
            {
                Message  = message,
                TopicArn = topicArn
            };



            waveIn = new WaveInEvent();
            waveIn.DataAvailable += OnDataAvailable;
            waveIn.StartRecording();
        }
Пример #27
0
        private static AWSCredentials GetNamedStoredProfile(string profileName)
        {
            var credentialProfileStoreChain = new CredentialProfileStoreChain();

            return(credentialProfileStoreChain.TryGetAWSCredentials(profileName, out var credentials)
                ? credentials
                : null);
        }
Пример #28
0
        private static AWSCredentials GetDefaultStoredProfile()
        {
            var credentialProfileStoreChain = new CredentialProfileStoreChain();

            return(credentialProfileStoreChain.TryGetAWSCredentials("default", out var credentials)
                ? credentials
                : throw new AmazonClientException("Unable to find a default profile in CredentialProfileStoreChain."));
        }
Пример #29
0
        private AWSCredentials GetAwsCredential()
        {
            var chain          = new CredentialProfileStoreChain();
            var awsCredentials = default(AWSCredentials);

            chain.TryGetAWSCredentials(_config.LocaAwsProfile, out awsCredentials);
            return(awsCredentials);
        }
Пример #30
0
        protected AWSCredentials DetermineAWSCredentials()
        {
            if (this._resolvedCredentials != null)
            {
                return(this._resolvedCredentials);
            }

            if (this.Credentials != null)
            {
                this._resolvedCredentials = this.Credentials;
            }
            else
            {
                var awsAccessKeyId = GetStringValueOrDefault(this.AWSAccessKeyId, CommonDefinedCommandOptions.ARGUMENT_AWS_ACCESS_KEY_ID, false);
                var profile        = this.GetStringValueOrDefault(this.Profile, CommonDefinedCommandOptions.ARGUMENT_AWS_PROFILE, false);

                if (!string.IsNullOrEmpty(awsAccessKeyId))
                {
                    var awsSecretKey    = GetStringValueOrDefault(this.AWSSecretKey, CommonDefinedCommandOptions.ARGUMENT_AWS_SECRET_KEY, false);
                    var awsSessionToken = GetStringValueOrDefault(this.AWSSessionToken, CommonDefinedCommandOptions.ARGUMENT_AWS_SESSION_TOKEN, false);

                    if (string.IsNullOrEmpty(awsSecretKey))
                    {
                        throw new ToolsException("An AWS access key id was specified without a required AWS secret key. Either set an AWS secret key or remove the AWS access key id and use profiles for credentials.", ToolsException.CommonErrorCode.InvalidCredentialConfiguration);
                    }

                    if (string.IsNullOrEmpty(awsSessionToken))
                    {
                        this._resolvedCredentials = new BasicAWSCredentials(awsAccessKeyId, awsSecretKey);
                    }
                    else
                    {
                        this._resolvedCredentials = new SessionAWSCredentials(awsAccessKeyId, awsSecretKey, awsSessionToken);
                    }
                }
                else if (!string.IsNullOrEmpty(profile))
                {
                    var chain = new CredentialProfileStoreChain(this.ProfileLocation);
                    if (!chain.TryGetAWSCredentials(profile, out this._resolvedCredentials))
                    {
                        this._resolvedCredentials = FallbackCredentialsFactory.GetCredentials();
                    }
                }
                else
                {
                    this._resolvedCredentials = FallbackCredentialsFactory.GetCredentials();
                }

                if (this._resolvedCredentials is AssumeRoleAWSCredentials)
                {
                    var assumeOptions = ((AssumeRoleAWSCredentials)this._resolvedCredentials).Options;
                    assumeOptions.MfaTokenCodeCallback = new AssumeRoleMfaTokenCodeCallback(assumeOptions).Execute;
                }
            }

            return(this._resolvedCredentials);
        }