Esempio n. 1
0
        static void Main(string[] args)
        {
            var basePath = Path.Combine(Directory.GetCurrentDirectory(), "Realms");

            Directory.CreateDirectory(basePath);
            FullSyncConfiguration.Initialize(UserPersistenceMode.Disabled, basePath: basePath);

            var credentials = new BasicAWSCredentials("access", "secret");

            FileManager.Initialize(new FileManagerOptions
            {
                PersistenceLocation  = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments),
                RemoteManagerFactory = () => new S3FileManager(credentials, RegionEndpoint.EUNorth1)
            });

            AsyncContext.Run(MainAsync);
        }
Esempio n. 2
0
 public static IAsyncOperation <string> GetFaceDetails(string base64, string AccessKey, string SecretKey)
 {
     return(Task.Run <string>(async() =>
     {
         byte[] imageBytes;
         try
         {
             base64 = base64.Substring(base64.IndexOf(',') + 1).Trim('\0');
             imageBytes = System.Convert.FromBase64String(base64);
         }
         catch (Exception e) {
             return e.Message;
         }
         string sJSONResponse = "";
         AWSCredentials credentials;
         try
         {
             credentials = new BasicAWSCredentials(AccessKey, SecretKey);
         }
         catch (Exception e)
         {
             throw new AmazonClientException("Cannot load the credentials from the credential profiles file. "
                                             + "Please make sure that your credentials file is at the correct "
                                             + "location (/Users/<userid>/.aws/credentials), and is in a valid format.", e);
         }
         DetectFacesRequest request = new DetectFacesRequest {
             Attributes = new List <string>(new string[] { "ALL" })
         };
         DetectFacesResponse result = null;
         request.Image = new Image {
             Bytes = new MemoryStream(imageBytes, 0, imageBytes.Length)
         };
         AmazonRekognitionClient rekognitionClient = new AmazonRekognitionClient(credentials, RegionEndpoint.USWest2);
         try
         {
             result = await rekognitionClient.DetectFacesAsync(request);
         }
         catch (AmazonRekognitionException e)
         {
             throw e;
         }
         // Return server status as unhealthy with appropriate status code
         sJSONResponse = JsonConvert.SerializeObject(result.FaceDetails);
         return sJSONResponse;
     }).AsAsyncOperation());
 }
Esempio n. 3
0
        private string UploadImageToS3(Stream memoryStream, string filePrefix = "img")
        {
            string         bucketName   = _appSettingService.GetAppSettingData("gallery_s3_bucket_name");
            string         keyName      = $"{filePrefix}_{CommonUtility.GetNewID()}.png";
            RegionEndpoint bucketRegion = RegionEndpoint.APSouth1;
            string         _accessKey   = _appSettingService.GetAppSettingData("aws_s3_access_key");
            string         _secretKey   = _appSettingService.GetAppSettingData("aws_s3_secret_key");
            IAmazonS3      s3Client;


            _logger.Debug($"{bucketName}:::{_accessKey}:::{_secretKey}");
            try
            {
                var credentials = new BasicAWSCredentials(_accessKey, _secretKey);
                s3Client = new AmazonS3Client(credentials, bucketRegion);


                S3CannedACL permissions = S3CannedACL.NoACL;
                var         putObject   = new PutObjectRequest
                {
                    BucketName  = bucketName,
                    Key         = keyName,
                    InputStream = memoryStream,
                    ContentType = "image/png",
                    CannedACL   = permissions
                };

                //setting content length for streamed input
                putObject.Metadata.Add("Content-Length", memoryStream.Length.ToString());
                var putResponse = s3Client.PutObjectAsync(putObject).GetAwaiter().GetResult();

                if (putResponse.HttpStatusCode == HttpStatusCode.OK)
                {
                    return($"/{keyName}");
                }
                else
                {
                    throw new Exception($"Error while upload image to s3 HttpStatusCode: {putResponse.HttpStatusCode }");
                }
            }
            catch (AmazonS3Exception e)
            {
                _logger.Error($"AmazonS3Exception : {e.Message}", e);
                throw;
            }
        }
Esempio n. 4
0
        private static async Task Get()
        {
            var creds  = new BasicAWSCredentials(AccessKey, SecretKey);
            var client = new AmazonDynamoDBClient(creds, Region);

            var table = Table.LoadTable(client, "Image");

            var config = new GetItemOperationConfig
            {
                AttributesToGet = new List <string> {
                    "Hash", "testing"
                },
                ConsistentRead = true
            };

            var image = await table.GetItemAsync("2a8d7291-78fe-44f6-9f4d-33178bad00d0", config);
        }
