Exemplo n.º 1
0
        public ArcgisService(ILogger <ArcgisService> logger,
                             IConfiguration configuration,
                             IHttpClientFactory?http = null)
        {
            _logger = logger;
            var httpClient = http?.CreateClient() ?? new HttpClient();

            _datasetState = new StateDataset(httpClient);
            _datasetCity  = new CityDataset(httpClient);

            Options = new ArcgisServiceOptions();
            configuration.GetSection(ArcgisServiceOptions.OptionsPath).Bind(Options);
        }
Exemplo n.º 2
0
 public JobAppService(ISubscriptionRepository subscriptionRepository,
                      ISubscriptionCycleRepository subscriptionCycleRepository,
                      IRepository <SubscriptionCycleOrder, Guid> subscriptionCycleOrderRepository,
                      IRepository <Notification, Guid> notificationRepository,
                      INotificationDomainService notificationDomainService,
                      IPlanPriceRepository planPriceRepository,
                      IOrderRepository orderRepository,
                      IRepository <Invoice, Guid> invoiceRepository,
                      IRepository <InvoicePaymentProvider, Guid> invoicePaymentProviderRepository,
                      IOrderDomainService orderDomainService,
                      ISubscriptionDomainService subscriptionDomainService,
                      ISubscriptionCycleDomainService subscriptionCycleDomainService,
                      ISubscriptionCycleOrderDomainService subscriptionCycleOrderDomainService,
                      IInvoiceDomainService invoiceDomainService,
                      IObjectMapper mapper,
                      IPaypalService paypalService,
                      IMobbexService mobbexService,
                      IClientOptions clientOptions,
                      IHttpClientFactory httpClientFactory)
 {
     _subscriptionRepository           = subscriptionRepository ?? throw new ArgumentNullException(nameof(subscriptionRepository));
     _subscriptionCycleRepository      = subscriptionCycleRepository ?? throw new ArgumentNullException(nameof(subscriptionCycleRepository));
     _subscriptionCycleOrderRepository = subscriptionCycleOrderRepository ?? throw new ArgumentNullException(nameof(subscriptionCycleOrderRepository));
     _noticationRepository             = notificationRepository ?? throw new ArgumentNullException(nameof(notificationRepository));
     _notificationDomainService        = notificationDomainService ?? throw new ArgumentNullException(nameof(notificationDomainService));
     _planPriceRepository = planPriceRepository ?? throw new ArgumentNullException(nameof(planPriceRepository));
     _orderRepository     = orderRepository ?? throw new ArgumentNullException(nameof(orderRepository));
     _invoiceRepository   = invoiceRepository ?? throw new ArgumentNullException(nameof(invoiceRepository));
     _invoicePaymentProviderRepository = invoicePaymentProviderRepository ?? throw new ArgumentNullException(nameof(invoicePaymentProviderRepository));
     _orderDomainService                  = orderDomainService ?? throw new ArgumentNullException(nameof(orderDomainService));
     _subscriptionDomainService           = subscriptionDomainService ?? throw new ArgumentNullException(nameof(subscriptionDomainService));
     _subscriptionCycleDomainService      = subscriptionCycleDomainService ?? throw new ArgumentNullException(nameof(subscriptionCycleDomainService));
     _subscriptionCycleOrderDomainService = subscriptionCycleOrderDomainService ?? throw new ArgumentNullException(nameof(subscriptionCycleOrderDomainService));
     _invoiceDomainService                = invoiceDomainService ?? throw new ArgumentNullException(nameof(invoiceDomainService));
     _mapper        = mapper ?? throw new ArgumentNullException(nameof(mapper));
     _paypalService = paypalService ?? throw new ArgumentNullException(nameof(paypalService));
     _mobbexService = mobbexService ?? throw new ArgumentNullException(nameof(mobbexService));
     _clientOptions = clientOptions ?? throw new ArgumentNullException(nameof(clientOptions));
     _httpClient    = httpClientFactory?.CreateClient() ?? throw new ArgumentNullException(nameof(httpClientFactory));
 }
Exemplo n.º 3
0
 protected WorldOfWarshipsHandler(IHttpClientFactory factory) : base(factory.CreateClient(nameof(WorldOfWarshipsHandler)))
 {
 }
 public MeshServiceClient(IHttpClientFactory httpClientFactory, IEnvironment environment, ILogger <MeshServiceClient> logger)
 {
     _client      = httpClientFactory?.CreateClient() ?? throw new ArgumentNullException(nameof(httpClientFactory));
     _logger      = logger ?? throw new ArgumentNullException(nameof(logger));
     _environment = environment ?? throw new ArgumentNullException(nameof(environment));
 }
Exemplo n.º 5
0
 internal SalesforceClient(IHttpMessageService messageService, IOptions <SalesforceConnectorOptions> options, IHttpClientFactory clientFactory = default, ILogger <SalesforceClient> logger = default, HttpClient client = default)
 {
     _logger         = logger;
     _messageService = messageService;
     _client         = options.Value.HttpClientInstanceName is null ? client : clientFactory?.CreateClient(options.Value.HttpClientInstanceName);
     _client ??= _clientInitializer.Value;
 }
