Abstract class that represents a credentials object for AWS services.
        static void WriteToQueue(AWSCredentials credentials)
        {
            AmazonSQSClient client = new AmazonSQSClient(credentials, RegionEndpoint.USEast1);

            string message = "my message";
            string queueUrl = "https://sqs.us-east-1.amazonaws.com/025631894481/aws-talk";

            SendMessageResponse sendMessageResponse = client.SendMessage(queueUrl, message);
        }
Esempio n. 2
0
        /// <summary>
        /// Generate a presigned URL based on a <see cref="SynthesizeSpeechRequest"/>.
        /// </summary>
        /// <param name="credentials">The credentials to use in the presigned URL.</param>
        /// <param name="region">The region for the URL.</param>
        /// <param name="request">The request to base the presigned URL on.</param>
        /// <returns></returns>
        public static string GeneratePresignedUrl(AWSCredentials credentials, RegionEndpoint region, SynthesizeSpeechRequest request)
        {
            if (credentials == null)
                throw new ArgumentNullException("credentials");

            if (region == null)
                throw new ArgumentNullException("region");

            if (request == null)
                throw new ArgumentNullException("request");

            // Marshall this request and prepare it to be signed
            var marshaller = new SynthesizeSpeechRequestMarshaller();
            var iRequest = marshaller.Marshall(request);
            iRequest.UseQueryString = true;
            iRequest.HttpMethod = HTTPGet;
            iRequest.Endpoint = new UriBuilder(HTTPS, region.GetEndpointForService(PollyServiceName).Hostname).Uri;
            iRequest.Parameters[XAmzExpires] = ((int)FifteenMinutes.TotalSeconds).ToString(CultureInfo.InvariantCulture);

            if (request.IsSetLexiconNames())
            {
                var sortedLexiconNames = new List<string>(request.LexiconNames);
                sortedLexiconNames.Sort(StringComparer.Ordinal);
                iRequest.Parameters[LexiconNamesParameter] = JsonMapper.ToJson(sortedLexiconNames);
            }

            if (request.IsSetOutputFormat())
                iRequest.Parameters["OutputFormat"] = request.OutputFormat.ToString();

            if (request.IsSetSampleRate())
                iRequest.Parameters["SampleRate"] = request.SampleRate.ToString();

            if (request.IsSetText())
                iRequest.Parameters["Text"] = request.Text;

            if (request.IsSetTextType())
                iRequest.Parameters["TextType"] = request.TextType.ToString();

            if (request.IsSetVoiceId())
                iRequest.Parameters["VoiceId"] = request.VoiceId;

            var immutableCredentials = credentials.GetCredentials();
            if (immutableCredentials.UseToken)
            {
                // Don't use HeaderKeys.XAmzSecurityTokenHeader because Polly treats this as case-sensitive
                iRequest.Parameters["X-Amz-Security-Token"] = immutableCredentials.Token;
            }

            // Only the host header should be signed, and the signer adds that.
            // So clear out headers.
            iRequest.Headers.Clear();

            // Create presigned URL and assign it
            var signingResult = SynthesizeSpeechPresignedUrlSigner.SignSynthesizeSpeechRequest(iRequest, new RequestMetrics(),
                immutableCredentials.AccessKey, immutableCredentials.SecretKey, PollyServiceName, region.SystemName);

            var authorization = "&" + signingResult.ForQueryParameters;

            return ComposeUrl(iRequest).AbsoluteUri + authorization;
        }
        public FoundationTemplateUtil(Amazon.Runtime.AWSCredentials credentials)
        {
            //IAmazonCloudFormation stackbuilder = new AmazonCloudFormationClient(credentials);

            IAmazonCloudFormation stackbuilder = new AmazonCloudFormationClient();

            AmazonCloudFormationRequest request = new DescribeStacksRequest();

            var response = stackbuilder.DescribeStacks(new DescribeStacksRequest());

            foreach (var stack in response.Stacks)
            {
                Console.WriteLine("Stack: {0}", stack.StackName);
                Console.WriteLine("  Status: {0}", stack.StackStatus);
                Console.WriteLine("  Created: {0}", stack.CreationTime);

                var ps = stack.Parameters;

                if (ps.Any())
                {
                    Console.WriteLine("  Parameters:");

                    foreach (var p in ps)
                    {
                        Console.WriteLine("    {0} = {1}",
                                          p.ParameterKey, p.ParameterValue);
                    }
                }
            }

            //AWSRegion euWest1 = AWSRegion.SetRegionFromName(RegionEndpoint.EUWest1);

            Console.WriteLine("===========================================");
            Console.WriteLine("Getting Started with AWS CloudFormation");
            Console.WriteLine("===========================================\n");

            String stackName           = "CloudFormationSampleStack";
            String logicalResourceName = "SampleNotificationTopic";

            //C:\Bitbucket\Analytics\MetaDataStore\F2B\main-bastion-json.template\main-bastion-json.template
            try
            {
                // Create a stack
                CreateStackRequest createRequest = new CreateStackRequest();
                createRequest.StackName = stackName;
                //createRequest.StackPolicyBody = ;
                //createRequest.
                //Clou
                //createRequest.StackPolicyBody = convertStreamToString(CloudFormationSample.class.getResourceAsStream("CloudFormationSample.template"));
                //Console.WriteLine("Creating a stack called " + createRequest.getStackName() + ".");
                //stackbuilder.createStack(createRequest);

                //// Wait for stack to be created
                //// Note that you could use SNS notifications on the CreateStack call to track the progress of the stack creation
                //Console.WriteLine("Stack creation completed, the stack " + stackName + " completed with " + waitForCompletion(stackbuilder, stackName);
            }
            catch
            {
            }
        }