Esempio n. 5
0
        public AwsBlobs(IConfiguration configuration)
        {
            Ensure.Argument.IsNotNull(configuration, nameof(configuration));

            // Create the credentials for our AWS account.
            var awsCredentials = new BasicAWSCredentials(
                configuration.AwsAccessKey,
                configuration.AwsAccessSecret);

            // Create the underlying S3 client.
            var region = RegionEndpoint.GetBySystemName(configuration.AwsBlobsRegion);
            var client = new AmazonS3Client(awsCredentials, region);

            // Create our blob containers.
            this.PostVersions = new AwsBlobContainer(client, "postversions", string.Empty);
            this.Attachments  = new AwsBlobContainer(client, "attachments", string.Empty);
        }
Esempio n. 6
0
        public DogService(IConfiguration cfg, KrustanDbContext ctx)
        {
            this._context = ctx;
            Configuration = cfg;

            var credentials = new BasicAWSCredentials(Configuration["s3:AccessKey"].Trim(), Configuration["s3:SecretAccessKey"].Trim());

            client = new AmazonS3Client(credentials, Amazon.RegionEndpoint.USEast1);

            if (dogs.Count == 0)
            {
                dogs.Add(new Dog
                {
                    Name        = "Cosmo",
                    Weight      = 1.2f,
                    Height      = 3.2f,
                    Description = "Jugueton, amigable",
                    Age         = 2,
                    DogPicture  = @"https://images.dog.ceo/breeds/deerhound-scottish/n02092002_1339.jpg",
                    Sex         = "male",
                    OwnerId     = "123456789"
                });
                dogs.Add(new Dog
                {
                    Name        = "Locria",
                    Weight      = 4,
                    Height      = 6,
                    Description = "fuerte, amigable",
                    Age         = 3,
                    DogPicture  = @"https://images.dog.ceo/breeds/appenzeller/n02107908_3190.jpg",
                    Sex         = "male",
                    OwnerId     = "123456789"
                });
                dogs.Add(new Dog
                {
                    Name        = "Karma",
                    Weight      = 4.1f,
                    Height      = 12.5f,
                    Description = "juguetona, amigable, fuerte, coqueta...",
                    Age         = 4,
                    DogPicture  = @"https://images.dog.ceo/breeds/samoyed/n02111889_5463.jpg",
                    Sex         = "female",
                    OwnerId     = "123456789"
                });
            }
        }
        public static void Initialize(TestContext testContext)
        {
            BasicAWSCredentials creds = new BasicAWSCredentials(ConfigurationManager.AppSettings["S3_ACCESS_KEY_ID"], ConfigurationManager.AppSettings["S3_SECRET_KEY"]);

            AmazonS3Config cc = new AmazonS3Config()
            {
                ForcePathStyle   = true,
                ServiceURL       = ConfigurationManager.AppSettings["S3_ENDPOINT"],
                SignatureVersion = ConfigurationManager.AppSettings["SIGNATURE_VERSION"],
                SignatureMethod  = SigningAlgorithm.HmacSHA1,
                UseHttp          = false,
            };

            client = new ECSS3Client(creds, cc);

            PutBucketRequestECS request = new PutBucketRequestECS()
            {
                BucketName = temp_bucket,
            };

            // Set the indexable search keys on the bucket.
            request.SetMetadataSearchKeys(bucketMetadataSearchKeys);
            string vpool_id = ConfigurationManager.AppSettings["VPOOL_ID"];

            if (!string.IsNullOrWhiteSpace(vpool_id))
            {
                request.VirtualPoolId = vpool_id;
            }

            client.PutBucket(request);

            for (int i = 0; i < 5; i++)
            {
                PutObjectRequest object_request = new PutObjectRequest()
                {
                    BucketName  = temp_bucket,
                    Key         = string.Format("obj-{0}", i),
                    ContentBody = string.Format("This is sample content for object {0}", i)
                };

                object_request.Metadata.Add("x-amz-meta-decimalvalue", Convert.ToString(i * 2));
                object_request.Metadata.Add("x-amz-meta-stringvalue", string.Format("sample-{0}", Convert.ToString(i)));

                client.PutObject(object_request);
            }
        }
