Ejemplo n.º 1
0
        /// <summary>
        /// Executes the specified request against the alpha stream rest server
        /// </summary>
        /// <typeparam name="T">The response type</typeparam>
        /// <param name="request">The request object that will be transformed into a rest request</param>
        /// <returns>The response</returns>
        public async Task <T> Execute <T>(IRequest <T> request)
        {
            var restRequest = request.ToRestRequest();

            if (RequestTracingEnabled)
            {
                var pathAndQuery = client.BuildUri(restRequest).ToString().Replace(DefaultBaseUrl, string.Empty);
                Trace.TraceInformation($"{restRequest.Method} {pathAndQuery}");

                var body = restRequest.GetBody();
                if (body != null)
                {
                    Trace.TraceInformation($"Request Body: {Environment.NewLine}{body.FormatAsJsonIfPossible()}");
                }
            }

            // add required authorization headers
            var stamp = GetUnixTimeStamp();

            restRequest.AddHeader("Timestamp", stamp.ToString());
            client.Authenticator = new HttpBasicAuthenticator(
                credentials.ClientId,
                credentials.CreateSecureHash(stamp)
                );

            var taskCompletionSource = new TaskCompletionSource <JToken>();

            client.ExecuteAsync(restRequest, response =>
            {
                if (ResponseTracingEnabled)
                {
                    Trace.TraceInformation("Response Body: " + Environment.NewLine + response.Content.FormatAsJsonIfPossible());
                    LastRestResponse = response.Content;
                }

                if (response.StatusCode == HttpStatusCode.OK)
                {
                    try
                    {
                        taskCompletionSource.SetResult(JToken.Parse(response.Content));
                        return;
                    }
                    catch (Exception exception)
                    {
                        Trace.TraceError("Error Deserializing Response: " + Environment.NewLine + exception.ToString());
                    }
                }

                // either received a non 200 status code or failed to parse as the requested type
                taskCompletionSource.SetException(AlphaServiceException.ForResponse(response));
            });

            var jtokenResponse = await taskCompletionSource.Task.ConfigureAwait(false);

            return(jtokenResponse.ToObject <T>());
        }
Ejemplo n.º 2
0
        private async Task <IRestResponse> ExecuteRestRequest(IRestRequest query)
        {
            var result = await _restClient.ExecuteAsync(query, CancellationToken.None);

            if (!result.IsSuccessful)
            {
                throw new HttpRequestException(result.StatusCode + ": " + result.ErrorMessage);
            }
            return(result);
        }
Ejemplo n.º 3
0
        public async Task <List <PokemonRegion> > GetPokemonRegions(string urlCompose)
        {
            client.BaseUrl   = new Uri(options.Value.PokeApiUrl);
            request.Resource = urlCompose;

            var response = await client.ExecuteAsync(request);

            if (response.StatusCode == System.Net.HttpStatusCode.NotFound)
            {
                throw new NotFoundException(response.Content);
            }

            var jsonObject = JObject.Parse(response.Content);

            var pokemons = JsonConvert.DeserializeObject <List <PokemonRegion> >
                               (jsonObject.SelectToken("results").ToString());

            return(pokemons);
        }
Ejemplo n.º 4
0
        public async Task <byte[]> GetMapImage(float lat, float lon)
        {
            var request =
                new RestRequest(
                    $"styles/v1/mapbox/dark-v10/static/pin-s({lon},{lat})/{lon},{lat},7,0,0/350x350");

            var response = await _client.ExecuteAsync(request);

            return(response.RawBytes);
        }
        public static IRestResponse Execute(this IRestClient restClient, IRestRequest request)
        {
            var task = new TaskCompletionSource <IRestResponse>();

            var asyncHandle = restClient.ExecuteAsync(request, response => {
                task.SetResult(response);
            });

            return(task.Task.Result);
        }
Ejemplo n.º 6
0
        private async Task <T> ExecuteAsync <T>(IRestRequest request)
        {
            request.AddHeader("accept", "application/vnd.github.v3+json");

            var response = await _client.ExecuteAsync <T>(request).ConfigureAwait(false);

            return(response.IsSuccessful && response.ErrorException is null ?
                   response.Data :
                   throw new Exception("An error response received from GitHub server. Response Status: " + response.StatusCode, response.ErrorException));
        }
        private Task <T> ExecuteAsync <T>(IRestClient client, IRestRequest request, Func <IRestResponse, T> selector)
        {
            LogRequest(request);

            var completionSource = new TaskCompletionSource <T>();

            client.ExecuteAsync(request, response => ProcessResponse(selector, response, completionSource));

            return(completionSource.Task);
        }
