示例#1
0
        protected async Task LoadMissions(Robot host, ApplicationDbContext db)
        {
            try
            {
                _client.DefaultRequestHeaders.Accept.Clear();
                var response = await _client.SendAsync(HttpRequestMessage(host, "/missions"));

                if (response.IsSuccessStatusCode)
                {
                    await using var responseStream = await response.Content.ReadAsStreamAsync();

                    var missions =
                        await JsonSerializer.DeserializeAsync <List <Mission> >(responseStream, _options);

                    foreach (var mission in missions)
                    {
                        mission.RobotId = host.Id;
                        if (!db.Missions.Any(m => m.Name.Contains(mission.Name) &&
                                             m.RobotId.Equals(mission.RobotId)))
                        {
                            db.Missions.Add(mission);
                        }
                    }

                    host.IsOnline = true;
                    db.Robots.Update(host);
                    db.SaveChanges();
                }
            }
            catch (Exception e)
            {
                SetRobotOffline(host, db, e);
            }
        }
示例#2
0
        public async Task <ListWithMetadata <T> > GetListAsync <T>(string resourceUri)
        {
            var response = await HttpClient.GetAsync(resourceUri);

            var stream = await response.Content.ReadAsStreamAsync();

            if (response.StatusCode == HttpStatusCode.NotFound)
            {
                var notFound = await JsonSerializer.DeserializeAsync <NotFoundProblemDetails>(stream, new JsonSerializerOptions { PropertyNameCaseInsensitive = true });

                throw new ApiError(notFound, HttpStatusCode.NotFound);
            }

            var result = await JsonSerializer.DeserializeAsync <List <T> >(stream, new JsonSerializerOptions()
            {
                PropertyNameCaseInsensitive = true
            });

            if (response.Headers.TryGetValues("x-pagination", out var values))
            {
                var paginationMeta = JsonSerializer.Deserialize <PaginationMetadata>(values.First(), _jsonDeserOpt);
                return(new ListWithMetadata <T>
                {
                    Data = result,
                    Metadata = paginationMeta
                });
            }

            return(new ListWithMetadata <T>
            {
                Data = result,
                Metadata = new PaginationMetadata()
            });
        }
示例#3
0
        public async Task <CityViewModelResponse> GetTempByCity(string cityName)
        {
            var request = new HttpRequestMessage(HttpMethod.Get,
                                                 "http://api.openweathermap.org/data/2.5/weather?q=" + cityName + "&units=metric&lang=pt_br&appid=142d374d2ea6105f400f36546592a3d4");
            var client   = _clientFactory.CreateClient();
            var response = await client.SendAsync(request);

            Stream responseStream;

            if (!response.IsSuccessStatusCode)
            {
                responseStream = await response.Content.ReadAsStreamAsync();

                var objBadRequest = await JsonSerializer.DeserializeAsync
                                    <BadRequestViewModelAPI>(responseStream);

                throw new Exception(objBadRequest.message);
            }
            responseStream = await response.Content.ReadAsStreamAsync();

            var objApi = await JsonSerializer.DeserializeAsync
                         <CityAPI>(responseStream);

            return(_mapper.Map <CityViewModelResponse>(objApi));
        }
示例#4
0
        public async Task CanDeserialize(SampleDataDescriptor sampleDataFile)
        {
            await using var sampleData = File.OpenRead(sampleDataFile.FullPath);
            var payload = await JsonSerializer.DeserializeAsync <TType>(sampleData, this.Options);

            Assert.NotNull(payload);
        }