Esempio n. 8
0
        private void CreateTable()
        {
            var credentials = new BasicAWSCredentials(accessKey, secretKey);

            client = new AmazonDynamoDBClient(credentials, RegionEndpoint.USWest1);

            var tableResponse = client.ListTables();

            if (!tableResponse.TableNames.Contains(tableName))
            {
                MessageBox.Show("Table not found, creating table => " + tableName);
                client.CreateTable(new CreateTableRequest
                {
                    TableName             = tableName,
                    ProvisionedThroughput = new ProvisionedThroughput
                    {
                        ReadCapacityUnits  = 3,
                        WriteCapacityUnits = 1
                    },
                    KeySchema = new List <KeySchemaElement>
                    {
                        new KeySchemaElement
                        {
                            AttributeName = hashKey,
                            KeyType       = KeyType.HASH
                        }
                    },
                    AttributeDefinitions = new List <AttributeDefinition>
                    {
                        new AttributeDefinition {
                            AttributeName = hashKey, AttributeType = ScalarAttributeType.S
                        }
                    }
                });

                bool isTableAvailable = false;
                while (!isTableAvailable)
                {
                    Console.WriteLine("Waiting for table to be active...");
                    Thread.Sleep(5000);
                    var tableStatus = client.DescribeTable(tableName);
                    isTableAvailable = tableStatus.Table.TableStatus == "ACTIVE";
                }
                MessageBox.Show("DynamoDB Table Created Successfully!");
            }
        }
        public static String SendSMS(String recipientPhoneNumber, String message)
        {
            BasicAWSCredentials awsCredentials =
                new BasicAWSCredentials("", "");

            AmazonSimpleNotificationServiceClient snsClient =
                new AmazonSimpleNotificationServiceClient(awsCredentials, Amazon.RegionEndpoint.USEast1);

            PublishRequest pubRequest = new PublishRequest();

            pubRequest.PhoneNumber = recipientPhoneNumber;
            pubRequest.Message     = message;

            PublishResponse pubResponse = snsClient.Publish(pubRequest);

            return(pubResponse.MessageId);
        }
Esempio n. 10
0
        private void RunPreInvoke(AmazonWebServiceRequest request)
        {
            var credentials      = new BasicAWSCredentials(accessKey, secretKey);
            var handler          = new PreSignedUrlRequestHandler(credentials);
            var requestContext   = new RequestContext(false, new NullSigner());
            var responseContext  = new ResponseContext();
            var executionContext = new ExecutionContext(requestContext, responseContext);
            var marshaller       = new CopyDBClusterSnapshotRequestMarshaller();
            var clientConfig     = new AmazonDocDBConfig();

            clientConfig.RegionEndpoint    = clientRegion;
            requestContext.OriginalRequest = request;
            requestContext.Marshaller      = marshaller;
            requestContext.ClientConfig    = clientConfig;

            ReflectionHelpers.Invoke(handler, "PreInvoke", executionContext);
        }
Esempio n. 11
0
        public DynamoDbTestHelper()
        {
            var credentials = new BasicAWSCredentials("FakeAccessKey", "FakeSecretKey");

            var clientConfig = new AmazonDynamoDBConfig
            {
                ServiceURL = "http://localhost:8000"
            };

            Client = new AmazonDynamoDBClient(credentials, clientConfig);

            var tableName = $"test_{Guid.NewGuid()}";

            DynamoDbContext = new DynamoDBContext(Client);
            DynamoDbCommandStoreTestConfiguration = new DynamoDbCommandStoreConfiguration($"command_{tableName}", true, "CommandId", "ContextKey");
            DynamoDbMessageStoreTestConfiguration = new DynamoDbMessageStoreConfiguration($"message_{tableName}", true, "MessageId");
        }
        private static async Task Run()
        {
            var credentials = new BasicAWSCredentials("accessKey", "secretKey");

            using (var snsClient = new AmazonSimpleNotificationServiceClient(credentials))
            {
                var publisher = new Publisher(snsClient, "topicName");

                while (true)
                {
                    Console.WriteLine("Type a message to send:");
                    var message = Console.ReadLine();

                    await publisher.PublishAsync(message);
                }
            }
        }
Esempio n. 13
0
        public ExternalProviderS3(GXService providerService)
        {
            string         keyId       = CryptoImpl.Decrypt(providerService.Properties.Get(ACCESS_KEY_ID));
            string         keySecret   = CryptoImpl.Decrypt(providerService.Properties.Get(SECRET_ACCESS_KEY));
            AWSCredentials credentials = null;

            if (!string.IsNullOrEmpty(keyId) && !string.IsNullOrEmpty(keySecret))
            {
                credentials = new BasicAWSCredentials(keyId, keySecret);
            }

            var region = Amazon.RegionEndpoint.GetBySystemName(providerService.Properties.Get(REGION));

            Endpoint = providerService.Properties.Get(ENDPOINT);

            AmazonS3Config config = new AmazonS3Config()
            {
                ServiceURL     = Endpoint,
                RegionEndpoint = region
            };

#if NETCORE
            if (credentials != null)
            {
                Client = new AmazonS3ClientExtended(credentials, config);
            }
            else
            {
                Client = new AmazonS3ClientExtended(config);
            }
#else
            if (credentials != null)
            {
                Client = new AmazonS3Client(credentials, config);
            }
            else
            {
                Client = new AmazonS3Client(config);
            }
#endif
            Bucket = CryptoImpl.Decrypt(providerService.Properties.Get(BUCKET));
            Folder = providerService.Properties.Get(FOLDER);

            CreateBucket();
            CreateFolder(Folder);
        }