Ejemplo n.º 8
0
        public async Task <T> ExecuteAsync <T>(RestRequest request) where T : new()
        {
            var response = await restClient.ExecuteAsync <T>(request);

            if (response.ErrorException != null)
            {
                LogException(response.ErrorException);
            }
            return(response.Data);
        }
        public static async Task <IRestResponse <T> > ExecuteWithLogsAsync <T>(this IRestClient client, IRestRequest request, ILogger logger)
        {
            var response = await client.ExecuteAsync <T>(request);

            if (response.StatusCode != HttpStatusCode.OK)
            {
                logger.LogError($"REST call failed for => {response.ResponseUri.AbsoluteUri} {response.Content}");
            }
            return(response);
        }
Ejemplo n.º 10
0
        private async Task <T> ExecuteAsync <T>(IRestRequest request)
        {
            request.AddHeader("cache-control", "no-cache");
            request.AddQueryParameter("api_key", _endpoint.APIKey);
            request.AddQueryParameter("format", "json");

            var response = await _client.ExecuteAsync <T>(request).ConfigureAwait(false);

            return(response.IsSuccessful && response.ErrorException is null ? response.Data : throw new Exception("An error response received from UptimeRobot server. Response Status: " + response.StatusCode, response.ErrorException));
        }
Ejemplo n.º 11
0
        public void ExecuteAsyncOnNullRestClientThrowsArgumentNullException()
        {
            // Arrange
            IRestClient nullRestClient = null;

            // Act

            // Assert
            Assert.Throws <ArgumentNullException>(() => nullRestClient.ExecuteAsync(CreateRestRequest(), CancellationToken.None));
        }
Ejemplo n.º 12
0
        protected Task <IRestResponse> GetResponseContentAsync(IRestClient theClient, RestRequest theRequest)
        {
            var tcs = new TaskCompletionSource <IRestResponse>();

            theClient.ExecuteAsync(theRequest, response =>
            {
                tcs.SetResult(response);
            });
            return(tcs.Task);
        }
Ejemplo n.º 13
0
        public static void SimpleAsync(this IRestClient client, IRestRequest req, Action <IRestResponse> Callback)
        {
            //parse
            var url = new Uri(req.Resource);

            client.BaseUrl = new Uri(url.Scheme + "://" + url.Host);
            req.Resource   = url.PathAndQuery;

            var res = client.ExecuteAsync(req, Callback);
        }
Ejemplo n.º 14
0
        public async Task <string> ExecuteRequestAsync(RestRequest request)
        {
            request.AddHeader("Content-Type", "application/json");

            var response = await _client.ExecuteAsync(request);

            StatusDescription = response.StatusDescription.ToString();

            return(response.Content);
        }
Ejemplo n.º 15
0
        private async Task <AirQualityData> Execute(IRestRequest request)
        {
            var response = await restClient.ExecuteAsync <AirQualityResponse>(request);

            if (!response.IsSuccessful || response.Data.Status != "ok")
            {
                return(null); // TODO: Handle error
            }
            return(response.Data.Data);
        }
Ejemplo n.º 16
0
        protected Task <IRestResponse <T> > GetAsyncRequestAwaiter <T>() where T : new()
        {
            IRestRequest request = PrepareRequest();
            IRestClient  client  = PrepareClient();

            var tcs = new TaskCompletionSource <IRestResponse <T> >();

            client.ExecuteAsync <T>(request, response => tcs.SetResult(response));

            return(tcs.Task);
        }
Ejemplo n.º 17
0
        private async Task <T> Execute <T>(string url)
        {
            _request.Parameters.Clear();
            _request.Resource = url;
            _request.Method   = Method.GET;
            _request.AddHeader("Content-type", "application/json");
            foreach (var header in _misApiModel.Value.Headers)
            {
                _request.AddHeader(header.Key, header.Value);
            }

            var response = await _client.ExecuteAsync(_request);

            if (response.StatusCode == HttpStatusCode.OK || response.StatusCode == HttpStatusCode.NotFound)
            {
                return(JsonConvert.DeserializeObject <T>(response.Content));
            }

            throw new ApplicationException(response.Content);
        }
Ejemplo n.º 18
0
        public RestRequestAsyncHandle GetServersAsync(string token, Action <List <Server> > callback)
        {
            var request = new RestRequest("servers", Method.GET);

            request.AddHeader("Authorization", $"Bearer {token}");

            return(_client.ExecuteAsync <List <Server> >(request, (response) =>
            {
                callback(response.Data);
            }));
        }