Exemplo n.º 6
0
        void InitExchanges()
        {
            // We need to be careful to only add exchanges which OnGetTickers implementation make only 1 request
            Providers.Add("binance", new ExchangeSharpRateProvider("binance", new ExchangeBinanceAPI(), true));
            Providers.Add("bittrex", new ExchangeSharpRateProvider("bittrex", new ExchangeBittrexAPI(), true));
            Providers.Add("poloniex", new ExchangeSharpRateProvider("poloniex", new ExchangePoloniexAPI(), true));
            Providers.Add("hitbtc", new ExchangeSharpRateProvider("hitbtc", new ExchangeHitBTCAPI(), true));
            Providers.Add("ndax", new ExchangeSharpRateProvider("ndax", new ExchangeNDAXAPI(), true));

            // Handmade providers
            Providers.Add(CoinGeckoRateProvider.CoinGeckoName, new CoinGeckoRateProvider(_httpClientFactory));
            Providers.Add(CoinAverageRateProvider.CoinAverageName, new CoinAverageRateProvider()
            {
                Exchange = CoinAverageRateProvider.CoinAverageName, HttpClient = _httpClientFactory?.CreateClient("EXCHANGE_COINAVERAGE"), Authenticator = _CoinAverageSettings
            });
            Providers.Add("kraken", new KrakenExchangeRateProvider()
            {
                HttpClient = _httpClientFactory?.CreateClient("EXCHANGE_KRAKEN")
            });
            Providers.Add("bylls", new ByllsRateProvider(_httpClientFactory?.CreateClient("EXCHANGE_BYLLS")));
            Providers.Add("bitbank", new BitbankRateProvider(_httpClientFactory?.CreateClient("EXCHANGE_BITBANK")));
            Providers.Add("bitpay", new BitpayRateProvider(_httpClientFactory?.CreateClient("EXCHANGE_BITPAY")));

            // Those exchanges make multiple requests when calling GetTickers so we remove them
            //DirectProviders.Add("gemini", new ExchangeSharpRateProvider("gemini", new ExchangeGeminiAPI()));
            //DirectProviders.Add("bitfinex", new ExchangeSharpRateProvider("bitfinex", new ExchangeBitfinexAPI()));
            //DirectProviders.Add("okex", new ExchangeSharpRateProvider("okex", new ExchangeOkexAPI()));
            //DirectProviders.Add("bitstamp", new ExchangeSharpRateProvider("bitstamp", new ExchangeBitstampAPI()));

            foreach (var provider in Providers.ToArray())
            {
                if (provider.Key == "cryptopia") // Shitty exchange, rate often unavailable, it spams the logs
                {
                    continue;
                }
                var prov = new BackgroundFetcherRateProvider(provider.Key, Providers[provider.Key]);
                if (provider.Key == CoinGeckoRateProvider.CoinGeckoName)
                {
                    prov.RefreshRate  = CacheSpan;
                    prov.ValidatyTime = CacheSpan + TimeSpan.FromMinutes(1.0);
                }
                else
                {
                    prov.RefreshRate  = TimeSpan.FromMinutes(1.0);
                    prov.ValidatyTime = TimeSpan.FromMinutes(5.0);
                }
                Providers[provider.Key] = prov;
            }

            var cache = new MemoryCache(_CacheOptions);

            foreach (var supportedExchange in GetCoinGeckoSupportedExchanges())
            {
                if (!Providers.ContainsKey(supportedExchange.Id))
                {
                    var coinAverage = new CoinGeckoRateProvider(_httpClientFactory)
                    {
                        Exchange = supportedExchange.Id
                    };
                    var cached = new CachedRateProvider(supportedExchange.Id, coinAverage, cache)
                    {
                        CacheSpan = CacheSpan
                    };
                    Providers.Add(supportedExchange.Id, cached);
                }
            }
            foreach (var supportedExchange in GetCoinAverageSupportedExchanges())
            {
                if (!Providers.ContainsKey(supportedExchange.Id))
                {
                    var coinAverage = new CoinGeckoRateProvider(_httpClientFactory)
                    {
                        Exchange = supportedExchange.Id
                    };
                    var cached = new CachedRateProvider(supportedExchange.Id, coinAverage, cache)
                    {
                        CacheSpan = CacheSpan
                    };
                    Providers.Add(supportedExchange.Id, cached);
                }
            }
        }
 public EmployeeService(IHttpClientFactory httpClientFactory)
 {
     _httpClient = httpClientFactory.CreateClient("EmployeeManagementApi");
 }
Exemplo n.º 8
0
 public WeatherRepository(IHttpClientFactory clientFactory)
 {
     _httpClient = clientFactory.CreateClient("weatheApi");
 }
Exemplo n.º 9
0
 /// <summary>
 /// Gets the movie db response.
 /// </summary>
 internal Task <HttpResponseMessage> GetMovieDbResponse(HttpRequestMessage message)
 {
     message.Headers.UserAgent.Add(new ProductInfoHeaderValue(_appHost.ApplicationUserAgent));
     return(_httpClientFactory.CreateClient().SendAsync(message));
 }