示例#5
0
        protected async Task GetQueue(Robot host, ApplicationDbContext db)
        {
            if (!host.IsOnline)
            {
                return;
            }

            try
            {
                _client.DefaultRequestHeaders.Accept.Clear();
                var httpResponse = await _client.SendAsync(HttpRequestMessage(host, "/mission_queue"));

                if (httpResponse.IsSuccessStatusCode)
                {
                    await using var responseStream = await httpResponse.Content.ReadAsStreamAsync();

                    var response =
                        await JsonSerializer.DeserializeAsync <List <MissionQueuesResponse> >(responseStream, _options);

                    foreach (var queuesResponse in response)
                    {
                        queuesResponse.RobotId = host.Id;
                        var isAvailable = db.MissionQueuesResponse
                                          .Where(s => s.Id.Equals(queuesResponse.Id))
                                          .Any(s => s.RobotId.Equals(host.Id));

                        if (isAvailable)
                        {
                            db.MissionQueuesResponse.Update(new MissionQueuesResponse
                            {
                                Id      = queuesResponse.Id,
                                Robot   = host,
                                RobotId = host.Id,
                                State   = queuesResponse.State,
                                Url     = queuesResponse.Url
                            });
                        }
                        else
                        {
                            var missq = new MissionQueuesResponse
                            {
                                Id      = queuesResponse.Id,
                                Robot   = host,
                                RobotId = host.Id,
                                State   = queuesResponse.State,
                                Url     = queuesResponse.Url
                            };

                            await db.MissionQueuesResponse.AddAsync(missq);
                        }
                    }

                    await db.SaveChangesAsync();
                }
            }
            catch (Exception e)
            {
                _logger.LogCritical("The Robot may be is offline");
            }
        }
示例#6
0
 private static async Task <MuntContext> DeserializeMuntContext(Stream stream)
 {
     return(await JsonSerializer.DeserializeAsync <MuntContext>(new StreamReader(stream).BaseStream,
                                                                new JsonSerializerOptions
     {
         PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
         Converters = { new JsonStringEnumConverter() }
     }));
 }
 public async Task <IEnumerable <UserFormViewModel> > GetUsersAsync()
 {
     return(await JsonSerializer.DeserializeAsync <IEnumerable <UserFormViewModel> >(
                await _httpClient.GetStreamAsync("api/users"),
                new JsonSerializerOptions
     {
         PropertyNameCaseInsensitive = true
     }));
 }
示例#8
0
        new public async Task <List <EventMarker> > GetAll()
        {
            var response = await JsonSerializer.DeserializeAsync <IEnumerable <EventMarker> >
                               (await _httpClient.GetStreamAsync($"api/" + ControllerName), new JsonSerializerOptions()
            {
                PropertyNameCaseInsensitive = true
            });

            return(response.ToList());
        }
示例#9
0
        public async Task <TEntity> GetById(int id)
        {
            var response = await JsonSerializer.DeserializeAsync <TEntity>
                               (await _httpClient.GetStreamAsync($"api/" + ControllerName + $"/{id}"), new JsonSerializerOptions()
            {
                PropertyNameCaseInsensitive = true
            });

            return(response);
        }
        public async Task CanSerialize(string sampleDataPath)
        {
            await using var sampleData = File.OpenRead(sampleDataPath);
            var payload = await JsonSerializer.DeserializeAsync <TType>(sampleData, this.Options);

            Assert.NotNull(payload);

            await using var stream = new MemoryStream();
            await JsonSerializer.SerializeAsync(stream, payload !, this.Options);
        }
示例#11
0
 public IEnumerable <Factory> DeSerializeJSON(string fileName) //работает
 {
     using (FileStream fs = new FileStream(fileName, FileMode.Open))
     {
         var options = new JsonSerializerOptions {
             IncludeFields = true
         };
         var result = JsonSerializer.DeserializeAsync <List <Factory> >(fs, options).Result;
         return(result);
     }
 }