Ejemplo n.º 19
0
 public void OneTimeSetup()
 {
     _serviceUnavailableClient = Substitute.For <IRestClient>();
     _serviceUnavailableClient.Execute(Arg.Any <IRestRequest>()).Returns(new RestResponse {
         StatusCode = HttpStatusCode.ServiceUnavailable
     });
     _serviceUnavailableClient.ExecuteAsync(Arg.Any <IRestRequest>(), Arg.Any <Method>(), Arg.Any <CancellationToken>())
     .Returns(new RestResponse {
         StatusCode = HttpStatusCode.ServiceUnavailable
     });
 }
Ejemplo n.º 20
0
 private Task <NewsRoot> GetNewsData()
 {
     return(_cache.GetOrAddAsync($"{GetType().FullName}_news_data", () => DoAsync(async() =>
     {
         var request = new RestRequest(Method.GET);
         var result = _newsClient.ExecuteAsync <NewsRoot>(request);
         return (await result)?.Data ?? new NewsRoot();
     }, TimeSpan.FromSeconds(1)), new MemoryCacheEntryOptions {
         AbsoluteExpiration = DateTime.Now.AddMinutes(5)
     }));
 }
Ejemplo n.º 21
0
        public async Task <decimal> GetSalaryAsync(string employeeCode, string inn)
        {
            var request = new RestRequest($"/{inn}", Method.POST);
            var body    = new { BuhCode = employeeCode };

            request.AddJsonBody(body);

            var result = await _restClient.ExecuteAsync <decimal>(request);

            return(result.Data);
        }
Ejemplo n.º 22
0
        public static Task <IRestResponse> RestExecuteAsync(this IRestClient client, IRestRequest request)
        {
            var tcs = new TaskCompletionSource <IRestResponse>();

            client.ExecuteAsync(request, response =>
            {
                tcs.SetResult(response);
            });

            return(tcs.Task);
        }
Ejemplo n.º 23
0
        private static void SetupTokenResultSuccess(IRestClient restClient, string token)
        {
            var facebookResponse = Substitute.For <IRestResponse <AccessTokenResult> >();

            facebookResponse.IsSuccessful.Returns(true);
            facebookResponse.StatusCode.Returns(HttpStatusCode.OK);
            facebookResponse.Data.Returns(new AccessTokenResult {
                AccessToken = token
            });
            restClient.ExecuteAsync <AccessTokenResult>(Arg.Any <RestRequest>()).Returns(Task.FromResult(facebookResponse));
        }
Ejemplo n.º 24
0
        private async Task <T> ExecuteAsync <T>(IRestRequest request, CancellationToken cancellationToken) where T : new()
        {
            var response = await _client.ExecuteAsync <T>(request, cancellationToken).ConfigureAwait(false);

            if (response.IsSuccessful && response.ErrorException is null)
            {
                return(response.Data);
            }

            throw new Exception("An error response received from Jenkins server.", response.ErrorException);
        }
Ejemplo n.º 25
0
        private static void SetupTokenResultSuccess(IRestClient restClient, string token, string secret)
        {
            var twitterResponse = Substitute.For <IRestResponse <TokenResult> >();

            twitterResponse.IsSuccessful.Returns(true);
            twitterResponse.StatusCode.Returns(HttpStatusCode.OK);
            twitterResponse.Data.Returns(new TokenResult {
                OauthToken = token, OauthTokenSecret = secret
            });
            restClient.ExecuteAsync <TokenResult>(Arg.Any <RestRequest>()).Returns(Task.FromResult(twitterResponse));
        }
Ejemplo n.º 26
0
        public async Task <bool> KeyAvailable(string key, CancellationToken cancellationToken)
        {
            var request  = new RestRequest(string.Empty, Method.GET, DataFormat.None).AddQueryParameter("command", "key_available").AddQueryParameter("key", key);
            var response = await _client.ExecuteAsync(request, cancellationToken);

            if (response.StatusCode != System.Net.HttpStatusCode.OK)
            {
                throw new Exception($"Failed to successfully query against BYOND, response code {response.StatusCode}");
            }

            var match = BYONDCommandResponse.Match(response.Content);

            if (!match.Success)
            {
                throw new Exception($"Invalid response from BYOND, unexpected response pattern. Response content: {response.Content}");
            }

            var responseComponents = match.Groups["response"].Value.Split(',');

            return(responseComponents[0] == "true");
        }
