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)); }
public async Task InvokeAsync(HttpContext context) { try { await _next(context); } catch (Exception ex) { _logger.LogError(ex, ex.Message); context.Response.ContentType = "application/json"; context.Response.StatusCode = (int)HttpStatusCode.InternalServerError; var response = _env.IsDevelopment() ? new ApiException(context.Response.StatusCode, ex.Message, ex.StackTrace?.ToString()) : new ApiException(context.Response.StatusCode, "Internal Server Error"); var options = new JsonSerializerOptions { PropertyNamingPolicy = JsonNamingPolicy.CamelCase }; var json = JsonSerializer.Serialize(response, options); await context.Response.WriteAsync(json); ; } }
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)); }
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 ActionResult <string> UltimaAvaliacao([FromBody] dynamic rec) { lock (_system) { var jobject = JObject.Parse(JsonSerializer.Serialize(rec)); if (!_system.isUserOnline(jobject.valueST.ToString())) { return(Unauthorized("Client Offline")); } string email = jobject.email.ToString(); Avaliaçao av = _system.GetUltAvaliaçaoR(email); if (av == null) { return(NotFound("Utilizador ainda não tem Avaliaçoes")); } JObject job = JObject.Parse(JsonConvert.SerializeObject(av)); var nome = _system.GetUser(email).GetName(); //---------------- Patch job.Remove("id"); job.Remove("realizada"); job.Remove("instrutor_email"); job.Add("comentario", " "); job.Add("massa_gorda_img", " "); job.Add("cliente_nome", nome); //------------ return(Ok(job.ToString())); } }
string GetObjectInfo(object obj, string title) { if (obj == null) { return(string.Empty); } var strBuilder = new StringBuilder(); strBuilder.AppendLine(title); strBuilder.AppendLine($"Type -> {obj.GetType().Name}"); Type objType = obj.GetType(); var resultProp = objType.GetProperties() .FirstOrDefault(x => x.Name.Equals(nameof(FlowResult.Result))); var result = resultProp?.GetValue(obj); if (result != null) { var serialized = JsonSerializer.Serialize(obj, options: new JsonSerializerOptions() { PropertyNameCaseInsensitive = true, IgnoreNullValues = true, }); strBuilder.AppendLine("Object result props:"); strBuilder.AppendLine(serialized); } return(strBuilder.ToString()); }
public async Task SetTransforms(TransformCollection transforms) { using (var writer = File.CreateText(PATH)) { var json = JsonSerializer.Serialize(transforms); await writer.WriteLineAsync(json); } }
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 <string> GetLocationsAsync(ClaimsPrincipal user) { int userid; if (!int.TryParse(user.Claims.FirstOrDefault(x => x.Type == "ID").Value, out userid)) { return(null); } var User = await _context.Users .Include(x => x.UserLocations) .ThenInclude(y => y.Location) .FirstOrDefaultAsync(x => x.UserID == userid); if (User != null) { var LocationNames = User.UserLocations.Select(x => new { ID = x.Location.ID, Name = x.Location.Name }).ToList(); var jsonLocations = JsonSerializer.Serialize(LocationNames); return(jsonLocations); } return(null); }
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 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 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 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; }
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 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 async Task SaveUserAsync(ApplicationUser user, bool isNewUser) { Uri uri = new Uri(string.Format(Constants.GetUserUrl, string.Empty)); try { string json = JsonSerializer.Serialize <ApplicationUser>(user, serializerOptions); StringContent content = new StringContent(json, Encoding.UTF8, "application/json"); client.DefaultRequestHeaders.Add("Authorization", $"Bearer {this.BearerToken}"); HttpResponseMessage response = null; if (isNewUser) { response = await client.PostAsync(uri, content); } else { response = await client.PutAsync(uri, content); } if (response.IsSuccessStatusCode) { Debug.WriteLine(@"\user successfully saved."); } } catch (Exception ex) { Debug.WriteLine(@"\tERROR {0}", ex.Message); } }
public static void Attaching_a_serialized_graph_4() { Console.WriteLine($">>>> Sample: {nameof(Attaching_a_serialized_graph_4)}"); Console.WriteLine(); Helpers.RecreateCleanDatabase(); Helpers.PopulateDatabase(); using var context = new BlogsContext(); var posts = context.Posts.Include(e => e.Blog).ToList(); #region Attaching_a_serialized_graph_4 var serialized = JsonSerializer.Serialize( posts, new JsonSerializerOptions { ReferenceHandler = ReferenceHandler.Preserve, WriteIndented = true }); #endregion Console.WriteLine(serialized); UpdatePostsFromJson(serialized); }
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); }
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 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 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 ActionResult <string> AvaliacoesAgendadas([FromBody] dynamic rec) { lock (_system) { var jobject = JObject.Parse(JsonSerializer.Serialize(rec)); if (!_system.isUserOnline(jobject.valueST.ToString())) { return(Unauthorized("Client Offline")); } string email = jobject.email.ToString(); List <Avaliaçao> av = _system.GetAvaAgendCli(email); JArray array = new JArray(); foreach (Avaliaçao a in av) { JObject tmp = new JObject(); tmp.Add("instrutor_email", a.instrutor_email); tmp.Add("instrutor_nome", _system.GetUser(a.instrutor_email).GetName()); tmp.Add("data", a.data.ToString("yyyy-MM-dd HH:mm:ss")); array.Add(tmp); } JObject avaliacoes = new JObject(); avaliacoes.Add("avaliacoes", array); return(Ok(avaliacoes.ToString())); } }
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 XPaginationHeader( IPaginationMetadata pagination, Func <object, string> urlBuilder, CollectionConfig collectionConfig) { _collectionConfig = collectionConfig; var metadata = new { totalCount = pagination.TotalCount, pageSize = pagination.PageSize, currentPage = pagination.CurrentPage, totalPages = pagination.TotalPages, previousPageUrl = pagination.HasPrevious ? CreatePlayersResourceUri(ResourceUriType.PreviousPage, urlBuilder) : null, nextPageUrl = pagination.HasNext ? CreatePlayersResourceUri(ResourceUriType.NextPage, urlBuilder) : null }; var key = "X-Pagination"; var value = JsonSerializer.Serialize(metadata, new JsonSerializerOptions() { // NOTE: Stops the '?' & '&' chars in the links being escaped Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping, IgnoreNullValues = true }); Value = new KeyValuePair <string, StringValues>(key, value); }
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 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 <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 }); } }
async Task WriteCache(List <StakePool> allPools) { BlockChainCache = new BlockChainCache { StakePools = new ObservableCollection <StakePool>(allPools), CacheDate = DateTime.Now }; var options = new JsonSerializerOptions { WriteIndented = true }; byte[] jsonUtf8Bytes = JsonSerializer.SerializeToUtf8Bytes(BlockChainCache, options); if (BlockChainCache.StakePools.Any()) { BlockChainCache.StakePools.Clear(); } OnPropertyChanged("BlockChainCache"); if (!_stakePoolListDatabase.HasWritePermissionOnDir()) { throw new Exception(string.Format( "Failed caching to local system. Software can still be used but without caching it results in slower performance. {0}No write permission for: {1}", Environment.NewLine, _stakePoolListDatabase)); } await File.WriteAllBytesAsync(_stakePoolListDatabase, jsonUtf8Bytes); }
public async Task Update(Category category) { var categoryJson = new StringContent(JsonSerializer.Serialize(category), Encoding.UTF8, "application/json"); await _httpClient.PutAsync("api/category", categoryJson); }