Esempio n. 14
0
        public static async Task AWSUploadAudioVideo(string filePath, string requiredFileName, string mediatype)
        {
            try
            {
                //   CommonConstants.
                AWSCredentials creds = new BasicAWSCredentials(CommonHelper.GetAWS_ACCESS_KEY(),
                                                               CommonHelper.GetAWS_SECRET_KEY());
                //    TransferUtilityConfig config = new TransferUtilityConfig () { ConcurrentServiceRequests = 5 };
                var client = new AmazonS3Client(creds, RegionEndpoint.USWest2);
                //    TransferUtility trans = new TransferUtility (client, config);
                var po = new PutObjectRequest();
                po.CannedACL = S3CannedACL.PublicReadWrite;
                po.FilePath  = filePath;
                if (mediatype == "Audio")
                {
                    po.BucketName = "chatcloud-audio";
                }
                if (mediatype == "Video")
                {
                    po.BucketName = "inpower-video";
                }
                po.Key = requiredFileName;
                await client.PutObjectAsync(po);

                //   var go = new GetObjectRequest ();
                //   go.BucketName = "bitmob-videos";
                //   go.Key = "abcdefhij.jpg";
                //   var res = await client.GetObjectAsync (go);

                Console.WriteLine("Upload completed");
            }
            catch (AmazonS3Exception amazonS3Exception)
            {
                if (amazonS3Exception.ErrorCode != null &&
                    (amazonS3Exception.ErrorCode.Equals("InvalidAccessKeyId")
                     ||
                     amazonS3Exception.ErrorCode.Equals("InvalidSecurity")))
                {
                    throw new Exception("Check the provided AWS Credentials.");
                }
                else
                {
                    throw new Exception("Error occurred: " + amazonS3Exception.Message);
                }
            }
        }
Esempio n. 15
0
        /// <summary>
        /// Get the key that we want to use in the encryption from KMS
        /// </summary>
        /// <param name="alias">The "key name"</param>
        /// <returns>The key id</returns>
        private static string GetKeyByAlias(string alias)
        {
            try
            {
                var credentials =
                    new BasicAWSCredentials("acessKey", "secretKey");

                var kmsClient = new AwsKeyManagementServiceClient(Region, credentials);
                var key       = kmsClient.GetKeyAsync(alias);
                return(key.Result);
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                throw;
            }
        }
        /// <summary>
        /// Activates logging to AWS CloudWatch
        /// </summary>
        /// <remarks>This overload is intended to be used via AppSettings integration.</remarks>
        /// <param name="loggerConfiguration">The LoggerSinkConfiguration to register this sink with.</param>
        /// <param name="logGroupName">The log group name to be used in AWS CloudWatch.</param>
        /// <param name="logStreamNameProvider">The log stream name provider.</param>
        /// <param name="accessKey">The access key to use to access AWS CloudWatch.</param>
        /// <param name="secretAccessKey">The secret access key to use to access AWS CloudWatch.</param>
        /// <param name="regionName">The system name of the region to which to write.</param>
        /// <param name="logEventRenderer">A renderer to render Serilog's LogEvent.</param>
        /// <param name="minimumLogEventLevel">The minimum log event level required in order to write an event to the sink.</param>
        /// <param name="batchSizeLimit">The batch size to be used when uploading logs to AWS CloudWatch.</param>
        /// <param name="period">The period to be used when a batch upload should be triggered.</param>
        /// <returns></returns>
        /// <exception cref="ArgumentNullException"><paramref name="logGroupName"/> is <see langword="null"/>.</exception>
        /// <exception cref="ArgumentNullException"><paramref name="accessKey"/> is <see langword="null"/>.</exception>
        /// <exception cref="ArgumentNullException"><paramref name="secretAccessKey"/> is <see langword="null"/>.</exception>
        /// <exception cref="ArgumentNullException"><paramref name="logStreamNameProvider"/> is <see langword="null"/>.</exception>
        public static LoggerConfiguration AmazonCloudWatch(
            this LoggerSinkConfiguration loggerConfiguration,
            string logGroupName,
            ILogStreamNameProvider logStreamNameProvider,
            string accessKey,
            string secretAccessKey,
            string regionName = null,
            ILogEventRenderer logEventRenderer = null,
            LogEventLevel minimumLogEventLevel = CloudWatchSinkOptions.DefaultMinimumLogEventLevel,
            int batchSizeLimit  = CloudWatchSinkOptions.DefaultBatchSizeLimit,
            TimeSpan?period     = null,
            bool createLogGroup = CloudWatchSinkOptions.DefaultCreateLogGroup)
        {
            if (logGroupName == null)
            {
                throw new ArgumentNullException(nameof(logGroupName));
            }
            if (logStreamNameProvider == null)
            {
                throw new ArgumentNullException(nameof(logStreamNameProvider));
            }
            if (accessKey == null)
            {
                throw new ArgumentNullException(nameof(accessKey));
            }
            if (secretAccessKey == null)
            {
                throw new ArgumentNullException(nameof(secretAccessKey));
            }

            var options = new CloudWatchSinkOptions
            {
                LogGroupName         = logGroupName,
                MinimumLogEventLevel = minimumLogEventLevel,
                BatchSizeLimit       = batchSizeLimit,
                Period = period ?? CloudWatchSinkOptions.DefaultPeriod,
                LogStreamNameProvider = logStreamNameProvider,
                LogEventRenderer      = logEventRenderer,
                CreateLogGroup        = createLogGroup
            };

            var credentials = new BasicAWSCredentials(accessKey, secretAccessKey);
            var client      = CreateClient(credentials, regionName);

            return(loggerConfiguration.AmazonCloudWatch(options, client));
        }
