Esempio n. 1
0
        public void ExecuteQuery(string sql)
        {
            var awsCredentials = new Amazon.Runtime.BasicAWSCredentials("A", "B");
            var c = new AmazonAthenaClient(awsCredentials);

            QueryExecutionContext queryExecutionContext = new QueryExecutionContext();

            queryExecutionContext.Database = ATHENA_DEFAULT_DATABASE;

            // The result configuration specifies where the results of the query should go in S3 and encryption options
            ResultConfiguration resultConfiguration = new ResultConfiguration();

            // You can provide encryption options for the output that is written.
            // .withEncryptionConfiguration(encryptionConfiguration)
            resultConfiguration.OutputLocation = ATHENA_OUTPUT_BUCKET;

            // Create the StartQueryExecutionRequest to send to Athena which will start the query.
            StartQueryExecutionRequest startQueryExecutionRequest = new StartQueryExecutionRequest();

            startQueryExecutionRequest.QueryString           = sql;
            startQueryExecutionRequest.QueryExecutionContext = queryExecutionContext;
            startQueryExecutionRequest.ResultConfiguration   = resultConfiguration;

            var startQueryExecutionResponse = c.StartQueryExecutionAsync(startQueryExecutionRequest);
            //Console.WriteLine($"Query ID {startQueryExecutionResponse.QueryExecutionId}");
//            return startQueryExecutionResponse.QueryExecutionId();
        }
Esempio n. 2
0
        public async Task <IActionResult> Post([FromBody] users _user)
        {
            var             credentials   = new Amazon.Runtime.BasicAWSCredentials(Constants.access_key, Constants.secret_key);
            var             S3Client      = new AmazonDynamoDBClient(credentials, Constants.regionEndpoint);
            var             tableName     = "users";
            DynamoDBContext context       = new DynamoDBContext(S3Client);
            var             tableResponse = await S3Client.ListTablesAsync();

            if (tableResponse.TableNames.Contains(tableName))
            {
                var conditions = new List <ScanCondition>();
                conditions.Add(new ScanCondition("userId", ScanOperator.Equal, _user.userId));
                var allDocs = await context.ScanAsync <users>(conditions).GetRemainingAsync();

                allDocs[0].userEmail     = _user.userEmail;
                allDocs[0].userImageUrl  = _user.userImageUrl;
                allDocs[0].userFirstName = _user.userFirstName;
                allDocs[0].userId        = _user.userId;
                allDocs[0].userLastName  = _user.userLastName;
                allDocs[0].userName      = _user.userName;
                allDocs[0].userPassword  = _user.userPassword;

                await context.SaveAsync <users>(allDocs[0]);
            }
            return(Ok());
        }
Esempio n. 3
0
        /// <summary>
        /// Constructor
        /// </summary>
        /// <param name="localizer"></param>
        /// <param name="settings"></param>
        /// <param name="logger"></param>
        public GoSMSQueueSender(
            IStringLocalizer <GoSMSQueueSender> localizer,
            IOptions <Model.Settings.GoSMSQueueConfiguration> settings,
            ILogger <GoSMSQueueSender> logger
            )
        {
            if (localizer is null)
            {
                throw new ArgumentNullException(nameof(localizer));
            }

            this.logger   = logger ?? throw new ArgumentNullException(nameof(logger));
            this.settings = settings ?? throw new ArgumentNullException(nameof(settings));
            if (string.IsNullOrEmpty(settings.Value.QueueURL))
            {
                throw new Exception(localizer["Invalid SMS endpoint"].Value);
            }

            var sqsConfig = new AmazonSQSConfig
            {
                RegionEndpoint = RegionEndpoint.GetBySystemName(settings.Value.Region)
            };
            var awsCredentials = new Amazon.Runtime.BasicAWSCredentials(settings.Value.AccessKeyID, settings.Value.SecretAccessKey);

            amazonSQSClient = new AmazonSQSClient(awsCredentials, sqsConfig);
        }