Exemplo n.º 10
0
        public async Task TripProcessor([CosmosDBTrigger(
                                             databaseName: "ContosoAuto",
                                             collectionName: "telemetry",
                                             ConnectionStringSetting = "CosmosDBConnection",
                                             LeaseCollectionName = "leases",
                                             LeaseCollectionPrefix = "trips",
                                             CreateLeaseCollectionIfNotExists = true,
                                             StartFromBeginning = true)] IReadOnlyList <Document> vehicleEvents,
                                        ILogger log)
        {
            log.LogInformation($"Evaluating {vehicleEvents.Count} events from Cosmos DB to optionally update Trip and Consignment metadata.");

            // Retrieve the Trip records by VIN, compare the odometer reading to the starting odometer reading to calculate miles driven,
            // and update the Trip and Consignment status and send an alert if needed once completed.
            var sendTripAlert     = false;
            var database          = "ContosoAuto";
            var metadataContainer = "metadata";

            if (vehicleEvents.Count > 0)
            {
                foreach (var group in vehicleEvents.GroupBy(singleEvent => singleEvent.GetPropertyValue <string>("vin")))
                {
                    // TODO 3: We have grouped the events by vehicle VIN. Assign local variables to hold the VIN, get the max odometer value, and average refrigeration unit temperature.
                    // Complete: var vin = ...; var odometerHigh = ...; var averageRefrigerationUnitTemp = ...;

                    // First, retrieve the metadata Cosmos DB container reference:
                    var container = _cosmosClient.GetContainer(database, metadataContainer);

                    // Create a query, defining the partition key so we don't execute a fan-out query (saving RUs), where the entity type is a Trip and the status is not Completed, Canceled, or Inactive.
                    var query = container.GetItemLinqQueryable <Trip>(requestOptions: new QueryRequestOptions {
                        PartitionKey = new Microsoft.Azure.Cosmos.PartitionKey(vin)
                    })
                                .Where(p => p.status != WellKnown.Status.Completed &&
                                       p.status != WellKnown.Status.Canceled &&
                                       p.status != WellKnown.Status.Inactive &&
                                       p.entityType == WellKnown.EntityTypes.Trip)
                                .ToFeedIterator();

                    if (query.HasMoreResults)
                    {
                        // Only retrieve the first result.
                        var trip = (await query.ReadNextAsync()).FirstOrDefault();

                        if (trip != null)
                        {
                            // Retrieve the Consignment record.
                            var document = await container.ReadItemAsync <Consignment>(trip.consignmentId,
                                                                                       new Microsoft.Azure.Cosmos.PartitionKey(trip.consignmentId));

                            var consignment       = document.Resource;
                            var updateTrip        = false;
                            var updateConsignment = false;

                            // Calculate how far along the vehicle is for this trip.
                            var milesDriven = odometerHigh - trip.odometerBegin;
                            if (milesDriven >= trip.plannedTripDistance)
                            {
                                // The trip is completed!
                                trip.status        = WellKnown.Status.Completed;
                                trip.odometerEnd   = odometerHigh;
                                trip.tripEnded     = DateTime.UtcNow;
                                consignment.status = WellKnown.Status.Completed;

                                // Update the trip and consignment records.
                                updateTrip        = true;
                                updateConsignment = true;

                                sendTripAlert = true;
                            }
                            else
                            {
                                if (DateTime.UtcNow >= consignment.deliveryDueDate && trip.status != WellKnown.Status.Delayed)
                                {
                                    // The trip is delayed!
                                    trip.status        = WellKnown.Status.Delayed;
                                    consignment.status = WellKnown.Status.Delayed;

                                    // Update the trip and consignment records.
                                    updateTrip        = true;
                                    updateConsignment = true;

                                    sendTripAlert = true;
                                }
                            }

                            if (trip.tripStarted == null)
                            {
                                // Set the trip start date.
                                trip.tripStarted = DateTime.UtcNow;
                                // Set the trip and consignment status to Active.
                                trip.status        = WellKnown.Status.Active;
                                consignment.status = WellKnown.Status.Active;

                                updateTrip        = true;
                                updateConsignment = true;

                                sendTripAlert = true;
                            }

                            // Update the trip and consignment records.
                            // TODO 4: Complete the code to update the Trip and Consignment records.
                            // Complete: if (updateTrip) { ... } if (updateConsignment) { ... }

                            // Send a trip alert.
                            if (sendTripAlert)
                            {
                                // Have the HttpClient factory create a new client instance.
                                var httpClient = _httpClientFactory.CreateClient(NamedHttpClients.LogicAppClient);

                                // Create the payload to send to the Logic App.
                                var payload = new LogicAppAlert
                                {
                                    consignmentId        = trip.consignmentId,
                                    customer             = trip.consignment.customer,
                                    deliveryDueDate      = trip.consignment.deliveryDueDate,
                                    hasHighValuePackages = trip.packages.Any(p => p.highValue),
                                    id = trip.id,
                                    lastRefrigerationUnitTemperatureReading = averageRefrigerationUnitTemp,
                                    location = trip.location,
                                    lowestPackageStorageTemperature = trip.packages.Min(p => p.storageTemperature),
                                    odometerBegin       = trip.odometerBegin,
                                    odometerEnd         = trip.odometerEnd,
                                    plannedTripDistance = trip.plannedTripDistance,
                                    tripStarted         = trip.tripStarted,
                                    tripEnded           = trip.tripEnded,
                                    status             = trip.status,
                                    vin                = trip.vin,
                                    temperatureSetting = trip.temperatureSetting,
                                    recipientEmail     = Environment.GetEnvironmentVariable("RecipientEmail")
                                };

                                var postBody = JsonConvert.SerializeObject(payload);

                                // TODO 5: Add code to post the LogicAppAlert payload to the Logic App in JSON format.
                                // Complete: await httpClient.PostAsync( ... ));
                            }
                        }
                    }
                }
            }
        }
Exemplo n.º 11
0
        public async Task <IActionResult> Login(LoginInputModel model, string button)
        {
            // check if we are in the context of an authorization request
            var context = await _interaction.GetAuthorizationContextAsync(model.ReturnUrl);

            // the user clicked the "cancel" button
            if (button != "login")
            {
                if (context != null)
                {
                    // if the user cancels, send a result back into IdentityServer as if they
                    // denied the consent (even if this client does not require consent).
                    // this will send back an access denied OIDC error response to the client.
                    await _interaction.GrantConsentAsync(context, ConsentResponse.Denied);

                    // we can trust model.ReturnUrl since GetAuthorizationContextAsync returned non-null
                    if (await _clientStore.IsPkceClientAsync(context.ClientId))
                    {
                        // if the client is PKCE then we assume it's native, so this change in how to
                        // return the response is for better UX for the end user.
                        return(View("Redirect", new RedirectViewModel {
                            RedirectUrl = model.ReturnUrl
                        }));
                    }

                    return(Redirect(model.ReturnUrl));
                }
                else
                {
                    // since we don't have a valid context, then we just go back to the home page
                    return(Redirect("~/"));
                }
            }

            if (ModelState.IsValid)
            {
                HttpClient client = _httpClientFactory.CreateClient();

                var disco = await client.GetDiscoveryDocumentAsync(new DiscoveryDocumentRequest
                {
                    Address = Configuration["IdentityService:Authority"],
                    Policy  =
                    {
                        RequireHttps = false
                    }
                });

                if (disco.IsError)
                {
                    throw new Exception(disco.Error);
                }
                var tokenResponse = await client.RequestPasswordTokenAsync(new PasswordTokenRequest
                {
                    Address      = disco.TokenEndpoint,
                    ClientId     = "GeneralApiClient",
                    ClientSecret = "P@ssw0rd",
                    UserName     = model.Username,
                    Password     = model.Password,
                    Scope        = "GeneralServiceApi offline_access"
                });

                if (!tokenResponse.IsError)
                {
                    await _events.RaiseAsync(new UserLoginSuccessEvent("", model.Username, ""));

                    // only set explicit expiration here if user chooses "remember me".
                    // otherwise we rely upon expiration configured in cookie middleware.
                    AuthenticationProperties props = null;
                    if (AccountOptions.AllowRememberLogin && model.RememberLogin)
                    {
                        props = new AuthenticationProperties
                        {
                            IsPersistent = true,
                            ExpiresUtc   = DateTimeOffset.UtcNow.Add(AccountOptions.RememberMeLoginDuration)
                        };
                    }
                    ;
                    Claim        accessTokenClaim  = new Claim("general_access_token", tokenResponse.AccessToken);
                    Claim        refreshTokenClaim = new Claim("general_refresh_token", tokenResponse.RefreshToken);
                    List <Claim> listClaim         = new List <Claim>()
                    {
                        accessTokenClaim, refreshTokenClaim
                    };
                    // issue authentication cookie with subject ID and username
                    await HttpContext.SignInAsync(model.Username, props, listClaim.ToArray());

                    if (context != null)
                    {
                        if (await _clientStore.IsPkceClientAsync(context.ClientId))
                        {
                            // if the client is PKCE then we assume it's native, so this change in how to
                            // return the response is for better UX for the end user.
                            return(View("Redirect", new RedirectViewModel {
                                RedirectUrl = model.ReturnUrl
                            }));
                        }

                        // we can trust model.ReturnUrl since GetAuthorizationContextAsync returned non-null
                        return(Redirect(model.ReturnUrl));
                    }

                    // request for a local page
                    if (Url.IsLocalUrl(model.ReturnUrl))
                    {
                        return(Redirect(model.ReturnUrl));
                    }
                    else if (string.IsNullOrEmpty(model.ReturnUrl))
                    {
                        return(Redirect("~/"));
                    }
                    else
                    {
                        // user might have clicked on a malicious link - should be logged
                        throw new Exception("invalid return URL");
                    }
                }
                else
                {
                    await _events.RaiseAsync(new UserLoginFailureEvent(model.Username, "invalid credentials"));

                    string errMsg = tokenResponse.Error + ":" + (string.IsNullOrEmpty(tokenResponse.ErrorDescription) ? "" : tokenResponse.ErrorDescription);
                    ModelState.AddModelError(string.Empty, errMsg);
                }
            }

            // something went wrong, show form with error
            var vm = await BuildLoginViewModelAsync(model);

            return(View(vm));
        }