Esempio n. 17
0
        /// <summary>
        /// The method opens the queue
        /// </summary>
        public bool OpenQueue(string queuename, int maxnumberofmessages, String AWSAccessKey, String AWSSecretKey)
        {
            ClearErrorInfo();

            IsValid = false;

            if (!string.IsNullOrWhiteSpace(queuename))
            {
                // Checking for the need to use provided credentials instead of reading from app.Config
                if (!String.IsNullOrWhiteSpace(AWSSecretKey) && !String.IsNullOrWhiteSpace(AWSSecretKey))
                {
                    AWSCredentials awsCredentials = new BasicAWSCredentials(AWSAccessKey, AWSSecretKey);
                    queue = AWSClientFactory.CreateAmazonSQSClient(awsCredentials, RegionEndpoint.USEast1);
                }
                else
                {
                    queue = AWSClientFactory.CreateAmazonSQSClient(RegionEndpoint.USEast1);
                }

                try
                {
                    // Get queue url
                    GetQueueUrlRequest sqsRequest = new GetQueueUrlRequest();
                    sqsRequest.QueueName = queuename;
                    queueurl             = queue.GetQueueUrl(sqsRequest);

                    // Format receive messages request
                    rcvMessageRequest                     = new ReceiveMessageRequest();
                    rcvMessageRequest.QueueUrl            = queueurl.QueueUrl;
                    rcvMessageRequest.MaxNumberOfMessages = maxnumberofmessages;

                    // Format the delete messages request
                    delMessageRequest          = new DeleteMessageRequest();
                    delMessageRequest.QueueUrl = queueurl.QueueUrl;

                    IsValid = true;
                }
                catch (Exception ex)
                {
                    ErrorCode    = e_Exception;
                    ErrorMessage = ex.Message;
                }
            }

            return(IsValid);
        }
Esempio n. 18
0
        /// <summary>
        /// Uploads a file to S3.
        /// </summary>
        /// <param name="file">The full filename and path of the file to upload.</param>
        /// <param name="targetName">The file name that should be used for the upload</param>
        public void Upload(string file, String targetName)
        {
            IFormatProvider formatProvider = TinyIoCContainer.Current.Resolve <IFormatProvider>();

            try
            {
                var credentials = new BasicAWSCredentials(_appSettings.Get(AppSettingKeys.AwsAccessKey), _appSettings.Get(AppSettingKeys.AwsSecretKey));
                var region      = RegionEndpoint.GetBySystemName(_appSettings.Get(AppSettingKeys.AwsRegion));
                using (var client = new AmazonS3Client(credentials, region))
                {
                    var request = new PutObjectRequest
                    {
                        BucketName = _appSettings.Get(AppSettingKeys.S3Bucket),
                        Key        = String.Join("/", new[] { _appSettings.Get(AppSettingKeys.S3Folder), targetName }),
                        FilePath   = file
                    };
                    Console.Write(string.Format(formatProvider, Properties.Resources.StatusUploadingS3, targetName));
                    client.PutObject(request);
                    Console.WriteLine("\u221A");
                }
            }
            catch (AmazonS3Exception e)
            {
                if (e.ErrorCode != null && ("InvalidAccessKeyId" == e.ErrorCode || "InvalidSecurity" == e.ErrorCode))
                {
                    _errorHandler.HandleError(e, (int)Enums.ExitCode.AwsCredentials, Properties.Resources.ConfigurationS3Credentials);
                }
                else
                {
                    _errorHandler.HandleError(e, (int)Enums.ExitCode.AwsS3Error, string.Format(formatProvider, Properties.Resources.StatusS3UploadFailed, e.Message));
                }
            }
            finally
            {
                try
                {
                    if (File.Exists(file))
                    {
                        File.Delete(file);
                    }
                } catch (Exception ex)
                {
                    _errorHandler.HandleError(ex, (int)Enums.ExitCode.AwsS3Error, string.Format(formatProvider, Properties.Resources.StatusUnknownError, ex.Message));
                }
            }
        }
