Exemple #1
0
        public string Upload(string storageBasePath, string localPath, Guid userId)
        {
            String key = String.Empty;

            if (String.IsNullOrEmpty(storageBasePath))
            {
                key = "backup/" + Path.GetFileName(localPath);
            }
            else
            {
                key = String.Concat(storageBasePath.Trim(new char[] { ' ', '/', '\\' }), "/", Path.GetFileName(localPath));
            }

            using (var fileTransferUtility = new TransferUtility(accessKeyId, secretAccessKey, RegionEndpoint.GetBySystemName(region)))
            {
                fileTransferUtility.Upload(
                    new TransferUtilityUploadRequest
                {
                    BucketName   = bucket,
                    FilePath     = localPath,
                    StorageClass = S3StorageClass.StandardInfrequentAccess,
                    PartSize     = 6291456, // 6 MB.
                    Key          = key
                });
            }


            return(key);
        }
Exemple #2
0
        public static void ProcessRequestHandlers(IExecutionContext executionContext)
        {
            var request = executionContext.RequestContext.Request;
            var config  = executionContext.RequestContext.ClientConfig;

            // If the marshalled request has the SSE header and it is set to KMS,
            // force SigV4 for this request.
            // Current operations that may set this header:
            //  CopyObject, CopyPart, InitiateMultipart, PutObject
            string sseHeaderValue;

            if (request.Headers.TryGetValue(HeaderKeys.XAmzServerSideEncryptionHeader, out sseHeaderValue) &&
                string.Equals(sseHeaderValue, ServerSideEncryptionMethod.AWSKMS.Value, StringComparison.Ordinal))
            {
                request.SignatureVersion = SignatureVersion.SigV4;
            }
            var bucketResourcePathToken = GetBucketName(request.ResourcePath);

            if (string.IsNullOrEmpty(bucketResourcePathToken))
            {
                return;
            }

            var s3Config = config as AmazonS3Config;

            if (s3Config == null)
            {
                throw new AmazonClientException("Current config object is not of type AmazonS3Config");
            }

            //If a ServiceURL is set the config ClientRegion should be null. Under this case
            //the region needs to be determined from the ServiceURL.
            var regionEndpoint = config.RegionEndpoint;

            if (regionEndpoint == null && !string.IsNullOrEmpty(config.ServiceURL))
            {
                var regionName = AWSSDKUtils.DetermineRegion(config.ServiceURL);
                regionEndpoint = RegionEndpoint.GetBySystemName(regionName);
            }

            bool isHttp;
            bool removeBucketFromResourcePath = false;

            if (Arn.IsArn(bucketResourcePathToken))
            {
                string     accessPoint;
                UriBuilder ub;
                Arn        s3Arn = Arn.Parse(bucketResourcePathToken);
                if (s3Arn.IsService("s3") && s3Arn.TryParseAccessPoint(out accessPoint))
                {
                    if (s3Arn.IsMRAPArn())
                    {
                        var partitionDnsSuffix = RegionEndpoint.GetDnsSuffixForPartition(s3Arn.Partition);
                        ValidateMRAPAccessPoint(s3Arn, s3Config, accessPoint, partitionDnsSuffix);

                        request.SignatureVersion     = SignatureVersion.SigV4a;
                        request.AuthenticationRegion = "*";

                        isHttp = config.UseHttp;
                        var scheme = isHttp ? "http" : "https";
                        ub = new UriBuilder($"{scheme}://{accessPoint}.accesspoint.s3-global.{partitionDnsSuffix}");
                    }
                    else // Non-MRAP access point
                    {
                        ValidateS3AccessPoint(s3Arn, s3Config, regionEndpoint);
                        if (!string.IsNullOrEmpty(config.ServiceURL))
                        {
                            ub      = new UriBuilder(EndpointResolver.DetermineEndpoint(s3Config, request));
                            isHttp  = string.Equals(ub.Scheme, "http", StringComparison.OrdinalIgnoreCase);
                            ub.Host = string.Concat($"{accessPoint}-{s3Arn.AccountId}.", ub.Host);
                        }
                        else
                        {
                            isHttp = config.UseHttp;
                            var scheme     = isHttp ? "http" : "https";
                            var fipsSuffix = regionEndpoint?.SystemName?.ToLower().Contains("fips") == true ? "-fips" : "";
                            ub = new UriBuilder($"{scheme}://{accessPoint}-{s3Arn.AccountId}.s3-accesspoint{fipsSuffix}{(config.UseDualstackEndpoint ? ".dualstack" : "")}.{s3Arn.Region}.{config.RegionEndpoint.PartitionDnsSuffix}");
                        }
                    }

                    request.Endpoint = ub.Uri;
                }
                else if (s3Arn.IsService(s3ObjectLambdaServiceName) && s3Arn.TryParseAccessPoint(out accessPoint))
                {
                    ValidateS3ObjectLambdaAccessPoint(s3Arn, s3Config, regionEndpoint);

                    if (!string.IsNullOrEmpty(config.ServiceURL))
                    {
                        ub      = new UriBuilder(EndpointResolver.DetermineEndpoint(s3Config, request));
                        isHttp  = string.Equals(ub.Scheme, "http", StringComparison.OrdinalIgnoreCase);
                        ub.Host = string.Concat($"{accessPoint}-{s3Arn.AccountId}.", ub.Host);
                    }
                    else
                    {
                        isHttp = s3Config.UseHttp;
                        var scheme     = isHttp ? "http" : "https";
                        var fipsSuffix = regionEndpoint?.SystemName?.ToLower().Contains("fips") == true ? "-fips" : "";
                        ub = new UriBuilder($"{scheme}://{accessPoint}-{s3Arn.AccountId}.{s3ObjectLambdaServiceName}{fipsSuffix}.{s3Arn.Region}.{config.RegionEndpoint.PartitionDnsSuffix}");
                    }

                    request.Endpoint = ub.Uri;
                }
                else if (s3Arn.IsOutpostArn())
                {
                    var outpost = s3Arn.ParseOutpost();
                    ValidateOutpostAccessPoint(s3Arn, s3Config, regionEndpoint);
                    var region = s3Config.UseArnRegion ? s3Arn.Region : regionEndpoint.SystemName;
                    bucketResourcePathToken = outpost.FullAccessPointName;

                    if (!string.IsNullOrEmpty(config.ServiceURL))
                    {
                        ub      = new UriBuilder(EndpointResolver.DetermineEndpoint(s3Config, request));
                        isHttp  = string.Equals(ub.Scheme, "http", StringComparison.OrdinalIgnoreCase);
                        ub.Host = string.Concat($"{outpost.AccessPointName}-{s3Arn.AccountId}.{outpost.OutpostId}.", ub.Host);
                    }
                    else
                    {
                        isHttp = config.UseHttp;
                        var scheme = isHttp ? "http" : "https";
                        ub = new UriBuilder($"{scheme}://{outpost.AccessPointName}-{s3Arn.AccountId}.{outpost.OutpostId}.s3-outposts.{region}.{config.RegionEndpoint.PartitionDnsSuffix}");
                    }

                    request.Endpoint = ub.Uri;
                }
                else
                {
                    throw new AmazonClientException("Invalid ARN specified for bucket name. Only access point ARNs are allowed for the value of bucket name.");
                }
                request.OverrideSigningServiceName = s3Arn.Service;
                // The access point arn can be using a region different from the configured region for the service client.
                // If so be sure to set the authentication region so the signer will use the correct region.
                if (!s3Arn.IsMRAPArn())    // Except for MRAP where signing region and ARN region diverge
                {
                    request.AuthenticationRegion = s3Arn.Region;
                    request.SignatureVersion     = SignatureVersion.SigV4;
                }

                removeBucketFromResourcePath = true;
            }
            else // not an arn
            {
                // If path style is not forced and the bucket name is DNS
                // compatible modify the endpoint to use virtual host style
                // addressing
                var bucketIsDnsCompatible = IsDnsCompatibleBucketName(bucketResourcePathToken);
                var ub = new UriBuilder(EndpointResolver.DetermineEndpoint(s3Config, request));
                isHttp = string.Equals(ub.Scheme, "http", StringComparison.OrdinalIgnoreCase);

                if (!s3Config.ForcePathStyle && bucketIsDnsCompatible)
                {
                    // If using HTTPS, bucketName cannot contain a period
                    if (isHttp || bucketResourcePathToken.IndexOf('.') < 0)
                    {
                        // Add bucket to host
                        ub.Host                      = string.Concat(bucketResourcePathToken, ".", ub.Host);
                        request.Endpoint             = ub.Uri;
                        removeBucketFromResourcePath = true;
                    }
                }

                if (request.OriginalRequest.GetType() == typeof(WriteGetObjectResponseRequest))
                {
                    if (!string.IsNullOrEmpty(config.ServiceURL))
                    {
                        ub     = new UriBuilder(EndpointResolver.DetermineEndpoint(s3Config, request));
                        isHttp = string.Equals(ub.Scheme, "http", StringComparison.OrdinalIgnoreCase);
                    }
                    else
                    {
                        isHttp = s3Config.UseHttp;
                        var scheme = isHttp ? "http" : "https";
                        var region = regionEndpoint.SystemName == "us-east-1-regional" ? "us-east-1" : regionEndpoint.SystemName;
                        ub = new UriBuilder($"{scheme}://{request.Headers["x-amz-request-route"]}.{s3ObjectLambdaServiceName}.{region}.{config.RegionEndpoint.PartitionDnsSuffix}");
                    }

                    request.Endpoint = ub.Uri;
                    request.OverrideSigningServiceName = s3ObjectLambdaServiceName;
                    request.SignatureVersion           = SignatureVersion.SigV4;
                }

                if (s3Config.UseAccelerateEndpoint)
                {
                    // Validate if bucket name is accelerate compatible and enable acceleration by using
                    // Accelerate endpoint for this request

                    if (!bucketIsDnsCompatible || BucketNameContainsPeriod(bucketResourcePathToken))
                    {
                        throw new AmazonClientException(
                                  @"S3 accelerate is enabled for this request but the bucket name is not accelerate compatible." +
                                  " The bucket name must be DNS compatible (http://docs.aws.amazon.com/AmazonS3/latest/dev/BucketRestrictions.html)" +
                                  " and must not contain any period (.) characters to be accelerate compatible.");
                    }

                    var  originalRequest        = request.OriginalRequest;
                    bool accelerateSupportedApi = !UnsupportedAccelerateRequestTypes.Contains(originalRequest.GetType());

                    // Skip requests which are not supported
                    if (accelerateSupportedApi)
                    {
                        request.Endpoint = GetAccelerateEndpoint(bucketResourcePathToken, s3Config);

                        if (request.SignatureVersion == SignatureVersion.SigV4 && s3Config.RegionEndpoint != null)
                        {
                            request.AlternateEndpoint = s3Config.RegionEndpoint;
                        }
                    }
                }
            }

            if (removeBucketFromResourcePath)
            {
                // Remove bucket from resource path but retain in canonical resource
                // prefix, so it gets included when we sign the request later
                var resourcePath        = request.ResourcePath;
                var canonicalBucketName = string.Concat("/", bucketResourcePathToken);
                if (resourcePath.IndexOf(canonicalBucketName, StringComparison.Ordinal) == 0)
                {
                    resourcePath = resourcePath.Substring(canonicalBucketName.Length);
                }

                request.ResourcePath            = resourcePath;
                request.CanonicalResourcePrefix = canonicalBucketName;
            }

            // Some parameters should not be sent over HTTP, just HTTPS
            if (isHttp)
            {
                ValidateHttpsOnlyHeaders(request);
            }
        }