Esempio n. 4
0
        public async Task <IActionResult> DesignAutomationCallback(string connectionId, string resultJson, [FromBody] JObject body)
        {
            var       awsCredentials = new Amazon.Runtime.BasicAWSCredentials(Utils.GetAppSetting("AWS_ACCESS_KEY"), Utils.GetAppSetting("AWS_SECRET_KEY"));
            IAmazonS3 client         = new AmazonS3Client(awsCredentials, Amazon.RegionEndpoint.USWest2);

            if (!await client.DoesS3BucketExistAsync(Utils.S3BucketName))
            {
                return(Ok());
            }
            Uri downloadFromS3 = new Uri(client.GeneratePreSignedURL(Utils.S3BucketName, resultJson, DateTime.Now.AddMinutes(10), null));

            string resultJsonPath = Path.Combine(_env.WebRootPath, resultJson);
            var    keys           = await client.GetAllObjectKeysAsync(Utils.S3BucketName, null, null);

            if (!keys.Contains(resultJson))
            {
                return(Ok());                            // file is not there
            }
            await client.DownloadToFilePathAsync(Utils.S3BucketName, resultJson, resultJsonPath, null);

            string contents = System.IO.File.ReadAllText(resultJsonPath);

            System.IO.File.Delete(resultJsonPath);
            //await client.DeleteObjectAsync(Utils.S3BucketName, resultJson);

            await ValidationHub.ValidationFinished(_hubContext, connectionId, resultJson, JObject.Parse(contents));

            return(Ok());
        }
Esempio n. 5
0
        public Function()
        {
            var awsCredentials = new Amazon.Runtime.BasicAWSCredentials("AKIAJI5RF4RFXM7U3ELQ", "4GH/cZnUMg9a+Tmwr6EJ5DQOplrduK3gTHYYb2D+");

            _s3Client = new AmazonS3Client();
            _sqs      = new AmazonSQSClient(awsCredentials, RegionEndpoint.USEast2);
        }
Esempio n. 6
0
        public static string PushMetrics(string ns, List <MetricDatum> metrics)
        {
            var request = new PutMetricDataRequest
            {
                Namespace  = ns,
                MetricData = metrics
            };

            //
            Amazon.Runtime.AWSCredentials credentials = null;
            if (Configuration.IsLinux())
            {
                string AccessKey = "xxx";
                string SecretKey = "xxx";
                credentials = new Amazon.Runtime.BasicAWSCredentials(AccessKey, SecretKey);
            }
            else
            {
                credentials = new Amazon.Runtime.StoredProfileAWSCredentials("cloudwatch");
            }
            //
            var client = new AmazonCloudWatchClient(credentials, Amazon.RegionEndpoint.APSoutheast1);

            System.Threading.Tasks.Task <PutMetricDataResponse> task = client.PutMetricDataAsync(request);
            PutMetricDataResponse response = task.Result;

            //
            System.Net.HttpStatusCode statusCode = response.HttpStatusCode;
            Console.WriteLine(DateTime.Now.ToString("HH:mm ") + statusCode.ToString());
            return(statusCode.ToString());
        }
Esempio n. 7
0
        static void GetPreSigUrl()
        {
            String fileKey = "test-txt.log";

            Amazon.Runtime.BasicAWSCredentials cred = new Amazon.Runtime.BasicAWSCredentials("61140DEQBD8L2QSRATPS", "1oZedqSsM2DLjer2VvZ74ACpn998TamNbz4LEURN");
            Amazon.RegionEndpoint endpoint          = Amazon.RegionEndpoint.APNortheast1;


            //首先创建一个s3的客户端操作对象(需要amazon提供的密钥)
            AmazonS3Client s3 = new AmazonS3Client(cred, endpoint);

            try
            {
                // 验证名称为bucketName的bucket是否存在,不存在则创建

                Amazon.S3.Model.GetPreSignedUrlRequest urlRequest = new Amazon.S3.Model.GetPreSignedUrlRequest();
                urlRequest.BucketName = bucketName;
                urlRequest.Key        = fileKey;
                urlRequest.Protocol   = Protocol.HTTP;
                urlRequest.Verb       = HttpVerb.GET;
                urlRequest.Expires    = DateTime.Now.AddHours(12); // ;.Now + dtSpan; //new TimeSpan(12,0,0); //12小时有效期
                String strSinnedURL = s3.GetPreSignedURL(urlRequest);
                Console.WriteLine(strSinnedURL);
            }
            catch (Amazon.S3.AmazonS3Exception e)
            {
                Console.WriteLine("GenerateFileSignURL AmazonS3Exception:" + e.ToString());
            }
            catch (Exception e)
            {
                Console.WriteLine("GenerateFileSignURL Exception:" + e.ToString());
            }
        }