示例#12
0
        public async Task <Tool> Get(string id)
        {
            var result = await _client.GetAsync(id, HttpCompletionOption.ResponseHeadersRead).ConfigureAwait(false);

            using var streamReader        = new StreamReader(await result.Content.ReadAsStreamAsync());
            await using var contentStream = await result.Content.ReadAsStreamAsync();

            return(await JsonSerializer.DeserializeAsync <Tool>(contentStream, new JsonSerializerOptions
            {
                PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
                IgnoreNullValues = true
            }));
        }
        private async Task <T> GetAsync <T>(string url, CancellationToken cancellationToken)
        {
            var responseMessage = await _httpClient.GetAsync(url, cancellationToken);

            var responseStream = await responseMessage.Content.ReadAsStreamAsync();

            if (responseMessage.StatusCode == HttpStatusCode.OK)
            {
                return(await JsonSerializer.DeserializeAsync <T>(responseStream, _jsonSerializerOptions, cancellationToken));
            }

            var error = await JsonSerializer.DeserializeAsync <ApiError>(responseStream, _jsonSerializerOptions, cancellationToken);

            throw new ApiException(error);
        }
        private async Task AssertStoredLog(HttpResponseMessage response)
        {
            await Task.Delay(500);

            await using var logFileStream = File.OpenRead(_logFilePath);

            var logContext = (await JsonSerializer.DeserializeAsync <LogContext[]>(logFileStream, SerializerOptions))
                             .Single();

            logContext.Request.ShouldBe(response.RequestMessage);

            logContext.Response.ShouldBe(response);

            Assert.Equal(logContext.Protocol, $"HTTP/{response.Version}");
        }
示例#15
0
        public async Task <T> CreateAsync <T>(string resourceUri, T resource)
        {
            var response = await HttpClient.PostAsJsonAsync(resourceUri, resource);

            if (response.IsSuccessStatusCode)
            {
                var result = await JsonSerializer.DeserializeAsync <T>(await response.Content.ReadAsStreamAsync(),
                                                                       new JsonSerializerOptions { PropertyNameCaseInsensitive = true });

                return(result);
            }

            await ThrowException(response);

            throw new Exception("Server returned error");
        }
        public async Task <OpenWeatherDto> GetWeather(LatLonParameters latLonParameters)
        {
            var lat = latLonParameters.Lat;
            var lon = latLonParameters.Lon;

            var requestUri =
                $"https://api.openweathermap.org/data/2.5/onecall?lat={lat}&lon={lon}&appid={APIKeys.OpenWeatherApiKey}&units=imperial";

            // Look for cached version
            if (_memoryCache.TryGetValue(requestUri, out OpenWeatherDto weatherDto))
            {
                //  We found it in cache, use this.
                return(weatherDto);
            }

            var request = new HttpRequestMessage(HttpMethod.Get, requestUri);
            // request.Headers.Add("Accept", "application/vnd.github.v3+json");
            // request.Headers.Add("User-Agent", "HttpClientFactory-Sample");

            var client = _clientFactory.CreateClient();

            var response = await client.SendAsync(request);

            if (!response.IsSuccessStatusCode)
            {
                return(null);
            }
            await using var responseStream = await response.Content.ReadAsStreamAsync();

            weatherDto = await JsonSerializer.DeserializeAsync <OpenWeatherDto>(responseStream,
                                                                                new JsonSerializerOptions()
            {
                PropertyNameCaseInsensitive = true,
            });

            // Save to cache
            var cacheEntryOptions = new MemoryCacheEntryOptions()
                                    // Keep in cache for this time, reset time if accessed.
                                    .SetAbsoluteExpiration(TimeSpan
                                                           .FromMinutes(1));

            // Save data in cache.
            _memoryCache.Set(requestUri, weatherDto, cacheEntryOptions);

            return(weatherDto);
        }
示例#17
0
        public async Task <TModel> PatchAsync <TModel>(string resourceUri, JsonPatchDocument patchDocument)
        {
            var serializedItemToUpdate = JsonConvert.SerializeObject(patchDocument);
            var response = await HttpClient.PatchAsync(resourceUri, new StringContent(serializedItemToUpdate, null, "application/json"));

            if (response.IsSuccessStatusCode)
            {
                var result = await JsonSerializer.DeserializeAsync <TModel>(await response.Content.ReadAsStreamAsync(),
                                                                            new JsonSerializerOptions { PropertyNameCaseInsensitive = true });

                return(result);
            }

            await ThrowException(response);

            throw new Exception("Server returned error");
        }