Exemple #3
0
 public S3Connector(string systemName, string defaultBucket = null)
 {
     Client         = new AmazonS3Client(new StoredProfileAWSCredentials(), RegionEndpoint.GetBySystemName(systemName));
     _defaultBucket = defaultBucket;
 }
Exemple #4
0
        public string GetImagePath(string altId, ImageType imageType)
        {
            try
            {
                var clientId     = _settings.GetConfigSetting <string>(SettingKeys.Messaging.Aws.S3.AccessKey);
                var clientSecret = _settings.GetConfigSetting <string>(SettingKeys.Messaging.Aws.S3.SecretKey);
                var bucketName   = _settings.GetConfigSetting <string>(SettingKeys.Messaging.Aws.S3.BucketName);

                using (IAmazonS3 s3Client = new AmazonS3Client(clientId, clientSecret, RegionEndpoint.GetBySystemName("us-west-2")))
                {
                    GetPreSignedUrlRequest request = new GetPreSignedUrlRequest
                    {
                        BucketName = bucketName,
                        Key        = ImageFilePathProvider.GetImageFilePath(altId, imageType),
                        Expires    = DateTime.Now.AddYears(1)
                    };
                    return(s3Client.GetPreSignedURL(request));
                }
            }
            catch (Exception ex)
            {
                _logger.Log(Logging.Enums.LogCategory.Error, ex);
                return("");
            }
        }