Esempio n. 19
0
        public AmazonSqsService(IOptions <SuperDumpSettings> settings, SuperDumpRepository superDumpRepo, LinkGenerator linkGenerator, ILoggerFactory loggerFactory)
        {
            this.amazonSqsSettings = settings.Value.AmazonSqsSettings;
            this.superDumpRepo     = superDumpRepo;
            this.linkGenerator     = linkGenerator;

            this.logger = loggerFactory.CreateLogger <AmazonSqsService>();

            var credentials = new BasicAWSCredentials(amazonSqsSettings.AccessKey, amazonSqsSettings.SecretKey);
            var config      = new AmazonSQSConfig {
                RegionEndpoint = RegionEndpoint.GetBySystemName(amazonSqsSettings.Region)
            };

            this.sqsClient = new AmazonSQSClient(credentials, config);

            this.baseUri = new Uri(amazonSqsSettings.SuperDumpBaseUrl);
        }
Esempio n. 20
0
        public PersistentService()
        {
            _settings = Settings.Default;
            var credentials = new BasicAWSCredentials(_settings.AWSAccessKey, _settings.AWSSecretKey);

            var region = RegionEndpoint.GetBySystemName(_settings.AWSRegion);

            _s3Client = new AmazonS3Client(credentials, region);
            _config   = new TransferUtilityConfig
            {
                // Use 5 concurrent requests.
                ConcurrentServiceRequests = 5,

                // Use multipart upload for file size greater 20 MB.
                MinSizeBeforePartUpload = 20 * MB_SIZE,
            };
        }
Esempio n. 21
0
        public AwsSesSender(
            IOptions <AwsSesMailingSettings> settingsOptions,
            ILogger <AwsSesSender> logger)
        {
            _logger = logger.GuardIsNotNull(nameof(logger));
            var settings = settingsOptions?.Value.GuardIsNotNull(nameof(settingsOptions));

            var credentials = new BasicAWSCredentials(
                settings.AccessKeyId,
                settings.AccessKeySecret);

            var regionEndpoint = settings.RegionEndpoint.IsNullOrWhiteSpace()
                ? RegionEndpoint.USEast1
                : RegionEndpoint.GetBySystemName(settings.RegionEndpoint);

            _client = new AmazonSimpleEmailServiceClient(credentials, regionEndpoint);
        }
        public AWSDynamoDBStream(BasicAWSCredentials basicAWSCredentials, RegionEndpoint regionEndpoint, string tableName, AWSDynamoDBIteratorType type)
        {
            this.TableName = tableName;
            this.AmazonDynamoDBStreamsClient = new AmazonDynamoDBStreamsClient(basicAWSCredentials, regionEndpoint);
            this.AWSDynamoDBIteratorType     = type;
            var listStreams = AmazonDynamoDBStreamsClient.ListStreams(new ListStreamsRequest()
            {
                TableName = this.TableName
            });

            this.StreamArn = listStreams.Streams.First().StreamArn;

            DescribeStreamRequest describeStreamRequest = new DescribeStreamRequest()
            {
                StreamArn = this.StreamArn
            };

            var describeStreamResponse = this.AmazonDynamoDBStreamsClient.DescribeStream(describeStreamRequest);
            var shards = describeStreamResponse.StreamDescription.Shards;

            GetShardIteratorRequest getShardIteratorRequest = null;

            if (this.AWSDynamoDBIteratorType == AWSDynamoDBIteratorType.TRIM_HORIZON)
            {
                getShardIteratorRequest = new GetShardIteratorRequest()
                {
                    StreamArn         = this.StreamArn,
                    ShardIteratorType = ShardIteratorType.TRIM_HORIZON,
                    ShardId           = shards.First().ShardId,
                };
            }
            if (this.AWSDynamoDBIteratorType == AWSDynamoDBIteratorType.LATEST)
            {
                getShardIteratorRequest = new GetShardIteratorRequest()
                {
                    StreamArn         = this.StreamArn,
                    ShardIteratorType = ShardIteratorType.LATEST,
                    ShardId           = shards.Last().ShardId,
                    //SequenceNumber = shards.First().SequenceNumberRange.StartingSequenceNumber
                };
            }

            var shardIteratorResponse = this.AmazonDynamoDBStreamsClient.GetShardIterator(getShardIteratorRequest);

            this.LatestShardID = shardIteratorResponse.ShardIterator;
        }