Esempio n. 4
0
        /// <summary>
        /// Constructor of <see cref="Amazon.MobileAnalytics.MobileAnalyticsManager.Internal.DeliveryClient"/> class.
        /// </summary>
        /// <param name="policyFactory">An instance of IDeliveryPolicyFactory. <see cref="Amazon.MobileAnalytics.MobileAnalyticsManager.Internal.IDeliveryPolicyFactory"/></param>
        /// <param name="maConfig">Mobile Analytics Manager configuration. <see cref="Amazon.MobileAnalytics.MobileAnalyticsManager.MobileAnalyticsManagerConfig"/></param>
        /// <param name="clientContext">An instance of ClientContext. <see cref="Amazon.Runtime.Internal.ClientContext"/></param>
        /// <param name="credentials">An instance of Credentials. <see cref="Amazon.Runtime.AWSCredentials"/></param>
        /// <param name="regionEndPoint">Region endpoint. <see cref="Amazon.RegionEndpoint"/></param>
        public DeliveryClient(IDeliveryPolicyFactory policyFactory, MobileAnalyticsManagerConfig maConfig, ClientContext clientContext, AWSCredentials credentials, RegionEndpoint regionEndPoint)
        {
            _policyFactory = policyFactory;
            _deliveryPolicies = new List<IDeliveryPolicy>();
            _deliveryPolicies.Add(_policyFactory.NewConnectivityPolicy());

            _clientContext = clientContext;
            _appID = clientContext.AppID;
            _maConfig = maConfig;
            _eventStore = new SQLiteEventStore(maConfig);

#if PCL
            _mobileAnalyticsLowLevelClient = new AmazonMobileAnalyticsClient(credentials, regionEndPoint);
#elif BCL
            if (null == credentials && null == regionEndPoint)
            {
                _mobileAnalyticsLowLevelClient = new AmazonMobileAnalyticsClient();
            }
            else if (null == credentials)
            {
                _mobileAnalyticsLowLevelClient = new AmazonMobileAnalyticsClient(regionEndPoint);
            }
            else if (null == regionEndPoint)
            {
                _mobileAnalyticsLowLevelClient = new AmazonMobileAnalyticsClient(credentials);
            }
            else
            {
                _mobileAnalyticsLowLevelClient = new AmazonMobileAnalyticsClient(credentials, regionEndPoint);
            }
#endif
        }