Exemplo n.º 12
0
 public ChatHub(IHttpClientFactory httpClientFactory)
 {
     httpClient = httpClientFactory.CreateClient();
     eh         = new EntityHelper();
 }
Exemplo n.º 13
0
 public AnimalService(IHttpClientFactory httpClientFactory)
 {
     _animalClient = httpClientFactory.CreateClient("AnimalCenter");
 }
Exemplo n.º 14
0
 public UploadAudioCommandHandler(IHttpClientFactory httpClientFactory, IHttpContextAccessor httpContextAccessor)
 {
     _httpClient         = httpClientFactory.CreateClient(HASClientFactories.UPLOAD);
     _httpContextAcessor = httpContextAccessor;
 }
Exemplo n.º 15
0
 public WebSiteDownloadRequestHandler(IHttpClientFactory httpClientFactory)
 {
     _httpClient = httpClientFactory.CreateClient(nameof(WebSiteDownloadRequestHandler));
 }
Exemplo n.º 16
0
        public async Task <ImageCacherObject[]> DownloadImages(string[] tags, bool isExplicit, DapiSearchType type)
        {
            var tag = "rating%3Aexplicit+";

            tag += string.Join('+', tags.Select(x => x.Replace(" ", "_", StringComparison.InvariantCulture).ToLowerInvariant()));
            if (isExplicit)
            {
                tag = "rating%3Aexplicit+" + tag;
            }
            var website = "";

            switch (type)
            {
            case DapiSearchType.Safebooru:
                website = $"https://safebooru.org/index.php?page=dapi&s=post&q=index&limit=1000&tags={tag}";
                break;

            case DapiSearchType.E621:
                website = $"https://e621.net/post/index.json?limit=1000&tags={tag}";
                break;

            case DapiSearchType.Danbooru:
                website = $"http://danbooru.donmai.us/posts.json?limit=100&tags={tag}";
                break;

            case DapiSearchType.Gelbooru:
                website = $"http://gelbooru.com/index.php?page=dapi&s=post&q=index&limit=100&tags={tag}";
                break;

            case DapiSearchType.Rule34:
                website = $"https://rule34.xxx/index.php?page=dapi&s=post&q=index&limit=100&tags={tag}";
                break;

            case DapiSearchType.Konachan:
                website = $"https://konachan.com/post.json?s=post&q=index&limit=100&tags={tag}";
                break;

            case DapiSearchType.Yandere:
                website = $"https://yande.re/post.json?limit=100&tags={tag}";
                break;

            case DapiSearchType.Derpibooru:
                website = $"https://derpibooru.org/search.json?q={tag?.Replace('+', ',')}&perpage=49";
                break;
            }

            try
            {
                if (type == DapiSearchType.Konachan || type == DapiSearchType.Yandere ||
                    type == DapiSearchType.E621 || type == DapiSearchType.Danbooru)
                {
                    using (var http = _httpFactory.CreateClient().AddFakeHeaders())
                    {
                        var data = await http.GetStringAsync(website).ConfigureAwait(false);

                        return(JsonConvert.DeserializeObject <DapiImageObject[]>(data)
                               .Where(x => x.FileUrl != null)
                               .Select(x => new ImageCacherObject(x, type))
                               .ToArray());
                    }
                }

                if (type == DapiSearchType.Derpibooru)
                {
                    using (var http = _httpFactory.CreateClient().AddFakeHeaders())
                    {
                        var data = await http.GetStringAsync(website).ConfigureAwait(false);

                        return(JsonConvert.DeserializeObject <DerpiContainer>(data)
                               .Search
                               .Where(x => !string.IsNullOrWhiteSpace(x.Image))
                               .Select(x => new ImageCacherObject("https:" + x.Image,
                                                                  type, x.Tags, x.Score))
                               .ToArray());
                    }
                }

                return((await LoadXmlAsync(website, type).ConfigureAwait(false)).ToArray());
            }
            catch (Exception ex)
            {
                _log.Warn(ex.Message);
                return(Array.Empty <ImageCacherObject>());
            }
        }