Exemple #5
0
        public static void ProcessRequestHandlers(IExecutionContext executionContext)
        {
            var request = executionContext.RequestContext.Request;
            var config  = executionContext.RequestContext.ClientConfig;

            //If a ServiceURL is set the config ClientRegion should be null. Under this case
            //the region needs to be determined from the ServiceURL.
            RegionEndpoint useRegion = config.RegionEndpoint;

            if (useRegion == null && !string.IsNullOrEmpty(config.ServiceURL))
            {
                var regionName = AWSSDKUtils.DetermineRegion(config.ServiceURL);
                useRegion = RegionEndpoint.GetBySystemName(regionName);
            }

            string nonArnOutpostId;
            Arn    s3Arn;

            if (S3ArnUtils.RequestContainsArn(request, out s3Arn))
            {
                IS3Resource s3Resource = null;
                if (s3Arn.IsOutpostArn())
                {
                    if (!s3Arn.IsValidService())
                    {
                        throw new AmazonClientException($"Invalid ARN: {s3Arn.ToString()}, not S3 Outposts ARN");
                    }
                    s3Resource = s3Arn.ParseOutpost();
                    request.Headers[HeaderKeys.XAmzOutpostId] = ((S3OutpostResource)s3Resource).OutpostId;
                }
                if (s3Resource != null)
                {
                    s3Resource.ValidateArnWithClientConfig(config, useRegion);
                    if (string.IsNullOrEmpty(config.ServiceURL))
                    {
                        request.Endpoint = s3Resource.GetEndpoint(config);
                    }
                    else
                    {
                        request.Endpoint = new Uri(config.ServiceURL);
                    }
                    request.SignatureVersion           = SignatureVersion.SigV4;
                    request.CanonicalResourcePrefix    = string.Concat("/", s3Resource.FullResourceName);
                    request.OverrideSigningServiceName = s3Arn.Service;
                    // The access point arn can be using a region different from the configured region for the service client.
                    // If so be sure to set the authentication region so the signer will use the correct region.
                    request.AuthenticationRegion = s3Arn.Region;
                    request.Headers[HeaderKeys.XAmzAccountId] = s3Arn.AccountId;
                    // replace the ARNs in the resource path or query params with the extracted name of the resource
                    // These methods assume that there is max 1 Arn in the PathResources or Parameters
                    S3ArnUtils.ReplacePathResourceArns(request.PathResources, s3Resource.Name);
                    S3ArnUtils.ReplacePathResourceArns(request.Parameters, s3Resource.Name);
                }
            }
            else if (S3ArnUtils.DoesRequestHaveOutpostId(request.OriginalRequest, out nonArnOutpostId))
            {
                if (!S3ArnUtils.IsValidOutpostId(nonArnOutpostId))
                {
                    throw new AmazonClientException($"Invalid outpost ID. ID must contain only alphanumeric characters and dashes");
                }
                request.OverrideSigningServiceName = S3ArnUtils.S3OutpostsService;
                if (string.IsNullOrEmpty(config.ServiceURL))
                {
                    request.Endpoint = S3ArnUtils.GetNonStandardOutpostIdEndpoint(config);
                }
                else
                {
                    request.Endpoint = new Uri(config.ServiceURL);
                }
                request.Headers[HeaderKeys.XAmzOutpostId] = nonArnOutpostId;
            }
        }
        /// <summary>
        /// Retrieves the configuration information using the Microsoft
        /// ConfigurationManager, initializes the DynamoDB client, retrieves the
        /// items in the table using GetItemsAsync, and finally, displays the
        /// list of items in the table.
        /// </summary>
        public static async Task Main()
        {
            var configfile = "app.config";
            var region     = string.Empty;
            var table      = string.Empty;

            // Get default AWS Region and table from config file.
            var efm = new ExeConfigurationFileMap
            {
                ExeConfigFilename = configfile,
            };

            Configuration configuration = ConfigurationManager.OpenMappedExeConfiguration(efm, ConfigurationUserLevel.None);

            if (configuration.HasFile)
            {
                AppSettingsSection appSettings = configuration.AppSettings;
                region = appSettings.Settings["Region"].Value;
                table  = appSettings.Settings["Table"].Value;
            }
            else
            {
                Console.WriteLine($"Could not find {configfile}");
                return;
            }

            var empty = false;
            var sb    = new StringBuilder("You must supply a non-empty ");

            if (table == string.Empty)
            {
                empty = true;
                sb.Append("table name (-t TABLE), ");
            }

            if (region == string.Empty)
            {
                empty = true;
                sb.Append("region -r (REGION)");
            }

            if (empty)
            {
                Console.WriteLine(sb.ToString());
                return;
            }

            var             newRegion = RegionEndpoint.GetBySystemName(region);
            IAmazonDynamoDB client    = new AmazonDynamoDBClient(newRegion);

            var response = await GetItemsAsync(client, table);

            Console.WriteLine($"Found {response.Items.Count} items in {table} table in region {region}\n");

            StringBuilder output;

            foreach (var item in response.Items)
            {
                output = new StringBuilder();

                foreach (string attr in item.Keys)
                {
                    if (item[attr].S != null)
                    {
                        output.Append(attr + ": " + item[attr].S + ", ");
                    }
                    else if (item[attr].N != null)
                    {
                        output.Append(attr + ": " + item[attr].N + ", ");
                    }
                }

                Console.WriteLine(output.ToString());
            }
        }
Exemple #7
0
 public void UploadQrImages(List <MatchSeatTicketInfo> matchSeatTicketInfos, ImageType imageType)
 {
     try
     {
         var clientId     = _settings.GetConfigSetting <string>(SettingKeys.Messaging.Aws.S3.AccessKey);
         var clientSecret = _settings.GetConfigSetting <string>(SettingKeys.Messaging.Aws.S3.SecretKey);
         var bucketName   = _settings.GetConfigSetting <string>(SettingKeys.Messaging.Aws.S3.BucketName);
         foreach (var item in matchSeatTicketInfos)
         {
             using (var stream = QrCodeGenerator.GetQrcodeStream(item.BarcodeNumber))
             {
                 using (IAmazonS3 s3Client = new AmazonS3Client(clientId, clientSecret, RegionEndpoint.GetBySystemName("us-west-2")))
                 {
                     var transferUtility = new TransferUtility(s3Client);
                     {
                         transferUtility.Upload(stream, bucketName, ImageFilePathProvider.GetImageFilePath(item.BarcodeNumber, imageType));
                     };
                 }
             }
         }
     }
     catch (Exception ex)
     {
         _logger.Log(LogCategory.Error, ex);
     }
 }