Esempio n. 5
0
        internal S3ClientCache(AWSCredentials credentials, AmazonS3Config config)
        {
            this.credentials = credentials;
            this.config = config;

            this.clientsByRegion = new Dictionary<string,AmazonS3Client>(StringComparer.OrdinalIgnoreCase);
            this.transferUtilitiesByRegion = new Dictionary<string,TransferUtility>(StringComparer.OrdinalIgnoreCase);
        }
 public IntegrationAwsClientFactory()
 {
     var ci = System.Environment.GetEnvironmentVariable(_ci);
     if (string.IsNullOrWhiteSpace(ci))
         this._credentials = new StoredProfileAWSCredentials(IntegrationTestConfig.AwsProfileName);
     else
         _credentials = CredentialsFromEnvironment();
 }
        /// <summary>
        /// Gets or creates Mobile Analytics Manager instance. If the instance already exists, returns the instance; otherwise
        /// creates new instance and returns it.
        /// </summary>
        /// <param name="appID">Amazon Mobile Analytics Application ID.</param>
        /// <param name="credentials">AWS Credentials.</param>
        /// <returns>Mobile Analytics Manager instance. </returns>
        public static MobileAnalyticsManager GetOrCreateInstance(string appID, AWSCredentials credentials)
        {
            if (string.IsNullOrEmpty(appID))
                throw new ArgumentNullException("appID");
            if (null == credentials)
                throw new ArgumentNullException("credentials");

            return GetOrCreateInstanceHelper(appID, credentials, null, null);
        }
        public static MobileAnalyticsManager GetOrCreateInstance(AWSCredentials credential,
                                                                 string appId)
        {
            if (credential == null)
                throw new ArgumentNullException("credential");
            if (string.IsNullOrEmpty(appId))
                throw new ArgumentNullException("appId");

            return MobileAnalyticsManager.GetOrCreateInstanceHelper(appId, credential, null);
        }
Esempio n. 9
0
 /// <summary>
 /// Constructor of <see cref="Amazon.MobileAnalytics.MobileAnalyticsManager.DeliveryClient"/> class.
 /// </summary>
 /// <param name="isDataAllowed">An instance of IDeliveryPolicyFactory <see cref="Amazon.MobileAnalytics.MobileAnalyticsManager.Internal.IDeliveryPolicyFactory"/></param>
 /// <param name="clientContext">An instance of ClientContext <see cref="Amazon.MobileAnalytics.MobileAnalyticsManager.Internal.ClientContext"/></param>
 /// <param name="credentials">An instance of Credentials <see cref="Amazon.Runtime.AWSCredentials"/></param>
 /// <param name="regionEndPoint">Region end point <see cref="Amazon.RegionEndpoint"/></param>
 public DeliveryClient(IDeliveryPolicyFactory policyFactory, ClientContext clientContext, AWSCredentials credentials, RegionEndpoint regionEndPoint)
 {
     _policyFactory = policyFactory;
     _mobileAnalyticsLowLevelClient = new AmazonMobileAnalyticsClient(credentials, regionEndPoint);
     _clientContext = clientContext;
     _appId = clientContext.Config.AppId;
     _eventStore = new SQLiteEventStore(AWSConfigsMobileAnalytics.MaxDBSize, AWSConfigsMobileAnalytics.DBWarningThreshold);
     _deliveryPolicies = new List<IDeliveryPolicy>();
     _deliveryPolicies.Add(_policyFactory.NewConnectivityPolicy());
     _deliveryPolicies.Add(_policyFactory.NewBackgroundSubmissionPolicy());
 }
        /// <summary>
        /// Gets the or creates Mobile Analytics Manager instance. If the instance already exists, returns the instance; otherwise
        /// creates new instance and returns it.
        /// </summary>
        /// <returns>Mobile Analytics Manager instance.</returns>
        /// <param name="credentials">AWS Credentials.</param>
        /// <param name="appId">Amazon Mobile Analytics Application ID.</param>
        public static MobileAnalyticsManager GetOrCreateInstance(AWSCredentials credential,
                                                                         string appId)
        {
            if (credential == null)
                throw new ArgumentNullException("credential");
            if (string.IsNullOrEmpty(appId))
                throw new ArgumentNullException("appId");

            ClientContextConfig config = new ClientContextConfig(appId);
            return MobileAnalyticsManager.GetOrCreateInstance(credential, null, config);
        }