Esempio n. 8
0
    public AWSClass(string region, string AccessKey, string Secret)
    {
        RegionEndpoint EndPoint = RegionEndpoint.GetBySystemName(region);

        Amazon.Runtime.BasicAWSCredentials Credentials = new Amazon.Runtime.BasicAWSCredentials(AccessKey, Secret);
        _client = new AmazonEC2Client(Credentials, EndPoint);
    }
Esempio n. 9
0
        public AmazonActivities(IAmazonS3 client)
        {
            var awsCredentials = new Amazon.Runtime.BasicAWSCredentials("AKIAJI5RF4RFXM7U3ELQ", "4GH/cZnUMg9a+Tmwr6EJ5DQOplrduK3gTHYYb2D+");

            client  = new AmazonS3Client(awsCredentials, RegionEndpoint.USEast2);
            _client = client;
        }
Esempio n. 10
0
        private async Task <XrefTreeArgument> BuildS3DownloadURL(string fileName)
        {
            var       awsCredentials = new Amazon.Runtime.BasicAWSCredentials(Credentials.GetAppSetting("AWS_ACCESS_KEY"), Credentials.GetAppSetting("AWS_SECRET_KEY"));
            IAmazonS3 client         = new AmazonS3Client(awsCredentials, Amazon.RegionEndpoint.USWest2);

            if (!await client.DoesS3BucketExistAsync(Utils.S3BucketName))
            {
                throw new Exception("Bucket does not exist");
            }

            var keys = await client.GetAllObjectKeysAsync(Utils.S3BucketName, null, null);

            if (!keys.Contains(fileName))
            {
                throw new Exception("Object does not exist in bucket");
            }

            Uri downloadFromS3 = new Uri(client.GeneratePreSignedURL(Utils.S3BucketName, fileName, DateTime.Now.AddMinutes(5), null));

            return(new XrefTreeArgument()
            {
                Url = downloadFromS3.ToString(),
                Verb = Verb.Get
            });
        }
Esempio n. 11
0
        private AmazonRekognitionClient CreateAwsClient()
        {
            var cred = new Amazon.Runtime.BasicAWSCredentials(this.AccessKeyId, this.AccessKeySecret);
            var cli  = new AmazonRekognitionClient(cred, Amazon.RegionEndpoint.EUWest1);

            return(cli);
        }
Esempio n. 12
0
        private AmazonDynamoDBClient CreateDynamoDbClient()
        {
            var awsAccessKey = Environment.GetEnvironmentVariable(ConfigKeys.g_env_ps_builds_aws_access_key);
            var awsSecretKey = Environment.GetEnvironmentVariable(ConfigKeys.g_env_ps_builds_aws_access_secret);
            var creds        = new Amazon.Runtime.BasicAWSCredentials(awsAccessKey, awsSecretKey);

            return(new AmazonDynamoDBClient(creds, RegionEndpoint.USWest2));
        }
Esempio n. 13
0
        public UserService()
        {
            var awsAccessKey = Environment.GetEnvironmentVariable(ConfigKeys.g_env_ps_builds_aws_access_key);
            var awsSecretKey = Environment.GetEnvironmentVariable(ConfigKeys.g_env_ps_builds_aws_access_secret);
            var creds        = new Amazon.Runtime.BasicAWSCredentials(awsAccessKey, awsSecretKey);

            _client = new AmazonDynamoDBClient(creds, RegionEndpoint.USWest2);
        }
Esempio n. 14
0
        static AmazonS3Client CreateS3Client()
        {
            var awsAccessKey = Environment.GetEnvironmentVariable(ConfigKeys.g_env_ps_builds_aws_access_key);
            var awsSecretKey = Environment.GetEnvironmentVariable(ConfigKeys.g_env_ps_builds_aws_access_secret);
            var creds        = new Amazon.Runtime.BasicAWSCredentials(awsAccessKey, awsSecretKey);
            var client       = new AmazonS3Client(creds, Amazon.RegionEndpoint.USEast2);

            return(client);
        }