示例#18
0
        public async Task <T> SendAsync <T>(HttpRequestMessage request, bool insensitiveCase = false)
        {
            var result = await _httpClient.SendAsync(request, HttpCompletionOption.ResponseHeadersRead).ConfigureAwait(false);

            await using (var responseStream = await result.Content.ReadAsStreamAsync())
            {
                if (insensitiveCase)
                {
                    return(await JsonSerializer.DeserializeAsync <T>(responseStream, new JsonSerializerOptions
                    {
                        PropertyNameCaseInsensitive = true,
                    }));
                }

                return(await JsonSerializer.DeserializeAsync <T>(responseStream));
            }
        }
        public async Task <OpenUVDto> GetCurrentUVIndex(LatLonParameters latLngParameters)
        {
            var lat = latLngParameters.Lat;
            var lon = latLngParameters.Lon;

            var requestUri = $"https://api.openuv.io/api/v1/uv?lat={lat}&lng={lon}";

            // Look for cached version
            if (_memoryCache.TryGetValue(requestUri, out OpenUVDto openUvDto))
            {
                //  We found it in cache, use this.
                return(openUvDto);
            }

            var request = new HttpRequestMessage(HttpMethod.Get, requestUri);

            request.Headers.Add("x-access-token", APIKeys.OpenUVIndexApiKey);

            var client = _clientFactory.CreateClient();

            var response = await client.SendAsync(request);

            if (!response.IsSuccessStatusCode)
            {
                return(null);
            }
            await using var responseStream = await response.Content.ReadAsStreamAsync();

            openUvDto = await JsonSerializer.DeserializeAsync <OpenUVDto>(responseStream, new JsonSerializerOptions()
            {
                PropertyNameCaseInsensitive = true,
            });

            // Save to cache
            var cacheEntryOptions = new MemoryCacheEntryOptions()
                                    // Keep in cache for this time, reset time if accessed.
                                    .SetAbsoluteExpiration(TimeSpan
                                                           .FromMinutes(
                                                               30)); // We are allowed 50 hits per day. We will only ever hit this 48 times. (2 * 24 = 48)

            // Save data in cache.
            _memoryCache.Set(requestUri, openUvDto, cacheEntryOptions);

            return(openUvDto);
        }
示例#20
0
        public async Task <ServiceResponse> DeserializeResponse(Type type, byte[] message, HttpDataSerializerOptions options = null)
        {
            var opts = TextJsonSerializerSettings.CreateJsonSerializerOptions(options, _debugMode);

            try
            {
                using (var ms = new MemoryStream(message))
                {
                    var result = await JsonSerializer.DeserializeAsync(ms, type, opts);

                    return((ServiceResponse)result);
                }
            }
            catch (JsonException ex)
            {
                _logger.LogError("Cannot deserialize request", ex);
                throw;
            }
        }
示例#21
0
文件: LPServer.cs 项目: 20chan/lp
        public async Task <Response> CreatePost(Request req)
        {
            try {
                var postReq = await JsonSerializer.DeserializeAsync <AuthPostRequest>(req.Body, options);

                if (!TryAuth(postReq.Auth))
                {
                    return(ErrorResp(new JSON {
                        ["success"] = false,
                        ["message"] = "auth failed",
                    }, status: StatusCode.Unauthorized));
                }

                var post = postReq.Post;
                post.WrittenDate = DateTime.Now;

                if (string.IsNullOrEmpty(post.Name))
                {
                    return(ErrorResp("name should not be empty"));
                }
                if (string.IsNullOrEmpty(post.Title))
                {
                    return(ErrorResp("title should not be empty"));
                }
                if (string.IsNullOrEmpty(post.Content))
                {
                    return(ErrorResp("content should not be empty"));
                }

                posts.Insert(post);
                db.Checkpoint();
                return(new JsonResponse(new JSON {
                    ["success"] = true,
                    ["id"] = post.Id,
                }));
            }
            catch (JsonException ex) {
                return(ErrorResp("invalid json", ex));
            }
            catch (Exception ex) {
                return(ErrorResp("server error", ex, StatusCode.InternalServerError));
            }
        }