Esempio n. 11
0
 /// <summary>
 /// Deletes the image file artifacts associated with the specified conversion task.
 /// If the task is still active, ignoreActiveTask must be set true to enable artifact
 /// deletion, which will cause the task to fail. Use this option at your own risk.
 /// </summary>
 /// <param name="awsCredentials">
 /// Credentials to use to instantiate the Amazon EC2 and Amazon S3 clients needed to
 /// complete the operation.
 /// </param>
 /// <param name="region">
 /// The region containing the bucket where the image file artifacts were stored
 /// </param>
 /// <param name="conversionTaskId">
 /// The ID of the conversion task that used the image file
 /// </param>
 /// <param name="ignoreActiveTask">
 /// If true the artifacts are deleted even if the conversion task is still in progress
 /// </param>
 /// <param name="progressCallback">Optional progress callback</param>
 public static void DeleteImageArtifacts(AWSCredentials awsCredentials, 
                                         RegionEndpoint region, 
                                         string conversionTaskId, 
                                         bool ignoreActiveTask,
                                         CleanupProgressCallback progressCallback)
 {
     DeleteImageArtifacts(new AmazonEC2Client(awsCredentials, region), 
                          new AmazonS3Client(awsCredentials, region), 
                          conversionTaskId, 
                          ignoreActiveTask,
                          progressCallback);                        
 }
Esempio n. 12
0
        public AwsClient(AWSCredentials credentials, IStackItConfiguration configuration)
        {
            _credentials = credentials;

            _cloudFormationClient = new Lazy<IAmazonCloudFormation>(() => AWSClientFactory.CreateAmazonCloudFormationClient(_credentials));
            _ec2Client = new Lazy<IAmazonEC2>(() => AWSClientFactory.CreateAmazonEC2Client(_credentials));
            _route53Client = new Lazy<IAmazonRoute53>(() => AWSClientFactory.CreateAmazonRoute53Client(_credentials));
            _s3Client = new Lazy<IAmazonS3>(() => AWSClientFactory.CreateAmazonS3Client(_credentials));
            _iamClient = new Lazy<IAmazonIdentityManagementService>(() => AWSClientFactory.CreateAmazonIdentityManagementServiceClient(_credentials));

            _configuration = configuration;
        }
Esempio n. 13
0
 /// <summary>
 /// Deletes the image file artifacts associated with the specified conversion task.
 /// If the task is still active, ignoreActiveTask must be set true to enable artifact
 /// deletion, which will cause the task to fail. Use this option at your own risk.
 /// </summary>
 /// <param name="awsCredentials">
 /// Credentials to use to instantiate the Amazon EC2 and Amazon S3 clients needed to
 /// complete the operation.
 /// </param>
 /// <param name="region">
 /// The region containing the bucket where the image file artifacts were stored
 /// </param>
 /// <param name="conversionTaskId">
 /// The ID of the conversion task that used the image file
 /// </param>
 /// <param name="ignoreActiveTask">
 /// If true the artifacts are deleted even if the conversion task is still in progress
 /// </param>
 /// <param name="progressCallback">Optional progress callback</param>
 public static void DeleteImageArtifacts(AWSCredentials awsCredentials, 
                                         RegionEndpoint region, 
                                         string conversionTaskId, 
                                         bool ignoreActiveTask,
                                         CleanupProgressCallback progressCallback)
 {
     DeleteImageArtifacts(new AmazonEC2Client(awsCredentials, region),
                          ServiceClientHelpers.CreateServiceFromAssembly<ICoreAmazonS3>(ServiceClientHelpers.S3_ASSEMBLY_NAME, ServiceClientHelpers.S3_SERVICE_CLASS_NAME, awsCredentials, region),
                          conversionTaskId, 
                          ignoreActiveTask,
                          progressCallback);                        
 }
        /// <summary>
        /// Gets or creates Mobile Analytics Manager instance. If the instance already exists, returns the instance; otherwise
        /// creates new instance and returns it.
        /// </summary>
        /// <param name="appID">Amazon Mobile Analytics Application ID.</param>
        /// <param name="credentials">AWS Credentials.</param>
        /// <param name="regionEndpoint">Region endpoint.</param>
        /// <returns>Mobile Analytics Manager instance.</returns>
        public static MobileAnalyticsManager GetOrCreateInstance(string appID, AWSCredentials credentials, RegionEndpoint regionEndpoint)
        {
            if (string.IsNullOrEmpty(appID))
                throw new ArgumentNullException("appID");
            if (null == credentials)
                throw new ArgumentNullException("credentials");
            if (null == regionEndpoint)
                throw new ArgumentNullException("regionEndpoint");

            MobileAnalyticsManagerConfig maConfig = new MobileAnalyticsManagerConfig();
            return GetOrCreateInstanceHelper(appID, credentials, regionEndpoint, maConfig);
        }
