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);
        }
Ejemplo n.º 2
0
        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);
            }
        }
Ejemplo n.º 3
0
        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");
                }
            }
        }
Ejemplo n.º 4
0
        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");
                }
            }
        }
Ejemplo n.º 5
0
        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");
                }
            }
        }
Ejemplo n.º 6
0
        /// <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");
                }
            }
        }
Ejemplo n.º 7
0
 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"));
 }
Ejemplo n.º 8
0
        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");
                }
            }
        }
Ejemplo n.º 9
0
        /// <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);
        }
Ejemplo n.º 10
0
        public void NewHttpClientReturnsForEachCreationRequest()
        {
            var firstHttpClient  = HttpClientFactory.CreateHttpClient();
            var secondHttpClient = HttpClientFactory.CreateHttpClient();

            Assert.That(firstHttpClient, Is.Not.EqualTo(secondHttpClient));
        }
Ejemplo n.º 11
0
        /// <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();
                    }
                }
            }
        }
Ejemplo n.º 12
0
        /// <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));
        }
Ejemplo n.º 13
0
        /// <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));
        }
Ejemplo n.º 14
0
        /// <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));
        }
Ejemplo n.º 15
0
        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);
        }
Ejemplo n.º 16
0
        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);
        }
Ejemplo n.º 18
0
        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);
        }
Ejemplo n.º 19
0
        /// <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);
            }
        }
Ejemplo n.º 20
0
        /// <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);
        }
Ejemplo n.º 21
0
 public Buckets(B2Options options)
 {
     _options = options;
     _client  = HttpClientFactory.CreateHttpClient(options.RequestTimeout);
 }
Ejemplo n.º 22
0
 /// <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()));
 }
Ejemplo n.º 23
0
 public Files(B2Options options)
 {
     _options = options;
     _client  = HttpClientFactory.CreateHttpClient();
 }
Ejemplo n.º 24
0
 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"));
 }
Ejemplo n.º 25
0
        public RestClient RestClientFactory()
        {
            var serializer = new JsonRestSerializer();

            return(new RestClient(HttpClientFactory.CreateHttpClient(), serializer));
        }