Esempio n. 15
0
        private AmazonS3Client GetS3Client()
        {
            var awsSecret    = Environment.GetEnvironmentVariable("AWS_SECRET_KEY");
            var awsAccessKey = Environment.GetEnvironmentVariable("AWS_ACCESS_KEY");

            var awsCredentials = new Amazon.Runtime.BasicAWSCredentials(awsAccessKey, awsSecret);
            var s3Client       = new AmazonS3Client(awsCredentials, RegionEndpoint.EUWest1);

            return(s3Client);
        }
            public DisposableDatabase()
            {
                var creds = new Amazon.Runtime.BasicAWSCredentials("test", "test");

                Client = new AmazonDynamoDBClient(creds, new AmazonDynamoDBConfig
                {
                    ServiceURL = "http://localhost:8000"
                });
                Context = new DynamoDBContext(Client);
            }
Esempio n. 17
0
        private void InitializeClients()
        {
            switch (_StorageType)
            {
            case StorageType.AwsS3:
                _S3Region      = _AwsSettings.GetAwsRegionEndpoint();
                _S3Credentials = new Amazon.Runtime.BasicAWSCredentials(_AwsSettings.AccessKey, _AwsSettings.SecretKey);

                if (String.IsNullOrEmpty(_AwsSettings.Endpoint))
                {
                    _S3Config = new AmazonS3Config
                    {
                        RegionEndpoint = _S3Region,
                        UseHttp        = !_AwsSettings.Ssl,
                    };

                    // _S3Client = new AmazonS3Client(_S3Credentials, _S3Region);
                    _S3Client = new AmazonS3Client(_S3Credentials, _S3Config);
                }
                else
                {
                    _S3Config = new AmazonS3Config
                    {
                        RegionEndpoint = _S3Region,
                        ServiceURL     = _AwsSettings.Endpoint,
                        ForcePathStyle = true,
                        UseHttp        = !_AwsSettings.Ssl
                    };

                    _S3Client = new AmazonS3Client(_S3Credentials, _S3Config);
                }
                break;

            case StorageType.Azure:
                _AzureCredentials = new StorageCredentials(_AzureSettings.AccountName, _AzureSettings.AccessKey);
                _AzureAccount     = new CloudStorageAccount(_AzureCredentials, true);
                _AzureBlobClient  = new CloudBlobClient(new Uri(_AzureSettings.Endpoint), _AzureCredentials);
                _AzureContainer   = _AzureBlobClient.GetContainerReference(_AzureSettings.Container);
                break;

            case StorageType.Disk:
                if (!Directory.Exists(_DiskSettings.Directory))
                {
                    Directory.CreateDirectory(_DiskSettings.Directory);
                }
                break;

            case StorageType.Kvpbase:
                _Kvpbase = new KvpbaseClient(_KvpbaseSettings.UserGuid, _KvpbaseSettings.ApiKey, _KvpbaseSettings.Endpoint);
                break;

            default:
                throw new ArgumentException("Unknown storage type: " + _StorageType.ToString());
            }
        }
Esempio n. 18
0
        private void UploadToS3(Stream stream, string bucketName, string filename)
        {
            var awsCredentials = new Amazon.Runtime.BasicAWSCredentials(
                ApplicationSettings.TryGetValueFromAppSettings("accessKey"),
                ApplicationSettings.TryGetValueFromAppSettings("secretKey"));

            RegionEndpoint  endPoint            = (RegionEndpoint)ApplicationSettings.AppSettings["regionEndpoint"];
            AmazonS3Client  client              = new AmazonS3Client(awsCredentials, endPoint ?? RegionEndpoint.EUCentral1);
            TransferUtility fileTransferUtility = new TransferUtility(client);

            fileTransferUtility.Upload(stream, bucketName, filename);
        }