示例#22
0
        public async Task <T> DeserializeResponse <T>(byte[] message, HttpDataSerializerOptions options = null) where T : new()
        {
            var opts = TextJsonSerializerSettings.CreateJsonSerializerOptions(options, _debugMode);

            try
            {
                using (var ms = new MemoryStream(message))
                {
                    var result = await JsonSerializer.DeserializeAsync <T>(ms, opts);

                    return(result);
                }
            }
            catch (JsonException ex)
            {
                _logger.LogError("Cannot deserialize response", ex);
                throw new CodeWorksSerializationException("Cannot deserialize JSON payload", ex);
            }
        }
示例#23
0
        public async Task SurvivesRoundTrip(SampleDataDescriptor sampleDataFile)
        {
            await using var sampleData = File.OpenRead(sampleDataFile.FullPath);
            var deserialized = await JsonSerializer.DeserializeAsync <TType>(sampleData, this.Options);

            Assert.NotNull(deserialized);

            await using var stream = new MemoryStream();
            await JsonSerializer.SerializeAsync(stream, deserialized !, this.Options);

            await stream.FlushAsync();

            stream.Seek(0, SeekOrigin.Begin);
            sampleData.Seek(0, SeekOrigin.Begin);

            var serialized = await JsonDocument.ParseAsync(stream);

            var original = await JsonDocument.ParseAsync(sampleData);

            JsonAssert.Equivalent(original, serialized, this.AssertOptions);
        }
示例#24
0
        public async Task <BaseRequest> DeserializeRequest(
            Type type,
            byte[] message,
            HttpDataSerializerOptions options = null)
        {
            var opts = TextJsonSerializerSettings.CreateJsonSerializerOptions(options, _debugMode);

            if (message.Length == 0)
            {
                return((BaseRequest)Activator.CreateInstance(type));
            }

            try
            {
                using (var ms = new MemoryStream(message))
                {
                    var result = await JsonSerializer.DeserializeAsync(ms, type, opts);

                    return((BaseRequest)result);
                }
            }
            catch (JsonException ex)
            {
                var contents = Encoding.UTF8.GetString(message);

                if (ex.StackTrace.Contains("JsonConverterEnum"))
                {
                    // INVALID ENUM FOUND - TRY AND FIGURE IT OUT
                    var property = ex.Path.Substring(2, ex.Path.Length - 2);
                    throw new ValidationErrorException("Invalid enum value provided", property);
                }

                if (string.IsNullOrWhiteSpace(contents))
                {
                    return((BaseRequest)Activator.CreateInstance(type));
                }
                _logger.LogError(ex, $"Cannot deserialize request payload {contents}");
                throw new CodeWorksSerializationException($"Cannot parse payload as JSON. Payload={contents}", contents);
            }
        }
        public async Task <UserPaginationViewModel> GetByPageAsync(string trueName,
                                                                   Gender?gender,
                                                                   IsEnabled?isEnabled,
                                                                   int current,
                                                                   int pageSize,
                                                                   string orderByPropertyName,
                                                                   bool isAsc)
        {
            //return await JsonSerializer.DeserializeAsync<UserPaginationViewModel>(
            //    await _httpClient.GetStreamAsync("api/users/pagination"),
            //    new JsonSerializerOptions
            //    {
            //        PropertyNameCaseInsensitive = true
            //    });

            return(await JsonSerializer.DeserializeAsync <UserPaginationViewModel>(
                       await _httpClient.GetStreamAsync("api/users/pagination"),
                       new JsonSerializerOptions
            {
                PropertyNameCaseInsensitive = true
            }));
        }
示例#26
0
        private async Task ThrowException(HttpResponseMessage response)
        {
            if (response.StatusCode == HttpStatusCode.UnprocessableEntity)
            {
                var unprocessableResult = await JsonSerializer.DeserializeAsync <UnprocessableEntityProblemDetails>(
                    await response.Content.ReadAsStreamAsync(),
                    new JsonSerializerOptions()
                {
                    PropertyNameCaseInsensitive = true
                });

                throw new ApiError(unprocessableResult, HttpStatusCode.UnprocessableEntity);
            }
            if (response.StatusCode == HttpStatusCode.InternalServerError)
            {
                throw new Exception("Server returned error");
            }
            if (response.StatusCode == HttpStatusCode.BadRequest)
            {
                throw new Exception("Server returned Bad Request error");
            }
        }
