private void SetupOrdersApi()
        {
            MessageHandler.When(HttpMethod.Get,
                                ApiEndpoints.GetOrdersUri().ToString())
            .Respond("application/json", JsonConvert.SerializeObject(Data.Orders.Cast <OrderSummaryDto>()));

            MessageHandler.When(HttpMethod.Get,
                                $"{ApiEndpoints.GetOrdersUri()}/*")
            .Respond(request =>
            {
                var orderId = GetIdFromUrl(request);

                var order = Data.Orders.FirstOrDefault(o => o.Id == orderId);

                return(CreateJsonResponse(order));
            });

            MessageHandler.When(HttpMethod.Post,
                                $"{ApiEndpoints.GetOrdersUri()}")
            .Respond(async request =>
            {
                var orderRequest = await GetObjectFromRequest <OrderProductRequestDto[]>(request);

                var nextOrderId = Data.Orders.Max(o => o.Id) + 1;
                var order       = Data.CreateOrderDto(nextOrderId, DateTime.Now,
                                                      orderRequest.Select(o => Data.CreateOrderProductSummaryDto(o.Id, o.Quantity)).ToArray());

                Data.Orders.Add(order);

                return(CreateJsonResponse(order));
            });
        }
 public WeatherForecastClient(
     HttpClient httpClient,
     IOptions <ApiEndpoints> options)
 {
     _httpClient   = httpClient;
     _apiEndpoints = options.Value;
 }
Ejemplo n.º 3
0
        public async Task <UpdateResult> SendUpdateRequestAsync(string serverId, string branch, string commitHash)
        {
            var request = new UpdateRequest()
            {
                Branch     = branch,
                CommitHash = commitHash,
                SecretKey  = _secret,
                Id         = serverId
            };
            HttpContent content = BuildStringContent(JsonConvert.SerializeObject(request));

            var response = await _http.PostAsync(ApiEndpoints.ServerUpdate(serverId), content);

            string resultJson = await response.Content.ReadAsStringAsync();

            if (!response.IsSuccessStatusCode)
            {
                return(new UpdateResult
                {
                    Error = true,
                    ErrorMessage = $"Got {response.StatusCode} with following JSON {resultJson}"
                });
            }

            var result = JsonConvert.DeserializeObject <UpdateResult>(resultJson);

            return(result);
        }
Ejemplo n.º 4
0
 public CityClient(
     HttpClient httpClient,
     IOptions <ApiEndpoints> options)
 {
     _httpClient   = httpClient;
     _apiEndpoints = options.Value;
 }
Ejemplo n.º 5
0
        private void SetupUsersApi()
        {
            MessageHandler.When(HttpMethod.Get,
                                ApiEndpoints.GetUsersUri().ToString())
            .Respond("application/json", JsonConvert.SerializeObject(Data.AppUsers));

            MessageHandler.When(HttpMethod.Get,
                                $"{ApiEndpoints.GetUsersUri()}/*")
            .Respond(request =>
            {
                var id   = GetIdFromUrl(request);
                var user = Data.AppUsers.FirstOrDefault(u => u.Id == id);

                return(CreateJsonResponse(user));
            });

            MessageHandler.When(HttpMethod.Put,
                                ApiEndpoints.PostUserUri().ToString())
            .Respond(async request =>
            {
                var userRequest = await GetObjectFromRequest <AppUserDto>(request);
                var currentUser = Data.AppUsers.FirstOrDefault(u => u.Id == userRequest.Id);

                Data.AppUsers.Remove(currentUser);
                Data.AppUsers.Add(userRequest);

                return(CreateJsonResponse(userRequest));
            });
        }
 public DailyImageRequestHandler(SpigotCaseStudyDbContext context, HttpClient client, string apiKey, IConfiguration config)
     : base(config)
 {
     _context = context;
     _client  = client;
     _apiKey  = apiKey;
     Endpoint = ApiEndpoints.First(x => x.EndpointName == "apod");
 }