Esempio n. 23
0
 private void CreateClient()
 {
     if (service.StartsWith("http://", StringComparison.InvariantCultureIgnoreCase) ||
         service.StartsWith("https://", StringComparison.InvariantCultureIgnoreCase))
     {
         ddbClient = new AmazonDynamoDBClient(new AmazonDynamoDBConfig {
             ServiceURL = service
         });
     }
     else
     {
         var credentials = new BasicAWSCredentials(accessKey, secretKey);
         ddbClient = new AmazonDynamoDBClient(credentials, new AmazonDynamoDBConfig {
             ServiceURL = service, RegionEndpoint = AWSUtils.GetRegionEndpoint(service)
         });
     }
 }
Esempio n. 24
0
        private static AmazonS3Client CreateClient(AmazonS3Config config = null)
        {
            if (config == null)
            {
                config = new AmazonS3Config();
            }

            // load the ViPR S3 endpoint information and credentials from app.config
            Uri            endpoint = new Uri(ConfigurationManager.AppSettings["AWSServiceURI"]);
            AWSCredentials creds    = new BasicAWSCredentials(
                ConfigurationManager.AppSettings["AWSAccessKey"],
                ConfigurationManager.AppSettings["AWSSecretKey"]);

            // establish the configuration, for either a host-based endpoint or an IP-based endpoint
            if (endpoint.HostNameType == UriHostNameType.IPv4 || endpoint.HostNameType == UriHostNameType.IPv6)
            {
                // By default, the AWS .NET SDK does not support
                // path-style buckets and nonstandard ports in the service
                // URL.  Therefore, we need to configure the ViPR endpoint
                // as a proxy instead of the ServiceURL since most test
                // configurations will use IP addresses and the internal
                // 9020/9021 ports.

                config.ProxyHost = endpoint.Host;
                config.ProxyPort = endpoint.Port;
                if (endpoint.Scheme == "https")
                {
                    throw new ArgumentException("ViPR S3 via HTTPS is not supported through .NET with the AWS SDK: " + endpoint);
                }
                else
                {
                    config.CommunicationProtocol = Protocol.HTTP;
                }
            }
            else
            {
                config.CommunicationProtocol =
                    string.Equals("http", endpoint.Scheme, StringComparison.InvariantCultureIgnoreCase) ?
                    Protocol.HTTP : Protocol.HTTPS;
                config.ServiceURL = endpoint.GetComponents(UriComponents.HostAndPort, UriFormat.UriEscaped);
            }

            var client = new AmazonS3Client(creds, config);

            return(client);
        }
Esempio n. 25
0
        public async Task <IActionResult> Upload(PolicyRequest policy, string policyRef)
        {
            try
            {
                string guid = Guid.NewGuid().ToString();

                var credentials = new BasicAWSCredentials(accessKey, secretKey);
                var config      = new AmazonS3Config
                {
                    RegionEndpoint = Amazon.RegionEndpoint.EUWest2
                };
                using var client             = new AmazonS3Client(credentials, config);
                await using var memoryStream = new MemoryStream(Convert.FromBase64String(policy.PolicyPDF));

                var uploadRequest = new TransferUtilityUploadRequest
                {
                    InputStream = memoryStream,
                    Key         = guid,
                    BucketName  = "karl",
                    CannedACL   = S3CannedACL.PublicRead,
                    ContentType = "application/pdf"
                };

                // https://docs.aws.amazon.com/sdkfornet1/latest/apidocs/html/M_Amazon_S3_AmazonS3Client_GetPreSignedURL.htm //

                GetPreSignedUrlRequest request = new GetPreSignedUrlRequest
                {
                    BucketName = "karl",
                    Key        = guid,
                    Expires    = DateTime.Now.AddMinutes(5)
                };

                string path = client.GetPreSignedURL(request);

                // --------------------------------------------------------------------------------------------------------- //

                var fileTransferUtility = new TransferUtility(client);
                await fileTransferUtility.UploadAsync(uploadRequest);
            }
            catch (Exception ex)
            {
                Console.WriteLine("An error occurred: " + ex.Message);
            }

            return(Ok());
        }
Esempio n. 26
0
        public async Task <bool> SendDistributionListEmail(MimeMessage message)
        {
            var stream = new MemoryStream();

            message.WriteTo(stream);
            var request = new SendRawEmailRequest()
            {
                RawMessage = new RawMessage()
                {
                    Data = stream
                }
            };

            // Choose the AWS region of the Amazon SES endpoint you want to connect to. Note that your sandbox
            // status, sending limits, and Amazon SES identity-related settings are specific to a given
            // AWS region, so be sure to select an AWS region in which you set up Amazon SES. Here, we are using
            // the US West (Oregon) region. Examples of other regions that Amazon SES supports are USEast1
            // and EUWest1. For a complete list, see http://docs.aws.amazon.com/ses/latest/DeveloperGuide/regions.html
            Amazon.RegionEndpoint REGION = Amazon.RegionEndpoint.USWest2;

            var credentials = new BasicAWSCredentials(Config.OutboundEmailServerConfig.AwsAccessKey, Config.OutboundEmailServerConfig.AwsSecretKey);

            // Instantiate an Amazon SES client, which will make the service call.
            AmazonSimpleEmailServiceClient client = new AmazonSimpleEmailServiceClient(credentials, REGION);

            // Send the email.
            try
            {
                //TODO: Might not be right -SJ
                var result = await client.SendRawEmailAsync(request);

                if (!String.IsNullOrWhiteSpace(result.MessageId))
                {
                    return(true);
                }

                return(false);
            }
            catch (Exception ex)
            {
                var exc = ex.ToString();
            }

            return(false);
        }
