Beispiel #1
0
        public S3Service(ILogger logger, AWSOptions options = null)
        {
            this.logger = logger;
            var s3Access = Environment.GetEnvironmentVariable("S3Access");
            var s3Secret = Environment.GetEnvironmentVariable("S3Secret");
            var s3Region = Environment.GetEnvironmentVariable("S3Region");

            try
            {
                if (options != null && options.Credentials != null)
                {
                    s3Client = new(options.Credentials, options.Region);
                }
                else if (!string.IsNullOrEmpty(s3Access) && !string.IsNullOrEmpty(s3Secret) && !string.IsNullOrEmpty(s3Region))
                {
                    s3Client = new AmazonS3Client(s3Access, s3Secret, GetRegionFromString(s3Region));
                }
                else
                {
                    var creds = Amazon.Runtime.FallbackCredentialsFactory.GetCredentials();
                    s3Client = new(creds);
                }
            }
            catch (Exception ex)
            {
                logger.LogError(ex, "Error Starting S3 Service");
            }
        }
        /// <summary>
        /// This exists only to populate some sample data to be used by this example project
        /// </summary>
        private static async Task PopulateSampleDataForThisProject()
        {
            var awsOptions = new AWSOptions {
                Region = RegionEndpoint.USEast1
            };

            var root       = $"/dotnet-aws-samples/systems-manager-sample/common";
            var parameters = new[]
            {
                new { Name = "StringValue", Value = "string-value" },
                new { Name = "IntegerValue", Value = "10" },
                new { Name = "DateTimeValue", Value = "2000-01-01" },
                new { Name = "BooleanValue", Value = "True" },
                new { Name = "TimeSpanValue", Value = "00:05:00" },
            };

            using (var client = awsOptions.CreateServiceClient <IAmazonSimpleSystemsManagement>())
            {
                var result = await client.GetParametersByPathAsync(new GetParametersByPathRequest { Path = root, Recursive = true }).ConfigureAwait(false);

                if (result.Parameters.Count == parameters.Length)
                {
                    return;
                }

                foreach (var parameter in parameters)
                {
                    var name = $"{root}/settings/{parameter.Name}";
                    await client.PutParameterAsync(new PutParameterRequest { Name = name, Value = parameter.Value, Type = ParameterType.String, Overwrite = true }).ConfigureAwait(false);
                }
            }
        }
Beispiel #3
0
        protected void ResolveHostConfig()
        {
            _logger.LogInformation("Resolving Host Configuration");
            var configBuilder = new ConfigurationBuilder()
                                .SetBasePath(Directory.GetCurrentDirectory())
                                .AddEnvironmentVariables(prefix: HostSettings.ConfigEnvPrefix);

            _hostConfig = configBuilder.Build();
            _settings   = _hostConfig.Get <HostSettings>();
            _awsOptions = _hostConfig.GetAWSOptions();

            if (_settings.AppSettingsS3Bucket != null && _settings.AppSettingsS3Key != null)
            {
                _logger.LogInformation($"Resolved AppSettings S3 source as"
                                       + $" [{_settings.AppSettingsS3Bucket}][{_settings.AppSettingsS3Key}]");
                var s3      = _awsOptions.CreateServiceClient <IAmazonS3>();
                var getResp = s3.GetObjectAsync(_settings.AppSettingsS3Bucket, _settings.AppSettingsS3Key).Result;

                var localJson = HostSettings.AppSettingsLocalJsonFile;

                using (getResp)
                    using (var rs = getResp.ResponseStream)
                        using (var fs = File.OpenWrite(localJson))
                        {
                            rs.CopyTo(fs);
                        }
                _logger.LogInformation($"Copied AppSettings from S3 source to local file at [{localJson}]");
            }
        }
Beispiel #4
0
        public async void Test()
        {
            var graphQLOptions = new GraphQLClientOptions
            {
                EndPoint = new Uri("")
            };

            var awsOptions = new AWSOptions()
            {
                AccessKey    = "",
                SecretKey    = "",
                SessionToken = "",
            };

            var client = new GraphQLAWSClient(graphQLOptions, awsOptions, RegionEndpoint.USEast1, "");

            var request = new GraphQLRequest
            {
                Query = ""
            };

            var response = await client.PostSignedRequestAsync(request, null);

            response.Should().NotBeNull();
        }