Exemple #8
0
 /// <summary>
 /// Initializes a new instance of the AwsHttpConnection class with credentials from the Instance Profile service
 /// </summary>
 /// <param name="region">AWS region</param>
 public AwsHttpConnection(string region)
     : this(FallbackCredentialsFactory.GetCredentials(), RegionEndpoint.GetBySystemName(region))
 {
 }
        /// <summary>
        /// Create a signed URL allowing access to a resource that would
        /// usually require authentication.
        /// </summary>
        /// <remarks>
        /// <para>
        /// When using query string authentication you create a query,
        /// specify an expiration time for the query, sign it with your
        /// signature, place the data in an HTTP request, and distribute
        /// the request to a user or embed the request in a web page.
        /// </para>
        /// <para>
        /// A PreSigned URL can be generated for GET, PUT, DELETE and HEAD
        /// operations on your bucketName, keys, and versions.
        /// </para>
        /// </remarks>
        /// <param name="request">The GetPreSignedUrlRequest that defines the
        /// parameters of the operation.</param>
        /// <returns>A string that is the signed http request.</returns>
        /// <exception cref="T:System.ArgumentException" />
        /// <exception cref="T:System.ArgumentNullException" />
        public string GetPreSignedURL(GetPreSignedUrlRequest request)
        {
            if (Credentials == null)
            {
                throw new AmazonS3Exception("Credentials must be specified, cannot call method anonymously");
            }

            if (request == null)
            {
                throw new ArgumentNullException("request", "The PreSignedUrlRequest specified is null!");
            }

            if (!request.IsSetExpires())
            {
                throw new InvalidOperationException("The Expires specified is null!");
            }

            var aws4Signing = AWSConfigs.S3Config.UseSignatureVersion4;
            var region      = AWS4Signer.DetermineSigningRegion(Config, "s3", alternateEndpoint: null, request: null);

            if (aws4Signing && string.IsNullOrEmpty(region))
            {
                throw new InvalidOperationException("To use AWS4 signing, a region must be specified in the client configuration using the AuthenticationRegion or Region properties, or be determinable from the service URL.");
            }

            RegionEndpoint endpoint = RegionEndpoint.GetBySystemName(region);

            if (endpoint.GetEndpointForService("s3").SignatureVersionOverride == "4")
            {
                aws4Signing = true;
            }

            var immutableCredentials = Credentials.GetCredentials();
            var irequest             = Marshall(request, immutableCredentials.AccessKey, immutableCredentials.Token, aws4Signing);

            irequest.Endpoint = EndpointResolver.DetermineEndpoint(this.Config, irequest);

            var context = new Amazon.Runtime.Internal.ExecutionContext(new Amazon.Runtime.Internal.RequestContext(true)
            {
                Request = irequest, ClientConfig = this.Config
            }, null);

            AmazonS3PostMarshallHandler.ProcessRequestHandlers(context);

            var metrics = new RequestMetrics();

            string authorization;

            if (aws4Signing)
            {
                var aws4Signer    = new AWS4PreSignedUrlSigner();
                var signingResult = aws4Signer.SignRequest(irequest,
                                                           this.Config,
                                                           metrics,
                                                           immutableCredentials.AccessKey,
                                                           immutableCredentials.SecretKey);
                authorization = "&" + signingResult.ForQueryParameters;
            }
            else
            {
                this.Signer.Sign(irequest, this.Config, metrics, immutableCredentials.AccessKey, immutableCredentials.SecretKey);
                authorization = irequest.Headers[HeaderKeys.AuthorizationHeader];
                authorization = authorization.Substring(authorization.IndexOf(":", StringComparison.Ordinal) + 1);
                authorization = "&Signature=" + AmazonS3Util.UrlEncode(authorization, false);
            }

            Uri    url    = AmazonServiceClient.ComposeUrl(irequest);
            string result = url.AbsoluteUri + authorization;

            Protocol protocol = DetermineProtocol();

            if (request.Protocol != protocol)
            {
                switch (protocol)
                {
                case Protocol.HTTP:
                    result = result.Replace("http://", "https://");
                    break;

                case Protocol.HTTPS:
                    result = result.Replace("https://", "http://");
                    break;
                }
            }
            return(result);
        }
        public async Task SendEmailQueued(IEnumerable <string> emails, string subject, string message) // Not part of the interface, but needs to be public so that hangfire can queue it
        {
            SendEmailRequest emailRequest = new SendEmailRequest()
            {
                Source      = authOptions.FromAddress,
                Destination = new Destination(emails.ToList()),
                Message     = new Message()
                {
                    Body = new Body()
                    {
                        Html = new Content(message)
                    },
                    Subject = new Content(subject)
                }
            };

            using AmazonSimpleEmailServiceClient client = new AmazonSimpleEmailServiceClient(authOptions.SesAwsAccessKeyID, authOptions.SesAwsAccessKey, RegionEndpoint.GetBySystemName(authOptions.SesRegion));
            SendEmailResponse response = await client.SendEmailAsync(emailRequest).ConfigureAwait(false);

            if (!response.HttpStatusCode.IsSuccess())
            {
                logger.LogError("failed to send email to {0}", string.Join(", ", emails));
                throw new InvalidOperationException($"failed to send email to {string.Join(", ", emails)}, {response.HttpStatusCode}");
            }

            logger.LogInformation("successfully send email to {0}", string.Join(", ", emails));
        }
        /// <summary>
        /// Constructs an AWSOptions class with the options specified 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);
        }
Exemple #12
0
        /*
         * AWSSDK.SecretsManager version="3.3.0" targetFramework="net45"
         */

        public static string GetSecret(ILambdaContext context)
        {
            string secretName = "ReadPnlyWideWorlImporters"; // Environment.GetEnvironmentVariable("SecretName");
            string region     = "us-east-2";
            string secret     = "read_only";                 // Environment.GetEnvironmentVariable("DBUser");

            MemoryStream memoryStream = new MemoryStream();

            IAmazonSecretsManager client = new AmazonSecretsManagerClient(RegionEndpoint.GetBySystemName(region));

            GetSecretValueRequest request = new GetSecretValueRequest();

            request.SecretId     = secretName;
            request.VersionStage = "AWSCURRENT"; // VersionStage defaults to AWSCURRENT if unspecified.

            GetSecretValueResponse response = null;

            // In this sample we only handle the specific exceptions for the 'GetSecretValue' API.
            // See https://docs.aws.amazon.com/secretsmanager/latest/apireference/API_GetSecretValue.html
            // We rethrow the exception by default.
            context.Logger.Log("i am here");

            try
            {
                response = client.GetSecretValueAsync(request).Result;
                context.Logger.Log($"{response.ARN}");
            }
            catch (DecryptionFailureException e)
            {
                // Secrets Manager can't decrypt the protected secret text using the provided KMS key.
                // Deal with the exception here, and/or rethrow at your discretion.
                throw;
            }
            catch (InternalServiceErrorException e)
            {
                // An error occurred on the server side.
                // Deal with the exception here, and/or rethrow at your discretion.
                throw;
            }
            catch (InvalidParameterException e)
            {
                // You provided an invalid value for a parameter.
                // Deal with the exception here, and/or rethrow at your discretion
                throw;
            }
            catch (InvalidRequestException e)
            {
                // You provided a parameter value that is not valid for the current state of the resource.
                // Deal with the exception here, and/or rethrow at your discretion.
                throw;
            }
            catch (ResourceNotFoundException e)
            {
                // We can't find the resource that you asked for.
                // Deal with the exception here, and/or rethrow at your discretion.
                throw;
            }
            catch (System.AggregateException ae)
            {
                // More than one of the above exceptions were triggered.
                // Deal with the exception here, and/or rethrow at your discretion.
                throw;
            }

            // Decrypts secret using the associated KMS CMK.
            // Depending on whether the secret is a string or binary, one of these fields will be populated.
            var retVal = string.Empty;

            context.Logger.LogLine($"secret string {response.SecretString}");
            if (response.SecretString != null)
            {
                retVal = response.SecretString;
            }
            else
            {
                memoryStream = response.SecretBinary;
                StreamReader reader = new StreamReader(memoryStream);
                retVal = System.Text.Encoding.UTF8.GetString(Convert.FromBase64String(reader.ReadToEnd()));
                context.Logger.LogLine($"secret string {retVal}");
            }
            return(retVal);

            // Your code goes here.
        }