Esempio n. 27
0
        public static void Main(string[] args)
        {
            LabVariables labVariables = null;
            var          program      = new Program();

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

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

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

                        var s3Client = new AmazonS3Client(credentials, RegionEndpoint);

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

                Console.WriteLine("\nPress <enter> to end.");
                Console.ReadLine();
            }
        }
Esempio n. 28
0
    public static async Task <string> DeployRestApi(this ICakeContext context, DeployApiGatewayConfig config)
    {
        if (config == null)
        {
            throw new ArgumentNullException(nameof(config));
        }

        config.EnsureValid();

        context.Log.Write(
            Cake.Core.Diagnostics.Verbosity.Normal,
            Cake.Core.Diagnostics.LogLevel.Information,
            $"Deploying api {config.RestApiId} on {config.StageName} stage"
            );

        var credentials = new BasicAWSCredentials(config.AccessKey, config.SecretKey);

        using (var client = new Amazon.APIGateway.AmazonAPIGatewayClient(credentials, config))
        {
            var response = await client.CreateDeploymentAsync(new Amazon.APIGateway.Model.CreateDeploymentRequest()
            {
                RestApiId = config.RestApiId,
                StageName = config.StageName,
            });

            var meta = string.Join(" | ", response.ResponseMetadata.Metadata.Select(q => $"{q.Key}={q.Value}"));

            if ((int)response.HttpStatusCode < 300)
            {
                context.Log.Write(
                    Cake.Core.Diagnostics.Verbosity.Normal,
                    Cake.Core.Diagnostics.LogLevel.Information,
                    $"Deployment for api {config.RestApiId} succeeded on stage {config.StageName} with http code {response.HttpStatusCode}; {meta}"
                    );

                return(response.Id);
            }
            else
            {
                var message = $"Deployment for api {config.RestApiId} failed on stage {config.StageName} with http code {response.HttpStatusCode}; {meta}";

                throw new Exception(message);
            }
        }
    }
        public async Task <ActionResult <string> > Signin([FromBody] User user)
        {
            var validation = user != default(User) &&
                             !string.IsNullOrEmpty(user.UserName) &&
                             !string.IsNullOrEmpty(user.Password);

            if (!validation)
            {
                return(BadRequest());
            }

            var token          = string.Empty;
            var clientId       = "20jo0qhegstp7ovimab8nln5pg";
            var userPoolId     = @"ap-southeast-1_TarRBIFR7";
            var awsCredentials = new BasicAWSCredentials(
                accessKey: "AKIAJLCJTGLJZ67AAAZA",
                secretKey: "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");

            try
            {
                var authenticationRequest = new AdminInitiateAuthRequest
                {
                    UserPoolId = userPoolId,
                    ClientId   = clientId,
                    AuthFlow   = AuthFlowType.ADMIN_NO_SRP_AUTH
                };

                authenticationRequest.AuthParameters.Add("USERNAME", user.UserName);
                authenticationRequest.AuthParameters.Add("PASSWORD", user.Password);

                using (var client =
                           new AmazonCognitoIdentityProviderClient(awsCredentials, RegionEndpoint.APSouth1))
                {
                    var response = await client.AdminInitiateAuthAsync(authenticationRequest);

                    token = response.AuthenticationResult.IdToken;
                }
            }
            catch (Exception exceptionObject)
            {
                throw exceptionObject;
            }

            return(Ok(token));
        }
Esempio n. 30
0
        public ICustomActivityResult Execute()
        {
            var credentials = new BasicAWSCredentials(AccessKey, SecretKey);
            ListBucketsResponse response = new AmazonS3Client(credentials, RegionEndpoint.USEast1).ListBuckets();
            var dataTable = new DataTable("List bucket", "AWSS3");

            dataTable.Columns.Add("Id");
            dataTable.Columns.Add("BucketName");
            dataTable.Columns.Add("Created date");
            int id = 0;

            foreach (S3Bucket bucket in response.Buckets)
            {
                id++;
                dataTable.Rows.Add(id, bucket.BucketName, bucket.CreationDate);
            }
            return(this.GenerateActivityResult(dataTable));
        }