Esempio n. 19
0
        public TextExtractionResults Extract(byte[] image)
        {
            var end = Amazon.RegionEndpoint.EUWest1;

            Amazon.Runtime.BasicAWSCredentials awsCreds =
                new Amazon.Runtime.BasicAWSCredentials(this.AmazonAccessKey, this.AmazonSecretKey);
            var region = Amazon.RegionEndpoint.GetBySystemName("eu-west-1");
            var cfg    = new Amazon.Textract.AmazonTextractConfig();

            Amazon.Textract.AmazonTextractClient client = new Amazon.Textract.AmazonTextractClient(awsCreds, end);
            //Amazon.Textract.AmazonTextractClient client1 = new Amazon.Textract.AmazonTextractClient(awsCreds, cfg);
            var request = new Amazon.Textract.Model.DetectDocumentTextRequest();

            request.Document = new Amazon.Textract.Model.Document();
            Amazon.Textract.Model.DetectDocumentTextResponse result = null;
            using (var memstm = new System.IO.MemoryStream(image))
            {
                request.Document.Bytes = memstm;
                result = client.DetectDocumentTextAsync(request).Result;
            }
            TextExtractionResults rs           = new TextExtractionResults();
            List <TextBlock>      lstTextBoxes = new List <TextBlock>();

            DetermineDimensions(image);
            foreach (var block in result.Blocks)
            {
                TextBlock rsText = new TextBlock();
                rsText.Text = block.Text;
                if (string.IsNullOrWhiteSpace(rsText.Text))
                {
                    continue;                                        //The first element is always NULL, so it appears
                }
                if (block.BlockType == Amazon.Textract.BlockType.WORD)
                {
                    double xTopLeft = block.Geometry.BoundingBox.Left * this.Width;
                    double yTopLeft = block.Geometry.BoundingBox.Top * this.Height;
                    double width    = block.Geometry.BoundingBox.Width * this.Width;
                    double height   = block.Geometry.BoundingBox.Height * this.Height;
                    rsText.X1 = xTopLeft;
                    rsText.Y1 = yTopLeft;
                    rsText.X2 = rsText.X1 + width;
                    rsText.Y2 = rsText.Y1 + height;
                    lstTextBoxes.Add(rsText);
                }
                else
                {
                    //Para or line perhaps?
                }
            }
            rs.Blocks = lstTextBoxes.ToArray();
            return(rs);
        }
Esempio n. 20
0
        private static void CheckBucket()
        {
            Amazon.Runtime.AWSCredentials credentials = new Amazon.Runtime.BasicAWSCredentials(awsAccessKey, awsSecretKey);
            using (var client = new AmazonS3Client(credentials, Amazon.RegionEndpoint.EUCentral1))
            {
                if (!(AmazonS3Util.DoesS3BucketExist(client, bucketName)))
                {
                    CreateBucket(client);
                }

                UploadFiles(client);
            }
        }