Exemple #13
0
        public static void Main(string[] args)
        {
            var configuration = new ConfigurationBuilder()
                                .AddJsonFile("Settings.json", true)
                                .AddEnvironmentVariables()
                                .AddCommandLine(args)
                                .Build();

            var manualResetEvent = new ManualResetEvent(false);

            var settings = configuration.GetSection("App").Get <AppSettings>();

            Console.CancelKeyPress += (sender, eventArgs) =>
            {
                eventArgs.Cancel = true;
                manualResetEvent.Set();
            };

            client = new AmazonRoute53Client(new BasicAWSCredentials(settings.AccessKey, settings.SecretKey), RegionEndpoint.GetBySystemName(settings.Region));

            var timer = new Timer(Update, settings, 1000, settings.Interval);

            Console.WriteLine("Application started. Press Ctrl+C to shut down.");

            manualResetEvent.WaitOne();
        }
        private void UploadToCdn()
        {
            try
            {
                // one thread only
                if (Interlocked.CompareExchange(ref work, 1, 0) == 0)
                {
                    var @continue = false;
                    try
                    {
                        CdnItem item;
                        if (queue.TryDequeue(out item))
                        {
                            @continue = true;

                            var cdnpath     = GetCdnPath(item.Bundle.Path);
                            var key         = new Uri(cdnpath).PathAndQuery.TrimStart('/');
                            var content     = Encoding.UTF8.GetBytes(item.Response.Content);
                            var inputStream = new MemoryStream();

                            if (ClientSettings.GZipEnabled)
                            {
                                using (var zip = new GZipStream(inputStream, CompressionMode.Compress, true))
                                {
                                    zip.Write(content, 0, content.Length);
                                    zip.Flush();
                                }
                            }
                            else
                            {
                                inputStream.Write(content, 0, content.Length);
                            }
                            inputStream.Position = 0;
                            var checksum = AmazonS3Util.GenerateChecksumForContent(item.Response.Content, true);

                            var config = new AmazonS3Config
                            {
                                RegionEndpoint = RegionEndpoint.GetBySystemName(s3region),
                                UseHttp        = true
                            };
                            using (var s3 = new AmazonS3Client(s3publickey, s3privatekey, config))
                            {
                                var upload = false;
                                try
                                {
                                    var request = new GetObjectMetadataRequest
                                    {
                                        BucketName = s3bucket,
                                        Key        = key,
                                    };
                                    var response = s3.GetObjectMetadata(request);
                                    upload = !string.Equals(checksum, response.Metadata["x-amz-meta-etag"], StringComparison.InvariantCultureIgnoreCase);
                                }
                                catch (AmazonS3Exception ex)
                                {
                                    if (ex.StatusCode == HttpStatusCode.NotFound)
                                    {
                                        upload = true;
                                    }
                                    else
                                    {
                                        throw;
                                    }
                                }

                                if (upload)
                                {
                                    var request = new PutObjectRequest
                                    {
                                        BucketName  = s3bucket,
                                        CannedACL   = S3CannedACL.PublicRead,
                                        Key         = key,
                                        ContentType = AmazonS3Util.MimeTypeFromExtension(Path.GetExtension(key).ToLowerInvariant())
                                    };

                                    request.InputStream = inputStream;
                                    if (ClientSettings.GZipEnabled)
                                    {
                                        request.Headers.ContentEncoding = "gzip";
                                    }

                                    var cache = TimeSpan.FromDays(365);
                                    request.Headers.CacheControl       = string.Format("public, maxage={0}", (int)cache.TotalSeconds);
                                    request.Headers.Expires            = DateTime.UtcNow.Add(cache);
                                    request.Headers["x-amz-meta-etag"] = checksum;

                                    s3.PutObject(request);
                                }

                                item.Bundle.CdnPath = cdnpath;
                            }
                        }
                    }
                    catch (Exception err)
                    {
                        log.Error(err);
                    }
                    finally
                    {
                        work = 0;
                        if (@continue)
                        {
                            Action upload = () => UploadToCdn();
                            upload.BeginInvoke(null, null);
                        }
                    }
                }
            }
            catch (Exception fatal)
            {
                log.Fatal(fatal);
            }
        }