Esempio n. 15
0
 /// <summary>
 /// Constructor of <see cref="Amazon.MobileAnalytics.MobileAnalyticsManager.Internal.DeliveryClient"/> class.
 /// </summary>
 /// <param name="policyFactory">An instance of IDeliveryPolicyFactory <see cref="Amazon.MobileAnalytics.MobileAnalyticsManager.Internal.IDeliveryPolicyFactory"/></param>
 /// <param name="maConfig"></param>
 /// <param name="maManager"></param>
 /// <param name="clientContext">An instance of ClientContext <see cref="Amazon.Runtime.Internal.ClientContext"/></param>
 /// <param name="credentials">An instance of Credentials <see cref="Amazon.Runtime.AWSCredentials"/></param>
 /// <param name="regionEndPoint">Region end point <see cref="Amazon.RegionEndpoint"/></param>
 public DeliveryClient(IDeliveryPolicyFactory policyFactory, MobileAnalyticsManagerConfig maConfig, ClientContext clientContext, AWSCredentials credentials, RegionEndpoint regionEndPoint, MobileAnalyticsManager maManager)
 {
     _policyFactory = policyFactory;
     _mobileAnalyticsLowLevelClient = new AmazonMobileAnalyticsClient(credentials, regionEndPoint);
     _clientContext = clientContext;
     _appID = clientContext.AppID;
     _maConfig = maConfig;
     _maManager = maManager;
     _eventStore = new SQLiteEventStore(maConfig);
     _deliveryPolicies = new List<IDeliveryPolicy>();
     _deliveryPolicies.Add(_policyFactory.NewConnectivityPolicy());
 }
Esempio n. 16
0
        public AwsClient()
        {
            this.key = ConfigurationManager.AppSettings["AWSKey"];
            this.secret = ConfigurationManager.AppSettings["AWSSecret"];

            if (string.IsNullOrEmpty(this.key))
                throw new ArgumentNullException("key", "Missing AWSKey appSettings entry.");

            if (string.IsNullOrEmpty(this.secret))
                throw new ArgumentNullException("secret", "Missing AWSSecret appSettings entry.");

            this.credentials = new BasicAWSCredentials(this.key, this.secret);
        }
Esempio n. 17
0
        public static AmazonS3Client GetApi(AWSCredentials credentials, RegionEndpoint region)
        {
            if (credentials == null) throw new ArgumentNullException("credentials");
            if (region == null) throw new ArgumentNullException("region");

            var config = new AmazonS3Config
            {
                RegionEndpoint = region,
            };

            ApplyProxy(config);

            var api = new AmazonS3Client(credentials, config);
            return api;
        }
Esempio n. 18
0
        static void ReadFromQueue(AWSCredentials credentials)
        {
            AmazonSQSClient client = new AmazonSQSClient(credentials, RegionEndpoint.USEast1);

            string queueUrl = "https://sqs.us-east-1.amazonaws.com/025631894481/aws-talk";

            ReceiveMessageRequest request = new ReceiveMessageRequest(queueUrl);
            request.MaxNumberOfMessages = 1;
            ReceiveMessageResponse response = client.ReceiveMessage(request);

            foreach (var message in response.Messages)
            {
                // Do something with the message
            }
        }
