public async Task<IActionResult> ServerSniffer(string uri) { var request_headers = new Dictionary<string, string>(); var response_headers = new Dictionary<string, string>(); var http_headers = new HttpHeaders(); http_headers.RequestHeaders = request_headers; http_headers.ResponseHeaders = response_headers; using (var http_client = new HttpClient()) { var request = new HttpRequestMessage(HttpMethod.Head, uri); using (var response = await http_client.SendAsync(request)) { foreach (var header in response.Headers) { response_headers.Add(header.Key, string.Join(",", header.Value)); } foreach (var header in request.Headers) { request_headers.Add(header.Key, string.Join(",", header.Value)); } } } var json_result = new JsonResult(http_headers); return json_result; }
public IActionResult Editar([FromBody]Categoria model) { try { if (ModelState.IsValid) { _categoriaDAL.Update(model); _categoriaDAL.SaveChanges(); _jsonResult = Json(new { status = "OK", resultado = "Registro alterado com sucesso!" }); } else { var erros = ""; foreach (var erro in ModelState.Values.SelectMany(sel => sel.Errors)) { erros += $"{ erro.Exception?.Message ?? erro.ErrorMessage}<br/>"; } _jsonResult = Json(new { status = "FALHA", resultado = erros }); } } catch (Exception ex) { _jsonResult = Json(new { status = "FALHA", resultado = ex.Message }); }; return _jsonResult; }
public IActionResult ReturnJsonResult_WithCustomMediaType() { var jsonResult = new JsonResult(new { MethodName = "ReturnJsonResult_WithCustomMediaType" }, new CustomFormatter("application/custom-json")); jsonResult.ContentTypes.Add(MediaTypeHeaderValue.Parse("application/custom-json")); return jsonResult; }
public async Task ExecuteResult_UsesEncoderIfSpecified() { // Arrange var expected = Enumerable.Concat(Encoding.UTF8.GetPreamble(), _abcdUTF8Bytes); var memoryStream = new MemoryStream(); var response = new Mock<HttpResponse>(); response.SetupGet(r => r.Body) .Returns(memoryStream); var context = new Mock<HttpContext>(); context.SetupGet(c => c.Response) .Returns(response.Object); var actionContext = new ActionContext(context.Object, new RouteData(), new ActionDescriptor()); var result = new JsonResult(new { foo = "abcd" }) { Encoding = Encoding.UTF8 }; // Act await result.ExecuteResultAsync(actionContext); // Assert Assert.Equal(expected, memoryStream.ToArray()); }
public IActionResult Editar([FromBody]DespesaVM modelVM) { try { if (ModelState.IsValid) { var model = new Despesa(); model.Id = modelVM.Id; model.CategoriaId = modelVM.CategoriaId; model.Data = modelVM.Data.Value; model.Observacao = modelVM.Observacao; model.Valor = modelVM.Valor.Value; _DespesaDAL.Update(model); _DespesaDAL.SaveChanges(); _jsonResult = Json(new { status = "OK", resultado = "Registro alterado com sucesso!" }); } else { var erros = ""; foreach (var erro in ModelState.Values.SelectMany(sel => sel.Errors)) { erros += $"{ erro.Exception?.Message ?? erro.ErrorMessage}<br/>"; } _jsonResult = Json(new { status = "FALHA", resultado = erros }); } } catch (Exception ex) { _jsonResult = Json(new { status = "FALHA", resultado = ex.Message }); }; return _jsonResult; }
public ActionResult UserJson() { var jsonResult = new JsonResult(_user); jsonResult.Indent = false; return jsonResult; }
public JsonResult CustomContentType() { var formatter = new JsonOutputFormatter(); formatter.SupportedMediaTypes.Add(MediaTypeHeaderValue.Parse("application/message+json")); var result = new JsonResult(new { Message = "hello" }, formatter); result.ContentTypes.Add(MediaTypeHeaderValue.Parse("application/message+json")); return result; }
public override Task ExecuteResultAsync(ActionContext context) { if (StatusCode.HasValue) { context.HttpContext.Response.StatusCode = StatusCode.Value; } var json = new JsonResult(this); return json.ExecuteResultAsync(context); }
public override void ExecuteResult(ActionContext context) { if (StatusCode.HasValue) { context.HttpContext.Response.StatusCode = StatusCode.Value; } var json = new JsonResult(this); json.ExecuteResult(context); }
public void GIVEN_AGoodAction_WHEN_IsBadAction_THEN_False() { // Arrange var objectResult = new JsonResult(new Post()); // Act var result = BadActionResultTransformer.IsBadAction(objectResult); // Assert Assert.False(result); }
public async Task<IActionResult> GetUsers() { JsonResult result = null; try { var users = UserManager.Users; if (await users.AnyAsync()) { result = new JsonResult(users); } } catch (Exception exc) { throw exc; } return result; }
public IActionResult Excluir(string id) { try { _DespesaDAL.Delete(obj => obj.Id.Equals(id)); _DespesaDAL.SaveChanges(); _jsonResult = Json(new { status = "OK", resultado = "Registro excluído com sucesso!" }); } catch (Exception ex) { _jsonResult = Json(new { status = "FALHA", resultado = ex.Message }); }; return _jsonResult; }
public async Task<JsonResult> Post(int tripId, [FromBody]StopViewModel stopVM) { if (ModelState.IsValid) { try { var stop = Mapper.Map<Stop>(stopVM); string URI="http://maps.google.com/maps/api/geocode/json?address="+stop.Name+"&sensor=false"; HttpClient client = new HttpClient(); var response = await client.GetAsync(URI); var responseContent = response.Content; var jsonGeo = await responseContent.ReadAsStringAsync(); _repo.GetTripWithStopsByTripId(tripId, User.Identity.Name).Destinations.Add(stop); var json=new JsonResult(jsonGeo); var obj=JObject.Parse(jsonGeo); var lat=FindJObject(obj.Children(), "results[0].geometry.location.lat"); var lng = FindJObject(obj.Children(), "results[0].geometry.location.lng"); if (lat != null && lng != null) { stop.Latitude = lat.Values<double>().First(); stop.Longitude = lng.Values<double>().First(); } if (_repo.SaveAll()) { Response.StatusCode = StatusCodes.Status200OK; return Json(Mapper.Map<StopViewModel>(stop)); } else { Response.StatusCode = StatusCodes.Status500InternalServerError; return Json(false); } } catch (Exception e) { _logger.LogError(e.Message); return Json(e); } } else { return Json(new { error = ModelState }); } }
public async Task ExecuteAsync_WritesJsonContent() { // Arrange var value = new { foo = "abcd" }; var expected = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(value)); var context = GetActionContext(); var result = new JsonResult(value); // Act await result.ExecuteResultAsync(context); // Assert var written = GetWrittenBytes(context.HttpContext); Assert.Equal(expected, written); Assert.Equal("application/json; charset=utf-8", context.HttpContext.Response.ContentType); }
public async Task ExecuteResultAsync_UsesDefaultContentType_IfNoContentTypeSpecified() { // Arrange var expected = _abcdUTF8Bytes; var context = GetHttpContext(); var actionContext = new ActionContext(context, new RouteData(), new ActionDescriptor()); var result = new JsonResult(new { foo = "abcd" }); // Act await result.ExecuteResultAsync(actionContext); var written = GetWrittenBytes(context); // Assert Assert.Equal(expected, written); Assert.Equal("application/json; charset=utf-8", context.Response.ContentType); }
public async Task ExecuteResultAsync_NullEncoding_SetsContentTypeAndDefaultEncoding() { // Arrange var expected = _abcdUTF8Bytes; var context = GetHttpContext(); var actionContext = new ActionContext(context, new RouteData(), new ActionDescriptor()); var result = new JsonResult(new { foo = "abcd" }); result.ContentType = new MediaTypeHeaderValue("text/json"); // Act await result.ExecuteResultAsync(actionContext); var written = GetWrittenBytes(context); // Assert Assert.Equal(expected, written); Assert.Equal("text/json; charset=utf-8", context.Response.ContentType); }
public async Task<JsonResult> SubmittedVote(string pollId, string optionId) { var model = new SubmittedVoteViewModel { PollId = pollId, VotedOptionId = optionId }; try { model.LatestVotes = await this._pollVoter.SubmitVote(pollId, optionId); model.Success = true; } catch(Exception e) { model.Success = false; model.ErrorMessage = Pollster.CommonCode.Utilities.FormatInnerException(e); } var result = new JsonResult(model); return result; }
public async Task ExecuteResult_GeneratesResultsWithoutBOMByDefault() { // Arrange var expected = _abcdUTF8Bytes; var memoryStream = new MemoryStream(); var response = new Mock<HttpResponse>(); response.SetupGet(r => r.Body) .Returns(memoryStream); var context = new Mock<HttpContext>(); context.SetupGet(c => c.Response) .Returns(response.Object); var actionContext = new ActionContext(context.Object, new RouteData(), new ActionDescriptor()); var result = new JsonResult(new { foo = "abcd" }); // Act await result.ExecuteResultAsync(actionContext); // Assert Assert.Equal(expected, memoryStream.ToArray()); }
public async Task ExecuteResultAsync_Null() { // Arrange var expected = _abcdUTF8Bytes; var optionsFormatters = new List<IOutputFormatter>() { new XmlDataContractSerializerOutputFormatter(), // This won't be used new JsonOutputFormatter(), }; var context = GetHttpContext(optionsFormatters); var actionContext = new ActionContext(context, new RouteData(), new ActionDescriptor()); var result = new JsonResult(new { foo = "abcd" }); // Act await result.ExecuteResultAsync(actionContext); var written = GetWrittenBytes(context); // Assert Assert.Equal(expected, written); Assert.Equal("application/json; charset=utf-8", context.Response.ContentType); }
public ActionResult UserJson() { var jsonResult = new JsonResult(_user); return jsonResult; }
public async Task ExecuteResultAsync_UsesPassedInSerializerSettings() { // Arrange var expected = AbcdIndentedUTF8Bytes; var context = GetHttpContext(); var actionContext = new ActionContext(context, new RouteData(), new ActionDescriptor()); var serializerSettings = new JsonSerializerSettings(); serializerSettings.Formatting = Formatting.Indented; var result = new JsonResult(new { foo = "abcd" }, serializerSettings); // Act await result.ExecuteResultAsync(actionContext); var written = GetWrittenBytes(context); // Assert Assert.Equal(expected, written); Assert.Equal("application/json; charset=utf-8", context.Response.ContentType); }
public IActionResult Agrupado(string dataInicio, string dataFim, string categoriaId) { try { Expression<Func<Despesa, bool>> expressaoDespesa = null; Expression<Func<Receita, bool>> expressaoReceita = null; if (!string.IsNullOrEmpty(dataInicio) && !string.IsNullOrEmpty(dataFim)) { DateTime expressaoDataInicio = DateTime.Parse(dataInicio); DateTime expressaoDataFim = DateTime.Parse(dataFim); expressaoDespesa = obj => obj.Data >= expressaoDataInicio && obj.Data <= expressaoDataFim; expressaoReceita = obj => obj.Data >= expressaoDataInicio && obj.Data <= expressaoDataFim; } if (!string.IsNullOrEmpty(categoriaId)) { expressaoDespesa = expressaoDespesa == null ? obj => obj.CategoriaId.Equals(categoriaId) : expressaoDespesa.And(obj => obj.CategoriaId.Equals(categoriaId)); expressaoReceita = expressaoReceita == null ? obj => obj.CategoriaId.Equals(categoriaId) : expressaoReceita.And(obj => obj.CategoriaId.Equals(categoriaId)); } var despesas = new List<RelatorioDetalhadoVM>(); var receitas = new List<RelatorioDetalhadoVM>(); if (expressaoDespesa == null && expressaoReceita == null) { despesas = _despesaDAL.Get.Select(sel => new RelatorioDetalhadoVM { Tipo = "Despesa", Categoria = sel.Categoria.Nome, Data = sel.Data, Observacao = sel.Observacao, Valor = sel.Valor }).ToList(); receitas = _receitaDAL.Get.Select(sel => new RelatorioDetalhadoVM { Tipo = "Receitas", Categoria = sel.Categoria.Nome, Data = sel.Data, Observacao = sel.Observacao, Valor = sel.Valor }).ToList(); } else { despesas = _despesaDAL.Get.Where(expressaoDespesa).Select(sel => new RelatorioDetalhadoVM { Tipo = "Despesa", Categoria = sel.Categoria.Nome, Data = sel.Data, Observacao = sel.Observacao, Valor = sel.Valor }).ToList(); receitas = _receitaDAL.Get.Where(expressaoReceita).Select(sel => new RelatorioDetalhadoVM { Tipo = "Receitas", Categoria = sel.Categoria.Nome, Data = sel.Data, Observacao = sel.Observacao, Valor = sel.Valor }).ToList(); } var lista = despesas.Concat(receitas).GroupBy(sel => sel.Categoria, (k, c) => new RelatorioAgrupadoVM { Categoria = k, Detalhes = c.ToList() }).ToList(); _jsonResult = Json(new { status = "OK", resultado = lista }); } catch (Exception ex) { _jsonResult = Json(new { status = "FALHA", resultado = ex.Message }); } return _jsonResult; }
public static JsonResult BadRequestJsonResult(object value) { JsonResult r = new JsonResult(value); r.StatusCode = (int)HttpStatusCode.BadRequest; return r; }
public JsonResult Lista(string data, string categoriaId) { try { Expression<Func<Despesa, bool>> expressao = null; if (!string.IsNullOrEmpty(data)) { DateTime expressaoData = DateTime.Parse(data); expressao = obj => obj.Data.Equals(expressaoData); } if (!string.IsNullOrEmpty(categoriaId)) { expressao = expressao == null ? obj => obj.CategoriaId.Equals(categoriaId) : expressao.And(obj => obj.CategoriaId.Equals(categoriaId)); } var lista = expressao == null ? _DespesaDAL.Get.OrderBy(obj => obj.Data) .Select(sel => new DespesaVM { CategoriaId = sel.Categoria.Id, CategoriaNome = sel.Categoria.Nome, Data = sel.Data, Id = sel.Id, Observacao = sel.Observacao, Valor = sel.Valor }) .ToList() : _DespesaDAL.Get.Where(expressao).OrderBy(obj => obj.Data) .Select(sel => new DespesaVM { CategoriaId = sel.Categoria.Id, CategoriaNome = sel.Categoria.Nome, Data = sel.Data, Id = sel.Id, Observacao = sel.Observacao, Valor = sel.Valor }) .ToList<DespesaVM>(); _jsonResult = Json(new { status = "OK", resultado = lista }); } catch (Exception ex) { _jsonResult = Json(new { status = "FALHA", resultado = ex.Message }); }; return _jsonResult; }
public async Task ExecuteResultAsync_UsesGlobalFormatter_IfNoFormatterIsConfigured() { // Arrange var expected = _abcdUTF8Bytes; var context = GetHttpContext(enableFallback: true); var actionContext = new ActionContext(context, new RouteData(), new ActionDescriptor()); var result = new JsonResult(new { foo = "abcd" }); // Act await result.ExecuteResultAsync(actionContext); var written = GetWrittenBytes(context); // Assert Assert.Equal(expected, written); Assert.Equal("application/json; charset=utf-8", context.Response.ContentType); }
public async Task ExecuteResultAsync_UsesPassedInFormatter_ContentTypeSpecified() { // Arrange var expected = _abcdUTF8Bytes; var context = GetHttpContext(); var actionContext = new ActionContext(context, new RouteData(), new ActionDescriptor()); var formatter = new JsonOutputFormatter(); formatter.SupportedMediaTypes.Add(MediaTypeHeaderValue.Parse("application/hal+json")); var result = new JsonResult(new { foo = "abcd" }, formatter); result.ContentTypes.Add(MediaTypeHeaderValue.Parse("application/hal+json")); // Act await result.ExecuteResultAsync(actionContext); var written = GetWrittenBytes(context); // Assert Assert.Equal(expected, written); Assert.Equal("application/hal+json; charset=utf-8", context.Response.ContentType); }
public JsonResult CustomContentType() { var result = new JsonResult(new { Message = "hello" }); result.ContentType = MediaTypeHeaderValue.Parse("application/message+json"); return result; }
public async Task ExecuteResultAsync_OptionsFormatter_Conneg() { // Arrange var expected = _abcdUTF8Bytes; var optionsFormatters = new List<IOutputFormatter>() { Mock.Of<IOutputFormatter>(), // This won't be used new JsonOutputFormatter(), }; var context = GetHttpContext(optionsFormatters); context.Request.Headers["Accept"] = "text/json"; var actionContext = new ActionContext(context, new RouteData(), new ActionDescriptor()); var result = new JsonResult(new { foo = "abcd" }); // Act await result.ExecuteResultAsync(actionContext); var written = GetWrittenBytes(context); // Assert Assert.Equal(expected, written); Assert.Equal("text/json; charset=utf-8", context.Response.ContentType); }
public async Task<IActionResult> BuiltWith(string uri) { var info = new BuiltWithInfo(); using (var http_client = new HttpClient()) { var request = new HttpRequestMessage(HttpMethod.Get, uri); using (var response = await http_client.SendAsync(request)) { if (response.IsSuccessStatusCode) { var resp_stream = await response.Content.ReadAsStreamAsync(); HtmlDocument doc = new HtmlDocument(); doc.Load(resp_stream); resp_stream.Dispose(); var doc_node = doc.DocumentNode; var script_tags = doc_node.SelectNodes("//script"); var style_tags = doc_node.SelectNodes("//style"); var link_tags = doc_node.SelectNodes("//link"); foreach(var script in script_tags) { var src_attr = script.Attributes["src"]; info.Scripts.Add(src_attr == null ? "inline" : src_attr.Value); } foreach (var link in link_tags) { var href_attr = link.Attributes["href"]; info.Stylesheets.Add(href_attr == null ? "inline" : href_attr.Value); } } } } var json_result = new JsonResult(info); return json_result; }
public async Task ExecuteResultAsync_UsesPassedInFormatter() { // Arrange var expected = _abcdUTF8Bytes; var context = GetHttpContext(); var actionContext = new ActionContext(context, new RouteData(), new ActionDescriptor()); var formatter = new JsonOutputFormatter(); formatter.SupportedEncodings.Clear(); // This is UTF-8 WITH BOM formatter.SupportedEncodings.Add(Encoding.UTF8); var result = new JsonResult(new { foo = "abcd" }, formatter); // Act await result.ExecuteResultAsync(actionContext); var written = GetWrittenBytes(context); // Assert Assert.Equal(expected, written); Assert.Equal("application/json; charset=utf-8", context.Response.ContentType); }