Esempio n. 21
0
        public async Task <bool> Upload(string key, string path)
        {
            var s3credentials = new Amazon.Runtime.BasicAWSCredentials(access_id, secret_key);
            //var s3config = new AmazonS3Config();
            //s3config.ProxyHost = "";
            //s3config.ProxyPort = 8080;
            var ok = false;

            using (s3client = new AmazonS3Client(s3credentials, RegionEndpoint.USWest2)) {
                ok = await UploadFileAsync(key, path);
            }
            return(ok);
        }
        public async Task CreateIssues(string userId, string hubId, string projectId, string versionId, string contentRootPath, string host)
        {
            string    bucketName     = "revitdesigncheck" + DesignAutomation4Revit.NickName.ToLower();
            var       awsCredentials = new Amazon.Runtime.BasicAWSCredentials(Credentials.GetAppSetting("AWS_ACCESS_KEY"), Credentials.GetAppSetting("AWS_SECRET_KEY"));
            IAmazonS3 client         = new AmazonS3Client(awsCredentials, Amazon.RegionEndpoint.USWest2);

            string resultFilename = versionId + ".txt";

            // create AWS Bucket
            if (!await client.DoesS3BucketExistAsync(bucketName))
            {
                return;
            }
            Uri downloadFromS3 = new Uri(client.GeneratePreSignedURL(bucketName, resultFilename, DateTime.Now.AddMinutes(10), null));


            // ToDo: is there a better way?
            string results = Path.Combine(contentRootPath, resultFilename);
            var    keys    = await client.GetAllObjectKeysAsync(bucketName, null, null);

            if (!keys.Contains(resultFilename))
            {
                return;                                 // file is not there
            }
            await client.DownloadToFilePathAsync(bucketName, resultFilename, results, null);

            string contents = System.IO.File.ReadAllText(results);

            Credentials credentials = await Credentials.FromDatabaseAsync(userId);

            VersionsApi versionApi = new VersionsApi();

            versionApi.Configuration.AccessToken = credentials.TokenInternal;
            dynamic versionItem = await versionApi.GetVersionItemAsync(projectId, versionId.Base64Decode());

            string itemId  = versionItem.data.id;
            int    version = Int32.Parse(versionId.Split("_")[1].Base64Decode().Split("=")[1]);

            string title       = string.Format("Column clash report for version {0}", version);
            string description = string.Format("<a href=\"http://{0}/issues/?urn={1}&id={2}\" target=\"_blank\">Click to view issues</a>", host, versionId, contents.Base64Encode());

            // create issues
            BIM360Issues issues      = new BIM360Issues();
            string       containerId = await issues.GetContainer(credentials.TokenInternal, hubId, projectId);

            await issues.CreateIssue(credentials.TokenInternal, containerId, itemId, version, title, description);

            // only delete if it completes
            System.IO.File.Delete(resultFilename);
            await client.DeleteObjectAsync(bucketName, resultFilename);
        }
        public async Task <userResponse> Get([FromBody] loginRequest request)
        {
            userResponse userResponse  = new userResponse();
            var          credentials   = new Amazon.Runtime.BasicAWSCredentials(Constants.access_key, Constants.secret_key);
            var          tableName     = "users";
            var          S3Client      = new AmazonDynamoDBClient(credentials, Constants.regionEndpoint);
            var          tableResponse = await S3Client.ListTablesAsync();

            if (tableResponse.TableNames.Contains(tableName))
            {
                var conditions = new List <ScanCondition>();
                conditions.Add(new ScanCondition("userName", ScanOperator.Equal, request.username));
                conditions.Add(new ScanCondition("userPassword", ScanOperator.Equal, request.userpassword));
                var allDocs = await _context.ScanAsync <users>(conditions).GetRemainingAsync();

                user _user = new user();
                _user.userEmail      = allDocs[0].userEmail;
                _user.userImageUrl   = allDocs[0].userImageUrl;
                _user.userFirstName  = allDocs[0].userFirstName;
                _user.userId         = allDocs[0].userId;
                _user.userLastName   = allDocs[0].userLastName;
                _user.userName       = allDocs[0].userName;
                _user.userPassword   = allDocs[0].userPassword;
                userResponse.user    = _user;
                userResponse.code    = (int)System.Net.HttpStatusCode.OK;
                userResponse.message = "Success";
                // Create our table if it doesn't exist

                DynamoDBContext context        = new DynamoDBContext(S3Client);
                var             tableResponse1 = await S3Client.ListTablesAsync();

                if (tableResponse1.TableNames.Contains(tableName))
                {
                    var conditions1 = new List <ScanCondition>();
                    conditions.Add(new ScanCondition("userId", ScanOperator.Equal, allDocs[0].userId));
                    var allDocs1 = await context.ScanAsync <users>(conditions1).GetRemainingAsync();

                    users _user1 = new users();
                    _user1.userEmail     = allDocs1[0].userEmail;
                    _user1.userImageUrl  = request.imageUrl;
                    _user1.userFirstName = allDocs1[0].userFirstName;
                    _user1.userId        = allDocs1[0].userId;
                    _user1.userLastName  = allDocs1[0].userLastName;
                    _user1.userName      = allDocs1[0].userName;
                    _user1.userPassword  = allDocs1[0].userPassword;
                    await context.SaveAsync <users>(_user1);
                }
            }

            return(userResponse);
        }