Exemple #15
0
        /// <summary>
        /// Create a signed URL allowing access to a resource that would
        /// usually require authentication.
        /// </summary>
        /// <remarks>
        /// <para>
        /// When using query string authentication you create a query,
        /// specify an expiration time for the query, sign it with your
        /// signature, place the data in an HTTP request, and distribute
        /// the request to a user or embed the request in a web page.
        /// </para>
        /// <para>
        /// A PreSigned URL can be generated for GET, PUT, DELETE and HEAD
        /// operations on your bucketName, keys, and versions.
        /// </para>
        /// </remarks>
        /// <param name="request">The GetPreSignedUrlRequest that defines the
        /// parameters of the operation.</param>
        /// <param name="useSigV2Fallback">determines if signing will fall back to SigV2 if the
        /// signing region is us-east-1</param>
        /// <returns>A string that is the signed http request.</returns>
        /// <exception cref="T:System.ArgumentException" />
        /// <exception cref="T:System.ArgumentNullException" />
        internal string GetPreSignedURLInternal(GetPreSignedUrlRequest request, bool useSigV2Fallback = true)
        {
            if (Credentials == null)
            {
                throw new AmazonS3Exception("Credentials must be specified, cannot call method anonymously");
            }

            if (request == null)
            {
                throw new ArgumentNullException("request", "The PreSignedUrlRequest specified is null!");
            }

            if (!request.IsSetExpires())
            {
                throw new InvalidOperationException("The Expires specified is null!");
            }

            var aws4Signing = AWSConfigsS3.UseSignatureVersion4;

            Arn    arn;
            string accessPoint;

            if (Arn.TryParse(request.BucketName, out arn) && arn.TryParseAccessPoint(out accessPoint))
            {
                aws4Signing = true;
            }
            else
            {
                var region = AWS4Signer.DetermineSigningRegion(Config, "s3", alternateEndpoint: null, request: null);
                if (aws4Signing && string.IsNullOrEmpty(region))
                {
                    throw new InvalidOperationException("To use AWS4 signing, a region must be specified in the client configuration using the AuthenticationRegion or Region properties, or be determinable from the service URL.");
                }

                RegionEndpoint endpoint = RegionEndpoint.GetBySystemName(region);
                var            s3SignatureVersionOverride = endpoint.GetEndpointForService("s3").SignatureVersionOverride;
                if (s3SignatureVersionOverride == "4" || s3SignatureVersionOverride == null)
                {
                    aws4Signing = true;
                }

                var fallbackToSigV2 = useSigV2Fallback && !AWSConfigsS3.UseSigV4SetExplicitly;
                if (endpoint == RegionEndpoint.USEast1 && fallbackToSigV2)
                {
                    aws4Signing = false;
                }

                // If the expiration is longer than SigV4 will allow then automatically use SigV2 instead.
                // But only if the region we're signing for allows SigV2.
                if (aws4Signing)
                {
                    var secondsUntilExpiration = GetSecondsUntilExpiration(this.Config, request, aws4Signing);

                    if (secondsUntilExpiration > AWS4PreSignedUrlSigner.MaxAWS4PreSignedUrlExpiry &&
                        s3SignatureVersionOverride == "2")
                    {
                        aws4Signing = false;
                    }
                }
            }


            var immutableCredentials = Credentials.GetCredentials();
            var irequest             = Marshall(this.Config, request, immutableCredentials.AccessKey, immutableCredentials.Token, aws4Signing);

            irequest.Endpoint = EndpointResolver.DetermineEndpoint(this.Config, irequest);

            var context = new Amazon.Runtime.Internal.ExecutionContext(new Amazon.Runtime.Internal.RequestContext(true, new NullSigner())
            {
                Request = irequest, ClientConfig = this.Config
            }, null);

            AmazonS3PostMarshallHandler.ProcessRequestHandlers(context);

            var metrics = new RequestMetrics();

            string authorization;

            if (aws4Signing)
            {
                var aws4Signer    = new AWS4PreSignedUrlSigner();
                var signingResult = aws4Signer.SignRequest(irequest,
                                                           this.Config,
                                                           metrics,
                                                           immutableCredentials.AccessKey,
                                                           immutableCredentials.SecretKey);
                authorization = "&" + signingResult.ForQueryParameters;
            }
            else
            {
                Amazon.S3.Internal.S3Signer.SignRequest(irequest, metrics, immutableCredentials.AccessKey, immutableCredentials.SecretKey);
                authorization = irequest.Headers[HeaderKeys.AuthorizationHeader];
                authorization = authorization.Substring(authorization.IndexOf(":", StringComparison.Ordinal) + 1);
                authorization = "&Signature=" + AmazonS3Util.UrlEncode(authorization, false);
            }

            Uri    url    = AmazonServiceClient.ComposeUrl(irequest);
            string result = url.AbsoluteUri + authorization;

            Protocol protocol = DetermineProtocol();

            if (request.Protocol != protocol)
            {
                switch (protocol)
                {
                case Protocol.HTTP:
                    result = result.Replace("http://", "https://");
                    break;

                case Protocol.HTTPS:
                    result = result.Replace("https://", "http://");
                    break;
                }
            }
            return(result);
        }
Exemple #16
0
        public static string GetPrivateKey()
        {
            string secretName = "PrivateKey";
            string region     = "ap-southeast-2";

            MemoryStream memoryStream = new MemoryStream();

            IAmazonSecretsManager client = new AmazonSecretsManagerClient(RegionEndpoint.GetBySystemName(region));

            GetSecretValueRequest request = new GetSecretValueRequest();

            request.SecretId     = secretName;
            request.VersionStage = "AWSCURRENT"; // VersionStage defaults to AWSCURRENT if unspecified.

            GetSecretValueResponse response = null;

            // In this sample we only handle the specific exceptions for the 'GetSecretValue' API.
            // See https://docs.aws.amazon.com/secretsmanager/latest/apireference/API_GetSecretValue.html
            // We rethrow the exception by default.

            try
            {
                response = client.GetSecretValueAsync(request).Result;
            }
            catch (DecryptionFailureException e)
            {
                // Secrets Manager can't decrypt the protected secret text using the provided KMS key.
                // Deal with the exception here, and/or rethrow at your discretion.
                throw;
            }
            catch (InternalServiceErrorException e)
            {
                // An error occurred on the server side.
                // Deal with the exception here, and/or rethrow at your discretion.
                throw;
            }
            catch (InvalidParameterException e)
            {
                // You provided an invalid value for a parameter.
                // Deal with the exception here, and/or rethrow at your discretion
                throw;
            }
            catch (InvalidRequestException e)
            {
                // You provided a parameter value that is not valid for the current state of the resource.
                // Deal with the exception here, and/or rethrow at your discretion.
                throw;
            }
            catch (ResourceNotFoundException e)
            {
                // We can't find the resource that you asked for.
                // Deal with the exception here, and/or rethrow at your discretion.
                throw;
            }
            catch (System.AggregateException ae)
            {
                // More than one of the above exceptions were triggered.
                // Deal with the exception here, and/or rethrow at your discretion.
                throw;
            }

            string secretJsonString = "";

            // Decrypts secret using the associated KMS CMK.
            // Depending on whether the secret is a string or binary, one of these fields will be populated.
            if (response.SecretString != null)
            {
                secretJsonString = response.SecretString;
            }
            else
            {
                memoryStream = response.SecretBinary;
                StreamReader reader = new StreamReader(memoryStream);
                secretJsonString = System.Text.Encoding.UTF8.GetString(Convert.FromBase64String(reader.ReadToEnd()));
            }

            var    secretData = (JObject)JsonConvert.DeserializeObject(secretJsonString);
            string secret     = secretData[secretName].Value <string>();

            return(secret);
        }
 public static AmazonS3Client GetS3Client(string region, string profile = null)
 {
     return(new AmazonS3Client(GetAwsCredentials(profile), new AmazonS3Config {
         RegionEndpoint = RegionEndpoint.GetBySystemName(region)
     }));
 }
 public AmazonS3StorageManager(string awsAccessKeyId, string awsSecretAccessKey, string bucketName, string regionEndpoint)
 {
     _client     = new AmazonS3Client(awsAccessKeyId, awsSecretAccessKey, RegionEndpoint.GetBySystemName(regionEndpoint));
     _bucketName = bucketName;
 }
