private async Task <string> GetUserName() { var request = new HttpRequestMessage(HttpMethod.Get, _auth0UserInfo); request.Headers.Add("Authorization", Request.Headers["Authorization"].First()); var client = _clientFactory.CreateClient(); var response = await client.SendAsync(request); if (response.IsSuccessStatusCode) { var jsonContent = await response.Content.ReadAsStringAsync(); var user = JsonSerializer.Deserialize <User>(jsonContent, new JsonSerializerOptions() { PropertyNameCaseInsensitive = true }); return(user.Name); } else { return(""); } }
public void Microsoft_JsonSerializer_should_throw_for_wrong_types() { Action act = () => JsonSerializer.Deserialize <Secret>("false"); act.Should().Throw <System.Text.Json.JsonException>() .WithMessage("Cannot get the value of a token type 'False' as a string."); }
public static async Task <IActionResult> Run( [HttpTrigger(AuthorizationLevel.Function, "post", Route = null)] HttpRequest req, [SendGrid(ApiKey = "CustomSendGridKeyAppSettingName")] IAsyncCollector <SendGridMessage> messageCollector, ILogger log) { log.LogInformation("C# HTTP trigger function processed a request."); var options = new JsonSerializerOptions { PropertyNameCaseInsensitive = true, }; var requestBody = await new StreamReader(req.Body).ReadToEndAsync(); var meeting = JsonSerializer.Deserialize <DeaconMeeting>(requestBody, options); try { var message = new SendGridMessage(); var worker = new MessageWorker(message); meeting.Email = Environment.GetEnvironmentVariable("DeaconMeetingEmail"); meeting.Name = Environment.GetEnvironmentVariable("DeaconMeetingName"); meeting.FromEmail = Environment.GetEnvironmentVariable("DeaconMeetingFromEmail"); meeting.FromName = Environment.GetEnvironmentVariable("DeaconMeetingFromName"); meeting.Copy = Environment.GetEnvironmentVariable("DeaconMeetingCopy"); await messageCollector.AddAsync(worker.PrepareDiaconateMeetingEmail(meeting)); } catch (Exception e) { log.LogInformation(e.ToString()); return(new BadRequestResult()); } return(new OkResult()); }
public async Task <ApplicationUser> GetUser(string username, string password) { ApplicationUser user = new ApplicationUser(); dynamic jsonObject = new JObject(); jsonObject.Username = username; jsonObject.Password = password; try { var content = new StringContent(jsonObject.ToString(), Encoding.UTF8, "application/json"); client.DefaultRequestHeaders.Add("Authorization", $"Bearer {this.BearerToken}"); var responseMessage = await client.PostAsync(Constants.GetUserUrl, content); if (responseMessage.IsSuccessStatusCode) { string content2 = await responseMessage.Content.ReadAsStringAsync(); user = JsonSerializer.Deserialize <ApplicationUser>(content2, serializerOptions); } } catch (Exception ex) { Debug.WriteLine(@"\tERROR {0}", ex.Message); } return(user); }
public async Task <Response> UpdateMessageAsync(int id) { Uri uri = new Uri(string.Format(Constants.MessageUrl, id)); try { client.DefaultRequestHeaders.Add("Authorization", $"Bearer {this.BearerToken}"); HttpResponseMessage response = null; response = await client.PatchAsync(uri, null); string jsonresponse = await response.Content.ReadAsStringAsync(); Response response2 = JsonSerializer.Deserialize <Response>(jsonresponse, serializerOptions); if (response.IsSuccessStatusCode) { Debug.WriteLine(@"\food successfully saved."); } return(response2); } catch (Exception ex) { Debug.WriteLine(@"\tERROR {0}", ex.Message); return(new Response() { Status = Constants.Status.Error, Message = Constants.APIMessages.ErrorOnUpdate }); } }
public static bool TryLoadCareer(string json, Assembly assembly, string gameData, out InstalledContentPack pack) { try { var metadata = JsonSerializer.Deserialize <ContentPackMetadata>(json, new JsonSerializerOptions { IncludeFields = true }); pack = new InstalledContentPack(); pack.Name = metadata.Name; pack.Author = metadata.Author; pack.Description = metadata.Description; pack._dataReader = () => assembly.GetManifestResourceStream(gameData); return(true); } catch (Exception ex) { EntryPoint.CurrentApp.Logger.Log("Cannot load career mode data."); EntryPoint.CurrentApp.Logger.LogException(ex); } pack = null; return(false); }
public async Task <Response> UpdateUserAsync(UpdateUserModel model) { Uri uri = new Uri(string.Format(Constants.UpdateUserProfileUrl, string.Empty)); try { string json = JsonSerializer.Serialize <UpdateUserModel>(model, serializerOptions); StringContent content = new StringContent(json, Encoding.UTF8, "application/json"); client.DefaultRequestHeaders.Add("Authorization", $"Bearer {this.BearerToken}"); HttpResponseMessage response = null; response = await client.PatchAsync(uri, content); string jsonresponse = await response.Content.ReadAsStringAsync(); Response response2 = JsonSerializer.Deserialize <Response>(jsonresponse, serializerOptions); if (response.IsSuccessStatusCode) { Debug.WriteLine(@"\user password successfully saved."); } return(response2); } catch (Exception ex) { Debug.WriteLine(@"\tERROR {0}", ex.Message); return(new Response() { Status = Constants.Status.Error, Message = Constants.APIMessages.ErrorOnUpdate }); } }
public async Task <TCache> StoreAndGetAsync <TCache>(string key, Func <Task <TCache> > cacheFactory, CacheDuration duration = CacheDuration.Eternal) { string oldCache = await _multiplexer.Db.StringGetAsync(key); _logger.Information($"cache object: {typeof(TCache).Name} \n"); if (string.IsNullOrWhiteSpace(oldCache)) { try { var toBeCached = await cacheFactory(); var result = await StoreAsync(key, toBeCached, duration); return(result); } catch (Exception e) { _logger.Fatal($"create object to be cached failed: {typeof(TCache).Name} \n" + $"exception : {e}"); throw; } } return(JsonSerializer.Deserialize <TCache>(oldCache, _serializerOptions)); }
public static async Task <IActionResult> Run( [HttpTrigger(AuthorizationLevel.Function, "post", Route = null)] HttpRequest req, [CosmosDB( databaseName: "ministries", collectionName: "attendee", ConnectionStringSetting = "CosmosDBConnection")] IAsyncCollector <AttendeeDB> attendeeDocuments, ILogger log) { log.LogInformation("C# HTTP trigger function processed a request."); var options = new JsonSerializerOptions { PropertyNameCaseInsensitive = true, }; var requestBody = await new StreamReader(req.Body).ReadToEndAsync(); var attendee = JsonSerializer.Deserialize <AttendeeDB>(requestBody, options); try { if (attendee.id == null) { attendee.id = Guid.NewGuid().ToString(); } await attendeeDocuments.AddAsync(attendee); } catch (Exception e) { log.LogInformation(e.ToString()); } return(new OkObjectResult(attendee)); }
public async Task <List <object> > Get(Guid guidId) { var interactions = new List <JObject>(); var request = new ScanRequest { TableName = tableName }; ScanResponse result = await amazonDynamoDbClient.ScanAsync(request); foreach (var item in result.Items) { var document = Document.FromAttributeMap(item); if (document[idHospitalizationIndex] == guidId.ToString()) { var interaction = JObject.Parse(document[interactionIndex].AsString()); interactions.Add(interaction); } } var orderInteractions = interactions .OrderByDescending(obj => DateTime.Parse(obj["interactionAt"].ToString())) .Select(item => JsonSerializer.Deserialize <object>(item.ToString())) .ToList(); return(orderInteractions); }
public void Format() { var builder = new StringBuilder(); while (!_reader.EndOfStream) { builder.AppendLine(_reader.ReadLine()); } _reader.BaseStream.Seek(0, SeekOrigin.Begin); try { if (string.IsNullOrEmpty(builder.ToString())) { throw new NullReferenceException(); } if (string.IsNullOrWhiteSpace(builder.ToString())) { throw new NullReferenceException(); } //有憨憨作者在json里写除了string以外的内容全部抛出 JsonSerializer.Deserialize <Dictionary <string, string> >(builder.ToString(), new JsonSerializerOptions() { AllowTrailingCommas = true, ReadCommentHandling = JsonCommentHandling.Skip, Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping }); var jr = new JsonTextReader(_reader); var jo = new JObject(); var jt = (JObject)JToken.ReadFrom(jr, new JsonLoadSettings() { DuplicatePropertyNameHandling = DuplicatePropertyNameHandling.Ignore, CommentHandling = CommentHandling.Ignore }); foreach (var(key, value) in jt) { jo.Add(key, value.Value <string>()); } _writer.Write(jo.ToString()); _writer.Close(); _writer.Dispose(); _reader.Close(); _reader.Dispose(); } catch { if (!Directory.Exists($"{Directory.GetCurrentDirectory()}/broken")) { Directory.CreateDirectory($"{Directory.GetCurrentDirectory()}/broken"); } _writer.Write("{}"); _writer.Close(); _writer.Dispose(); _reader.Close(); _reader.Dispose(); File.WriteAllText($"{Directory.GetCurrentDirectory()}/broken/{_modName}{DateTime.UtcNow.Millisecond}.json", builder.ToString()); } }
public async Task <object> Get(Guid guidId) { var hospitalizations = new List <object>(); var request = new QueryRequest { TableName = tableName, KeyConditions = new Dictionary <string, Condition> { { primaryPartitionKey, new Condition() { ComparisonOperator = ComparisonOperator.EQ, AttributeValueList = new List <AttributeValue> { new AttributeValue { S = guidId.ToString() } } } } } }; var result = await amazonDynamoDbClient.QueryAsync(request); foreach (var item in result.Items) { var document = Document.FromAttributeMap(item); //var hospitalization = JsonSerializer.Deserialize<JObject>(document[registrationIndex].AsString()); var hospitalization = JObject.Parse(document[registrationIndex].AsString()); hospitalization["id"] = guidId; hospitalizations.Add(JsonSerializer.Deserialize <object>(hospitalization.ToString())); } return(hospitalizations.FirstOrDefault()); }
public async Task <User> ValidateUserLogin(string username, string password) { HttpClient client = new HttpClient(); User user = new() { Username = username, Password = password }; string userAsJson = JsonSerializer.Serialize(user); StringContent content = new StringContent( userAsJson, Encoding.UTF8, "application/json" ); HttpResponseMessage responseMessage = await client.PostAsync("https://localhost:5004/User", content); if (!responseMessage.IsSuccessStatusCode) { throw new Exception($"Error: {responseMessage.StatusCode}, {responseMessage.ReasonPhrase}"); } string someUser = await responseMessage.Content.ReadAsStringAsync(); User finalUser = JsonSerializer.Deserialize <User>(someUser, new JsonSerializerOptions { PropertyNamingPolicy = JsonNamingPolicy.CamelCase }); return(finalUser); } }
protected override async Task <HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) { var tiempo = Stopwatch.StartNew(); _logger.LogInformation("Inicia el Request"); var response = await base.SendAsync(request, cancellationToken); if (response.IsSuccessStatusCode) { var contenido = await response.Content.ReadAsStringAsync(); var options = new JsonSerializerOptions { PropertyNameCaseInsensitive = true }; var resultado = JsonSerializer.Deserialize <LibroModeloRemoto>(contenido, options); if (resultado.AutorLibro != null) { var responseAutor = await _autorRemote.GetAutor(resultado.AutorLibro ?? Guid.Empty); if (responseAutor.resultado) { var objetoAutor = responseAutor.autor; resultado.AutorData = objetoAutor; var resultadoStr = JsonSerializer.Serialize(resultado); response.Content = new StringContent(resultadoStr, System.Text.Encoding.UTF8, "application/json"); } } } _logger.LogInformation($"El proceso se hizo en {tiempo.ElapsedMilliseconds}ms"); return(response); }
public async Task <string?> GetOrRefreshTokenAsync() { if (_lastUpdateToken.AddMinutes(25) >= SystemTime.Now()) { return(_token); } using var client = _httpClientFactory.CreateClient(); client.BaseAddress = new Uri(_channel.MasterCommunication !.ToString()); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", _token); using var content = new StringContent(JsonSerializer.Serialize(_channel), Encoding.Default, "application/json"); var message = client.PutAsync(new Uri($"{client.BaseAddress}api/channel"), content); var result = JsonSerializer.Deserialize <ConnectionInfo>(await(await message.ConfigureAwait(false)).Content.ReadAsStringAsync().ConfigureAwait(false), new JsonSerializerOptions { PropertyNamingPolicy = JsonNamingPolicy.CamelCase }); _token = result?.Token; _lastUpdateToken = SystemTime.Now(); _logger.Information(LogLanguage.Instance.GetMessageFromKey(LogLanguageKey.SECURITY_TOKEN_UPDATED)); return(_token); }
public List <ExternalType> List() { var tsconfig = Path.Combine(projectDir, "tsconfig.json"); IEnumerable <string> files = null; if (File.Exists(tsconfig)) { var cfg = JsonSerializer.Deserialize <TSConfig>(File.ReadAllText(tsconfig), new JsonSerializerOptions { PropertyNameCaseInsensitive = true, }); if (!cfg.Files.IsEmptyOrNull()) { files = cfg.Files.Where(x => File.Exists(Path.Combine(projectDir, PathHelper.ToPath(x)))) .Select(x => Path.GetFullPath(Path.Combine(projectDir, PathHelper.ToPath(x)))); } else if (!cfg.Include.IsEmptyOrNull()) { var typeRoots = cfg.CompilerOptions?.TypeRoots?.IsEmptyOrNull() != false ? new string[] { "./node_modules/@types" } : cfg.CompilerOptions.TypeRoots; var types = new HashSet <string>(cfg.CompilerOptions?.Types ?? Array.Empty <string>(), StringComparer.OrdinalIgnoreCase); files = typeRoots.Select(typeRoot => { var s = PathHelper.ToUrl(typeRoot); if (s.StartsWith("./", StringComparison.Ordinal)) { s = s[2..]; } return(Path.Combine(projectDir, PathHelper.ToPath(s))); })
public async Task <List <ChannelInfo> > GetChannelsAsync() { var channels = MasterClientListSingleton.Instance.Channels; if (MasterClientListSingleton.Instance.Channels.Any()) { return(channels); } using var client = _httpClientFactory.CreateClient(); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", await GetOrRefreshTokenAsync().ConfigureAwait(false)); var response = await client.GetAsync(new Uri($"{_channel.MasterCommunication}/api/channel")).ConfigureAwait(false); if (response.IsSuccessStatusCode) { var chan = JsonSerializer.Deserialize <List <ChannelInfo> >(await response.Content.ReadAsStringAsync() , new JsonSerializerOptions { PropertyNamingPolicy = JsonNamingPolicy.CamelCase }); if (chan != null) { channels = chan; return(channels); } } throw new HttpRequestException(); }
public static T DeserializeWithSystemTextJson <T>(this string json, Action <MetadataJsonSerializationOptions>?configureSerialization = null) { JsonSerializerOptions jsonSerializerOptions = new JsonSerializerOptions().ConfigureJsonOptions(configureSerialization); T?restored = JsonSerializer.Deserialize <T>(json, jsonSerializerOptions); return(restored); }
public async Task <ChannelInfo?> GetChannelAsync(int channelId) { var channels = MasterClientListSingleton.Instance.Channels; if (MasterClientListSingleton.Instance.Channels.Any()) { return(channels?.FirstOrDefault(s => s.Id == channelId)); } using var client = _httpClientFactory.CreateClient(); client.BaseAddress = new Uri(_channel.MasterCommunication !.ToString()); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", await GetOrRefreshTokenAsync().ConfigureAwait(false)); var response = await client.GetAsync(new Uri($"{_channel.MasterCommunication}/api/channel?id={channelId}")).ConfigureAwait(false); if (response.IsSuccessStatusCode) { channels = JsonSerializer.Deserialize <List <ChannelInfo> >(await response.Content.ReadAsStringAsync().ConfigureAwait(false) , new JsonSerializerOptions { PropertyNamingPolicy = JsonNamingPolicy.CamelCase }); } return(channels?.FirstOrDefault(s => s.Id == channelId)); }
public void SerializeDeserializePropertyContainer() { var initialContainer = CreateTestContainer(); var propertyContainerContract = initialContainer.ToContract(new DefaultMapperSettings()); propertyContainerContract.Should().NotBeNull(); var contractJson = propertyContainerContract.ToJsonWithSystemTextJson(); var json1 = initialContainer.ToJsonWithSystemTextJson(); var jsonOptions = new JsonSerializerOptions().ConfigureJsonOptions(); DeserializeAndCompare <IPropertyContainer>(); DeserializeAndCompare <PropertyContainer>(); DeserializeAndCompare <IMutablePropertyContainer>(); DeserializeAndCompare <MutablePropertyContainer>(); DeserializeAndCompare <PropertyContainer <TestMeta> >(); var json2 = initialContainer.ToJsonWithNewtonsoftJson(); var container2 = json2.DeserializeWithNewtonsoftJson <IPropertyContainer>(); ObjectDiff objectDiff = MetadataComparer.GetDiff(initialContainer, container2); objectDiff.Diffs.Should().BeEmpty(); void DeserializeAndCompare <TContainer>() where TContainer : IPropertyContainer { TContainer?restored = JsonSerializer.Deserialize <TContainer>(json1, jsonOptions); ObjectDiff objectDiff = MetadataComparer.GetDiff(restored, initialContainer); objectDiff.Diffs.Should().BeEmpty(); } }
public async Task <Response> DeleteUserAsync(string id) { Uri uri = new Uri(string.Format(Constants.DeleteUserUrl)); DeleteUserModel userModel = new DeleteUserModel { UserId = id }; try { string json = JsonSerializer.Serialize <DeleteUserModel>(userModel, serializerOptions); var content = new StringContent(json, Encoding.UTF8, "application/json"); client.DefaultRequestHeaders.Add("Authorization", $"Bearer {this.BearerToken}"); HttpResponseMessage response = await client.PostAsync(uri, content); string jsonresponse = await response.Content.ReadAsStringAsync(); Response response2 = JsonSerializer.Deserialize <Response>(jsonresponse, serializerOptions); if (response.IsSuccessStatusCode) { Debug.WriteLine(@"\user successfully deleted."); } return(response2); } catch (Exception ex) { Debug.WriteLine(@"\tERROR {0}", ex.Message); return(new Response() { Status = Constants.Status.Error, Message = Constants.APIMessages.ErrorOnDeletion }); } }
public MainWindowViewModel(Window desktopMainWindow) { _desktopMainWindow = desktopMainWindow; BlockChainCache = new BlockChainCache(); BlockChainCache.StakePools = new ObservableCollection <StakePool>(); var stakePoolDbFileInfo = new FileInfo(StakePoolListDatabase); if (stakePoolDbFileInfo.Exists) { var jsonCacheStakePools = File.ReadAllBytes(StakePoolListDatabase); var readOnlySpan = new ReadOnlySpan <byte>(jsonCacheStakePools); BlockChainCache = JsonSerializer.Deserialize <BlockChainCache>(readOnlySpan); _allStakePools = BlockChainCache.StakePools; OnPropertyChanged("BlockChainCache"); } else { _allStakePools = new ObservableCollection <StakePool>(); } _allWallets = new ObservableCollection <Wallet>(); _cardanoServer = new CardanoServer(); _walletClient = new WalletClient(_nodePort); desktopMainWindow.Opened += StartCardanoServer; desktopMainWindow.Closing += WindowClosing; }
public async Task <List <Message> > GetMessageDataAsync(string UserId) { List <Message> Messages = new List <Message>(); Uri uri = new Uri(string.Format(Constants.MessageUrl, UserId)); try { client.DefaultRequestHeaders.Add("Authorization", $"Bearer {this.BearerToken}"); HttpResponseMessage response = await client.GetAsync(uri); if (response.IsSuccessStatusCode) { string content = await response.Content.ReadAsStringAsync(); if (!string.IsNullOrEmpty(content)) { Messages = JsonSerializer.Deserialize <List <Message> >(content, serializerOptions); } } } catch (Exception ex) { Debug.WriteLine(@"\tERROR {0}", ex.Message); } return(Messages); }
public void RunElevatedShouldEnableAlwaysRunElevatedWhenSuccessful() { // Assert Func <string, int> SendMockIPCConfigMSG = msg => { OutGoingGeneralSettings snd = JsonSerializer.Deserialize <OutGoingGeneralSettings>(msg); Assert.IsTrue(snd.GeneralSettings.RunElevated); return(0); }; Func <string, int> SendRestartAdminIPCMessage = msg => { return(0); }; Func <string, int> SendCheckForUpdatesIPCMessage = msg => { return(0); }; // Arrange GeneralViewModel viewModel = new GeneralViewModel( settingsRepository: SettingsRepository <GeneralSettings> .GetInstance(mockGeneralSettingsUtils.Object), "GeneralSettings_RunningAsAdminText", "GeneralSettings_RunningAsUserText", false, false, UpdateUIThemeMethod, SendMockIPCConfigMSG, SendRestartAdminIPCMessage, SendCheckForUpdatesIPCMessage, generalSettingsFileName); Assert.IsFalse(viewModel.RunElevated); // act viewModel.RunElevated = true; }
public async Task <Response> RegisterUserAsync(RegisterModel model) { Uri uri = new Uri(string.Format(Constants.RegisterUrl, string.Empty)); try { string json = JsonSerializer.Serialize <RegisterModel>(model, serializerOptions); StringContent content = new StringContent(json, Encoding.UTF8, "application/json"); HttpResponseMessage response = null; response = await client.PostAsync(uri, content); string jsonresponse = await response.Content.ReadAsStringAsync(); Response response2 = JsonSerializer.Deserialize <Response>(jsonresponse, serializerOptions); if (response.IsSuccessStatusCode) { Debug.WriteLine(@"\user successfully created."); } return(response2); } catch (Exception ex) { Debug.WriteLine(@"\tERROR {0}", ex.Message); return(new Response() { Status = Constants.Status.Error, Message = Constants.APIMessages.ErrorOnRegisterFailed }); } }
public void IsDarkThemeRadioButtonCheckedShouldThemeToDarkWhenSuccessful() { // Arrange // Assert Func <string, int> SendMockIPCConfigMSG = msg => { OutGoingGeneralSettings snd = JsonSerializer.Deserialize <OutGoingGeneralSettings>(msg); Assert.AreEqual("dark", snd.GeneralSettings.Theme); return(0); }; Func <string, int> SendRestartAdminIPCMessage = msg => { return(0); }; Func <string, int> SendCheckForUpdatesIPCMessage = msg => { return(0); }; GeneralViewModel viewModel = new GeneralViewModel( settingsRepository: SettingsRepository <GeneralSettings> .GetInstance(mockGeneralSettingsUtils.Object), "GeneralSettings_RunningAsAdminText", "GeneralSettings_RunningAsUserText", false, false, UpdateUIThemeMethod, SendMockIPCConfigMSG, SendRestartAdminIPCMessage, SendCheckForUpdatesIPCMessage, generalSettingsFileName); Assert.IsFalse(viewModel.IsDarkThemeRadioButtonChecked); // act viewModel.IsDarkThemeRadioButtonChecked = true; }
private Task OnJumpToState(JumpToStateCallback callbackInfo) { SequenceNumberOfCurrentState = callbackInfo.payload.actionId; using (Store.BeginInternalMiddlewareChange()) { var newFeatureStates = Json.Deserialize <Dictionary <string, object> >(callbackInfo.state); foreach (KeyValuePair <string, object> newFeatureState in newFeatureStates) { // Get the feature with the given name if (!Store.Features.TryGetValue(newFeatureState.Key, out IFeature feature)) { continue; } var serializedFeatureStateElement = (JsonElement)newFeatureState.Value; object stronglyTypedFeatureState = Json.Deserialize( json: serializedFeatureStateElement.ToString(), returnType: feature.GetStateType(), options: SerializationOptions); // Now set the feature's state to the deserialized object feature.RestoreState(stronglyTypedFeatureState); } } return(Task.CompletedTask); }
public async Task <Cell> GetCell(string queryString) { NpgsqlConnection _npgsqlConnection = new NpgsqlConnection(_databaseSettings.DatabaseConnectionString); await _npgsqlConnection.OpenAsync(); using var cmd = new NpgsqlCommand(queryString); cmd.Connection = _npgsqlConnection; var dataReader = await cmd.ExecuteReaderAsync(); Cell cell = null; while (dataReader.Read()) { cell = new Cell() { CellId = dataReader.GetFieldValue <int>(0), DashboardId = dataReader.GetFieldValue <int>(1), Input = JsonSerializer.Deserialize <CellGraphData>(dataReader.GetFieldValue <JsonElement>(2).GetRawText()), Options = JsonSerializer.Deserialize <CellOptions>(dataReader.GetFieldValue <JsonElement>(3).GetRawText()), }; } ; cmd.Parameters.Clear(); await dataReader.CloseAsync(); await _npgsqlConnection.CloseAsync(); return(cell); }
public IActionResult Details(int id) { Trace.WriteLine("ID = " + id); request = ConfigurationManager.AppSettings["baseUrl"] + ApiRoute.Films.FilmBase + "/" + ApiRoute.Films.GetFullFilmDetailsByIdFilm.Replace("{idFilm}", id.ToString()); Trace.WriteLine(request); response = client.GetAsync(request).Result; Trace.WriteLine("Api Reponse: " + response.Content.ReadAsStringAsync().Result); if (!response.IsSuccessStatusCode) { throw new Exception("http fail full film"); } FullFilmDTO film = JsonSerializer.Deserialize <ResponsePagine <FullFilmDTO> >(response.Content.ReadAsStringAsync().Result, options).Value; Trace.WriteLine(film.Title); //poster path HttpResponseMessage r = client.GetAsync(ConfigurationManager.AppSettings["movieAPI"] + film.Id + ConfigurationManager.AppSettings["appendKey"]).Result; if (!r.IsSuccessStatusCode) { throw new Exception("http fail poster path"); } string s = r.Content.ReadAsStringAsync().Result; var data = (JObject)JsonConvert.DeserializeObject(s); string newPath = data["poster_path"].Value <string>(); film.PosterPath = ConfigurationManager.AppSettings["pathToPoster"] + newPath + ConfigurationManager.AppSettings["appendKey"]; return(View(film)); }
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() }); }