Exemplo n.º 17
0
        public async Task <ActionResult> CreatePayment()
        {
            var hostingDomain = Request.Host.Value;
            var accessToken   = await GetAccessToken();

            var user = await RetrieveUser();

            Order order = _orderRepository.GetBy(user.Bills.Last().BillId);

            //var currentUser = await _workContext.GetCurrentUser();
            //var cart = await _cartService.GetActiveCartDetails(currentUser.Id);
            if (order == null)
            {
                return(NotFound());
            }

            var regionInfo          = new RegionInfo(new CultureInfo("en-US").LCID);
            var experienceProfileId = await CreateExperienceProfile(accessToken);

            var httpClient = _httpClientFactory.CreateClient();

            httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
            var paypalAcceptedNumericFormatCulture = CultureInfo.CreateSpecificCulture("en-US");
            var paymentCreateRequest = new PaymentCreateRequest
            {
                experience_profile_id = experienceProfileId,
                intent = "sale",
                payer  = new Payer
                {
                    payment_method = "paypal"
                },
                transactions = new Transaction[]
                {
                    new Transaction {
                        amount = new Amount
                        {
                            total    = (order.BillTotal / 23000 + CalculatePaymentFee(order.BillTotal / 23000)).ToString("N2", paypalAcceptedNumericFormatCulture),
                            currency = regionInfo.ISOCurrencySymbol,
                            details  = new Details
                            {
                                handling_fee = CalculatePaymentFee(order.BillTotal / 23000).ToString("N2", paypalAcceptedNumericFormatCulture),
                                subtotal     = (order.BillTotal / 23000).ToString("N2", paypalAcceptedNumericFormatCulture),
                                tax          = "0",
                                shipping     = "0"
                            }
                        }
                    }
                },
                redirect_urls = new Redirect_Urls
                {
                    cancel_url = $"http://{hostingDomain}/PaypalExpress/Cancel",  //Haven't seen it being used anywhere
                    return_url = $"http://{hostingDomain}/PaypalExpress/Success", //Haven't seen it being used anywhere
                }
            };

            var response = await httpClient.PostAsJsonAsync($"https://api{PaypalExpressConfig.EnvironmentUrlPart}.paypal.com/v1/payments/payment", paymentCreateRequest);

            var responseBody = await response.Content.ReadAsStringAsync();

            dynamic payment = JObject.Parse(responseBody);

            if (response.IsSuccessStatusCode)
            {
                string paymentId = payment.id;
                return(Ok(new { PaymentId = paymentId }));
            }

            return(BadRequest(responseBody));
        }
Exemplo n.º 18
0
 public VyService(IHttpClientFactory clientFactory, IMemoryCache cache, ILogger <VyService> logger)
 {
     _vyClient = clientFactory.CreateClient("vyClient");
     _cache    = cache;
     _logger   = logger;
 }
Exemplo n.º 19
0
        public async Task Google([Leftover] string query = null)
        {
            var oterms = query?.Trim();

            if (!await ValidateQuery(ctx.Channel, query).ConfigureAwait(false))
            {
                return;
            }

            query = WebUtility.UrlEncode(oterms).Replace(' ', '+');

            var fullQueryLink = $"https://www.google.ca/search?q={ query }&safe=on&lr=lang_eng&hl=en&ie=utf-8&oe=utf-8";

            using (var msg = new HttpRequestMessage(HttpMethod.Get, fullQueryLink))
            {
                msg.Headers.AddFakeHeaders();
                var parser = new HtmlParser();
                var test   = "";
                using (var http = _httpFactory.CreateClient())
                    using (var response = await http.SendAsync(msg).ConfigureAwait(false))
                        using (var document = await parser.ParseDocumentAsync(test = await response.Content.ReadAsStringAsync().ConfigureAwait(false)).ConfigureAwait(false))
                        {
                            var elems = document.QuerySelectorAll("div.g");

                            var resultsElem  = document.QuerySelectorAll("#resultStats").FirstOrDefault();
                            var totalResults = resultsElem?.TextContent;
                            //var time = resultsElem.Children.FirstOrDefault()?.TextContent
                            //^ this doesn't work for some reason, <nobr> is completely missing in parsed collection
                            if (!elems.Any())
                            {
                                return;
                            }

                            var results = elems.Select <IElement, GoogleSearchResult?>(elem =>
                            {
                                var aTag = elem.QuerySelector("a") as IHtmlAnchorElement; // <h3> -> <a>
                                var href = aTag?.Href;
                                var name = aTag?.Children.FirstOrDefault()?.TextContent;
                                if (href == null || name == null)
                                {
                                    return(null);
                                }

                                var txt = elem.QuerySelectorAll(".st").FirstOrDefault()?.TextContent;

                                if (txt == null)
                                {
                                    return(null);
                                }

                                return(new GoogleSearchResult(name, href, txt));
                            }).Where(x => x != null).Take(5);

                            var embed = new EmbedBuilder()
                                        .WithOkColor()
                                        .WithAuthor(eab => eab.WithName(GetText("search_for") + " " + oterms.TrimTo(50))
                                                    .WithUrl(fullQueryLink)
                                                    .WithIconUrl("http://i.imgur.com/G46fm8J.png"))
                                        .WithTitle(ctx.User.ToString())
                                        .WithFooter(efb => efb.WithText(totalResults));

                            var desc = await Task.WhenAll(results.Select(async res =>
                                                                         $"[{Format.Bold(res?.Title)}]({(await _google.ShortenUrl(res?.Link).ConfigureAwait(false))})\n{res?.Text?.TrimTo(400 - res.Value.Title.Length - res.Value.Link.Length)}\n\n"))
                                       .ConfigureAwait(false);

                            var descStr = string.Concat(desc);
                            await ctx.Channel.EmbedAsync(embed.WithDescription(descStr)).ConfigureAwait(false);
                        }
            }
        }
Exemplo n.º 20
0
 public MicrosoftLanguageDetectorClient(IHttpClientFactory httpClientFactory, ILogger <MicrosoftLanguageDetectorClient> logger)
 {
     _httpClient = httpClientFactory?.CreateClient("MicrosoftLanguageDetectorClient")
                   ?? throw new ArgumentNullException(nameof(httpClientFactory));
     _logger = logger ?? throw new ArgumentNullException(nameof(logger));
 }
