Exemplo n.º 1
0
        private async Task <AccessToken> GetNewAccessToken()
        {
            _logger.LogDebug("Requesting new access token for Devianart");

            var url      = string.Format(AUTHORIZATION_URI, _credentials.ClientId, _credentials.ClientSecret);
            var response = await _client.GetAsync(url);

            var responseStream = await response.Content.ReadAsStreamAsync().ConfigureAwait(false);

            var tokenReponse = await _deserializer.Deserialize <AccessTokenResponse>(responseStream).ConfigureAwait(false);

            if (tokenReponse.Status != "success")
            {
                _logger.LogError("Failed to get new access token for Devianart");
                throw new InvalidOperationException("DeviantArt authentication failed");
            }

            var token = new AccessToken
            {
                Token          = tokenReponse.AccessToken,
                ExpirationDate = DateTimeOffset.Now.AddSeconds(tokenReponse.ExpiresIn).AddSeconds(-5 * 60)
            };

            return(token);
        }
Exemplo n.º 2
0
 public async Task <Album> GetAlbumByIdAsync(int albumId)
 {
     using (var photoLookUp = await _client.GetAsync($"{_settings.BaseUrl}/albums/{albumId}"))
     {
         return((photoLookUp.IsSuccessStatusCode)
             ? _jsonDeserializer.Deserialize <Album>(await photoLookUp.Content.ReadAsStringAsync())
             : null);
     }
 }
Exemplo n.º 3
0
 public async Task <Photo> GetPhotoByIdAsync(int id)
 {
     using (var photoLookUp = await _client.GetAsync($"{_settings.BaseUrl}/photos/{id}"))
     {
         return((photoLookUp.IsSuccessStatusCode)
             ? _jsonDeserializer.Deserialize <Photo>(await photoLookUp.Content.ReadAsStringAsync())
             : null);
     }
 }
Exemplo n.º 4
0
        public object Parse(string json)
        {
            var jsonDocumentOptions = new JsonDocumentOptions();
            var jsonDocument        = JsonDocument.Parse(json, jsonDocumentOptions);

            return(_deserializer.Deserialize(jsonDocument.RootElement));
        }
Exemplo n.º 5
0
        public void Handle(string message)
        {
            var deserializedMessage = _jsonDeserializer.Deserialize <Metadata>(message);
            var updateResource      = _mapper.Map <UpdateResource>(deserializedMessage);

            _commandBus.Handle(updateResource);
        }
Exemplo n.º 6
0
        protected T Get <T>(string url)
        {
            try
            {
                ResponseMessage = HttpClient.SendRequest(url, Authorizable);
                ResponseContent = ResponseMessage.Content.ReadAsStringAsync().Result;
                object instance = Deserializer.Deserialize <T>(ResponseContent);

                if (Response != null)
                {
                    Response.ReadResponse(ResponseContent, ResponseMessage);
                }

                return((T)instance);
            }

            catch (Exception e)
            {
                if (ResponseMessage.StatusCode == HttpStatusCode.Unauthorized)
                {
                    throw new UnauthorizedException();
                }

                throw e;
            }
        }
Exemplo n.º 7
0
 public async Task <VehicleData> GetVehicleDataAsync(string vehicleLicense)
 {
     using (var vehicleDataLookUp = await _client.GetAsync(String.Format(_settings.FullUrl, _settings.Apikey, vehicleLicense)))
     {
         return((vehicleDataLookUp.IsSuccessStatusCode) ?
                _jsonDeserializer.Deserialize <VehicleData>(await vehicleDataLookUp.Content.ReadAsStringAsync()) : null);
     }
 }
Exemplo n.º 8
0
 public static object DeserializeProperty(
     IJsonDeserializer deserializer,
     JsonElement element,
     string propertyName)
 {
     return(element.TryGetProperty(propertyName, out var propertyValue)
         ? deserializer.Deserialize(propertyValue)
         : null);
 }
