/** * This method reads the key specified in PollyProperties and sets it as the new AWS profile. * At the moment, the region is always set to EU which is something you might want to care for. * Except for setting up the account, it is not used or verified at this point. * The method only fails if there is something wrong with the KeyFile. */ private void SetAwsProfile(PollyProperties pollyProps) { // Read the Credentials and store them shortly in an array var path = pollyProps.ApiKey; var credentialFile = new Dictionary <string, string>(); foreach (var row in File.ReadAllLines(path)) { credentialFile.Add(row.Split('=')[0], string.Join("=", row.Split('=').Skip(1).ToArray())); } // Create Amazon Credentials var options = new CredentialProfileOptions { AccessKey = credentialFile["AWSAccessKeyId"], SecretKey = credentialFile["AWSSecretKey"] }; // Make Amazon Credential profile var profile = new Amazon.Runtime.CredentialManagement.CredentialProfile("polly_profile", options); profile.Region = RegionEndpoint.EUCentral1; this._awsProfile = profile; }
private void btnCreateProfile_Click(object sender, EventArgs e) { String strProfileName = txtAWSProfileName.Text.Trim(); String strAccessKey = txtAWSAccessKey.Text.Trim(); String strSecretKey = txtAWSSecretKey.Text.Trim(); String strRegionServiceName = GetRegionEndpointServiceName(cboAWSRegions.Text.Trim()); var AmazonRegionEndpoint = RegionEndpoint.GetBySystemName(strRegionServiceName); var AWSProfileOptions = new CredentialProfileOptions { AccessKey = strAccessKey, SecretKey = strSecretKey }; var AWSProfile = new Amazon.Runtime.CredentialManagement.CredentialProfile(strProfileName, AWSProfileOptions); AWSProfile.Region = AmazonRegionEndpoint; //var AWSCredentialsFile = new Amazon.Runtime.CredentialManagement.SharedCredentialsFile(); var netSDKFile = new NetSDKCredentialsFile(); netSDKFile.RegisterProfile(AWSProfile); //refreshed the list of available profiles GetSavedProfiles(); GetProfilesToCleanUp(); //clear Create Profile Fields txtAWSProfileName.Text = ""; txtAWSAccessKey.Text = ""; txtAWSSecretKey.Text = ""; cboAWSRegions.Text = ""; cboAWSRegions.SelectedIndex = -1; btnCreateProfile.Enabled = false; }
public async Task <InvokeResult> InitAsync(DataStream stream) { _stream = stream; var options = new CredentialProfileOptions { AccessKey = stream.AwsAccessKey, SecretKey = stream.AwsSecretKey }; var profile = new Amazon.Runtime.CredentialManagement.CredentialProfile($"awsprofile_{stream.Id}", options); var netSDKFile = new NetSDKCredentialsFile(); netSDKFile.RegisterProfile(profile); var creds = AWSCredentialsFactory.GetAWSCredentials(profile, netSDKFile); try { _s3Client = new AmazonS3Client(creds, AWSRegionMappings.MapRegion(stream.AwsRegion)); await _s3Client.EnsureBucketExistsAsync(stream.S3BucketName); } catch (AmazonS3Exception amazonS3Exception) { _logger.AddException("AWSS3Connector_InitAsync", amazonS3Exception); return(InvokeResult.FromException("AWSS3Connector_InitAsync", amazonS3Exception)); } return(InvokeResult.Success); }
public void Init() { var stream = GetValidStream(); var options = new CredentialProfileOptions { AccessKey = System.Environment.GetEnvironmentVariable("AWSACCESSKEY"), SecretKey = System.Environment.GetEnvironmentVariable("AWSSECRET") }; var profile = new Amazon.Runtime.CredentialManagement.CredentialProfile("basic_profile", options); var netSDKFile = new NetSDKCredentialsFile(); var region = Amazon.RegionEndpoint.GetBySystemName(stream.AwsRegion); var creds = AWSCredentialsFactory.GetAWSCredentials(profile, netSDKFile); var connection = new AwsHttpConnection(creds, region); var pool = new SingleNodeConnectionPool(new Uri(stream.ElasticSearchDomainName)); var config = new Nest.ConnectionSettings(pool, connection); var client = new ElasticClient(config); if (client.Indices.Exists(stream.ElasticSearchIndexName).Exists) { var res = client.Indices.Delete(stream.ElasticSearchIndexName); Console.WriteLine(res.DebugInformation); } }
public static void Main() { var options = new CredentialProfileOptions { AccessKey = "放在rdisk", SecretKey = "放在rdisk" }; var profile = new Amazon.Runtime.CredentialManagement.CredentialProfile("gino355140", options); profile.Region = RegionEndpoint.APNortheast3; //var netSDKFile = new NetSDKCredentialsFile(); //netSDKFile.RegisterProfile(profile); using (var client = new AmazonS3Client(options.AccessKey, options.SecretKey, profile.Region)) { clientS3 = client; var response = client.ListBucketsAsync(); var list = response.Result; //可列出所有Bucket,範例先以自己的做測試 S3Bucket s3Bucket = list.Buckets.Find(x => x.BucketName == bucketName); Console.WriteLine("S3 Start"); Console.WriteLine("---------------------"); //"2021/01/SQL_Test.csv","123.csv" 測試用檔名 string fileName = "2021/02/SQL_Test_big.csv"; string sqlStr = "Select * from S3Object"; //除from S3Object固定外,其餘皆和一般SQL語法相同 //列出bucket and bucket內的東西 DateTime start = new DateTime(2021, 01, 01); //起始時間 DateTime end = new DateTime(2021, 03, 30); //結束時間 List <string> keys = getYearMotnhs(start, end); //時間區間轉字串 foreach (string key in keys) { ListingObjectsAsync(key).Wait(); } Console.WriteLine("---------------------"); //讀取bucket and bucket內的東西 var result = ReadObjectDataAsync(fileName).Result; Console.WriteLine("---------------------"); //讀取bucket內的東西 by sql var result2 = GetSelectObjectContent("2021/01/SQL_Test.csv", sqlStr); Console.WriteLine("---------------------"); //上傳物件,測試前請先看一下上傳內容 //WritingAnObjectAsync().Wait(); Console.WriteLine("---------------------"); Console.WriteLine("S3 End"); } }
internal static void RegisterAWSCredentialProfile(string profileName, string accessKey, string secretKey, string region) { var options = new CredentialProfileOptions { AccessKey = accessKey, SecretKey = secretKey }; var profile = new Amazon.Runtime.CredentialManagement.CredentialProfile(profileName, options); var file = Program.GetCredentialStore(); file.RegisterProfile(profile); }
// dotnet test --filter "FullyQualifiedName=damper_dan_client.tests.AWSTests.UploadToS3Bucket" public void UploadToS3Bucket() { Console.WriteLine("UploadToS3Bucket"); var options = new CredentialProfileOptions { AccessKey = "AKIAJETN6IOF34SLVHTQ", SecretKey = "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" }; var profile = new Amazon.Runtime.CredentialManagement.CredentialProfile("basic_profile", options); profile.Region = RegionEndpoint.USEast1; var netSDKFile = new NetSDKCredentialsFile(); netSDKFile.RegisterProfile(profile); }
/// <summary> /// IMPORTANT: /// This creates an AWS user profile entry in the file located in this /// folder: C:\Users\<username>\AppData\Local\AWSToolkit\RegisteredAccounts.json /// /// See reference at https://docs.aws.amazon.com/sdk-for-net/v3/developer-guide/net-dg-config-creds.html /// /// This is done for expediency, experiment and example purposes. For real production functionality you do /// not want to expose your credentials in this manner. For security and credential file concerns /// see this reference: https://docs.aws.amazon.com/sdk-for-net/v2/developer-guide/net-dg-config-creds.html#creds-assign /// /// </summary> private static void CreateProfile() { var options = new CredentialProfileOptions { AccessKey = "add-user-key-here", SecretKey = "add-user-secret-here" }; var profile = new Amazon.Runtime.CredentialManagement.CredentialProfile("basic_profile", options); profile.Region = awsRegion; var netSDKFile = new NetSDKCredentialsFile(); netSDKFile.RegisterProfile(profile); }
public AWSHelper() { var options = new CredentialProfileOptions { AccessKey = "", SecretKey = "" }; var profile = new Amazon.Runtime.CredentialManagement.CredentialProfile("basic_profile", options); profile.Region = RegionEndpoint.USWest1; var netSDKFile = new NetSDKCredentialsFile(); netSDKFile.RegisterProfile(profile); }
/// <summary> /// Sets credentials for AmazonCloudWatchLogsClient /// </summary> private void ConfigureCredentials() { var options = new CredentialProfileOptions { AccessKey = "access_key", SecretKey = "secret_key" }; // TODO: These would go into appsettings.json var profile = new Amazon.Runtime.CredentialManagement.CredentialProfile("basic_profile", options); profile.Region = RegionEndpoint.USEast2; var netSdkFile = new NetSDKCredentialsFile(); netSdkFile.RegisterProfile(profile); }
public AwsEc2(ShadowsocksController controller, string accessKey, string secretKey) { // aws 配置用户名和密码 AddOrUpdateAppSettings("AWSProfileName", "aws_profile"); var options = new CredentialProfileOptions { AccessKey = accessKey, SecretKey = secretKey }; var profile = new Amazon.Runtime.CredentialManagement.CredentialProfile("aws_profile", options); var netSDKFile = new NetSDKCredentialsFile(); netSDKFile.RegisterProfile(profile); // 初始化客户端 ec2Client = new AmazonEC2Client(RegionEndpoint.USWest2); this.controller = controller; }
private AmazonS3Client GetS3Client() { var options = new CredentialProfileOptions { AccessKey = System.Environment.GetEnvironmentVariable("AWSACCESSKEY"), SecretKey = System.Environment.GetEnvironmentVariable("AWSSECRET") }; var profile = new Amazon.Runtime.CredentialManagement.CredentialProfile("basic_profile", options); var netSDKFile = new NetSDKCredentialsFile(); netSDKFile.RegisterProfile(profile); var creds = AWSCredentialsFactory.GetAWSCredentials(profile, netSDKFile); return(new AmazonS3Client(creds, RegionEndpoint.USEast1)); }
public string RegistrarCredenciais() { //Apenas para desenvolver try { var options = new CredentialProfileOptions { AccessKey = "", SecretKey = "" }; var profile = new Amazon.Runtime.CredentialManagement.CredentialProfile("root_profile", options); profile.Region = RegionEndpoint.SAEast1; var netSDKFile = new NetSDKCredentialsFile(); netSDKFile.RegisterProfile(profile); return("Registrado"); } catch (Exception e) { return("Erro" + e.Message); } }
private void RegisterProfileInternal(CredentialProfile profile) { var reservedProperties = new Dictionary <string, string>(); if (profile.UniqueKey != null) { reservedProperties[ToolkitArtifactGuidField] = profile.UniqueKey.Value.ToString("D"); } if (profile.Region != null) { reservedProperties[RegionField] = profile.Region.SystemName; } if (profile.EndpointDiscoveryEnabled != null) { reservedProperties[EndpointDiscoveryEnabledField] = profile.EndpointDiscoveryEnabled.Value.ToString().ToLowerInvariant(); } if (profile.StsRegionalEndpoints != null) { reservedProperties[StsRegionalEndpointsField] = profile.StsRegionalEndpoints.ToString().ToLowerInvariant(); } if (profile.S3UseArnRegion != null) { reservedProperties[S3UseArnRegionField] = profile.S3UseArnRegion.Value.ToString().ToLowerInvariant(); } if (profile.S3RegionalEndpoint != null) { reservedProperties[S3RegionalEndpointField] = profile.S3RegionalEndpoint.ToString().ToLowerInvariant(); } var profileDictionary = PropertyMapping.CombineProfileParts( profile.Options, ReservedPropertyNames, reservedProperties, profile.Properties); _credentialsFile.EditSection(profile.Name, new SortedDictionary <string, string>(profileDictionary)); _credentialsFile.Persist(); profile.CredentialProfileStore = this; }
/// <summary> /// Add the profile given. If the profile already exists, update it. /// </summary> /// <param name="profile">The profile to be written.</param> public void RegisterProfile(CredentialProfile profile) { Refresh(); if (profile.CanCreateAWSCredentials || profile.Options.IsEmpty) { if (!IsSupportedProfileType(profile.ProfileType)) { throw new ArgumentException(string.Format(CultureInfo.InvariantCulture, "Unable to update profile {0}. The CredentialProfile object provided represents a " + "{1} profile but {2} does not support the {1} profile type.", profile.Name, profile.ProfileType, GetType().Name)); } RegisterProfileInternal(profile); } else { throw new ArgumentException(String.Format(CultureInfo.InvariantCulture, "Unable to update profile {0}. The CredentialProfile provided is not a valid profile.", profile.Name)); } }
/// <summary> /// <para> /// Try to get a <see cref="CredentialProfile"/> /// </para> /// <para> /// If ProfilesLocation is non-null and non-empty search the shared credentials /// file at the disk path in the ProfilesLocation property. /// </para> /// <para> /// If ProfilesLocation is null or empty and the platform supports the .NET SDK credentials file /// search the SDK credentials file. If the profile is not found search the shared credentials file in the default location. /// </para> ///<para> /// If ProfilesLocation is null or empty and the platform doesn't support the .NET SDK credentials file /// search the shared credentials file in the default location. /// </para> /// </summary> /// <param name="profileName">The name of the profile to get.</param> /// <param name="profile">The profile, if found</param> /// <returns>True if the profile was found, false otherwise.</returns> public bool TryGetProfile(string profileName, out CredentialProfile profile) { if (string.IsNullOrEmpty(ProfilesLocation) && UserCrypto.IsUserCryptAvailable) { var netCredentialsFile = new NetSDKCredentialsFile(); if (netCredentialsFile.TryGetProfile(profileName, out profile)) { return(true); } } var sharedCredentialsFile = new SharedCredentialsFile(ProfilesLocation); if (sharedCredentialsFile.TryGetProfile(profileName, out profile)) { return(true); } profile = null; return(false); }
/// <summary> /// Update the profile on disk regardless of the profile type. /// </summary> /// <param name="profile"></param> private void RegisterProfileInternal(CredentialProfile profile) { var reservedProperties = new Dictionary <string, string>(); if (profile.UniqueKey != null) { reservedProperties[ToolkitArtifactGuidField] = profile.UniqueKey.Value.ToString("D"); } if (profile.Region != null) { reservedProperties[RegionField] = profile.Region.SystemName; } var profileDictionary = PropertyMapping.CombineProfileParts( profile.Options, ReservedPropertyNames, reservedProperties, profile.Properties); credentialsFile.EditSection(profile.Name, new SortedDictionary <string, string>(profileDictionary)); credentialsFile.Persist(); profile.CredentialProfileStore = this; }
public void RegisterProfile(CredentialProfile profile) { if (profile.CanCreateAWSCredentials || profile.Options.IsEmpty) { var reservedProperties = new Dictionary <string, string>(); if (profile.CanCreateAWSCredentials) { // set profile type field for backward compatibility SetProfileTypeField(reservedProperties, profile.ProfileType.Value); } if (profile.Region != null) { reservedProperties[RegionField] = profile.Region.SystemName; } if (profile.EndpointDiscoveryEnabled != null) { reservedProperties[EndpointDiscoveryEnabledField] = profile.EndpointDiscoveryEnabled.Value.ToString().ToLowerInvariant(); } var profileDictionary = PropertyMapping.CombineProfileParts( profile.Options, ReservedPropertyNames, reservedProperties, profile.Properties); // Set the UniqueKey. It might change if the unique key is set by the objectManger, // or if this is an update to an existing profile. string newUniqueKeyStr = _settingsManager.RegisterObject(profile.Name, profileDictionary); Guid? newUniqueKey; if (GuidUtils.TryParseNullableGuid(newUniqueKeyStr, out newUniqueKey)) { profile.UniqueKey = newUniqueKey; } profile.CredentialProfileStore = this; } else { throw new ArgumentException(String.Format(CultureInfo.InvariantCulture, "Unable to register profile {0}. The CredentialProfileOptions provided is not valid.", profile.Name)); } }
/// <summary> /// Get the profile with the name given, if it exists in this store. /// </summary> /// <param name="profileName">The name of the profile to find.</param> /// <param name="profile">The profile, if it was found, null otherwise</param> /// <returns>True if the profile was found, false otherwise.</returns> public bool TryGetProfile(string profileName, out CredentialProfile profile) { Dictionary <string, string> properties; string uniqueKeyStr; if (_settingsManager.TryGetObject(profileName, out uniqueKeyStr, out properties)) { try { CredentialProfileOptions profileOptions; Dictionary <string, string> userProperties; Dictionary <string, string> reservedProperties; PropertyMapping.ExtractProfileParts(properties, ReservedPropertyNames, out profileOptions, out reservedProperties, out userProperties); string regionString; RegionEndpoint region = null; if (reservedProperties.TryGetValue(RegionField, out regionString)) { region = RegionEndpoint.GetBySystemName(regionString); } Guid?uniqueKey = null; if (!GuidUtils.TryParseNullableGuid(uniqueKeyStr, out uniqueKey)) { profile = null; return(false); } string endpointDiscoveryEnabledString; bool? endpointDiscoveryEnabled = null; if (reservedProperties.TryGetValue(EndpointDiscoveryEnabledField, out endpointDiscoveryEnabledString)) { bool endpointDiscoveryEnabledOut; if (!bool.TryParse(endpointDiscoveryEnabledString, out endpointDiscoveryEnabledOut)) { profile = null; return(false); } endpointDiscoveryEnabled = endpointDiscoveryEnabledOut; } profile = new CredentialProfile(profileName, profileOptions) { UniqueKey = uniqueKey, Properties = userProperties, Region = region, CredentialProfileStore = this, EndpointDiscoveryEnabled = endpointDiscoveryEnabled }; return(true); } catch (ArgumentException) { profile = null; return(false); } } else { profile = null; return(false); } }
public Solicitudes DetectText(List <Tab_ConfigSys> Tab_ConfigSys, byte[] bytes, string Identificacion, int IdTipoIdentificacion, int?OPC) { string xClase = string.Format("{0}|{1}", MethodBase.GetCurrentMethod().Module.Name, MethodBase.GetCurrentMethod().DeclaringType.Name); string xProceso = MethodBase.GetCurrentMethod().Name; bool resp = false; var param = new { UriFoto = bytes, TipoIdentificacion = IdTipoIdentificacion, cedula = Identificacion, OPCe = OPC }; var dto_excepcion = new UTL_TRA_EXCEPCION { STR_CLASE = xClase, STR_EVENTO = xProceso, FEC_CREACION = DateTime.Now, STR_PARAMETROS = JsonConvert.SerializeObject(param), STR_SERVIDOR = System.Net.Dns.GetHostName(), STR_APLICATIVO = ConfigurationManager.AppSettings["APLICATIVO"].ToString() }; Solicitudes _Solicitudes = new Solicitudes(); _Solicitudes.Identificacion = Identificacion; ManagerSolcitudes managerSolcitudes = new ManagerSolcitudes(); var FecVencCedula = managerSolcitudes.ConsultaFechaVencimientoCedula(_Solicitudes); var options = new CredentialProfileOptions { AccessKey = Tab_ConfigSys[0].llave_Config1, SecretKey = Tab_ConfigSys[0].llave_Config2 }; try { var profile = new Amazon.Runtime.CredentialManagement.CredentialProfile("AWSProfileName", options); profile.Region = RegionEndpoint.USWest1; var netSDKFile = new NetSDKCredentialsFile(); netSDKFile.RegisterProfile(profile); using (AmazonRekognitionClient rekoClient = new AmazonRekognitionClient(Tab_ConfigSys[0].llave_Config1, Tab_ConfigSys[0].llave_Config2, RegionEndpoint.USEast1)) { Amazon.Rekognition.Model.Image img = new Amazon.Rekognition.Model.Image(); img.Bytes = new MemoryStream(bytes); DetectTextRequest dfr = new DetectTextRequest(); dfr.Image = img; var outcome = rekoClient.DetectText(dfr); bool dia = false; bool mes = false; bool anio = false; foreach (var texto in outcome.TextDetections) { string cedula = ""; cedula = texto.DetectedText; cedula = cedula.Replace(" ", "").Trim(); var cedresp = cedula.Split(':'); var respuesta = cedresp.Where(x => x.ToString().Equals(Identificacion) || cedula.Equals(Identificacion)).Any(); if (respuesta) { resp = respuesta; } if (FecVencCedula != null) { var resDia = cedresp.Where(x => x.ToString().Equals(Convert.ToString(FecVencCedula.Dia)) || cedula.Equals(Convert.ToString(FecVencCedula.Dia))).Any(); if (resDia) { dia = resDia; } var resMes = cedresp.Where(x => x.ToString().Equals(Convert.ToString(FecVencCedula.Mes)) || cedula.Equals(Convert.ToString(FecVencCedula.Mes))).Any(); if (resMes) { mes = resMes; } var resAnio = cedresp.Where(x => x.ToString().Equals(Convert.ToString(FecVencCedula.Anio)) || cedula.Equals(Convert.ToString(FecVencCedula.Anio))).Any(); if (resAnio) { anio = resAnio; } if (respuesta == true && dia == true && mes == true && anio == true) { break; } } else { if (respuesta) { break; } } } var jsonString = Newtonsoft.Json.JsonConvert.SerializeObject(outcome.TextDetections.Select(x => x.DetectedText)); _Solicitudes.Result = resp; _Solicitudes.Dia = Convert.ToInt32(dia); _Solicitudes.Mes = Convert.ToInt32(mes); _Solicitudes.Anio = Convert.ToInt32(anio); _Solicitudes.DetectedText = jsonString; } //return outcome.TextDetections.Select(x => x.DetectedText).ToList(); return(_Solicitudes); } catch (Exception ex) { dto_excepcion.STR_MENSAJE = ex.Message; dto_excepcion.IS_TELEGRAM = true; TwoFunTwoMe_DataAccess.Utility.guardaExcepcion(dto_excepcion, ConfigurationManager.ConnectionStrings["TwoFunTwoMeConnection"].ConnectionString); _Solicitudes.Mensaje = "ERR_Detect Text"; throw; } }
private bool TryGetProfile(string profileName, bool doRefresh, out CredentialProfile profile) { if (doRefresh) { Refresh(); } Dictionary <string, string> profileDictionary = null; if (TryGetSection(profileName, out profileDictionary)) { CredentialProfileOptions profileOptions; Dictionary <string, string> reservedProperties; Dictionary <string, string> userProperties; PropertyMapping.ExtractProfileParts(profileDictionary, ReservedPropertyNames, out profileOptions, out reservedProperties, out userProperties); string toolkitArtifactGuidStr; Guid? toolkitArtifactGuid = null; if (reservedProperties.TryGetValue(ToolkitArtifactGuidField, out toolkitArtifactGuidStr)) { if (!GuidUtils.TryParseNullableGuid(toolkitArtifactGuidStr, out toolkitArtifactGuid)) { Logger.GetLogger(GetType()).InfoFormat("Invalid value {0} for {1} in profile {2}. GUID expected.", toolkitArtifactGuidStr, ToolkitArtifactGuidField, profileName); profile = null; return(false); } } string regionString; RegionEndpoint region = null; if (reservedProperties.TryGetValue(RegionField, out regionString)) { region = RegionEndpoint.GetBySystemName(regionString); } string endpointDiscoveryEnabledString; bool? endpointDiscoveryEnabled = null; if (reservedProperties.TryGetValue(EndpointDiscoveryEnabledField, out endpointDiscoveryEnabledString)) { bool endpointDiscoveryEnabledOut; if (!bool.TryParse(endpointDiscoveryEnabledString, out endpointDiscoveryEnabledOut)) { Logger.GetLogger(GetType()).InfoFormat("Invalid value {0} for {1} in profile {2}. A boolean true/false is expected.", endpointDiscoveryEnabledString, EndpointDiscoveryEnabledField, profileName); profile = null; return(false); } endpointDiscoveryEnabled = endpointDiscoveryEnabledOut; } StsRegionalEndpointsValue?stsRegionalEndpoints = null; if (reservedProperties.TryGetValue(StsRegionalEndpointsField, out var stsRegionalEndpointsString)) { #if BCL35 try { stsRegionalEndpoints = (StsRegionalEndpointsValue)Enum.Parse(typeof(StsRegionalEndpointsValue), stsRegionalEndpointsString, true); } catch (Exception) { _logger.InfoFormat("Invalid value {0} for {1} in profile {2}. A string regional/legacy is expected.", stsRegionalEndpointsString, StsRegionalEndpointsField, profileName); profile = null; return(false); } #else if (!Enum.TryParse <StsRegionalEndpointsValue>(stsRegionalEndpointsString, true, out var stsRegionalEndpointsTemp)) { _logger.InfoFormat("Invalid value {0} for {1} in profile {2}. A string regional/legacy is expected.", stsRegionalEndpointsString, StsRegionalEndpointsField, profileName); profile = null; return(false); } stsRegionalEndpoints = stsRegionalEndpointsTemp; #endif } string s3UseArnRegionString; bool? s3UseArnRegion = null; if (reservedProperties.TryGetValue(S3UseArnRegionField, out s3UseArnRegionString)) { bool s3UseArnRegionOut; if (!bool.TryParse(s3UseArnRegionString, out s3UseArnRegionOut)) { profile = null; return(false); } s3UseArnRegion = s3UseArnRegionOut; } S3UsEast1RegionalEndpointValue?s3RegionalEndpoint = null; if (reservedProperties.TryGetValue(S3RegionalEndpointField, out var s3RegionalEndpointString)) { #if BCL35 try { s3RegionalEndpoint = (S3UsEast1RegionalEndpointValue)Enum.Parse(typeof(S3UsEast1RegionalEndpointValue), s3RegionalEndpointString, true); } catch (Exception) { _logger.InfoFormat("Invalid value {0} for {1} in profile {2}. A string regional/legacy is expected.", s3RegionalEndpointString, S3RegionalEndpointField, profileName); profile = null; return(false); } #else if (!Enum.TryParse <S3UsEast1RegionalEndpointValue>(s3RegionalEndpointString, true, out var s3RegionalEndpointTemp)) { _logger.InfoFormat("Invalid value {0} for {1} in profile {2}. A string regional/legacy is expected.", s3RegionalEndpointString, S3RegionalEndpointField, profileName); profile = null; return(false); } s3RegionalEndpoint = s3RegionalEndpointTemp; #endif } RequestRetryMode?requestRetryMode = null; if (reservedProperties.TryGetValue(RetryModeField, out var retryModeString)) { #if BCL35 try { requestRetryMode = (RequestRetryMode)Enum.Parse(typeof(RequestRetryMode), retryModeString, true); } catch (Exception) { _logger.InfoFormat("Invalid value {0} for {1} in profile {2}. A string legacy/standard/adaptive is expected.", retryModeString, RetryModeField, profileName); profile = null; return(false); } #else if (!Enum.TryParse <RequestRetryMode>(retryModeString, true, out var retryModeTemp)) { _logger.InfoFormat("Invalid value {0} for {1} in profile {2}. A string legacy/standard/adaptive is expected.", retryModeString, RetryModeField, profileName); profile = null; return(false); } requestRetryMode = retryModeTemp; #endif } int?maxAttempts = null; if (reservedProperties.TryGetValue(MaxAttemptsField, out var maxAttemptsString)) { if (!int.TryParse(maxAttemptsString, out var maxAttemptsTemp) || maxAttemptsTemp <= 0) { Logger.GetLogger(GetType()).InfoFormat("Invalid value {0} for {1} in profile {2}. A positive integer is expected.", maxAttemptsString, MaxAttemptsField, profileName); profile = null; return(false); } maxAttempts = maxAttemptsTemp; } profile = new CredentialProfile(profileName, profileOptions) { UniqueKey = toolkitArtifactGuid, Properties = userProperties, Region = region, CredentialProfileStore = this, EndpointDiscoveryEnabled = endpointDiscoveryEnabled, StsRegionalEndpoints = stsRegionalEndpoints, S3UseArnRegion = s3UseArnRegion, S3RegionalEndpoint = s3RegionalEndpoint, RetryMode = requestRetryMode, MaxAttempts = maxAttempts }; if (!IsSupportedProfileType(profile.ProfileType)) { _logger.InfoFormat("The profile type {0} is not supported by SharedCredentialsFile.", profile.ProfileType); profile = null; return(false); } return(true); } profile = null; return(false); }
public bool TryGetProfile(string profileName, out CredentialProfile profile) { return(TryGetProfile(profileName, true, out profile)); }
private bool TryGetProfile(string profileName, bool doRefresh, out CredentialProfile profile) { if (doRefresh) { Refresh(); } Dictionary <string, string> profileDictionary = null; if (TryGetSection(profileName, out profileDictionary)) { CredentialProfileOptions profileOptions; Dictionary <string, string> reservedProperties; Dictionary <string, string> userProperties; PropertyMapping.ExtractProfileParts(profileDictionary, ReservedPropertyNames, out profileOptions, out reservedProperties, out userProperties); string toolkitArtifactGuidStr; Guid? toolkitArtifactGuid = null; if (reservedProperties.TryGetValue(ToolkitArtifactGuidField, out toolkitArtifactGuidStr)) { if (!GuidUtils.TryParseNullableGuid(toolkitArtifactGuidStr, out toolkitArtifactGuid)) { Logger.GetLogger(GetType()).InfoFormat("Invalid value {0} for {1} in profile {2}. GUID expected.", toolkitArtifactGuidStr, ToolkitArtifactGuidField, profileName); profile = null; return(false); } } string regionString; RegionEndpoint region = null; if (reservedProperties.TryGetValue(RegionField, out regionString)) { region = RegionEndpoint.GetBySystemName(regionString); } string endpointDiscoveryEnabledString; bool? endpointDiscoveryEnabled = null; if (reservedProperties.TryGetValue(EndpointDiscoveryEnabledField, out endpointDiscoveryEnabledString)) { bool endpointDiscoveryEnabledOut; if (!bool.TryParse(endpointDiscoveryEnabledString, out endpointDiscoveryEnabledOut)) { Logger.GetLogger(GetType()).InfoFormat("Invalid value {0} for {1} in profile {2}. A boolean true/false is expected.", endpointDiscoveryEnabledString, EndpointDiscoveryEnabledField, profileName); profile = null; return(false); } endpointDiscoveryEnabled = endpointDiscoveryEnabledOut; } profile = new CredentialProfile(profileName, profileOptions) { UniqueKey = toolkitArtifactGuid, Properties = userProperties, Region = region, CredentialProfileStore = this, EndpointDiscoveryEnabled = endpointDiscoveryEnabled }; if (!IsSupportedProfileType(profile.ProfileType)) { logger.InfoFormat("The profile type {0} is not supported by SharedCredentialsFile.", profile.ProfileType); profile = null; return(false); } return(true); } else { profile = null; return(false); } }
public Solicitudes GetTestAsync(List <Tab_ConfigSys> Tab_ConfigSys, Solicitudes sol) { string xClase = string.Format("{0}|{1}", MethodBase.GetCurrentMethod().Module.Name, MethodBase.GetCurrentMethod().DeclaringType.Name); string xProceso = MethodBase.GetCurrentMethod().Name; var dto_excepcion = new UTL_TRA_EXCEPCION { STR_CLASE = xClase, STR_EVENTO = xProceso, STR_PARAMETROS = JsonConvert.SerializeObject(sol), STR_APLICATIVO = ConfigurationManager.AppSettings["APLICATIVO"].ToString(), STR_SERVIDOR = System.Net.Dns.GetHostName(), FEC_CREACION = DateTime.Now }; Solicitudes _Solicitudes = new Solicitudes(); var options = new CredentialProfileOptions { AccessKey = Tab_ConfigSys[0].llave_Config1, SecretKey = Tab_ConfigSys[0].llave_Config2 }; try { var profile = new Amazon.Runtime.CredentialManagement.CredentialProfile("AWSProfileName", options); profile.Region = RegionEndpoint.USWest1; var netSDKFile = new NetSDKCredentialsFile(); netSDKFile.RegisterProfile(profile); float similarityThreshold = 70F; //String sourceImage = sol.arrImageSelfie; //String targetImage = sol.UrlFotoCedula; //using (AmazonRekognitionClient rekognitionClient = new AmazonRekognitionClient(Tab_ConfigSys[0].llave_Config1, Tab_ConfigSys[0].llave_Config2, RegionEndpoint.USWest1)) using (AmazonRekognitionClient rekognitionClient = new AmazonRekognitionClient(Tab_ConfigSys[0].llave_Config1, Tab_ConfigSys[0].llave_Config2)) { Amazon.Rekognition.Model.Image imageSource = new Amazon.Rekognition.Model.Image(); //using (FileStream fs = new FileStream(new MemoryStream(bytes), FileMode.Open, FileAccess.Read)) //{ // byte[] data = new byte[fs.Length]; // fs.Read(data, 0, (int)fs.Length); imageSource.Bytes = new MemoryStream(sol.arrImageSelfie); // } Amazon.Rekognition.Model.Image imageTarget = new Amazon.Rekognition.Model.Image(); // using (FileStream fs = new FileStream(targetImage, FileMode.Open, FileAccess.Read)) //{ // byte[] data = new byte[fs.Length]; // data = new byte[fs.Length]; // fs.Read(data, 0, (int)fs.Length); imageTarget.Bytes = new MemoryStream(sol.arrImageCedulaFrontal); // } CompareFacesRequest compareFacesRequest = new CompareFacesRequest() { SourceImage = imageSource, TargetImage = imageTarget, SimilarityThreshold = similarityThreshold }; // Call operation CompareFacesResponse compareFacesResponse = rekognitionClient.CompareFaces(compareFacesRequest); // Display results //foreach (CompareFacesMatch match in compareFacesResponse.FaceMatches) compareFacesResponse.FaceMatches.ForEach(match => { ComparedFace face = match.Face; BoundingBox position = face.BoundingBox; _Solicitudes.PorcentMatched = face.Confidence; _Solicitudes.PositionLeft = position.Left; _Solicitudes.PositionTop = position.Top; }); _Solicitudes.IdTipoIdentificacion = sol.IdTipoIdentificacion; _Solicitudes.Identificacion = sol.Identificacion; if (_Solicitudes.PorcentMatched == 0 || _Solicitudes.PorcentMatched == null) { _Solicitudes.UnMatchedFace = compareFacesResponse.UnmatchedFaces[0].Confidence; } else { _Solicitudes.UnMatchedFace = 0; } _Solicitudes.ImageRotationSource = compareFacesResponse.SourceImageOrientationCorrection; _Solicitudes.ImageRotationTarget = compareFacesResponse.TargetImageOrientationCorrection; } return(_Solicitudes); } catch (Exception ex) { dto_excepcion.STR_MENSAJE = ex.Message; dto_excepcion.IS_TELEGRAM = true; TwoFunTwoMe_DataAccess.Utility.guardaExcepcion(dto_excepcion, ConfigurationManager.ConnectionStrings["TwoFunTwoMeConnection"].ConnectionString); _Solicitudes.Mensaje = "ERR_imageTarget"; throw; } }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { // Enable CORS. services.AddCors(); // Add MVC service. services.AddMvc(); // Create AWS Profile options for basic profile. var awsProfileOptions = new Amazon.Runtime.CredentialManagement.CredentialProfileOptions() { AccessKey = Configuration.GetValue <string>("Secrets:AWS:AccessKey"), SecretKey = Configuration.GetValue <string>("Secrets:AWS:AccessKeySecret"), }; // Creates basic profile with above options, then set AWS region. var awsProfile = new Amazon.Runtime.CredentialManagement.CredentialProfile("basic-profile", awsProfileOptions); awsProfile.Region = RegionEndpoint.APNortheast2; // Registers AWS profile to AWS SDK's .NET SDK credentials file. var sdkFile = new NetSDKCredentialsFile(); sdkFile.RegisterProfile(awsProfile); // Add AWS options. services.AddDefaultAWSOptions(new AWSOptions() { Region = RegionEndpoint.APNortheast2, Profile = awsProfile.Name }); // Add DynamoDB service. services.AddAWSService <IAmazonDynamoDB>(); // Add UserServices. // If want to use classic user service, use `UserService`. services.AddScoped <IUserService, DynamoDBUserService>(); // Configure JWT authentication. services.AddAuthentication(x => { x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme; x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme; }) .AddJwtBearer(x => { x.RequireHttpsMetadata = false; // NOTE: This should be set to `true` on production. x.SaveToken = true; x.TokenValidationParameters = new TokenValidationParameters { ValidateIssuerSigningKey = true, IssuerSigningKey = new SymmetricSecurityKey(System.Text.Encoding.ASCII.GetBytes(Configuration.GetValue <string>("Secrets:JWT"))), ValidateIssuer = false, ValidateAudience = false }; }); // In production, the React files will be served from this directory // This code portion is not related to webpack_hmr. services.AddSpaStaticFiles(configuration => { configuration.RootPath = "wwwroot/dist"; }); }
/// <summary> /// Gets the AWSCredentials for this profile if CanCreateAWSCredentials is true /// and AWSCredentials can be created. Throws an exception otherwise. /// /// See <see cref="CredentialProfileOptions"/> for a list of AWSCredentials returned by this method. /// </summary> /// <param name="profile">The profile to get AWSCredentials for.</param> /// <param name="profileSource">The profile source, for profiles that reference other profiles.</param> /// <returns>AWSCredentials for this profile.</returns> public static AWSCredentials GetAWSCredentials(CredentialProfile profile, ICredentialProfileSource profileSource) { return(GetAWSCredentials(profile.Name, profileSource, profile.Options, profile.Region, false)); }
/// <summary> /// Return the credentials for the profile if valid credentials can created. /// </summary> /// <param name="profile">The profile to create credentials with.</param> /// <param name="profileSource">The profile source, for profiles that reference other profiles.</param> /// <param name="credentials">The credentials for the profile.</param> /// <returns>True if credentials can be created from the profile, false otherwise.</returns> public static bool TryGetAWSCredentials(CredentialProfile profile, ICredentialProfileSource profileSource, out AWSCredentials credentials) { credentials = GetAWSCredentialsInternal(profile.Name, profile.ProfileType, profile.Options, profile.Region, profileSource, false); return(credentials != null); }
/// <summary> /// Get the profile with the name given, if it exists in this store. /// </summary> /// <param name="profileName">The name of the profile to find.</param> /// <param name="profile">The profile, if it was found, null otherwise</param> /// <returns>True if the profile was found, false otherwise.</returns> public bool TryGetProfile(string profileName, out CredentialProfile profile) { Dictionary <string, string> properties; string uniqueKeyStr; if (_settingsManager.TryGetObject(profileName, out uniqueKeyStr, out properties)) { try { CredentialProfileOptions profileOptions; Dictionary <string, string> userProperties; Dictionary <string, string> reservedProperties; PropertyMapping.ExtractProfileParts(properties, ReservedPropertyNames, out profileOptions, out reservedProperties, out userProperties); string regionString; RegionEndpoint region = null; if (reservedProperties.TryGetValue(RegionField, out regionString)) { region = RegionEndpoint.GetBySystemName(regionString); } Guid?uniqueKey = null; if (!GuidUtils.TryParseNullableGuid(uniqueKeyStr, out uniqueKey)) { profile = null; return(false); } string endpointDiscoveryEnabledString; bool? endpointDiscoveryEnabled = null; if (reservedProperties.TryGetValue(EndpointDiscoveryEnabledField, out endpointDiscoveryEnabledString)) { bool endpointDiscoveryEnabledOut; if (!bool.TryParse(endpointDiscoveryEnabledString, out endpointDiscoveryEnabledOut)) { profile = null; return(false); } endpointDiscoveryEnabled = endpointDiscoveryEnabledOut; } StsRegionalEndpointsValue?stsRegionalEndpoints = null; if (reservedProperties.TryGetValue(StsRegionalEndpointsField, out var stsRegionalEndpointsString)) { #if BCL35 try { stsRegionalEndpoints = (StsRegionalEndpointsValue)Enum.Parse(typeof(StsRegionalEndpointsValue), stsRegionalEndpointsString, true); } catch (Exception) { profile = null; return(false); } #else if (!Enum.TryParse <StsRegionalEndpointsValue>(stsRegionalEndpointsString, true, out var tempStsRegionalEndpoints)) { profile = null; return(false); } stsRegionalEndpoints = tempStsRegionalEndpoints; #endif } string s3UseArnRegionString; bool? s3UseArnRegion = null; if (reservedProperties.TryGetValue(S3UseArnRegionField, out s3UseArnRegionString)) { bool s3UseArnRegionOut; if (!bool.TryParse(s3UseArnRegionString, out s3UseArnRegionOut)) { profile = null; return(false); } s3UseArnRegion = s3UseArnRegionOut; } S3UsEast1RegionalEndpointValue?s3RegionalEndpoint = null; if (reservedProperties.TryGetValue(S3RegionalEndpointField, out var s3RegionalEndpointString)) { #if BCL35 try { s3RegionalEndpoint = (S3UsEast1RegionalEndpointValue)Enum.Parse(typeof(S3UsEast1RegionalEndpointValue), s3RegionalEndpointString, true); } catch (Exception) { profile = null; return(false); } #else if (!Enum.TryParse <S3UsEast1RegionalEndpointValue>(s3RegionalEndpointString, true, out var tempS3RegionalEndpoint)) { profile = null; return(false); } s3RegionalEndpoint = tempS3RegionalEndpoint; #endif } profile = new CredentialProfile(profileName, profileOptions) { UniqueKey = uniqueKey, Properties = userProperties, Region = region, CredentialProfileStore = this, EndpointDiscoveryEnabled = endpointDiscoveryEnabled, StsRegionalEndpoints = stsRegionalEndpoints, S3UseArnRegion = s3UseArnRegion, S3RegionalEndpoint = s3RegionalEndpoint }; return(true); } catch (ArgumentException) { profile = null; return(false); } } else { profile = null; return(false); } }
/// <summary> /// Gets the AWSCredentials for this profile if CanCreateAWSCredentials is true /// and AWSCredentials can be created. Throws an exception otherwise. /// /// See <see cref="CredentialProfileOptions"/> for a list of AWSCredentials returned by this method. /// </summary> /// <param name="profile">The profile to get AWSCredentials for.</param> /// <param name="profileSource">The profile source, for profiles that reference other profiles.</param> /// <param name="nonCallbackOnly">If true, throw a descriptive exception for any credentials that would not operate as-is. /// In other words, any credentials that require programmatic callbacks at runtime.</param> /// <returns>AWSCredentials for this profile.</returns> public static AWSCredentials GetAWSCredentials(CredentialProfile profile, ICredentialProfileSource profileSource, bool nonCallbackOnly) { return(GetAWSCredentials(profile.Name, profileSource, profile.Options, profile.Region, nonCallbackOnly)); }
/// <summary> /// Get the profile with the name given, if it exists in this store. /// </summary> /// <param name="profileName">The name of the profile to find.</param> /// <param name="profile">The profile, if it was found, null otherwise</param> /// <returns>True if the profile was found, false otherwise.</returns> public bool TryGetProfile(string profileName, out CredentialProfile profile) { Dictionary <string, string> properties; string uniqueKeyStr; if (_settingsManager.TryGetObject(profileName, out uniqueKeyStr, out properties)) { try { CredentialProfileOptions profileOptions; Dictionary <string, string> userProperties; Dictionary <string, string> reservedProperties; PropertyMapping.ExtractProfileParts(properties, ReservedPropertyNames, out profileOptions, out reservedProperties, out userProperties); string regionString; RegionEndpoint region = null; if (reservedProperties.TryGetValue(RegionField, out regionString)) { region = RegionEndpoint.GetBySystemName(regionString); } Guid?uniqueKey = null; if (!GuidUtils.TryParseNullableGuid(uniqueKeyStr, out uniqueKey)) { profile = null; return(false); } string endpointDiscoveryEnabledString; bool? endpointDiscoveryEnabled = null; if (reservedProperties.TryGetValue(EndpointDiscoveryEnabledField, out endpointDiscoveryEnabledString)) { bool endpointDiscoveryEnabledOut; if (!bool.TryParse(endpointDiscoveryEnabledString, out endpointDiscoveryEnabledOut)) { profile = null; return(false); } endpointDiscoveryEnabled = endpointDiscoveryEnabledOut; } StsRegionalEndpointsValue?stsRegionalEndpoints = null; if (reservedProperties.TryGetValue(StsRegionalEndpointsField, out var stsRegionalEndpointsString)) { #if BCL35 try { stsRegionalEndpoints = (StsRegionalEndpointsValue)Enum.Parse(typeof(StsRegionalEndpointsValue), stsRegionalEndpointsString, true); } catch (Exception) { profile = null; return(false); } #else if (!Enum.TryParse <StsRegionalEndpointsValue>(stsRegionalEndpointsString, true, out var tempStsRegionalEndpoints)) { profile = null; return(false); } stsRegionalEndpoints = tempStsRegionalEndpoints; #endif } string s3UseArnRegionString; bool? s3UseArnRegion = null; if (reservedProperties.TryGetValue(S3UseArnRegionField, out s3UseArnRegionString)) { bool s3UseArnRegionOut; if (!bool.TryParse(s3UseArnRegionString, out s3UseArnRegionOut)) { profile = null; return(false); } s3UseArnRegion = s3UseArnRegionOut; } S3UsEast1RegionalEndpointValue?s3RegionalEndpoint = null; if (reservedProperties.TryGetValue(S3RegionalEndpointField, out var s3RegionalEndpointString)) { #if BCL35 try { s3RegionalEndpoint = (S3UsEast1RegionalEndpointValue)Enum.Parse(typeof(S3UsEast1RegionalEndpointValue), s3RegionalEndpointString, true); } catch (Exception) { profile = null; return(false); } #else if (!Enum.TryParse <S3UsEast1RegionalEndpointValue>(s3RegionalEndpointString, true, out var tempS3RegionalEndpoint)) { profile = null; return(false); } s3RegionalEndpoint = tempS3RegionalEndpoint; #endif } RequestRetryMode?requestRetryMode = null; if (reservedProperties.TryGetValue(RetryModeField, out var retryModeString)) { #if BCL35 try { requestRetryMode = (RequestRetryMode)Enum.Parse(typeof(RequestRetryMode), retryModeString, true); } catch (Exception) { profile = null; return(false); } #else if (!Enum.TryParse <RequestRetryMode>(retryModeString, true, out var tempRetryMode)) { profile = null; return(false); } requestRetryMode = tempRetryMode; #endif } int?maxAttempts = null; if (reservedProperties.TryGetValue(MaxAttemptsField, out var maxAttemptsString)) { if (!int.TryParse(maxAttemptsString, out var maxAttemptsTemp) || maxAttemptsTemp <= 0) { Logger.GetLogger(GetType()).InfoFormat("Invalid value {0} for {1} in profile {2}. A positive integer is expected.", maxAttemptsString, MaxAttemptsField, profileName); profile = null; return(false); } maxAttempts = maxAttemptsTemp; } profile = new CredentialProfile(profileName, profileOptions) { UniqueKey = uniqueKey, Properties = userProperties, Region = region, CredentialProfileStore = this, EndpointDiscoveryEnabled = endpointDiscoveryEnabled, StsRegionalEndpoints = stsRegionalEndpoints, S3UseArnRegion = s3UseArnRegion, S3RegionalEndpoint = s3RegionalEndpoint, RetryMode = requestRetryMode, MaxAttempts = maxAttempts }; return(true); } catch (ArgumentException) { profile = null; return(false); } } else { profile = null; return(false); } }