Beispiel #5
0
        static void ExecuteStepFunctionUsingAssumedExistingStateMachineRole()
        {
            var options = new AWSOptions()
            {
                Profile = "default",
                Region  = RegionEndpoint.EUWest2
            };

            var assumedRoleResponse       = ManualAssume(options).ConfigureAwait(false).GetAwaiter().GetResult();
            var assumedCredentials        = assumedRoleResponse.Credentials;
            var amazonStepFunctionsConfig = new AmazonStepFunctionsConfig {
                RegionEndpoint = RegionEndpoint.EUWest2
            };

            using (var amazonStepFunctionsClient = new AmazonStepFunctionsClient(
                       assumedCredentials.AccessKeyId,
                       assumedCredentials.SecretAccessKey, amazonStepFunctionsConfig))
            {
                var state = new State
                {
                    Name = "MyStepFunctions"
                };
                var jsonData1             = JsonConvert.SerializeObject(state);
                var startExecutionRequest = new StartExecutionRequest
                {
                    Input           = jsonData1,
                    Name            = $"SchedulingEngine_{Guid.NewGuid().ToString("N")}",
                    StateMachineArn = "arn:aws:states:eu-west-2:464534050515:stateMachine:StateMachine-z8hrOwmL9CiG"
                };
                var taskStartExecutionResponse = amazonStepFunctionsClient.StartExecutionAsync(startExecutionRequest).ConfigureAwait(false).GetAwaiter().GetResult();
            }

            Console.ReadLine();
        }
        public static ConfigurationManager BuildConfiguration(string rootPath, string environmentName)
        {
            //Log.Information("Building Configuration from Path {rootPath} for environmentName {environmentName}", rootPath, environmentName.ToLower());

            Console.WriteLine("Create builder");
            var builder = new ConfigurationBuilder().SetBasePath(rootPath)
                          //.AddJsonFile("appsettings.json", true, true)
                          //.AddJsonFile($"appsettings.{environmentName.ToLower()}.json", true, true)
                          //.AddJsonFile($"appsettings.{environmentName.ToLower()}.private.json", true, true)
                          .AddEnvironmentVariables();

            if (IsProduction())
            {
                var awsOptions = new AWSOptions
                {
                    Region = RegionEndpoint.APSoutheast2
                };
                Console.WriteLine("Add Systems Manager Parameter Store");
                builder.AddSystemsManager($"/tbi/{environmentName.ToLower()}", awsOptions);
            }

            try
            {
                Console.WriteLine("Build config");
                var newConfigManager = builder.Build();

                Console.WriteLine("Return builder");
                return(new ConfigurationManager(newConfigManager));
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                throw;
            }
        }
Beispiel #7
0
 /// <summary>
 /// Creates the AWS service client that implements the service client interface. The AWSOptions object
 /// will be searched for in the IServiceProvider.
 /// </summary>
 /// <param name="provider">The dependency injection provider.</param>
 /// <returns>The AWS service client</returns>
 internal static object CreateServiceClient(Type serviceInterfaceType, AWSOptions options)
 {
     var credentials = CreateCredentials(options);
     var config = CreateConfig(serviceInterfaceType, options);
     var client = CreateClient(serviceInterfaceType, credentials, config);
     return client;
 }
Beispiel #8
0
        public async Task Start(AWSOptions awsOptions, string queueName, CancellationToken cancel)
        {
            using (var client = awsOptions.CreateServiceClient <IAmazonSQS>())
            {
                var getQueueResult = await client.GetQueueUrlAsync(queueName, cancel);

                while (cancel.IsCancellationRequested == false)
                {
                    Console.WriteLine("Waiting for messages....");

                    ReceiveMessageRequest rxMessage = new ReceiveMessageRequest();
                    rxMessage.QueueUrl            = getQueueResult.QueueUrl;
                    rxMessage.WaitTimeSeconds     = 20;
                    rxMessage.MaxNumberOfMessages = 10;

                    ReceiveMessageResponse rxMessageResponse = await client.ReceiveMessageAsync(rxMessage);

                    if (rxMessageResponse.Messages.Any() == false)
                    {
                        return;
                    }

                    Console.WriteLine($"Got {rxMessageResponse.Messages.Count} messages");

                    var deletions = rxMessageResponse.Messages.Select(m => new DeleteMessageBatchRequestEntry(m.MessageId, m.ReceiptHandle));

                    Console.WriteLine("Deleting messages....");

                    await client.DeleteMessageBatchAsync(getQueueResult.QueueUrl, deletions.ToList());
                }
            }
        }