Exemplo n.º 9
0
 private async Task <TEntity> DeserializeTeamsObjectAsync <TEntity>(HttpResponseMessage result)
     where TEntity : TeamsObject
 {
     using (var streamReader = new StreamReader(await result.Content.ReadAsStreamAsync()))
     {
         using (var jsonTextReader = new JsonTextReader(streamReader))
         {
             return(_serializer.Deserialize <TEntity>(jsonTextReader));
         }
     }
 }
Exemplo n.º 10
0
 public void Handle(string message)
 {
     try
     {
         _logger.LogInfo($"Handling sensor message: {message}");
         var json     = _jsonDeserializer.Deserialize <JObject>(message);
         var dataType = (DataType)Enum.Parse(typeof(DataType), json["datatype"].ToString(), true);
         _handlers[dataType].Handle(message);
     }
     catch (Exception exception)
     {
         _logger.LogError("Error while handling sensor message", exception);
     }
 }
Exemplo n.º 11
0
        public void Handle(string message)
        {
            var deserializedMessage = _jsonDeserializer.Deserialize <Measurement>(message);

            foreach (var measurementValue in deserializedMessage.MeasuresArray)
            {
                var addMeasurement = new AddMeasurement()
                {
                    Guid      = measurementValue.MeasureId,
                    Timestamp = deserializedMessage.Timestamp,
                    Value     = measurementValue.Value
                };

                _commandBus.Handle(addMeasurement);
            }
        }
        public async Task <ForeignExchangeDTO> GetConvertionRates()
        {
            var currencies = await this.cache.GetOrCreateAsync("ConvertionRates", async entry =>
            {
                entry.AbsoluteExpiration = dateTimeProvider.UtcNow.AddDays(1);

                string resourceUrl = $"https://api.exchangeratesapi.io/latest?base={GlobalConstants.BaseCurrency}&symbols={GlobalConstants.Currencies}";

                string currenciesString = await foreignExchangeApiCaller.GetCurrencyData(resourceUrl);

                var convertionRates = jsonDeserializer.Deserialize <ForeignExchangeDTO>(currenciesString);

                return(convertionRates);
            });

            return(currencies);
        }
Exemplo n.º 13
0
        public async Task Return_UserPhotoAlbum_WhenValid_UserId_IsProvided()
        {
            //https://github.com/aspnet/AspNetCore/issues/4545
            //https://docs.microsoft.com/en-us/aspnet/core/test/integration-tests?view=aspnetcore-2.2#test-app-prerequisites
            //https://github.com/aspnet/Hosting/issues/1191
            //http://anthonygiretti.com/2018/11/26/common-features-in-asp-net-core-2-1-webapi-testing/
            //https://stackoverflow.com/questions/42222919/why-serviceprovider-is-unable-to-create-instance-of-controller-in-asp-net-core
            using (var fixture = new TestServerFixture())
            {
                var sut = await _client.GetAsync("/api/PhotoAlbum/5");

                sut.IsSuccessStatusCode.ShouldBeTrue();
                var val = await sut.Content.ReadAsStringAsync();

                var res = _deserializer.Deserialize <PhotoAlbums>(val);
                res.ShouldBeOfType <PhotoAlbums>();
            }
        }
        /// <summary> Получить список возможных объектов прогнозирвоания </summary>
        /// <returns>Список объектов по которым можно узнать прогноз потребления электроэнергии</returns>
        public IList <ForecastObject> GetDataFromServer()
        {
            string jsonData;

#if DEBUG
            var exePath    = AppDomain.CurrentDomain.BaseDirectory;
            var rootFolder = Directory.GetParent(exePath).Parent.Parent.Parent.FullName;
            var jsonFile   = Path.Combine(rootFolder, "WPF-client.Test", "TestData", "predict.json");

            jsonData = File.ReadAllText(jsonFile);
#else
            var request  = new RestRequest(ServerUrl.ForecastsObjectUrl, Method.GET);
            var response = _restClient.Execute(request);
            jsonData = response.Content;
#endif
            var forecastsObjects = _jsonDeserializer.Deserialize(jsonData);
            return(forecastsObjects);
        }