Ejemplo n.º 7
0
 public TwitterClient(String consumerKey, String consumerSecret)
     : base(consumerKey, consumerSecret
            , "https://api.twitter.com/oauth/request_token"
            , "https://api.twitter.com/oauth/authorize"
            , "https://api.twitter.com/oauth/access_token")
 {
     this.Api = new ApiEndpoints(this);
 }
Ejemplo n.º 8
0
        public void TestSelfHostedUrl()
        {
            string       url       = "https://selfhosted.customer.com";
            DataCenter   dc        = new DataCenter(url);
            ApiEndpoints endpoints = new ApiEndpoints(dc);

            Assert.AreEqual("/account", endpoints.GetAccountInfo().Endpoint);
        }
        private async Task CheckAuthToken(JwtTokenDto authToken, CancellationToken cancellationToken = default)
        {
            var url = ApiEndpoints.CheckAuthToken();

            var requestMessage = HttpRequestFactory.CreateAuthGetRequest(url, authToken);

            await _httpClient.ExecuteRequest(requestMessage, cancellationToken);
        }
Ejemplo n.º 10
0
        public ChallengeController(IOptions <ApiEndpoints> apiEndpoints, IHttpClientFactory httpClientFactory, IServiceHelper serviceHelper)
        {
            _apiEndpoints      = apiEndpoints?.Value;
            _httpClientFactory = httpClientFactory ??
                                 throw new ArgumentNullException(nameof(httpClientFactory));

            _serviceHelper = serviceHelper;
        }
 public void AddApiEndpoint(string apiEndpoint)
 {
     _namedApiEndpoints[apiEndpoint] = apiEndpoint;
     if (!ApiEndpoints.Contains(apiEndpoint))
     {
         ApiEndpoints.Add(apiEndpoint);
     }
 }
Ejemplo n.º 12
0
 public WeatherHistoryClient(
     HttpClient httpClient,
     IOptions <ApiEndpoints> options,
     ILogger <WeatherHistoryClient> logger)
 {
     _httpClient   = httpClient;
     _apiEndpoints = options.Value;
     _logger       = logger;
 }
 public WeatherPredictionController(
     WeatherForecastClient weatherForecastClient,
     CityClient cityClient,
     IconClient iconClient,
     IOptions <ApiEndpoints> options)
 {
     _weatherForecastClient = weatherForecastClient;
     _cityClient            = cityClient;
     _apiEndpoints          = options.Value;
 }
        public void RemoveNamedApiEndpoint(string apiEndpointName)
        {
            var apiEndpoint = GetApiEndpoint(apiEndpointName);

            if (!string.IsNullOrWhiteSpace(apiEndpoint))
            {
                _namedApiEndpoints.Remove(apiEndpointName);
                ApiEndpoints.Remove(apiEndpoint);
            }
        }
Ejemplo n.º 15
0
        private async Task UpdatingEmail(CancellationToken cancellationToken = default)
        {
            var url = ApiEndpoints.UpdateUserEmail();

            var newUserEmail = "*****@*****.**".ToStringContent();

            var requestMessage = _httpRequestFactory.CreateAuthPostRequest(url, newUserEmail);

            await _httpClient.ExecuteRequest(requestMessage, cancellationToken);
        }