Beispiel #9
0
        /// <summary>
        /// This constructor instantiates a new ElasticClient using the AWSOptions and AWS cluster URI
        /// </summary>
        /// <param name="awsOptions">AWSOptions containing the credentials and region endpoint</param>
        /// <param name="esClusterUri">URI of the Elasticsearch cluster in AWS</param>
        /// <param name="defaultIndex">(Optional) default index to use for writing documents</param>
        /// <param name="numberOfBulkDocumentsToWriteAtOnce">
        ///     (Optional) number of documents to write to Elasticsearch
        ///     - set to 0 to write every record immediately, default is 5
        /// </param>
        /// <param name="rollingDate">(Optional) whether or not to use a rolling date pattern when writing to indices, default is false</param>
        /// <param name="logger">(Optional) ILogger to use</param>
        public Floe(
            AWSOptions awsOptions,
            Uri esClusterUri,
            string defaultIndex = null,
            int numberOfBulkDocumentsToWriteAtOnce = _defaultNumberOfBulkDocumentsToWriteAtOnce,
            bool rollingDate = false,
            ILogger logger   = null)
        {
            if (awsOptions == null)
            {
                throw new ArgumentNullException(nameof(awsOptions));
            }

            if (!string.IsNullOrEmpty(defaultIndex))
            {
                _defaultIndex = defaultIndex;
            }

            _rollingDate = rollingDate;

            if (numberOfBulkDocumentsToWriteAtOnce > -1)
            {
                _numberOfBulkDocumentsToWriteAtOnce = numberOfBulkDocumentsToWriteAtOnce;
            }

            AwsHttpConnection httpConnection = new AwsHttpConnection(awsOptions);

            SingleNodeConnectionPool connectionPool     = new SingleNodeConnectionPool(esClusterUri);
            ConnectionSettings       connectionSettings = new ConnectionSettings(connectionPool, httpConnection);

            _client = new ElasticClient(connectionSettings);

            _logger = logger;
        }
Beispiel #10
0
 public S3StreamingCarrier(ILogger <S3StreamingCarrier> logger, Amazon.Extensions.NETCore.Setup.AWSOptions options, S3BucketsOptions s3BucketsConfiguration = null)
 {
     this.logger  = logger;
     this.options = options;
     this.s3BucketsConfiguration = s3BucketsConfiguration;
     Priority = 75;
 }
        //private static CognitoAWSCredentials awsCredentials;
        public AWSLexService(IOptions <AWSOptions> awsOptions)
        {
            _awsOptions = awsOptions.Value;

            InitLexService();

            /*
             * Use CognitoID as the Identifying User ID if you have the User Authenticate with Cognito
             * If using UnAuth, CognitoID changes and will affect bot response
             */
            //LexUserID += awsCredentials.GetIdentityId().Split(':')[1].Substring(0,7);

            #region CognitoSTS

            /*
             * This if for using initializing Cognito with STS, not needed
             */
            /*cognitoClient = new AmazonCognitoIdentityClient(
             *      awsCreds, // the anonymous credentials
             *      RegionEndpoint.USEast1); //Region
             *
             * _awsCredentials = Task.Run(async () =>
             *  {try
             *      {   return await GetAWSCredentialsFromSTS(
             *              await GetCognitoIDToken(
             *                  await GetCognitoID()
             *              ));
             *      }
             *   catch (Exception ex)
             *      { return null; }
             *  }).Result.Credentials;*/
            #endregion
        }
        // 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>();
        }
        private SendMessageResponse SendTestMessage()
        {
            var input = new SendParameters
            {
                QueueUrl = queueURL,
                Message  = $@"Frends.Community.AWS.SQS.Tests.SendMessage() test. 
Datetime: {DateTime.Now.ToString("o")}
"
            };

            var options = new SendOptions
            {
                DelaySeconds           = 0,
                MessageDeduplicationId = queueURL.Contains(".fifo") ? Guid.NewGuid().ToString() : "", // FIFO, ContentBasedDeduplication disabled
                MessageGroupId         = queueURL.Contains(".fifo") ? "1" : ""                        // FIFO
            };

            var awsOptions = new AWSOptions
            {
                AWSCredentials        = SQS.GetBasicAWSCredentials(credParams),
                UseDefaultCredentials = false,
                Region = region
            };

            return(SQS.SendMessage(input, options, awsOptions, new System.Threading.CancellationToken()).Result);
        }