Esempio n. 24
0
        private void UploadToS3(string filePath, string bucketName)
        {
            var awsCredentials = new Amazon.Runtime.BasicAWSCredentials(
                ApplicationSettings.TryGetValueFromAppSettings("accessKey"),
                ApplicationSettings.TryGetValueFromAppSettings("secretKey"));
            AmazonS3Client  client = new AmazonS3Client(awsCredentials, RegionEndpoint.EUCentral1);
            TransferUtility fileTransferUtility = new TransferUtility(client);

            filePath = "/UploadedFiles/" + filePath;
            using (var stream = new FileStream(filePath, FileMode.Create))
            {
                fileTransferUtility.Upload(stream, bucketName, filePath);
            }
        }
Esempio n. 25
0
        static void Main(string[] args)
        {
            var bucketName = Guid.NewGuid().ToString().ToLower();
            var creds      = new Amazon.Runtime.BasicAWSCredentials("key", "secret");
            var s3Client   = new AmazonS3Client(creds, new AmazonS3Config {
                ServiceURL = Environment.GetEnvironmentVariable("AWS_S3_ENDPOINT"), ForcePathStyle = true
            });

            //s3Client.ListBucketsAsync().Wait();
            s3Client.PutBucketAsync(new PutBucketRequest {
                BucketName = bucketName, UseClientRegion = true
            }).Wait();
            Console.WriteLine("Bucket Created!");
            // visit to see results http://localhost:9090
        }
Esempio n. 26
0
        private async Task EnsureTemplateExists(string contentRootPath)
        {
            var       awsCredentials = new Amazon.Runtime.BasicAWSCredentials(Credentials.GetAppSetting("AWS_ACCESS_KEY"), Credentials.GetAppSetting("AWS_SECRET_KEY"));
            IAmazonS3 client         = new AmazonS3Client(awsCredentials, Amazon.RegionEndpoint.USWest2);
            var       keys           = await client.GetAllObjectKeysAsync(Utils.S3BucketName, null, null);

            if (keys.Contains(RFA_TEMPLATE))
            {
                return;
            }

            // not there yet, let's create
            string rftPath = Path.Combine(contentRootPath, RFA_TEMPLATE);
            await client.UploadObjectFromFilePathAsync(Utils.S3BucketName, RFA_TEMPLATE, rftPath, null);
        }
Esempio n. 27
0
        public static void SendSMS(Letter letter)
        {
            var awsCredentials = new Amazon.Runtime.BasicAWSCredentials(Env.ACESS_KEY, Env.PRIVATE_KEY);
            AmazonSimpleNotificationServiceClient snsClient = new AmazonSimpleNotificationServiceClient(awsCredentials, Amazon.RegionEndpoint.USWest2);
            PublishRequest pubRequest = new PublishRequest();

            pubRequest.Message     = letter.Message;
            pubRequest.PhoneNumber = letter.Phone; //+1XXX5550100
            // add optional MessageAttributes, for example:
            //   pubRequest.MessageAttributes.Add("AWS.SNS.SMS.SenderID", new MessageAttributeValue
            //      { StringValue = "SenderId", DataType = "String" });
            Task <PublishResponse> pubResponse = snsClient.PublishAsync(pubRequest);

            Task.WaitAll(pubResponse);
            Console.WriteLine("All Fine");
        }
Esempio n. 28
0
        static Task <Amazon.S3.Model.PutObjectResponse> UploadToS3(CompatibilitySummary summary)
        {
            var awsAccessKey = Environment.GetEnvironmentVariable("ps_aws_access_key");
            var awsSecretKey = Environment.GetEnvironmentVariable("ps_aws_secret_key");
            var creds        = new Amazon.Runtime.BasicAWSCredentials(awsAccessKey, awsSecretKey);
            var client       = new AmazonS3Client(creds, Amazon.RegionEndpoint.USWest2);
            var summaryBody  = JsonConvert.SerializeObject(summary);
            var putRequest   = new Amazon.S3.Model.PutObjectRequest
            {
                BucketName  = "playcompatibility",
                Key         = "compat_summary.json",
                ContentBody = summaryBody
            };

            return(client.PutObjectAsync(putRequest));
        }
        private CognitoService()
        {
            cognitoRestApi = RestService.For <ICognitoRestApi>(new HttpClient(new HttpLoggingHandler())
            {
                BaseAddress = new Uri(Configurations.Cognito.CognitoUrl)
            });

            awsRestApi = RestService.For <IAWSRestApi>(new HttpClient(new HttpLoggingHandler())
            {
                BaseAddress = new Uri(Configurations.Cognito.AWSRestUrl)
            });

            var awsCredentials = new Amazon.Runtime.BasicAWSCredentials(Configurations.Cognito.CognitoKey, Configurations.Cognito.CognitoSecret);

            provider = new AmazonCognitoIdentityProviderClient(awsCredentials, RegionEndpoint.GetBySystemName(Configurations.Cognito.CognitoRegion));
        }