Ejemplo n.º 16
0
        public async Task <UserOverview> Overview(string username)
        {
            var endpoint = ApiEndpoints.UserAccount(username);
            var response = await api.Get(endpoint);

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

            var model = JsonConvert.DeserializeObject <UserOverview>(await response.Content.ReadAsStringAsync());

            return(model);
        }
 public void AddApiEndpoints(List <string> apiEndpoints)
 {
     foreach (string apiEndpoint in apiEndpoints)
     {
         _namedApiEndpoints[apiEndpoint] = apiEndpoint;
         if (!ApiEndpoints.Contains(apiEndpoint))
         {
             ApiEndpoints.Add(apiEndpoint);
         }
     }
 }
 public void RemoveApiEndpoint(string apiEndpoint)
 {
     if (!string.IsNullOrWhiteSpace(apiEndpoint))
     {
         foreach (var item in _namedApiEndpoints.Where(kvp => kvp.Value == apiEndpoint).ToList())
         {
             _namedApiEndpoints.Remove(item.Key);
         }
         ApiEndpoints.Remove(apiEndpoint);
     }
 }
        private async Task <JwtTokenDto> LoggingIn(CancellationToken cancellationToken = default)
        {
            var url = ApiEndpoints.CreateAuthToken();

            var requestBody = new CredentialsDto {
                Email = "*****@*****.**", Password = "******"
            }.ToStringContent();

            var requestMessage = _httpRequestFactory.CreatePostRequest(url, requestBody);

            return(await _httpClient.ExecuteRequest <JwtTokenDto>(requestMessage, cancellationToken));
        }
Ejemplo n.º 20
0
        public async Task <IActionResult> ProductDelete(int itemid)
        {
            var response = await api.Delete(ApiEndpoints.DropshipProductDelete(itemid));

            if (response.IsSuccessStatusCode)
            {
                return(RedirectToAction("Products"));
            }
            else
            {
                return(RedirectToAction("Products"));
            }
        }
Ejemplo n.º 21
0
        public async Task <IActionResult> ProductAddToIntegration(int itemid)
        {
            var response = await api.Get(ApiEndpoints.DropshipAddProductIntegration(itemid));

            if (response.IsSuccessStatusCode)
            {
                return(RedirectToAction("Products"));
            }
            else
            {
                return(RedirectToAction("Products"));
            }
        }
        public async Task <DropshipItem[]> GetProducts()
        {
            var response = await api.Get(ApiEndpoints.DropshipGetProducts(0, 28));

            if (response.IsSuccessStatusCode)
            {
                var json = await response.Content.ReadAsStringAsync();

                var products = JsonConvert.DeserializeObject <DropshipItem[]>(json);
                return(products);
            }

            return(new DropshipItem[0]);
        }
Ejemplo n.º 23
0
        public async Task <IActionResult> AjaxShopifyVerify(string listingid)
        {
            var response = await api.Get(ApiEndpoints.DropshipIntegrationGetProduct("Shopify", listingid));

            if (response.IsSuccessStatusCode)
            {
                var json = await response.Content.ReadAsStringAsync();

                var product = JsonConvert.DeserializeObject <ShopifyProductModel>(json);
                return(PartialView("Partials/ShopifyVerify", product));
            }

            return(NotFound());
        }
Ejemplo n.º 24
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddDbContext <WeatherContext>(options =>
                                                   options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

            var settings = new ApiEndpoints();

            Configuration.Bind("ApiEndpoints", settings);

            services.AddSingleton(settings);

            services.AddScoped <IWeatherStationRepository, WeatherStationRepository>();
            services.AddScoped <IWeatherImportService, SmhiWeatherImportService>();
            services.AddMvc();
        }
Ejemplo n.º 25
0
        public async Task <ServerStartStopResult> SendStopRequestAsync(string serverId)
        {
            var content         = BuildStringContent($"\"{_secret}\"");
            var responseMessage = await _http.PostAsync(ApiEndpoints.ServerStop(serverId), content);

            string resultJson = await responseMessage.Content.ReadAsStringAsync();

            if (string.IsNullOrEmpty(resultJson))
            {
                throw new Exception($"Got {responseMessage.StatusCode} code.");
            }

            var result = JsonConvert.DeserializeObject <ServerStartStopResult>(resultJson);

            return(result);
        }
        private void SetupProductsApi()
        {
            MessageHandler.When(HttpMethod.Get,
                                ApiEndpoints.GetProductsUri().ToString())
            .Respond("application/json", JsonConvert.SerializeObject(Data.Products.Cast <ProductSummaryDto>()));

            MessageHandler.When(HttpMethod.Get,
                                $"{ApiEndpoints.GetProductsUri()}/*")
            .Respond(request =>
            {
                int productId = GetIdFromUrl(request);

                var product = Data.Products.FirstOrDefault(p => p.Id == productId);

                return(CreateJsonResponse(product));
            });
        }