Beispiel #14
0
        /// <summary>
        /// Contructor initializing test fixture.
        /// </summary>
        public BucketIntegrationFixture()
        {
            // Setup Configuration
            var configBuilder = new ConfigurationBuilder()
                                .AddJsonFile("appsettings.json", optional: false);
            var configuration = configBuilder.Build();

            AWSOptions options = configuration.GetAWSOptions();

            // S3 Configuration
            BucketName    = Environment.GetEnvironmentVariable("BUCKET_NAME");
            BucketWebsite = $"http://{BucketName}.s3-website.{options.Region.SystemName}.amazonaws.com/";

            var storageConfig = new PiranhaS3StorageOptions {
                BucketName    = BucketName,
                PublicUrlRoot = BucketWebsite
            };

            // Service Provider
            IServiceCollection services = new ServiceCollection();

            services.AddPiranhaS3StorageOptions(storageConfig);
            services.AddDefaultAWSOptions(configuration.GetAWSOptions());
            services.AddPiranhaS3Storage();
            services.AddAWSService <IAmazonS3>();
            var serviceProvider = services.BuildServiceProvider();

            // Get the services
            S3Storage = serviceProvider.GetService <IStorage>();
            S3Client  = serviceProvider.GetService <IAmazonS3>();
        }
        public void DeleteMessage()
        {
            var ret = SendTestMessage();

            Assert.IsTrue(ret.HttpStatusCode == System.Net.HttpStatusCode.OK);

            var rec = ReceiveTestMessage();

            Assert.IsTrue(rec.HttpStatusCode == System.Net.HttpStatusCode.OK);
            Assert.IsTrue(rec.Messages.Count > 0);

            var input = new DeleteParameters
            {
                QueueUrl      = queueURL,
                ReceiptHandle = rec.Messages[0].ReceiptHandle
            };

            var awsOptions = new AWSOptions
            {
                AWSCredentials        = SQS.GetBasicAWSCredentials(credParams),
                UseDefaultCredentials = false,
                Region = region
            };

            var delres = SQS.DeleteMessage(input, awsOptions, new System.Threading.CancellationToken()).Result;

            Assert.IsTrue(delres.HttpStatusCode == System.Net.HttpStatusCode.OK);
        }
        private static ServiceDescriptor GetServiceFactoryDescriptor <TService>(AWSOptions options, ServiceLifetime lifetime) where TService : IAmazonService
        {
            var descriptor = new ServiceDescriptor(typeof(TService), provider =>
            {
                LocalStackOptions localStackOptions = provider.GetRequiredService <IOptions <LocalStackOptions> >().Value;

                AmazonServiceClient serviceInstance;

                if (localStackOptions.UseLocalStack)
                {
                    var session = provider.GetRequiredService <ISession>();

                    serviceInstance = session.CreateClientByInterface <TService>();
                }
                else
                {
                    var clientFactory = provider.GetRequiredService <IAwsClientFactoryWrapper>();

                    serviceInstance = clientFactory.CreateServiceClient <TService>(provider, options);
                }

                return(serviceInstance);
            }, lifetime);

            return(descriptor);
        }
        /// <summary>
        /// Contructor initializing test fixture.
        /// </summary>
        public TestConfigurationFixture()
        {
            // Fake AWS Options
            FakeAwsOptions = new AWSOptions
            {
                Region      = RegionEndpoint.USWest2,
                Credentials = new BasicAWSCredentials("accessId", "secretKey")
            };

            // Main Configuration
            var configBuilder = new ConfigurationBuilder()
                                .AddJsonFile("appsettings.json", optional: false);

            MainConfiguration = configBuilder.Build();

            // Root Configuration
            configBuilder = new ConfigurationBuilder()
                            .AddJsonFile("appsettings.root.json", optional: false);
            RootConfiguration = configBuilder.Build();

            // Other Configuration
            configBuilder = new ConfigurationBuilder()
                            .AddJsonFile("appsettings.other.json", optional: false);
            OtherConfiguration = configBuilder.Build();
        }
Beispiel #18
0
        public IntegTestFixture()
        {
            AWSOptions        = new AWSOptions();
            AWSOptions.Region = Amazon.RegionEndpoint.USWest2;

            seedTestData();
        }
Beispiel #19
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,
            });
        }