Ejemplo n.º 27
0
        public async Task <RemoteBudget> CreateNewBudget()
        {
            if (string.IsNullOrWhiteSpace(accessControlManager?.Jwt))
            {
                throw new ArgumentNullException();
            }

            restClient.Timeout = -1;
            var request = new RestRequest("budget/budgets", Method.PUT);

            request.AddHeader("Authorization", $"Bearer {accessControlManager.Jwt}");
            request.AddHeader("Cache-Control", "no-cache");
            request.AddHeader("Content-Type", "application/x-www-form-urlencoded");
            request.AddParameter("date", DateTime.Now.ToString("yyyy-MM-dd"));
            request.AddParameter("currency", "usd");
            IRestResponse response = await restClient.ExecuteAsync(request);

            if (response.StatusCode != HttpStatusCode.OK && response.StatusCode != HttpStatusCode.Created)
            {
                throw new Exception($"Unexpected response from created budget call: {response.StatusCode} - {response.Content}");
            }

            try
            {
                var json       = Cleaner.CleanJson(response.Content);
                var jsonObject = JObject.Parse(json);
                var budget     = JsonConvert.DeserializeObject <RemoteBudget>(json);
                return(budget);
            }
            catch (Exception e)
            {
                throw new Exception($"Unable to parse response from Get Budgets: {response.Content}", e);
            }
        }
Ejemplo n.º 28
0
        public async Task <WeatherResponse> GetCities(double lat, double lon)
        {
            var request = new RestRequest("find")
                          .AddParameter("lat", lat)
                          .AddParameter("lon", lon)
                          .AddParameter("cnt", 50)
                          .AddParameter("appid", "ce82774295db466472b892ef8345ae11")
                          .AddParameter("units", "metric");

            var response = await _client.ExecuteAsync <WeatherResponse>(request);

            return(response.Data);
        }
Ejemplo n.º 29
0
        public async Task <TResponse> ExecutePutAsync <TRequest, TResponse>(string endpoint, TRequest request)
        {
            _restClient.AddDefaultHeader("Content-Type", "application/json");
            var restRequest = new RestRequest(endpoint, Method.PUT, DataFormat.Json);
            var json        = JsonConvert.SerializeObject(request, new JsonSerializerSettings
            {
                NullValueHandling = NullValueHandling.Ignore
            });

            restRequest.AddParameter("application/json", json, ParameterType.RequestBody);

            var response = await _restClient.ExecuteAsync <TResponse>(restRequest).ConfigureAwait(false);

            if (response.IsSuccessful)
            {
                return(response.Data);
            }

            var error = new JsonDeserializer().Deserialize <Error>(response);

            throw new DevToApiException(error);
        }
Ejemplo n.º 30
0
        public async Task <GenerateTokenResponse> GenerateTokenAsync()
        {
            var path    = $"v3/Usuario/ValidarLogin";
            var request = ConfigureRequest(path, Method.POST);

            var validaLogin = new GenerateTokenRequest()
            {
                dsUsuario = _options.User,
                dsSenha   = _options.Password
            };

            request.AddJsonBody(validaLogin);

            var response = await _client.ExecuteAsync(request);

            if (!response.IsSuccessful)
            {
                throw new SmartShareException("Error from SmartShare.", response.Content);
            }

            return(JsonConvert.DeserializeObject <GenerateTokenResponse>(response.Content));
        }
        private void GetTypes(
            string geometry,
            string query,
            string token,
            string aoi,
            IRestClient client,
            string layerName,
            int attempts = 0)
        {
            var request =
                new RestRequest(
                    string.Format("/insight-vector/api/shape/query/{0}/types?q={1}", geometry, query),
                    Method.POST);
            request.AddHeader("Authorization", "Bearer " + token);
            request.AddHeader("Content-Type", "application/json");
            request.AddParameter("application/json", aoi, ParameterType.RequestBody);

            attempts++;

            client.ExecuteAsync<ResponseData>(
                request,
                resp => this.GetTypesResponseProcess(resp, geometry, query, token, aoi, client, layerName, attempts));
        }
        private void GetPages(
            string pageId,
            string token,
            IRestClient client,
            StreamWriter fileStreamWriter,
            string layerName,
            int attempts = 0)
        {
            var request = new RestRequest("/insight-vector/api/esri/paging", Method.POST);
            request.AddHeader("Authorization", "Bearer " + token);
            request.AddHeader("Content-Type", "application/json");

            request.AddParameter("ttl", "5m");
            request.AddParameter("fields", "attributes");
            request.AddParameter("pagingId", pageId);

            attempts++;
            client.ExecuteAsync<PagedData2>(
                request,
                resp => this.ProcessPageResponse(resp, token, pageId, client, layerName, attempts, fileStreamWriter));
        }