Exemplo n.º 15
0
        public async Task <RestaurantResults> GetAsync(string outcode)
        {
            if (string.IsNullOrEmpty(outcode))
            {
                return(new RestaurantResults());
            }

            var headers = new[]
            {
                new KeyValuePair <string, string>(AcceptLanguage, _webConfig.HeaderAcceptLanguageValue),
                new KeyValuePair <string, string>(AcceptTenant, _webConfig.HeaderAcceptTenantValue),
                new KeyValuePair <string, string>(Authorization, _webConfig.HeaderAuthorizationValue),
                new KeyValuePair <string, string>(Host, _webConfig.HeaderHostValue)
            };

            var restaurantsApiUrl = $"{_webConfig.RestaurantsApiUrl}{outcode}";
            var restaurants       = await(await _httpClient.GetAsync(restaurantsApiUrl, headers)).Content.ReadAsStringAsync();

            return(_jsonDeserializer.Deserialize <RestaurantResults>(restaurants));
        }
Exemplo n.º 16
0
        public IDictionary <string, object> Decode(string jwt, string secret)
        {
            var parts = jwt.Split('.');

            if (parts.Length != 3)
            {
                throw new Exception(string.Format("Incorrect token count. Expected 3, received : {0}", parts.Length));
            }

            var payload   = _jsonDeserializer.Deserialize <IDictionary <string, object> >(_base64Decoder.Decode(parts[1]));
            var signature = parts[2];

            VerifyExpiration(payload);

            var rawSignature = parts[0] + "." + parts[1];

            if (!VerifySignature(rawSignature, secret, signature))
            {
                throw new InvalidTokenSignatureException("Signature verification failed");
            }

            return(payload);
        }
Exemplo n.º 17
0
        /// <summary>
        /// Performs an asynchronous HTTP request to the Stack Exchange API, with the specified data, and request method.
        /// </summary>
        /// <typeparam name="T">The type implementing <see cref="IStackExchangeModel"/>, to which the response gets deserialized to.</typeparam>
        /// <param name="path">The path relative to <see cref="ApiBaseUrl"/> to which the request should be made.</param>
        /// <param name="data">The data to be sent along with the HTTP request.</param>
        /// <param name="requestMethod">The HTTP method used for the request.</param>
        public async Task <Models.Wrapper <T> > PerformRequestAsync <T>(string path, Dictionary <string, string> data, HttpRequestMethod requestMethod)
            where T : IStackExchangeModel
        {
            if (data == null)
            {
                data = new Dictionary <string, string>();
            }

            if (!IsAnonymous)
            {
                data.Add("key", Key);

                if (HasAccessToken)
                {
                    data.Add("access_token", accessToken);
                }
            }

            var url = ApiBaseUrl.AppendPathSegment(path);

            var response = await httpRequester.PerformRequestAsync(url, data, requestMethod).ConfigureAwait(false);

            return(jsonDeserializer.Deserialize <Models.Wrapper <T> >(response.Content));
        }
Exemplo n.º 18
0
 public static T FromJson <T>(string json) where T : new()
 {
     return(_jsonDeserializer.Deserialize <T>(new DataObject(json)));
 }