Beispiel #20
0
 public SnsSink(IFormatProvider formatProvider, AWSOptions awsOptions, string logTopicArn, LogEventLevel minimumLevel, string outputTemplate)
 {
     _minimumLevel   = minimumLevel;
     _formatProvider = formatProvider;
     _textFormatter  = new Serilog.Formatting.Display.MessageTemplateTextFormatter(outputTemplate, formatProvider);
     _logTopicArn    = logTopicArn;
     _snsClient      = awsOptions.CreateServiceClient <IAmazonSimpleNotificationService>();
 }
Beispiel #21
0
 public SQSQueueMananger(
     AWSOptions options,
     string queueName)
 {
     _AmazonSQSClient = options.CreateServiceClient <IAmazonSQS>();
     _QueueName       = queueName;
     _QueueUrl        = GetQueueUrl().Result.QueueUrl;
 }
Beispiel #22
0
        public T GetAWSClient <T>(AWSCredentials credentials, string region) where T : IAmazonService
        {
            var awsOptions = new AWSOptions {
                Credentials = credentials, Region = RegionEndpoint.GetBySystemName(region)
            };

            return(awsOptions.CreateServiceClient <T>());
        }
Beispiel #23
0
        public FunctionTest()
        {
            var builder = new ConfigurationBuilder()
                          .AddJsonFile("appsettings.json");

            _config     = builder.Build();
            _awsOptions = _config.GetAWSOptions();
        }
Beispiel #24
0
        public AdminController(IOptions <AWSOptions> awsOptions)
        {
            _awsOptions = awsOptions.Value;
            Amazon.RegionEndpoint AppRegion = Amazon.RegionEndpoint.GetBySystemName(_awsOptions.Region);

            _cloudAuthService = new CloudAuthService(_awsOptions.CognitoPoolId, AppRegion);
            _dbDataService    = new DBDataService(_cloudAuthService.GetAWSCredentials(), AppRegion);
        }
Beispiel #25
0
        public T GetAWSClient <T>() where T : IAmazonService
        {
            var awsOptions = new AWSOptions();

            _awsOptionsAction?.Invoke(awsOptions);

            return(awsOptions.CreateServiceClient <T>());
        }
Beispiel #26
0
 public static IHostBuilder CreateHostBuilder(string[] args) =>
 Host.CreateDefaultBuilder(args)
 .ConfigureServices((hostContext, services) =>
 {
     services.AddHostedService <Worker>();
     IConfiguration config = hostContext.Configuration;
     AWSOptions options    = config.GetAWSOptions();
     services.AddAWSService <IAmazonSQS>(options);
 });
        public static IServiceCollection AddDynamoDbServices(
            this IServiceCollection services,
            AWSOptions awsConfig)
        {
            services.AddDefaultAWSOptions(awsConfig);
            services.AddAWSService <IAmazonDynamoDB>();

            return(services);
        }