Ejemplo n.º 27
0
        public async Task <ServerStatusResult> SendStatusRequestAsync(string serverId)
        {
            var response = await _http.GetAsync(ApiEndpoints.Status(serverId));

            string resultText = await response.Content.ReadAsStringAsync();

            if (!response.IsSuccessStatusCode)
            {
                return(new ServerStatusResult()
                {
                    Error = true,
                    ErrorMessage = $"Got {response.StatusCode} with following text: {resultText}"
                });
            }
            var result = JsonConvert.DeserializeObject <ServerStatusResult>(resultText);

            return(result);
        }
Ejemplo n.º 28
0
        /// <summary>
        /// Adds the new  api handlers endpoints
        /// </summary>
        /// <param name="address">
        /// The handler node's address.
        /// </param>
        /// <param name="descriptions">
        /// The list of handles
        /// </param>
        private void AddHandlers(Address address, List <ApiDiscoverResponse> descriptions)
        {
            bool needsSchemaRebuild = false;

            foreach (var description in descriptions)
            {
                ApiEndpoints endpoints;
                if (!this.apiEndpoints.TryGetValue(description.Description.ApiName, out endpoints))
                {
                    needsSchemaRebuild = true;
                    endpoints          = new ApiEndpoints(
                        description.Description,
                        Context.System);
                    this.apiEndpoints.Add(description.Description.ApiName, endpoints);
                    Context.GetLogger()
                    .Info(
                        "{Type}: API {ApiName} is now supported",
                        this.GetType().Name,
                        description.Description.ApiName);
                }

                var currentMaximumApiVersion = endpoints.Descriptions.Any()
                                                   ? endpoints.Descriptions.Keys.Max()
                                                   : new Version(0, 0);

                if (description.Description.Version > currentMaximumApiVersion)
                {
                    needsSchemaRebuild = true;
                }

                if (!endpoints.Descriptions.ContainsKey(description.Description.Version))
                {
                    endpoints.Descriptions.Add(description.Description.Version, description.Description);
                }

                endpoints.Provider.Endpoints.TryAdd(address, description.Handler);
                endpoints.HandlerDescriptions[address] = description.Description.Version;
            }

            if (needsSchemaRebuild)
            {
                this.RebuildSchema();
            }
        }
Ejemplo n.º 29
0
        public async Task <IActionResult> AjaxSingleItem(string link)
        {
            var response = await api.Get(ApiEndpoints.SearchSingle(link, "Aliexpress"));

            if (response.IsSuccessStatusCode)
            {
                var json = await response.Content.ReadAsStringAsync();

                var product = JsonConvert.DeserializeObject <ItemDetail>(json);
                if (product == null)
                {
                    return(NotFound());
                }

                return(Json(product));
            }

            return(NotFound());
        }
Ejemplo n.º 30
0
        public async Task <IActionResult> Products(int page = 1)
        {
            var response = await api.Get(ApiEndpoints.DropshipGetProducts(productsPerPage * (page - 1), productsPerPage));

            var products = new DropshipItem[0];

            if (response.IsSuccessStatusCode)
            {
                var json = await response.Content.ReadAsStringAsync();

                products = JsonConvert.DeserializeObject <DropshipItem[]>(json);
            }

            //Add total count for pagination
            ViewBag.MaxCount     = response.Headers.Contains("X-Total-Count") ? Convert.ToInt32(response.Headers.GetValues("X-Total-Count").First()) : productsPerPage;
            ViewBag.Page         = page;
            ViewBag.ItemsPerPage = productsPerPage;

            return(View(products));
        }