Exemplo n.º 21
0
        public async Task <List <string> > checkQuantity(addedProduct[] addedToCart)
        {
            List <ProductDB> products = new List <ProductDB>();

            products = await GetAllProducts();

            //Products.ForEach(x => avl.Add(x.product_availableQuantity));

            for (int i = 0; i < addedToCart.Length; i++)
            {
                /*List<ProductDB> products = new List<ProductDB>();
                 * products = await GetAllProducts();*/
                var k = products.FindIndex(x => x.ProductId == addedToCart[i].productId);

                Debug.WriteLine(k);
                if (addedToCart[i].productaddedQuantity > products[k].ProductavailableQuantity)
                {
                    Debug.WriteLine("Insufficient");
                    msg.Add("Insufficient");
                    msg.Add("Order Incomplete");
                    msg.Add("Order could not be completed as we have Insufficient Quantity of Items required. Sorry!");
                    msg.Add("View Cart");
                    return(msg);
                }
                else
                {
                    var updateSql = _context.Products.SingleOrDefault(p => p.ProductId == addedToCart[i].productId);
                    if (updateSql != null)
                    {
                        updateSql.ProductavailableQuantity = updateSql.ProductavailableQuantity - addedToCart[i].productaddedQuantity;
                    }
                }
            }

            var client   = _clientFactory.CreateClient();
            var response = await client.GetStringAsync("https://localhost:44356/payment");

            bool paymentStatus = JsonConvert.DeserializeObject <bool>(response);

            if (paymentStatus)
            {
                _context.SaveChanges();//saved a loop

                var removeProduct = from p in _context.Products
                                    where p.ProductavailableQuantity == 0
                                    select p;

                foreach (var p in removeProduct.ToList())//can this cause performance issues in a huge data set
                {
                    _context.Products.Remove(p);
                    _context.SaveChanges();
                }


                Debug.WriteLine("Payment Succ");
                msg.Add("Success");
                msg.Add("Thank You!");
                msg.Add("Payment Successful.");
                msg.Add("Continue Shopping");
                return(msg);
            }
            else
            {
                Debug.WriteLine("Payment Fail");
                msg.Add("Failure");
                msg.Add("Order Incomplete");
                msg.Add("Order could not be completed as your Payment Failed. Please Try Again.");
                msg.Add("View Cart");
                return(msg);
            }
        }
 public IdentityServer(IHttpClientFactory httpClientFactory, IHttpContextAccessor httpContextAccessor)
 {
     _client      = httpClientFactory.CreateClient("IdentityServer");
     _httpContext = httpContextAccessor.HttpContext;
 }
 public BibleApiVerseLookupService(IHttpClientFactory clientFactory, ILogger <BibleApiVerseLookupService> logger)
 {
     Logger    = logger ?? throw new ArgumentNullException(nameof(logger));
     ApiClient = clientFactory?.CreateClient(BibleApiHttpClientName) ?? throw new ArgumentNullException(nameof(clientFactory));
 }
 public HttpEonetClient(IHttpClientFactory clientFactory, ILogger <HttpEonetClient> logger)
 {
     _httpClient = clientFactory.CreateClient("eonetClient");
     _logger     = logger;
 }
Exemplo n.º 25
0
        private void InitExchanges()
        {
            // We need to be careful to only add exchanges which OnGetTickers implementation make only 1 request
            Providers.Add("binance", new ExchangeSharpRateProvider("binance", new ExchangeBinanceAPI(), true));
            Providers.Add("bittrex", new ExchangeSharpRateProvider("bittrex", new ExchangeBittrexAPI(), true));
            Providers.Add("poloniex", new ExchangeSharpRateProvider("poloniex", new ExchangePoloniexAPI(), true));
            Providers.Add("hitbtc", new ExchangeSharpRateProvider("hitbtc", new ExchangeHitbtcAPI(), false));
            Providers.Add("cryptopia", new ExchangeSharpRateProvider("cryptopia", new ExchangeCryptopiaAPI(), false));

            // Handmade providers
            Providers.Add("bitpay", new BitpayRateProvider(new NBitpayClient.Bitpay(new NBitcoin.Key(), new Uri("https://bitpay.com/"))));
            Providers.Add(QuadrigacxRateProvider.QuadrigacxName, new QuadrigacxRateProvider());
            Providers.Add(CoinAverageRateProvider.CoinAverageName, new CoinAverageRateProvider()
            {
                Exchange = CoinAverageRateProvider.CoinAverageName, HttpClient = _httpClientFactory?.CreateClient(), Authenticator = _CoinAverageSettings
            });
            Providers.Add("kraken", new KrakenExchangeRateProvider()
            {
                HttpClient = _httpClientFactory?.CreateClient()
            });

            // Those exchanges make multiple requests when calling GetTickers so we remove them
            //DirectProviders.Add("gdax", new ExchangeSharpRateProvider("gdax", new ExchangeGdaxAPI()));
            //DirectProviders.Add("gemini", new ExchangeSharpRateProvider("gemini", new ExchangeGeminiAPI()));
            //DirectProviders.Add("bitfinex", new ExchangeSharpRateProvider("bitfinex", new ExchangeBitfinexAPI()));
            //DirectProviders.Add("okex", new ExchangeSharpRateProvider("okex", new ExchangeOkexAPI()));
            //DirectProviders.Add("bitstamp", new ExchangeSharpRateProvider("bitstamp", new ExchangeBitstampAPI()));

            foreach (var provider in Providers.ToArray())
            {
                var prov = new BackgroundFetcherRateProvider(Providers[provider.Key]);
                if (provider.Key == CoinAverageRateProvider.CoinAverageName)
                {
                    prov.RefreshRate  = CacheSpan;
                    prov.ValidatyTime = CacheSpan + TimeSpan.FromMinutes(1.0);
                }
                else
                {
                    prov.RefreshRate  = TimeSpan.FromMinutes(1.0);
                    prov.ValidatyTime = TimeSpan.FromMinutes(5.0);
                }
                Providers[provider.Key] = prov;
            }

            var cache = new MemoryCache(_CacheOptions);

            foreach (var supportedExchange in GetSupportedExchanges())
            {
                if (!Providers.ContainsKey(supportedExchange.Key))
                {
                    var coinAverage = new CoinAverageRateProvider()
                    {
                        Exchange      = supportedExchange.Key,
                        HttpClient    = _httpClientFactory?.CreateClient(),
                        Authenticator = _CoinAverageSettings
                    };
                    var cached = new CachedRateProvider(supportedExchange.Key, coinAverage, cache)
                    {
                        CacheSpan = CacheSpan
                    };
                    Providers.Add(supportedExchange.Key, cached);
                }
            }
        }