Beispiel #28
0
        private void seedTestData()
        {
            bool success = false;

            using (var client = AWSOptions.CreateServiceClient <IAmazonSimpleSystemsManagement>())
            {
                var tasks = new List <Task>();
                foreach (var kv in TestData)
                {
                    Console.WriteLine($"Adding parameter: ({ParameterPrefix + kv.Key}, {kv.Value})");
                    tasks.Add(client.PutParameterAsync(new PutParameterRequest
                    {
                        Name  = ParameterPrefix + kv.Key,
                        Value = kv.Value,
                        Type  = ParameterType.String
                    }));
                }
                ;
                Task.WaitAll(tasks.ToArray());

                // due to eventual consistency, wait for 5 sec increments for 3 times to verify
                // test data is correctly set before executing tests.
                const int tries = 3;
                for (int i = 0; i < tries; i++)
                {
                    int count = 0;
                    GetParametersByPathResponse response;
                    do
                    {
                        response = client.GetParametersByPathAsync(new GetParametersByPathRequest
                        {
                            Path = ParameterPrefix
                        }).Result;

                        count += response.Parameters.Count;
                    } while (!string.IsNullOrEmpty(response.NextToken));

                    success = (count == TestData.Count);

                    if (success)
                    {
                        Console.WriteLine("Verified that test data is available.");
                        break;
                    }
                    else
                    {
                        Console.WriteLine($"Waiting on test data to be available. Waiting {count + 1}/{tries}");
                        Thread.Sleep(5 * 1000);
                    }
                }
            }

            if (!success)
            {
                throw new Exception("Failed to seed integration test data");
            }
        }
        /// <summary>
        /// Adds the Amazon service client to the dependency injection framework. The Amazon service client is not
        /// created until it is requested. If the ServiceLifetime property is set to Singleton, the default, then the same
        /// instance will be reused for the lifetime of the process and the object should not be disposed.
        /// </summary>
        /// <typeparam name="TService">The AWS service interface, like IAmazonS3.</typeparam>
        /// <param name="collection"></param>
        /// <param name="options">The AWS options used to create the service client overriding the default AWS options added using AddDefaultAWSOptions.</param>
        /// <param name="lifetime">The lifetime of the service client created. The default is Singleton.</param>
        /// <returns>Returns back the IServiceCollection to continue the fluent system of IServiceCollection.</returns>
        public static IServiceCollection AddAwsService <TService>(this IServiceCollection collection,
                                                                  AWSOptions options,
                                                                  ServiceLifetime lifetime = ServiceLifetime.Singleton) where TService : IAmazonService
        {
            ServiceDescriptor descriptor = GetServiceFactoryDescriptor <TService>(options, lifetime);

            collection.Add(descriptor);

            return(collection);
        }
            //public CloudAuthService(string appPoolID, string awsRegion):
            //    this(appPoolID, Amazon.RegionEndpoint.GetBySystemName(awsRegion)){ }

            public CloudAuthService(IOptions <AWSOptions> awsOptions)
            {
                _awsOptions = awsOptions.Value;
                _awsRegion  = Amazon.RegionEndpoint.GetBySystemName(
                    _awsOptions.Region);
                if (!InitService())
                {
                    throw new AmazonCognitoIdentityException("Couldn't connect to Cognito Service", new Exception("InitService - CognitoClient"));
                }
            }
Beispiel #31
0
        public IAmazonSQS CreateClient(string profileName, string regionName)
        {
            var options = new AWSOptions
            {
                Profile = profileName,
                Region  = RegionEndpoint.GetBySystemName(regionName),
            };

            return(CreateAmazonSqsClient(options));
        }
        /// <summary>
        /// Constructs an AWSOptions class with the options specifed in the "AWS" section in the IConfiguration object.
        /// </summary>
        /// <param name="config"></param>
        /// <param name="configSection">The config section to extract AWS options from.</param>
        /// <returns>The AWSOptions containing the values set in configuration system.</returns>
        public static AWSOptions GetAWSOptions(this IConfiguration config, string configSection)
        {
            var options = new AWSOptions();

            IConfiguration section;
            if (string.IsNullOrEmpty(configSection))
                section = config;
            else
                section = config.GetSection(configSection);

            if (section == null)
                return options;

            var clientConfigTypeInfo = typeof(ClientConfig).GetTypeInfo();
            foreach(var element in section.GetChildren())
            {
                try
                {
                    var property = clientConfigTypeInfo.GetDeclaredProperty(element.Key);
                    if (property == null || property.SetMethod == null)
                        continue;

                    if (property.PropertyType == typeof(string) || property.PropertyType.GetTypeInfo().IsPrimitive)
                    {
                        var value = Convert.ChangeType(element.Value, property.PropertyType);
                        property.SetMethod.Invoke(options.DefaultClientConfig, new object[] { value });
                    }
                    else if (property.PropertyType == typeof(TimeSpan) || property.PropertyType == typeof(Nullable<TimeSpan>))
                    {
                        var milliSeconds = Convert.ToInt64(element.Value);
                        var timespan = TimeSpan.FromMilliseconds(milliSeconds);
                        property.SetMethod.Invoke(options.DefaultClientConfig, new object[] { timespan });
                    }
                }
                catch(Exception e)
                {
                    throw new ConfigurationException($"Error reading value for property {element.Key}.", e)
                    {
                        PropertyName = element.Key,
                        PropertyValue = element.Value
                    };
                }
            }

            if (!string.IsNullOrEmpty(section["Profile"]))
            {
                options.Profile = section["Profile"];
            }
            // Check legacy name if the new name isn't set
            else if (!string.IsNullOrEmpty(section["AWSProfileName"]))
            {
                options.Profile = section["AWSProfileName"];
            }

            if (!string.IsNullOrEmpty(section["ProfilesLocation"]))
            {
                options.ProfilesLocation = section["ProfilesLocation"];
            }
            // Check legacy name if the new name isn't set
            else if (!string.IsNullOrEmpty(section["AWSProfilesLocation"]))
            {
                options.ProfilesLocation = section["AWSProfilesLocation"];
            }

            if (!string.IsNullOrEmpty(section["Region"]))
            {
                options.Region = RegionEndpoint.GetBySystemName(section["Region"]);
            }
            // Check legacy name if the new name isn't set
            else if (!string.IsNullOrEmpty(section["AWSRegion"]))
            {
                options.Region = RegionEndpoint.GetBySystemName(section["AWSRegion"]);
            }

            return options;
        }