Esempio n. 30
0
        /// <summary>
        /// translates the text input
        /// </summary>
        /// <param name="sourceLang"></param>
        /// <param name="targetLang"></param>
        /// <param name="textToTranslate"></param>
        /// <param name="categoryId"></param>
        /// <param name="format"></param>
        /// <returns></returns>
        internal string Translate(string sourceLang, string targetLang, string textToTranslate)
        {
            //convert our language codes
            var sourceLc = convertLangCode(sourceLang);
            var targetLc = convertLangCode(targetLang);


            var translatedText = string.Empty;


            Amazon.Runtime.AWSCredentials awsCreds  = null;
            Amazon.RegionEndpoint         awsRegion = null;


            if (_options.SelectedAuthType == MtTranslationOptions.AWSAuthType.Profile)
            {
                var credentialsFile = new SharedCredentialsFile();                                                        //TODO: always SharedCredentialsFile?
                var prof            = credentialsFile.TryGetProfile(_options.ProfileName, out CredentialProfile profile); //TODO: add in error-handling
                awsCreds  = profile.GetAWSCredentials(credentialsFile);
                awsRegion = profile.Region;
            }
            else
            {
                awsCreds  = new Amazon.Runtime.BasicAWSCredentials(_accessKey, _secretKey);
                awsRegion = Amazon.RegionEndpoint.GetBySystemName(_options.RegionName);
            }

            var tclient  = new AmazonTranslateClient(awsCreds, awsRegion);
            var trequest = new TranslateTextRequest();

            trequest.SourceLanguageCode = sourceLc;
            trequest.TargetLanguageCode = targetLc;
            trequest.Text = textToTranslate;
            try
            {
                var result = tclient.TranslateText(trequest);
                System.Diagnostics.Debug.WriteLine(result.TranslatedText);
                translatedText = result.TranslatedText;
            }
            catch (Amazon.Translate.AmazonTranslateException e)
            {
                System.Diagnostics.Debug.WriteLine(e.Message);
                throw e;
            }
            return(translatedText);
        }
        /// <summary>
        /// Send the email message
        /// </summary>
        /// <param name="messageBody">the body text to include in the mail</param>
        protected virtual void SendEmail(string messageBody)
        {
            // Create the email object first, then add the properties.
            var subject = new Content(Subject);
            Body body = new Body();
            if (IsBodyHTML)
            {
                body.Html = new Content(messageBody);
            }
            else
            {
                body.Text = new Content(messageBody);
            }

            var destination = new Destination();
            var msg = new Message(subject, body);
            destination.ToAddresses = m_to.Split(ADDRESS_DELIMITERS).ToList();
            if (!String.IsNullOrWhiteSpace(m_cc))
            {
                destination.CcAddresses = m_cc.Split(ADDRESS_DELIMITERS).ToList();
            }
            if (!String.IsNullOrWhiteSpace(m_bcc))
            {
                destination.BccAddresses = m_bcc.Split(ADDRESS_DELIMITERS).ToList();
            }

            var request = new SendEmailRequest(From, destination, msg);
            var credentials = new Amazon.Runtime.BasicAWSCredentials(AccessKey, SecretKey);
            var client = new AmazonSimpleEmailServiceClient(credentials, Amazon.RegionEndpoint.EUWest1);

            try
            {
                client.SendEmailAsync(request);
            }
            catch (Exception ex)
            {
                ErrorHandler.Error("Error occurred while sending e-mail notification.", ex);
            }
        }