Esempio n. 19
0
        static void GetInstances(AWSCredentials credentials)
        {
            IAmazonEC2 client = AWSClientFactory.CreateAmazonEC2Client(credentials, RegionEndpoint.USEast1);

            DescribeInstancesRequest request = new DescribeInstancesRequest();
            request.Filters.Add(new Filter("instance-state-code", new List<string>() { "0", "16" }));

            DescribeInstancesResponse describeInstancesResponse = client.DescribeInstances();
            List<Reservation> reservations = describeInstancesResponse.Reservations;

            foreach (Instance instance in reservations.SelectMany(x => x.Instances))
            {
                Console.WriteLine("Instance with ID {0} is currently {1}", instance.InstanceId, instance.State.Name);
            }
        }
Esempio n. 20
0
        static void WriteToSimpleDb(AWSCredentials credentials)
        {
            var client = new AmazonSimpleDBClient(credentials, RegionEndpoint.USEast1);

            var request = new CreateDomainRequest("aws-talk");
            var response = client.CreateDomain(request);

            var putData = new PutAttributesRequest("aws-talk", "products/" + Guid.NewGuid().ToString(),
                new List<ReplaceableAttribute>()
                {
                    new ReplaceableAttribute("Name", "Couch", true),
                    new ReplaceableAttribute("Price", "20", true)
                });
            client.PutAttributes(putData);
        }
        /// <summary>
        ///  Given a policy and AWS credentials, produce a S3PostUploadSignedPolicy.
        /// </summary>
        /// <param name="policy">JSON string representing the policy to sign</param>
        /// <param name="credentials">Credentials to sign the policy with</param>
        /// <returns></returns>
        public static S3PostUploadSignedPolicy GetSignedPolicy(string policy, AWSCredentials credentials)
        {
            var policyBytes = Encoding.UTF8.GetBytes(policy.Trim());
            var base64Policy = Convert.ToBase64String(policyBytes);
            
            string signature = null;

            signature = CryptoUtilFactory.CryptoInstance.HMACSign(Encoding.UTF8.GetBytes(base64Policy), credentials.GetCredentials().SecretKey, SigningAlgorithm.HmacSHA1);

            return new S3PostUploadSignedPolicy
            {
                Policy = base64Policy,
                Signature = signature,
                AccessKeyId = credentials.GetCredentials().AccessKey
            };
        }
Esempio n. 22
0
 /// <summary>
 ///  Given a policy and AWS credentials, produce a S3PostUploadSignedPolicy.
 /// </summary>
 /// <param name="policy">JSON string representing the policy to sign</param>
 /// <param name="credentials">Credentials to sign the policy with</param>
 /// <returns>A signed policy object for use with an S3PostUploadRequest.</returns>
 public static S3PostUploadSignedPolicy GetSignedPolicy(string policy, AWSCredentials credentials)
 {
     ImmutableCredentials iCreds = credentials.GetCredentials();
     var policyBytes = iCreds.UseToken
         ? addTokenToPolicy(policy, iCreds.Token)
         : Encoding.UTF8.GetBytes(policy.Trim());
     var base64Policy = Convert.ToBase64String(policyBytes);
     string signature = CryptoUtilFactory.CryptoInstance.HMACSign(Encoding.UTF8.GetBytes(base64Policy), iCreds.SecretKey, SigningAlgorithm.HmacSHA1);
     return new S3PostUploadSignedPolicy
     {
         Policy = base64Policy,
         Signature = signature,
         AccessKeyId = iCreds.AccessKey,
         SecurityToken = iCreds.Token,
         SignatureVersion = "2"
     };
 }