Exemple #19
0
        public void UploadHotTicketImage(Image image, string altId)
        {
            try
            {
                var clientId     = _settings.GetConfigSetting <string>(SettingKeys.Messaging.Aws.S3.AccessKey);
                var clientSecret = _settings.GetConfigSetting <string>(SettingKeys.Messaging.Aws.S3.SecretKey);
                var bucketName   = _settings.GetConfigSetting <string>(SettingKeys.Messaging.Aws.S3.BucketName);

                var stream = new System.IO.MemoryStream();
                image.Save(stream, ImageFormat.Jpeg);
                stream.Position = 0;

                using (IAmazonS3 s3Client = new AmazonS3Client(clientId, clientSecret, RegionEndpoint.GetBySystemName("us-west-2")))
                {
                    var transferUtility = new TransferUtility(s3Client);
                    {
                        transferUtility.Upload(stream, bucketName, ImageFilePathProvider.GetImageFilePath(altId, FIL.Contracts.Enums.ImageType.HotTicket));
                    };
                }
            }
            catch (Exception ex)
            {
                _logger.Log(LogCategory.Error, ex);
            }
        }
Exemple #20
0
 private static void PurgeQueue(string queueName)
 {
     new AmazonSqsTransport(queueName, AmazonSQSTransportFactory.ConnectionInfo.AccessKeyId, AmazonSQSTransportFactory.ConnectionInfo.SecretAccessKey,
                            RegionEndpoint.GetBySystemName(AmazonSQSTransportFactory.ConnectionInfo.RegionEndpoint)).Purge();
 }
Exemple #21
0
        public void UploadBlogImage(Image image, int id)
        {
            try
            {
                var clientId     = _settings.GetConfigSetting <string>(SettingKeys.Messaging.Aws.S3.Feel.AccessKey);
                var clientSecret = _settings.GetConfigSetting <string>(SettingKeys.Messaging.Aws.S3.Feel.SecretKey);
                var bucketName   = _settings.GetConfigSetting <string>(SettingKeys.Messaging.Aws.S3.Feel.BucketName);
                var stream       = new System.IO.MemoryStream();
                image.Save(stream, ImageFormat.Jpeg);
                stream.Position = 0;

                using (IAmazonS3 s3Client = new AmazonS3Client(clientId, clientSecret, RegionEndpoint.GetBySystemName("us-west-2")))
                {
                    var transferUtility = new TransferUtility(s3Client);
                    {
                        transferUtility.Upload(stream, bucketName, $"images/blogs/{id}.jpg");
                    };
                }
            }
            catch (Exception ex)
            {
                _logger.Log(LogCategory.Error, ex);
            }
        }
Exemple #22
0
        /// <summary>
        /// Retrieves the configuration file, parses the command line
        /// arguments, and displays the contents. Then it calls the
        /// AddItemsAsync method to add the list of new items to the
        /// DynamoDB table.
        /// </summary>
        /// <param name="args">Command line arguments. The only valid argument
        /// for this application is -d for debug mode.</param>
        public static async Task Main(string[] args)
        {
            var    configfile = "app.config";
            string region;
            string table;
            string filename;
            string index;
            bool   debug = false;

            // Get default Region and table from config file.
            var efm = new ExeConfigurationFileMap
            {
                ExeConfigFilename = configfile,
            };

            Configuration configuration = ConfigurationManager.OpenMappedExeConfiguration(efm, ConfigurationUserLevel.None);

            if (configuration.HasFile)
            {
                AppSettingsSection appSettings = configuration.AppSettings;
                region   = appSettings.Settings["Region"].Value;
                table    = appSettings.Settings["Table"].Value;
                index    = appSettings.Settings["Index"].Value;
                filename = appSettings.Settings["Filename"].Value;

                if (string.IsNullOrEmpty(region) || string.IsNullOrEmpty(table) || string.IsNullOrEmpty(index) || string.IsNullOrEmpty(filename))
                {
                    Console.WriteLine($"You must specify a Region, Table, Index, and Filename in {configfile}");
                    return;
                }
            }
            else
            {
                Console.WriteLine("Could not find " + configfile);
                return;
            }

            int i = 0;

            while (i < args.Length)
            {
                switch (args[i])
                {
                case "-d":
                    debug = true;
                    break;
                }

                i++;
            }

            // Make sure index is an int >= 0.
            int indexVal;

            try
            {
                indexVal = int.Parse(index);
            }
            catch
            {
                Console.WriteLine($"Could not parse {index} as an int.");
                return;
            }

            if (indexVal < 0)
            {
                Console.WriteLine($"The index value {index} is less than zero.");
                return;
            }

            var             newRegion = RegionEndpoint.GetBySystemName(region);
            IAmazonDynamoDB client    = new AmazonDynamoDBClient(newRegion);

            // Open the file.
            // filename is the name of the .csv file that contains customer data.
            // Column1,...,ColumnN
            // in lines 2...N
            // Read the file and display it line by line.
            System.IO.StreamReader file =
                new System.IO.StreamReader(filename);

            DebugPrint(debug, "Opened file " + filename);

            // Store up to 25 at a time in an array.
            string[] inputs = new string[26];

            // Get column names from the first line.
            file.ReadLine();

            string line;
            var    input = 1;

            while (((line = file.ReadLine()) != null) && (input < 26))
            {
                inputs[input] = line;
                input++;
            }

            await AddItemsAsync(debug, client, table, inputs, indexVal);

            Console.WriteLine("Done");
        }
