public async Task <StartupResponse> AppStartup(string handle) { var c = new ColdRequestModel { DeviceInfo = new DeviceRegisterModel { Handle = handle } }; var client = _httpClientFactory.CreateHttpClient(); var POST_URL = $"{MagicValues.BackendUrl}/api/AppStartup"; var response = await client.PostJson <StartupResponseModel>(POST_URL, c); var result = response.Message.IsSuccessStatusCode ? new StartupResponse { HubRegistration = response.Object.HubRegistration, ClientAuth = response.Object.ClientAuth, IsSuccess = true } : new StartupResponse { HubRegistration = null, ClientAuth = null, IsSuccess = false }; return(result); }
public async Task <bool> TryUpdateRegistrationAsync(string regId, string handle, string authToken) { var deviceRegistration = GetDeviceRegistration(handle); using (var httpClient = _httpClientFactory.CreateHttpClient(authToken)) { var putUri = new Uri(_postUri, $"/api/register/{regId}"); string json = JsonConvert.SerializeObject(deviceRegistration); var response = await httpClient.PutAsync(putUri, new StringContent(json, Encoding.UTF8, "application/json")); return(response.StatusCode != HttpStatusCode.Gone); } }
public async Task <ApiResponse <bool> > RefundPayment(string transId, decimal price, Currency currency, bool test, string ComGateAPIEndpointUrl) { using (var httpClient = HttpClientFactory.CreateHttpClient(Core.Domain.Enums.ComGateHttpClient.HttpClient)) { RefundRequest refundRequest = new RefundRequest() .SetMerchant(this.Merchant) .SetSecret(this.Secret) .SetCurrency(currency) .SetTransactionID(transId) .SetAmount(price) .SetTest(test) ; var content = _serializer.Serialize <RefundRequest>(refundRequest); httpClient.BaseAddress = new Uri(ComGateAPIEndpointUrl); var response = await httpClient.PostAsync("refund", content); if (response.IsSuccessStatusCode) { var responseContent = await response.Content.ReadAsStringAsync(); return(_serializer.Deserialize <bool>(responseContent)); } else { throw new Exception("Cannot create method list"); } } }
public ApiResponse <PaymentStatusResponse> GetPaymentStatus(string transId, string ComGateAPIEndpointUrl) { transId = SunamoComgateHelper.Instance.InsertDashes(transId); using (var httpClient = HttpClientFactory.CreateHttpClient(Core.Domain.Enums.ComGateHttpClient.HttpClient)) { PaymentStatusRequest statusRequest = new PaymentStatusRequest() .SetMerchant(this.Merchant) .SetSecret(this.Secret) .SetTransactionId(transId); var content = _serializer.Serialize <PaymentStatusRequest>(statusRequest); httpClient.BaseAddress = new Uri(ComGateAPIEndpointUrl); var response = httpClient.PostAsync("status", content).Result; if (response.IsSuccessStatusCode) { var responseContent = response.Content.ReadAsStringAsync().Result; return(_serializer.Deserialize <PaymentStatusResponse>(responseContent)); } else { throw new Exception("Cannot create method list"); } } }
public async Task <ApiResponse <PaymentMethodsResponse> > GetAvailebleMethods(string ComGateAPIEndpointUrl) { using (var httpClient = HttpClientFactory.CreateHttpClient(Core.Domain.Enums.ComGateHttpClient.HttpClient)) { PaymentMethodsRequest methodsRequest = _requestBuilder .CreatePaymentMethodsRequest() .SetMerchant(this.Merchant) .SetSecret(this.Secret); var content = _serializer.Serialize <PaymentMethodsRequest>(methodsRequest); httpClient.BaseAddress = new Uri(ComGateAPIEndpointUrl); var response = await httpClient.PostAsync("methods", content); if (response.IsSuccessStatusCode) { var responseContent = await response.Content.ReadAsStringAsync(); return(_serializer.Deserialize <PaymentMethodsResponse>(responseContent)); } else { throw new Exception("Cannot create method list"); } } }
/// <summary> /// Is working in selling but not in Apps. Use CreatePayment which use everywhere /// </summary> /// <param name="payment"></param> /// <param name="payer"></param> /// <param name="ComGateAPIEndpointUrl"></param> /// <returns></returns> public ApiResponse <PaymentResponse> CreatePayment(BaseComGatePayment payment, Payer payer, string ComGateAPIEndpointUrl) { PaymentRequest paymentRequest = _requestBuilder .CreatePaymentRequest(payment, payer) .SetMerchant(this.Merchant) .SetEnviroment(this.IsTestEnviroment) .SetSecret(this.Secret); using (var httpClient = HttpClientFactory.CreateHttpClient(Core.Domain.Enums.ComGateHttpClient.HttpClient)) { _paymentLogger.LogPayment(paymentRequest); var content = _serializer.Serialize <PaymentRequest>(paymentRequest); httpClient.BaseAddress = new Uri(ComGateAPIEndpointUrl); var response = httpClient.PostAsync("create", content).Result; if (response.IsSuccessStatusCode) { var responseContent = response.Content.ReadAsStringAsync().Result; return(_serializer.Deserialize <PaymentResponse>(responseContent)); } else { throw new Exception("Cannot create payment"); } } }
public BasicAuth(string userName, string password, string endPointUrl) { Client = HttpClientFactory.CreateHttpClient(endPointUrl); AuthToken = Encoding.ASCII.GetBytes($"{userName}:{password}"); Client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(AuthToken)); Client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); }
public async Task <ApiResponse <bool> > CancelPreauth(string transId, string ComGateAPIEndpointUrl) { using (var httpClient = HttpClientFactory.CreateHttpClient(Core.Domain.Enums.ComGateHttpClient.HttpClient)) { CancelPreAuthRequest cancelPreauthRequest = new CancelPreAuthRequest() .SetMerchant(this.Merchant) .SetSecret(this.Secret) .SetTransactionID(transId); var content = _serializer.Serialize <CancelPreAuthRequest>(cancelPreauthRequest); httpClient.BaseAddress = new Uri(ComGateAPIEndpointUrl); var response = await httpClient.PostAsync("cancelPreauth", content); if (response.IsSuccessStatusCode) { var responseContent = await response.Content.ReadAsStringAsync(); return(_serializer.Deserialize <bool>(responseContent)); } else { throw new Exception("Cannot create method list"); } } }
/// <summary> /// Requires that AccountId and ApplicationKey on the options object be set. If you are using an application key you must specify the accountId, the keyId, and the applicationKey. /// </summary> /// <param name="options"></param> /// <returns></returns> public static B2Options Authorize(B2Options options) { // Return if already authenticated. if (options.Authenticated) { return(options); } var client = HttpClientFactory.CreateHttpClient(options.RequestTimeout); var requestMessage = AuthRequestGenerator.Authorize(options); var response = client.SendAsync(requestMessage).Result; var jsonResponse = response.Content.ReadAsStringAsync().Result; if (response.IsSuccessStatusCode) { var authResponse = JsonConvert.DeserializeObject <B2AuthResponse>(jsonResponse); options.SetState(authResponse); } else if (response.StatusCode == HttpStatusCode.Unauthorized) { // Return a better exception because of confusing Keys api. throw new AuthorizationException("If you are using an Application key and not a Master key, make sure that you are supplying the Key ID and Key Value for that Application Key. Do not mix your Account ID with your Application Key."); } else { throw new AuthorizationException(jsonResponse); } return(options); }
public void NewHttpClientReturnsForEachCreationRequest() { var firstHttpClient = HttpClientFactory.CreateHttpClient(); var secondHttpClient = HttpClientFactory.CreateHttpClient(); Assert.That(firstHttpClient, Is.Not.EqualTo(secondHttpClient)); }
/// <summary> /// Trigger notification. /// </summary> /// <param name="io">The input/output instance.</param> /// <param name="config">The config instance.</param> public virtual void Notify(IIO io, Config config) { var seen = new HashSet <string>(); foreach (var item in notifiablePackages) { if (!Uri.TryCreate(item.Key, UriKind.RelativeOrAbsolute, out Uri uri)) { continue; } var authHeader = string.Empty; if (io.HasAuthentication(uri.Host)) { var(username, password) = io.GetAuthentication(uri.Host); var authBytes = Encoding.UTF8.GetBytes($"{username}:{password}"); authHeader = $"Basic {Convert.ToBase64String(authBytes)}"; } seen.Clear(); var postData = new PostNotifyData(); foreach (var package in item.Value) { if (!seen.Add(package.GetName())) { continue; } postData.Downloads.Add((package.GetNamePretty(), package.GetVersion())); } using (var httpClient = HttpClientFactory.CreateHttpClient(config)) { var content = new StringContent(postData, Encoding.UTF8, "application/json"); if (!string.IsNullOrEmpty(authHeader)) { content.Headers.Add("Authorization", authHeader); } try { using (var response = httpClient.PostAsync(uri.ToString(), content).Result) { response.EnsureSuccessStatusCode(); } } #pragma warning disable CA1031 catch (SException ex) #pragma warning restore CA1031 { io.WriteError($"Notify {uri.ToString()} failed: {ex.Message}", true, Verbosities.Debug); } finally { httpClient.CancelPendingRequests(); } } } }
/// <summary> /// Creates an authenticated <see cref="ConfigurableHttpClient"/> from the /// factory. /// </summary> /// <returns>An HTTP client that can be used to OAuth2 authorized requests.</returns> /// <param name="clientFactory">The <see cref="HttpClientFactory"/> used to create /// the HTTP client.</param> /// <param name="credential">The Google credential that will be used to authenticate /// outgoing HTTP requests.</param> public static ConfigurableHttpClient CreateAuthorizedHttpClient( this HttpClientFactory clientFactory, GoogleCredential credential) { var args = new CreateHttpClientArgs(); args.Initializers.Add(credential.ThrowIfNull(nameof(credential))); return(clientFactory.CreateHttpClient(args)); }
/// <summary> /// Creates a new bucket. A bucket belongs to the account used to create it. If BucketType is not set allPrivate will be used by default. /// Use this method to set Cache-Control. /// </summary> /// <param name="bucketName"></param> /// <param name="bucketType"></param> /// <param name="cancelToken"></param> /// <returns></returns> public async Task <B2Bucket> Create(string bucketName, B2BucketOptions options, CancellationToken cancelToken = default(CancellationToken)) { var client = HttpClientFactory.CreateHttpClient(); var requestMessage = BucketRequestGenerators.CreateBucket(_options, bucketName, options); var response = await client.SendAsync(requestMessage, cancelToken); return(await ResponseParser.ParseResponse <B2Bucket>(response)); }
/// <summary> /// Update an existing bucket. bucketId is only optional if you are persisting a bucket for this client. /// </summary> /// <param name="bucketType"></param> /// <param name="bucketId"></param> /// <param name="cancelToken"></param> /// <returns></returns> public async Task <B2Bucket> Update(BucketTypes bucketType, string bucketId = "", CancellationToken cancelToken = default(CancellationToken)) { var operationalBucketId = Utilities.DetermineBucketId(_options, bucketId); var client = HttpClientFactory.CreateHttpClient(); var requestMessage = BucketRequestGenerators.UpdateBucket(_options, operationalBucketId, bucketType.ToString()); var response = await client.SendAsync(requestMessage, cancelToken); return(await ResponseParser.ParseResponse <B2Bucket>(response)); }
public async Task <List <B2Bucket> > GetList(CancellationToken cancelToken = default(CancellationToken)) { var client = HttpClientFactory.CreateHttpClient(); var requestMessage = BucketRequestGenerators.GetBucketList(_options); var response = await client.SendAsync(requestMessage, cancelToken); var bucketList = ResponseParser.ParseResponse <B2BucketListDeserializeModel>(response).Result; return(bucketList.Buckets); }
private async Task <GetDataApiResponse> GetDataInternalAsync( DateTime from, DateTime to, Country country, bool useShortDays, bool treatNonWorkingDaysByCovidAsWorkingDayAdvanced, bool useSixDaysWorkWeek, CancellationToken cancellationToken) { using (var httpClient = httpClientFactory.CreateHttpClient()) { var countryCode = GetCountryCode(country); var requestUrl = BuildGetDataRequestUrl( from, to, countryCode, useShortDays, treatNonWorkingDaysByCovidAsWorkingDayAdvanced, useSixDaysWorkWeek); try { httpClient.DefaultRequestHeaders.UserAgent.ParseAdd(userAgent); IsDayOff.Tracer.TraceEvent(TraceEventType.Information, TraceEventIds.Requesting.REQUEST_SENDING, "Sending HTTP GET: '{0}'", requestUrl); var response = await httpClient.GetAsync(requestUrl, cancellationToken); var responseAsString = await response.Content.ReadAsStringAsync(); IsDayOff.Tracer.TraceEvent(TraceEventType.Information, TraceEventIds.Requesting.REQUEST_SENT, "Response received with status code: '{0}' and string content: '{1}'", response.StatusCode, responseAsString); ValidateResponse(from, to, country, response, responseAsString); return(new GetDataApiResponse(responseAsString)); } catch (Exception e) { IsDayOff.Tracer.TraceEvent(TraceEventType.Error, TraceEventIds.Requesting.REQUEST_SENDING_ERROR, "An error occured while processing request: '{0}'\n{1}", requestUrl, e); throw new IsDayOffExternalServiceException(e); } } }
/// <summary>Constructs a new flow using the initializer's properties.</summary> public AuthorizationCodeFlow(Initializer initializer) { clientSecrets = initializer.ClientSecrets; if (clientSecrets == null) { if (initializer.ClientSecretsStream == null) { throw new ArgumentException("You MUST set ClientSecret or ClientSecretStream on the initializer"); } using (initializer.ClientSecretsStream) { clientSecrets = GoogleClientSecrets.FromStream(initializer.ClientSecretsStream).Secrets; } } else if (initializer.ClientSecretsStream != null) { throw new ArgumentException( "You CAN'T set both ClientSecrets AND ClientSecretStream on the initializer"); } accessMethod = initializer.AccessMethod.ThrowIfNull("Initializer.AccessMethod"); clock = initializer.Clock.ThrowIfNull("Initializer.Clock"); tokenServerUrl = initializer.TokenServerUrl.ThrowIfNullOrEmpty("Initializer.TokenServerUrl"); authorizationServerUrl = initializer.AuthorizationServerUrl.ThrowIfNullOrEmpty ("Initializer.AuthorizationServerUrl"); dataStore = initializer.DataStore; if (dataStore == null) { Logger.Warning("Datastore is null, as a result the user's credential will not be stored"); } scopes = initializer.Scopes; // Set the HTTP client. DefaultExponentialBackOffPolicy = initializer.DefaultExponentialBackOffPolicy; HttpClientFactory = initializer.HttpClientFactory ?? new HttpClientFactory(); var httpArgs = new CreateHttpClientArgs(); // Add exponential back-off initializer if necessary. if (DefaultExponentialBackOffPolicy != ExponentialBackOffPolicy.None) { httpArgs.Initializers.Add(new ExponentialBackOffInitializer( DefaultExponentialBackOffPolicy, () => new BackOffHandler(new ExponentialBackOff()))); } httpClient = HttpClientFactory.CreateHttpClient(httpArgs); }
public async Task <ForceClient> GetForceClient(string proxyUrl = null) { System.Net.Http.HttpClient proxyClient = null; if (!string.IsNullOrEmpty(proxyUrl)) { proxyClient = HttpClientFactory.CreateHttpClient(true, proxyUrl); } AuthenticationClient auth = new AuthenticationClient(); await auth.UsernamePasswordAsync(AuthInfo.ClientId, AuthInfo.ClientSecret, AuthInfo.Username, AuthInfo.Password, AuthInfo.TokenRequestEndpoint); ForceClient client = new ForceClient(auth.AccessInfo.InstanceUrl, auth.ApiVersion, auth.AccessInfo.AccessToken, proxyClient); return(client); }
/// <summary> /// Authorize against the B2 storage service. /// </summary> /// <returns>B2Options containing the download url, new api url, and authorization token.</returns> public async Task <B2Options> Authorize(CancellationToken cancelToken = default(CancellationToken)) { var client = HttpClientFactory.CreateHttpClient(); var requestMessage = AuthRequestGenerator.Authorize(_options); var response = await client.SendAsync(requestMessage, cancelToken); var jsonResponse = await response.Content.ReadAsStringAsync(); if (response.IsSuccessStatusCode) { var authResponse = JsonConvert.DeserializeObject <B2AuthResponse>(jsonResponse); _options.SetState(authResponse); return(_options); } else { throw new AuthorizationException(jsonResponse); } }
/// <summary> /// Requires that AccountId and ApplicationKey on the options object be set. /// </summary> /// <param name="options"></param> /// <returns></returns> public static B2Options Authorize(B2Options options) { var client = HttpClientFactory.CreateHttpClient(options.RequestTimeout); var requestMessage = AuthRequestGenerator.Authorize(options); var response = client.SendAsync(requestMessage).Result; var jsonResponse = response.Content.ReadAsStringAsync().Result; if (response.IsSuccessStatusCode) { var authResponse = JsonConvert.DeserializeObject <B2AuthResponse>(jsonResponse); options.SetState(authResponse); } else { throw new AuthorizationException(jsonResponse); } return(options); }
public Buckets(B2Options options) { _options = options; _client = HttpClientFactory.CreateHttpClient(options.RequestTimeout); }
/// <summary> /// Creates a default (unauthenticated) <see cref="ConfigurableHttpClient"/> from the /// factory. /// </summary> /// <returns>An HTTP client that can be used to make unauthenticated requests.</returns> /// <param name="clientFactory">The <see cref="HttpClientFactory"/> used to create /// the HTTP client.</param> public static ConfigurableHttpClient CreateDefaultHttpClient( this HttpClientFactory clientFactory) { return(clientFactory.CreateHttpClient(new CreateHttpClientArgs())); }
public Files(B2Options options) { _options = options; _client = HttpClientFactory.CreateHttpClient(); }
public BearerAuth(string endPointUrl, string authToken) { Client = HttpClientFactory.CreateHttpClient(endPointUrl); Client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", authToken); Client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); }
public RestClient RestClientFactory() { var serializer = new JsonRestSerializer(); return(new RestClient(HttpClientFactory.CreateHttpClient(), serializer)); }