Esempio n. 23
0
        public FDGlacier(FDUserSettings settings, FDOperationLog oplog, string optype)
        {
            this.vaultName = settings.AWSGlacierVaultName;
            log = oplog;

            switch (settings.AWSRegion) {
            case FDUserSettings.AWSRegionIndex.USWest1:
                region = RegionEndpoint.USWest1;
                break;
            case FDUserSettings.AWSRegionIndex.USWest2:
                region = RegionEndpoint.USWest2;
                break;
            case FDUserSettings.AWSRegionIndex.USEast1:
                region = RegionEndpoint.USEast1;
                break;
            case FDUserSettings.AWSRegionIndex.EUWest1:
                region = RegionEndpoint.EUWest1;
                break;
            case FDUserSettings.AWSRegionIndex.APNortheast1:
                region = RegionEndpoint.APNortheast1;
                break;
            default:
                region = RegionEndpoint.USEast1;
                break;
            }

            //Instantiate the glacier config with our settins (for future move to AmazonGlacierClient)
            glacierConfig = new AmazonGlacierConfig();
            glacierConfig.RegionEndpoint = region;

            //Instantiate AWS Credentials
            awsCredentials = new BasicAWSCredentials(settings.AWSAccessKey, settings.AWSSecretKey);

            //Instantiate the transfer manager with our settings
            //TODO: Switch to glacier client so we can abort this damn thing
            //glacierClient = new AmazonGlacierClient(appConfig["AWSAccessKey"], appConfig["AWSSecretKey"], region);
            transferManager = new ArchiveTransferManager(awsCredentials, region);

            upOptions = new UploadOptions();
            downOptions = new DownloadOptions();
            progress = 0;
            upOptions.StreamTransferProgress = downOptions.StreamTransferProgress = this.onProgress;

            OperationType = optype;
        }
Esempio n. 24
0
        /// <summary>
        /// Creates the service client using the credentials and client config.
        /// </summary>
        /// <param name="credentials"></param>
        /// <param name="config"></param>
        /// <returns></returns>
        private static AmazonServiceClient CreateClient(Type serviceInterfaceType, AWSCredentials credentials, ClientConfig config)
        {
            var clientTypeName = serviceInterfaceType.Namespace + "." + serviceInterfaceType.Name.Substring(1) + "Client";
            var clientType = serviceInterfaceType.GetTypeInfo().Assembly.GetType(clientTypeName);
            if (clientType == null)
            {
                throw new AmazonClientException($"Failed to find service client {clientTypeName} which implements {serviceInterfaceType.FullName}.");
            }

            var constructor = clientType.GetConstructor(new Type[] { typeof(AWSCredentials), config.GetType() });
            if (constructor == null)
            {
                throw new AmazonClientException($"Service client {clientTypeName} misisng a constructor with parameters AWSCredentials and {config.GetType().FullName}.");
            }

            var client = constructor.Invoke(new object[] { credentials, config }) as AmazonServiceClient;
            return client;
        }
Esempio n. 25
0
        static NoSQLCredential()
        {
            XmlDocument xmldoc = new XmlDocument();
            xmldoc.Load(@".\Credentials.xml");

            try
            {
                var attributes = xmldoc.GetElementsByTagName("Azure")[0].Attributes;
                _azureAccount = CloudStorageAccount.Parse("DefaultEndpointsProtocol=https;AccountName=" + attributes["AccountName"].Value + ";AccountKey=" + attributes["AccountKey"].Value);
            }
            catch { _azureAccount = null; }

            try
            {
                var attributes = xmldoc.GetElementsByTagName("AWS")[0].Attributes;
                _awsAccount = new BasicAWSCredentials(attributes["AccessKey"].Value, attributes["SecretKey"].Value);
            }
            catch { _awsAccount = null; }
        }