Exemplo n.º 26
0
        public async Task <string> SetWorkOrderMastersModel(int id)
        {
            try
            {
#if DEBUG
                // id = 34;
#endif
                var master             = _uow.VwWsWorkOrderMaster.Single(x => x.StokCikisId == id);
                var invoices           = _uow.VwWsWorkOrderInvoice.Search(x => x.StokCikisId == id);
                var invoiceDetails     = _uow.VwWsWorkOrderInvoiceDetails.Search(x => x.StokCikisId == id);
                var invoiceDetailsTcgb = _uow.VwWsWorkOrderInvoiceDetailsTcgb.Search(x => x.StokCikisId == id);

                if (master == null)
                {
                    return("Master kaydı null geldi. Bir sorun var!");
                }

                var dto = new WorkOrderMasterModelDTO
                {
                    VwWsWorkOrderMaster = new VwWsWorkOrderMasterDTO()
                    {
                        DeclarationType   = master.DeclarationType,
                        UserNameWs        = master.UserNameWs,
                        PasswordWs        = master.PasswordWs,
                        StokCikisId       = master.StokCikisId,
                        WorkOrderMasterId = master.WorkOrderMasterId,
                        WorkOrderNo       = master.WorkOrderNo
                    },
                    VwWsWorkOrderInvoices           = new List <VwWsWorkOrderInvoiceDTO>(),
                    VwWsWorkOrderInvoiceDetails     = new List <VwWsWorkOrderInvoiceDetailsDTO>(),
                    VwWsWorkOrderInvoiceDetailsTcgb = new List <VwWsWorkOrderInvoiceDetailsTcgbDto>()
                };

                foreach (var invoice in invoices)
                {
                    dto.VwWsWorkOrderInvoices.Add(new VwWsWorkOrderInvoiceDTO()
                    {
                        AgentName         = invoice.AgentName,
                        AwbNo             = invoice.AwbNo,
                        Blno              = invoice.Blno,
                        ConsgnAddress     = invoice.ConsgnAddress,
                        ConsgnCity        = invoice.ConsgnCity,
                        ConsgnCountry     = invoice.ConsgnCountry,
                        ConsgnName        = invoice.ConsgnName,
                        ConsgnNo          = invoice.ConsgnNo,
                        ContainerNo       = invoice.ContainerNo,
                        Customs           = invoice.Customs,
                        DeliveryLocation  = invoice.DeliveryLocation,
                        EntryExitCustoms  = invoice.EntryExitCustoms,
                        FreightAmount     = invoice.FreightAmount,
                        FreightCurrency   = invoice.FreightCurrency,
                        GtbReferenceNo    = invoice.GtbReferenceNo,
                        Incoterms         = invoice.Incoterms,
                        InsuranceAmount   = invoice.InsuranceAmount,
                        InsuranceCurrency = invoice.InsuranceCurrency,
                        InvoiceAmount     = invoice.InvoiceAmount,
                        InvoiceCurrency   = invoice.InvoiceCurrency,
                        InvoiceId         = invoice.InvoiceId,
                        PaymentMethod     = invoice.PaymentMethod,
                        PlateNo           = invoice.PlateNo,
                        SenderAddress     = invoice.SenderAddress,
                        SenderCity        = invoice.SenderCity,
                        SenderCountry     = invoice.SenderCountry,
                        SenderName        = invoice.SenderName,
                        SenderNo          = invoice.SenderNo,
                        StokCikisId       = invoice.StokCikisId,
                        TransptrName      = invoice.TransptrName,
                        VesselName        = invoice.VesselName,
                        WorkOrderMasterId = invoice.WorkOrderMasterId,
                        WorkOrderNo       = invoice.WorkOrderNo
                    });
                }

                foreach (var detail in invoiceDetails.OrderBy(x => x.ItemNumber))
                {
                    dto.VwWsWorkOrderInvoiceDetails.Add(new VwWsWorkOrderInvoiceDetailsDTO()
                    {
                        ActualQuantity    = detail.ActualQuantity,
                        CommclDesc        = detail.CommclDesc,
                        CountryOfOrigin   = detail.CountryOfOrigin,
                        DescGoods         = detail.DescGoods,
                        GrossWeight       = detail.GrossWeight,
                        HsCode            = detail.HsCode,
                        IncentiveLineNo   = detail.IncentiveLineNo,
                        IntrnlAgmt        = detail.IntrnlAgmt,
                        InvoiceAmount     = detail.InvoiceAmount,
                        InvoiceDate       = detail.InvoiceDate,
                        IncentiveDate     = detail.IncentiveDate,
                        InvoiceDetailId   = detail.InvoiceDetailId,
                        InvoiceId         = detail.InvoiceId,
                        InvoiceNo         = detail.InvoiceNo,
                        InvoiceQuantity   = detail.InvoiceQuantity,
                        ItemNumber        = detail.ItemNumber,
                        NetWeight         = detail.NetWeight,
                        NumberOfPackages  = detail.NumberOfPackages,
                        PkgType           = detail.PkgType,
                        ProducerCompany   = detail.ProducerCompany,
                        ProducerCompanyNo = detail.ProducerCompanyNo,
                        ProductNo         = detail.ProductNo,
                        StokCikisId       = detail.StokCikisId,
                        Uom = detail.Uom,
                        WorkOrderMasterId = detail.WorkOrderMasterId,
                        WorkOrderNo       = detail.WorkOrderNo,
                    });
                }

                foreach (var detailTcgb in invoiceDetailsTcgb)
                {
                    dto.VwWsWorkOrderInvoiceDetailsTcgb.Add(new VwWsWorkOrderInvoiceDetailsTcgbDto()
                    {
                        StokCikisId          = detailTcgb.StokCikisId,
                        DeclarationDate      = detailTcgb.DeclarationDate,
                        DeclarationNo        = detailTcgb.DeclarationNo,
                        Description          = detailTcgb.Description,
                        InvoiceDetailId      = detailTcgb.InvoiceDetailId,
                        InvoiceDetailsTcgbId = detailTcgb.InvoiceDetailsTcgbId,
                        ItemNo   = detailTcgb.ItemNo,
                        Quantity = detailTcgb.Quantity
                    });
                }

                var client  = _clientFactory.CreateClient();
                var content = JsonConvert.SerializeObject(dto);
                var ws      = await client.PostAsync(WebServiceUrl, new StringContent(content, System.Text.Encoding.UTF8, "application/json"));

                ws.EnsureSuccessStatusCode();

                var deger = (await ws.Content.ReadAsStringAsync()).ToString();

                return(deger);
            }
            catch (Exception ex)
            {
                return(ex.Message);
            }
        }
 /// <inheritdoc />
 public Task <HttpResponseMessage> GetImageResponse(string url, CancellationToken cancellationToken)
 {
     return(_httpClientFactory.CreateClient(NamedClient.Default).GetAsync(new Uri(url), cancellationToken));
 }
Exemplo n.º 28
0
 public MemberDataService(IHttpClientFactory clientFactory)
 {
     httpClient = clientFactory.CreateClient("FamilyTaskAPI");
     members    = new List <MemberVm>();
     LoadMembers();
 }