Exemplo n.º 19
0
        private async Task <EtcdResponse> SendRequest(HttpMethod method, string requestUri, IEnumerable <KeyValuePair <string, string> > formFields = null)
        {
            HttpClientEx startClient   = _currentClient;
            HttpClientEx currentClient = _currentClient;

            for (; ;)
            {
                try
                {
                    using (HttpRequestMessage requestMessage = new HttpRequestMessage(method, requestUri))
                    {
                        if (formFields != null)
                        {
                            requestMessage.Content = new FormUrlEncodedContent(formFields);
                        }

                        using (HttpResponseMessage responseMessage = await currentClient.SendAsync(requestMessage))
                        {
                            string json = null;

                            if (responseMessage.Content != null)
                            {
                                json = await responseMessage.Content.ReadAsStringAsync();
                            }

                            if (!responseMessage.IsSuccessStatusCode)
                            {
                                if (!string.IsNullOrWhiteSpace(json))
                                {
                                    ErrorResponse errorResponse = null;
                                    try
                                    {
                                        errorResponse = _jsonDeserializer.Deserialize <ErrorResponse>(json);
                                    }
                                    catch { }

                                    if (errorResponse != null)
                                    {
                                        throw EtcdGenericException.Create(requestMessage, errorResponse);
                                    }
                                }


                                currentClient = currentClient.Next;
                                if (currentClient != startClient)
                                {
                                    // try the next
                                    continue;
                                }
                                else
                                {
                                    responseMessage.EnsureSuccessStatusCode();
                                }
                            }

                            // if currentClient != _currentClient, update _currentClient
                            if (currentClient != startClient)
                            {
                                Interlocked.CompareExchange(ref _currentClient, currentClient, startClient);
                            }

                            if (!string.IsNullOrWhiteSpace(json))
                            {
                                EtcdResponse resp = _jsonDeserializer.Deserialize <EtcdResponse>(json);
                                resp.EtcdServer    = currentClient.BaseAddress.OriginalString;
                                resp.EtcdClusterID = GetStringHeader(responseMessage, "X-Etcd-Cluster-Id");
                                resp.EtcdIndex     = GetLongHeader(responseMessage, "X-Etcd-Index");
                                resp.RaftIndex     = GetLongHeader(responseMessage, "X-Raft-Index");
                                resp.RaftTerm      = GetLongHeader(responseMessage, "X-Raft-Term");

                                long previousIndex = _lastIndex;
                                if (resp.EtcdIndex > previousIndex)
                                {
                                    Interlocked.CompareExchange(ref _lastIndex, resp.EtcdIndex, previousIndex);
                                }
                                this.ClusterID = resp.EtcdClusterID;
                                return(resp);
                            }
                            return(null);
                        }
                    }
                }
                catch (EtcdRaftException)
                {
                    currentClient = currentClient.Next;
                    if (currentClient != startClient)
                    {
                        continue; // try the next
                    }
                    else
                    {
                        throw; // tried all clients, all failed
                    }
                }
                catch (EtcdGenericException)
                {
                    throw;
                }
                catch (Exception)
                {
                    currentClient = currentClient.Next;
                    if (currentClient != startClient)
                    {
                        continue; // try the next
                    }
                    else
                    {
                        throw; // tried all clients, all failed
                    }
                }
            }
        }
Exemplo n.º 20
0
 /// <summary>
 /// JSON反序列化
 /// </summary>
 public static bool Deserialize <T>(string jstr, out T obj) where T : new()
 {
     return(JsonDeserializer.Deserialize <T>(jstr, out obj));
 }
Exemplo n.º 21
0
        public static async Task <T> GetJsonRead <T>(string JsonQuary, IJsonDeserializer <T> jsonDeserializer = null)
        {
            try
            {
                // ask for Json
                string Json    = "";
                bool   success = false;

                await Task.Run(() =>
                {
                    Parallel.Invoke(() =>
                    {
                        // for no internet connection
                        // or bad Json quary
                        Thread.Sleep(5000);
                        if (!success)
                        {
                            throw new Exception();
                        }
                    }, async() =>
                    {
                        Json    = await ApiClient.HttpClient.GetStringAsync(JsonQuary);
                        success = true;
                    });
                });


                //return final variable
                return(jsonDeserializer == null?JsonConvert.DeserializeObject <T>(Json) : jsonDeserializer.Deserialize(Json));
            }
            catch
            {
                Console.WriteLine("Something Went Wrong.. Please Try Again.");
                return(default);
Exemplo n.º 22
0
 public Configuration Load()
 {
     return(_jsonDeserializer.Deserialize <Configuration>(File.ReadAllText(_configPath)));
 }