Esempio n. 26
0
        /// <summary>
        ///  Given a policy and AWS credentials, produce a S3PostUploadSignedPolicy.
        /// </summary>
        /// <param name="policy">JSON string representing the policy to sign</param>
        /// <param name="credentials">Credentials to sign the policy with</param>
        /// <param name="region">Service region endpoint.</param>
        /// <returns>A signed policy object for use with an S3PostUploadRequest.</returns>
        public static S3PostUploadSignedPolicy GetSignedPolicyV4(string policy, AWSCredentials credentials, RegionEndpoint region)
        {
            var signedAt = AWSSDKUtils.CorrectedUtcNow;

            ImmutableCredentials iCreds = credentials.GetCredentials();
            var algorithm = "AWS4-HMAC-SHA256";
            var dateStamp = Runtime.Internal.Auth.AWS4Signer.FormatDateTime(signedAt, AWSSDKUtils.ISO8601BasicDateFormat);
            var dateTimeStamp = Runtime.Internal.Auth.AWS4Signer.FormatDateTime(signedAt, AWSSDKUtils.ISO8601BasicDateTimeFormat);
            var credentialString = string.Format(CultureInfo.InvariantCulture, "{0}/{1}/{2}/{3}/{4}/", iCreds.AccessKey, dateStamp, region.SystemName, "s3", Runtime.Internal.Auth.AWS4Signer.Terminator);

            Dictionary<string, string> extraConditions = new Dictionary<string, string> {
                { S3Constants.PostFormDataXAmzCredential, credentialString },
                { S3Constants.PostFormDataXAmzAlgorithm, algorithm },
                { S3Constants.PostFormDataXAmzDate, dateTimeStamp }
            };
            if (iCreds.UseToken) { extraConditions[S3Constants.PostFormDataSecurityToken] = iCreds.Token; }

            var policyBytes = addConditionsToPolicy(policy, extraConditions);

            var base64Policy = Convert.ToBase64String(policyBytes);

            var signingKey = Runtime.Internal.Auth.AWS4Signer.ComposeSigningKey(iCreds.SecretKey, region.SystemName, dateStamp, "s3");

            var signature = AWSSDKUtils.ToHex(Runtime.Internal.Auth.AWS4Signer.ComputeKeyedHash(SigningAlgorithm.HmacSHA256, signingKey, base64Policy), true);

            return new S3PostUploadSignedPolicy
            {
                Policy = base64Policy,
                Signature = signature,
                AccessKeyId = iCreds.AccessKey,
                SecurityToken = iCreds.Token,
                SignatureVersion = "4",
                Algorithm = algorithm,
                Date = dateTimeStamp,
                Credential = credentialString
            };
        }
 /// <summary>
 /// Constructs AmazonSecurityTokenServiceClient with AWS Credentials and an
 /// AmazonSecurityTokenServiceClient Configuration object.
 /// </summary>
 /// <param name="credentials">AWS Credentials</param>
 /// <param name="clientConfig">The AmazonSecurityTokenServiceClient Configuration Object</param>
 public AmazonSecurityTokenServiceClient(AWSCredentials credentials, AmazonSecurityTokenServiceConfig clientConfig)
     : base(credentials, clientConfig)
 {
 }
 /// <summary>
 /// Constructs AmazonSecurityTokenServiceClient with AWS Credentials
 /// </summary>
 /// <param name="credentials">AWS Credentials</param>
 /// <param name="region">The region to connect.</param>
 public AmazonSecurityTokenServiceClient(AWSCredentials credentials, RegionEndpoint region)
     : this(credentials, new AmazonSecurityTokenServiceConfig{RegionEndpoint = region})
 {
 }
 /// <summary>
 /// Constructs AmazonSecurityTokenServiceClient with AWS Credentials
 /// </summary>
 /// <param name="credentials">AWS Credentials</param>
 public AmazonSecurityTokenServiceClient(AWSCredentials credentials)
     : this(credentials, new AmazonSecurityTokenServiceConfig())
 {
 }
 /// <summary>
 /// Constructs AmazonRoute53Client with AWS Credentials and an
 /// AmazonRoute53Client Configuration object.
 /// </summary>
 /// <param name="credentials">AWS Credentials</param>
 /// <param name="clientConfig">The AmazonRoute53Client Configuration Object</param>
 public AmazonRoute53Client(AWSCredentials credentials, AmazonRoute53Config clientConfig)
     : base(credentials, clientConfig, AuthenticationTypes.User | AuthenticationTypes.Session)
 {
 }
 public Ec2Caller(ICredentialsRetriever credentialsRetriever, string amiName, string securityGroupName, string keyPairName)
 {
     this.amiName = amiName;
     this.securityGroupName = securityGroupName;
     this.keyPairName = keyPairName;
     credentials = credentialsRetriever.GetCredentials();
 }