Exemplo n.º 29
0
        private void InitExchanges()
        {
            // We need to be careful to only add exchanges which OnGetTickers implementation make only 1 request
            Providers.Add("binance", new ExchangeSharpRateProvider("binance", new ExchangeBinanceAPI(), true));
            Providers.Add("bittrex", new ExchangeSharpRateProvider("bittrex", new ExchangeBittrexAPI(), true));
            Providers.Add("poloniex", new ExchangeSharpRateProvider("poloniex", new ExchangePoloniexAPI(), true));
            Providers.Add("hitbtc", new ExchangeSharpRateProvider("hitbtc", new ExchangeHitbtcAPI(), false));

            // Cryptopia is often not available
            // Disabled because of https://twitter.com/Cryptopia_NZ/status/1085084168852291586
            // Providers.Add("cryptopia", new ExchangeSharpRateProvider("cryptopia", new ExchangeCryptopiaAPI(), false));

            // Handmade providers
            Providers.Add(QuadrigacxRateProvider.QuadrigacxName, new QuadrigacxRateProvider());
            Providers.Add(CoinAverageRateProvider.CoinAverageName, new CoinAverageRateProvider()
            {
                Exchange = CoinAverageRateProvider.CoinAverageName, HttpClient = _httpClientFactory?.CreateClient("EXCHANGE_COINAVERAGE"), Authenticator = _CoinAverageSettings
            });
            Providers.Add("kraken", new KrakenExchangeRateProvider()
            {
                HttpClient = _httpClientFactory?.CreateClient("EXCHANGE_KRAKEN")
            });
            Providers.Add("bylls", new ByllsRateProvider(_httpClientFactory?.CreateClient("EXCHANGE_BYLLS")));

            // Those exchanges make multiple requests when calling GetTickers so we remove them
            //DirectProviders.Add("gdax", new ExchangeSharpRateProvider("gdax", new ExchangeGdaxAPI()));
            //DirectProviders.Add("gemini", new ExchangeSharpRateProvider("gemini", new ExchangeGeminiAPI()));
            //DirectProviders.Add("bitfinex", new ExchangeSharpRateProvider("bitfinex", new ExchangeBitfinexAPI()));
            //DirectProviders.Add("okex", new ExchangeSharpRateProvider("okex", new ExchangeOkexAPI()));
            //DirectProviders.Add("bitstamp", new ExchangeSharpRateProvider("bitstamp", new ExchangeBitstampAPI()));

            foreach (var provider in Providers.ToArray())
            {
                if (provider.Key == "cryptopia") // Shitty exchange, rate often unavailable, it spams the logs
                {
                    continue;
                }
                var prov = new BackgroundFetcherRateProvider(Providers[provider.Key]);
                if (provider.Key == CoinAverageRateProvider.CoinAverageName)
                {
                    prov.RefreshRate  = CacheSpan;
                    prov.ValidatyTime = CacheSpan + TimeSpan.FromMinutes(1.0);
                }
                else
                {
                    prov.RefreshRate  = TimeSpan.FromMinutes(1.0);
                    prov.ValidatyTime = TimeSpan.FromMinutes(5.0);
                }
                Providers[provider.Key] = prov;
            }

            var cache = new MemoryCache(_CacheOptions);

            foreach (var supportedExchange in GetSupportedExchanges())
            {
                if (!Providers.ContainsKey(supportedExchange.Key))
                {
                    var coinAverage = new CoinAverageRateProvider()
                    {
                        Exchange      = supportedExchange.Key,
                        HttpClient    = _httpClientFactory?.CreateClient(),
                        Authenticator = _CoinAverageSettings
                    };
                    var cached = new CachedRateProvider(supportedExchange.Key, coinAverage, cache)
                    {
                        CacheSpan = CacheSpan
                    };
                    Providers.Add(supportedExchange.Key, cached);
                }
            }
        }
Exemplo n.º 30
0
        public async Task <string> getAccessTokenAsync()
        {
            //get the expires_at value & parse it
            var expiresAt = await _httpContextAccessor.HttpContext.GetTokenAsync("expires_at");

            var expiresAtAsDateTimeoffset = DateTimeOffset.Parse(expiresAt, CultureInfo.InvariantCulture);

            if (expiresAtAsDateTimeoffset.AddSeconds(-60).ToUniversalTime() > DateTime.UtcNow)
            {
                //no need to refresh, truen the access token
                return(await _httpContextAccessor
                       .HttpContext.GetTokenAsync(OpenIdConnectParameterNames.AccessToken));
            }

            var idpClient = _httpClientFactory.CreateClient("IDPClient");

            //get the discovery document
            var discouverResponse = await idpClient.GetDiscoveryDocumentAsync();

            var refreshToken = await _httpContextAccessor
                               .HttpContext.GetTokenAsync(OpenIdConnectParameterNames.RefreshToken);

            var refreshResponse = await idpClient.RequestRefreshTokenAsync(
                new RefreshTokenRequest {
                Address      = discouverResponse.TokenEndpoint,
                ClientId     = "ImageGallaryClient1",
                ClientSecret = "secret",
                RefreshToken = refreshToken
            });

            // store the tokens
            var updatedTokens = new List <AuthenticationToken>();

            updatedTokens.Add(new AuthenticationToken
            {
                Name  = OpenIdConnectParameterNames.IdToken,
                Value = refreshResponse.IdentityToken
            });
            updatedTokens.Add(new AuthenticationToken
            {
                Name  = OpenIdConnectParameterNames.AccessToken,
                Value = refreshResponse.AccessToken
            });
            updatedTokens.Add(new AuthenticationToken
            {
                Name  = OpenIdConnectParameterNames.RefreshToken,
                Value = refreshResponse.RefreshToken
            });
            updatedTokens.Add(new AuthenticationToken
            {
                Name  = "expires_at",
                Value = (DateTime.UtcNow + TimeSpan.FromSeconds(refreshResponse.ExpiresIn)).
                        ToString("o", CultureInfo.InvariantCulture)
            });

            //get authantication result, containing the current principle & properties
            var currentAuthenticateResult = await _httpContextAccessor
                                            .HttpContext.AuthenticateAsync(CookieAuthenticationDefaults.AuthenticationScheme);

            //store the updated tokens
            currentAuthenticateResult.Properties.StoreTokens(updatedTokens);

            //sign in
            await _httpContextAccessor.HttpContext.SignInAsync(
                CookieAuthenticationDefaults.AuthenticationScheme,
                currentAuthenticateResult.Principal,
                currentAuthenticateResult.Properties);

            return(refreshResponse.AccessToken);
        }