Beispiel #33
0
 private Options(GeneralOptions generalOpts, AWSOptions awsOpts)
 {
     this.generalOptions = generalOpts;
     this.awsOptions = awsOpts;
 }
Beispiel #34
0
        // Factory method to read from config
        public static Options loadFromConfig(bool withDefaults = false)
        {
            lock (lockObject)
            {
                logger.Info("Loading configuration");
                GeneralOptions generalOpts = null;
                AWSOptions awsOpts = null;
                try
                {
                    generalOpts = GeneralOptions.load();
                    awsOpts = AWSOptions.load();
                    if (!String.IsNullOrEmpty(generalOpts.DomainName) 
                        && generalOpts.DomainName[generalOpts.DomainName.Length - 1] != '.')
                    {
                        logger.Debug("Forcefully terminating domain name with dot.");
                        generalOpts.DomainName = generalOpts.DomainName + ".";
                    }
                }
                catch (FileNotFoundException)
                {
                    if (generalOpts == null)
                    {
                        generalOpts = new GeneralOptions();
                        generalOpts.ExternalIPNeeded = true;
                        generalOpts.HasInitialDelay = true;
                        generalOpts.IPProviders = new List<IPProvider>();
                        generalOpts.RunOnStart = false;
                        generalOpts.TimerPeriodSec = 300;
                    }

                    if (awsOpts == null)
                    {
                        awsOpts = new AWSOptions();
                        awsOpts.AWSAccessKey = String.Empty;
                        awsOpts.AWSSecretKey = String.Empty;
                        awsOpts.HostedZoneId = String.Empty;
                    }
                }
                return new Options(generalOpts, awsOpts);
            }
        }
Beispiel #35
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();
        }
Beispiel #36
0
        /// <summary>
        /// Creates the ClientConfig object for the service client.
        /// </summary>
        /// <param name="options"></param>
        /// <returns></returns>
        private static ClientConfig CreateConfig(Type serviceInterfaceType, AWSOptions options)
        {
            var configTypeName = serviceInterfaceType.Namespace + "." + serviceInterfaceType.Name.Substring(1) + "Config";
            var configType = serviceInterfaceType.GetTypeInfo().Assembly.GetType(configTypeName);

            var constructor = configType.GetConstructor(EMPTY_TYPES);
            ClientConfig config = constructor.Invoke(EMPTY_PARAMETERS) as ClientConfig;

            var defaultConfig = options.DefaultClientConfig;
            if (options.IsDefaultClientConfigSet)
            {
                var emptyArray = new object[0];
                var singleArray = new object[1];

                var clientConfigTypeInfo = typeof(ClientConfig).GetTypeInfo();
                foreach (var property in clientConfigTypeInfo.DeclaredProperties)
                {
                    if (property.GetMethod != null && property.SetMethod != null)
                    {
                        // Skip RegionEndpoint because it is set below and calling the get method on the
                        // property triggers the default region fallback mechanism.
                        if (string.Equals(property.Name, "RegionEndpoint", StringComparison.Ordinal))
                            continue;

                        singleArray[0] = property.GetMethod.Invoke(defaultConfig, emptyArray);
                        if (singleArray[0] != null)
                        {
                            property.SetMethod.Invoke(config, singleArray);
                        }
                    }
                }
            }

            // Setting RegionEndpoint only if ServiceURL was not set, because ServiceURL value will be lost otherwise
            if (options.Region != null && string.IsNullOrEmpty(defaultConfig.ServiceURL))
            {
                config.RegionEndpoint = options.Region;
            }

            return config;
        }
Beispiel #37
0
 /// <summary>
 /// Constructs an instance of the ClientFactory
 /// </summary>
 /// <param name="type">The type object for the Amazon service client interface, for example IAmazonS3.</param>
 internal ClientFactory(Type type, AWSOptions awsOptions)
 {
     _serviceInterfaceType = type;
     _awsOptions = awsOptions;
 }