示例#27
0
        public async Task <ListWithMetadata <T> > GetListAnonymousAsync <T>(string resourceUri)
        {
            var response = await AnonymousHttpClient.GetAsync(resourceUri);

            var result = await JsonSerializer.DeserializeAsync <List <T> >(await response.Content.ReadAsStreamAsync(), _jsonDeserOpt);

            if (response.Headers.TryGetValues("x-pagination", out var values))
            {
                var paginationMeta = JsonSerializer.Deserialize <PaginationMetadata>(values.First(), _jsonDeserOpt);
                return(new ListWithMetadata <T>
                {
                    Data = result,
                    Metadata = paginationMeta
                });
            }

            return(new ListWithMetadata <T>
            {
                Data = result,
                Metadata = new PaginationMetadata()
            });
        }
        public async Task <ActionResult <List <CardVoteViewModel> > > GetVoteResult()
        {
            var request = new HttpRequestMessage(HttpMethod.Get,
                                                 "api/cards/votes");

            var client = _clientFactory.CreateClient("spring.festival.card.api");

            var response = await client.SendAsync(request);

            if (response.IsSuccessStatusCode)
            {
                await using var responseStream = await response.Content.ReadAsStreamAsync();

                var cardVotes = await JsonSerializer.DeserializeAsync
                                <List <CardVoteViewModel> >(responseStream,
                                                            new JsonSerializerOptions { PropertyNameCaseInsensitive = true });

                return(Ok(cardVotes));
            }

            return(NoContent());
        }
示例#29
0
        public async Task <CityViewModelResponse> GetTempByLonLat(string lat, string lon)
        {
            var teste   = new CityViewModelResponse();
            var request = new HttpRequestMessage(HttpMethod.Get,
                                                 "http://api.openweathermap.org/data/2.5/weather?lat=" + lat + "&lon=" + lon + "&units=metric&appid=142d374d2ea6105f400f36546592a3d4");
            var client = _clientFactory.CreateClient();

            var response = await client.SendAsync(request);

            Stream responseStream;
            JsonSerializerOptions options;

            if (!response.IsSuccessStatusCode)
            {
                responseStream = await response.Content.ReadAsStreamAsync();

                options = new JsonSerializerOptions
                {
                    DictionaryKeyPolicy = JsonNamingPolicy.CamelCase,
                    WriteIndented       = true
                };
                var objBadRequest = await JsonSerializer.DeserializeAsync
                                    <BadRequestViewModelAPI>(responseStream, options);

                throw new Exception(objBadRequest.message);
            }
            responseStream = await response.Content.ReadAsStreamAsync();

            options = new JsonSerializerOptions
            {
                DictionaryKeyPolicy = JsonNamingPolicy.CamelCase,
                WriteIndented       = true
            };
            var objApi = await JsonSerializer.DeserializeAsync
                         <CityAPI>(responseStream, options);

            teste = _mapper.Map <CityViewModelResponse>(objApi);
            return(teste);
        }
示例#30
0
        public static async Task <TV> DeserializeAsync <TV>(Stream stream,
                                                            JsonSerializerOptions jsonSerializerOptions = null)
        {
            try
            {
                return(jsonSerializerOptions is null
                    ? await JsonSerializer.DeserializeAsync <TV>(stream)
                    : await JsonSerializer.DeserializeAsync <TV>(stream, jsonSerializerOptions));
            }
            catch (Exception ex)
            {
                Logger.Error(ex, ex.Message);

                stream.Seek(0, SeekOrigin.Begin);

                using var reader = new StreamReader(stream, Encoding.UTF8);
                var value = await reader.ReadToEndAsync();

                Logger.Error($"Raw response: {value}");

                throw new FormatException(value);
            }
        }