Exemple #23
0
        public string GetImagePath(string altId)
        {
            try
            {
                var clientId     = _settings.GetConfigSetting <string>(SettingKeys.Messaging.Aws.S3.AccessKey);
                var clientSecret = _settings.GetConfigSetting <string>(SettingKeys.Messaging.Aws.S3.SecretKey);
                var bucketName   = _settings.GetConfigSetting <string>(SettingKeys.Messaging.Aws.S3.BucketName);

                using (IAmazonS3 s3Client = new AmazonS3Client(clientId, clientSecret, RegionEndpoint.GetBySystemName("us-west-2")))
                {
                    GetPreSignedUrlRequest request = new GetPreSignedUrlRequest
                    {
                        BucketName = bucketName,
                        Key        = $"Images/ProfilePictures/{altId}.jpg",
                        Expires    = DateTime.Now.AddMinutes(60)
                    };
                    return(s3Client.GetPreSignedURL(request));
                }
            }
            catch (Exception ex)
            {
                _logger.Log(LogCategory.Error, ex);
                return("");
            }
        }
        public SecretKeyService()
        {
            IAmazonSecretsManager client  = new AmazonSecretsManagerClient(awsAccessKey, awsSecretKey, RegionEndpoint.GetBySystemName(awsRegion));
            GetSecretValueRequest request = new GetSecretValueRequest
            {
                SecretId     = awsSecretKeysName,
                VersionStage = "AWSCURRENT"
            };

            GetSecretValueResponse response;

            try
            {
                response = client.GetSecretValueAsync(request).Result;
            }
            catch (Exception)
            {
                throw;
            }
            if (response.SecretString != null)
            {
                _secretKeys = JsonConvert.DeserializeObject <SecretKeys>(response.SecretString);
            }
        }
Exemple #25
0
 private AmazonS3Client GetStorageClient()
 {
     return(new AmazonS3Client(_awsSettings.Storage.AccessKey, _awsSettings.Storage.SecretKey, RegionEndpoint.GetBySystemName(_awsSettings.Storage.Region)));
 }
Exemple #26
0
 /// <summary>
 /// Initializes a new instance of the <see cref="SQSReceiver"/> class.
 /// Uses a default implementation of the <see cref="AmazonSQSClient"/> to
 /// communicate with SQS.
 /// </summary>
 /// <param name="name">The name of the sender.</param>
 /// <param name="queueUrl">The url of the SQS queue.</param>
 /// <param name="region">The region of the SQS queue.</param>
 /// <param name="messageGroupId">
 /// The tag that specifies that a message belongs to a specific message group. Messages
 /// that belong to the same message group are processed in a FIFO manner (however,
 /// messages in different message groups might be processed out of order). To interleave
 /// multiple ordered streams within a single queue, use MessageGroupId values (for
 /// example, session data for multiple users). In this scenario, multiple consumers
 /// can process the queue, but the session data of each user is processed in a FIFO
 /// fashion.
 /// <para>This parameter applies only to FIFO (first-in-first-out) queues.</para>
 /// </param>
 public SQSSender(string name, Uri queueUrl, string?region = null, string?messageGroupId = null)
     : this(region is null ? new AmazonSQSClient() : new AmazonSQSClient(RegionEndpoint.GetBySystemName(region)), name, queueUrl, messageGroupId !)
 {
 }
Exemple #27
0
        /// <summary>
        /// Constructs a parser for the S3 URI specified as a Uri instance.
        /// </summary>
        /// <param name="uri">The S3 URI to be parsed.</param>
        public AmazonS3Uri(Uri uri)
        {
            if (uri == null)
            {
                throw new ArgumentNullException("uri");
            }

            if (string.IsNullOrEmpty(uri.Host))
            {
                throw new ArgumentException("Invalid URI - no hostname present");
            }

            var match = new Regex(EndpointPattern).Match(uri.Host);

            if (!match.Success)
            {
                throw new ArgumentException("Invalid S3 URI - hostname does not appear to be a valid S3 endpoint");
            }

            // for host style urls:
            //   group 0 is bucketname plus 's3' prefix and possible region code
            //   group 1 is bucket name
            //   group 2 will be region or 'amazonaws' if US Classic region
            // for path style urls:
            //   group 0 will be s3 prefix plus possible region code
            //   group 1 will be empty
            //   group 2 will be region or 'amazonaws' if US Classic region
            var bucketNameGroup = match.Groups[1];

            if (string.IsNullOrEmpty(bucketNameGroup.Value))
            {
                // no bucket name in the authority, parse it from the path
                this.IsPathStyle = true;

                // grab the encoded path so we don't run afoul of '/'s in the bucket name
                var path = uri.AbsolutePath;
                if (path.Equals("/"))
                {
                    this.Bucket = null;
                    this.Key    = null;
                }
                else
                {
                    var index = path.IndexOf('/', 1);
                    if (index == -1)
                    {
                        // https://s3.amazonaws.com/bucket
                        this.Bucket = Decode(path.Substring(1));
                        this.Key    = null;
                    }
                    else if (index == (path.Length - 1))
                    {
                        // https://s3.amazonaws.com/bucket/
                        this.Bucket = Decode(path.Substring(1, index)).TrimEnd('/');
                        this.Key    = null;
                    }
                    else
                    {
                        // https://s3.amazonaws.com/bucket/key
                        this.Bucket = Decode(path.Substring(1, index)).TrimEnd('/');
                        this.Key    = Decode(path.Substring(index + 1));
                    }
                }
            }
            else
            {
                // bucket name in the host, path is the object key
                this.IsPathStyle = false;

                // remove any trailing '.' from the prefix to get the bucket name
                this.Bucket = bucketNameGroup.Value.TrimEnd('.');
                this.Key    = uri.AbsolutePath.Equals("/") ? null : uri.AbsolutePath.Substring(1);
            }

            if (match.Groups.Count > 2)
            {
                // US 'classic' urls will not have a region code in the endpoint
                var regionGroupValue = match.Groups[2].Value;
                if (regionGroupValue.Equals("amazonaws", StringComparison.Ordinal) ||
                    regionGroupValue.Equals("external-1", StringComparison.Ordinal))
                {
                    this.Region = RegionEndpoint.USEast1;
                }
                else
                {
                    this.Region = RegionEndpoint.GetBySystemName(regionGroupValue);
                }
            }
        }
Exemple #28
0
        public AwsFileStorageService(IOptionsSnapshot <AwsFileStorageOptions> options)
        {
            this.options = options.Value;

            regionEndpoint = RegionEndpoint.GetBySystemName(this.options.RegionName);
        }
        public async Task <ListMetricsResponse> ListMetrics(ListMetricsRequest listMetricsRequest)
        {
            using (var amazonCloudWatchClient = new AmazonCloudWatchClient(awsCredentials, RegionEndpoint.GetBySystemName(Region)))
            {
                var response = await amazonCloudWatchClient.ListMetricsAsync(listMetricsRequest);

                return(response);
            }
        }
Exemple #30
0
 private AmazonS3Client GetClient()
 {
     return(new AmazonS3Client(accessKeyId, secretAccessKey, new AmazonS3Config {
         RegionEndpoint = RegionEndpoint.GetBySystemName(region)
     }));
 }