Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Desafio Falizado com sucesso! #90

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
64 changes: 44 additions & 20 deletions Controllers/TarefaController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -8,63 +8,76 @@ namespace TrilhaApiDesafio.Controllers
[Route("[controller]")]
public class TarefaController : ControllerBase
{
private const string connectionString = "Server=localhost\\sqlexpress; Initial Catalog=Tarefa; Integrated Security=true";

private readonly OrganizadorContext _context;

public TarefaController(OrganizadorContext context)
{
_context = context;
}
// Salvar - Criar novo
[HttpPost]
public IActionResult Criar(Tarefa tarefa)
{
if (tarefa.Data == DateTime.MinValue)
return BadRequest(new { Erro = "A data da tarefa não pode ser vazia" });

_context.Add(tarefa);
_context.SaveChanges();

// TODO: Adicionar a tarefa recebida no EF e salvar as mudanças (save changes)
return CreatedAtAction(nameof(ObterPorId), new {id=tarefa.Id}, tarefa);
}
//elecionar por id
[HttpGet("{id}")]
public IActionResult ObterPorId(int id)
{
// TODO: Buscar o Id no banco utilizando o EF
var tarefa = _context.Tarefas.Find(id);
// TODO: Validar o tipo de retorno. Se não encontrar a tarefa, retornar NotFound,
if(tarefa == null)
return NotFound();

// caso contrário retornar OK com a tarefa encontrada
return Ok();
return Ok(tarefa);
}

// seçecionar todos
[HttpGet("ObterTodos")]
public IActionResult ObterTodos()
{
// TODO: Buscar todas as tarefas no banco utilizando o EF
return Ok();
//var tarefa = _context.Tarefas.Find(*);

var tarefas = _context.Tarefas.Where(x => x.Id > 0);
return Ok(tarefas);
}

// Selecionar pelo título
[HttpGet("ObterPorTitulo")]
public IActionResult ObterPorTitulo(string titulo)
{
// TODO: Buscar as tarefas no banco utilizando o EF, que contenha o titulo recebido por parâmetro
var tarefas = _context.Tarefas.Where(x => x.Titulo.Contains(titulo));
// Dica: Usar como exemplo o endpoint ObterPorData
return Ok();
return Ok(tarefas);
}

// selecionar por data aaaa-mm-dd
[HttpGet("ObterPorData")]
public IActionResult ObterPorData(DateTime data)
{
var tarefa = _context.Tarefas.Where(x => x.Data.Date == data.Date);
return Ok(tarefa);
}

//Selecionar por status
[HttpGet("ObterPorStatus")]
public IActionResult ObterPorStatus(EnumStatusTarefa status)
{
// TODO: Buscar as tarefas no banco utilizando o EF, que contenha o status recebido por parâmetro
// Dica: Usar como exemplo o endpoint ObterPorData
var tarefa = _context.Tarefas.Where(x => x.Status == status);
// Dica: Usar como exemplo o endpoint ObterPorData
return Ok(tarefa);
}

[HttpPost]
public IActionResult Criar(Tarefa tarefa)
{
if (tarefa.Data == DateTime.MinValue)
return BadRequest(new { Erro = "A data da tarefa não pode ser vazia" });

// TODO: Adicionar a tarefa recebida no EF e salvar as mudanças (save changes)
return CreatedAtAction(nameof(ObterPorId), new { id = tarefa.Id }, tarefa);
}

// Update - Aterar poi id
[HttpPut("{id}")]
public IActionResult Atualizar(int id, Tarefa tarefa)
{
Expand All @@ -77,8 +90,16 @@ public IActionResult Atualizar(int id, Tarefa tarefa)
return BadRequest(new { Erro = "A data da tarefa não pode ser vazia" });

// TODO: Atualizar as informações da variável tarefaBanco com a tarefa recebida via parâmetro
tarefaBanco.Titulo = tarefa.Titulo;
tarefaBanco.Descricao = tarefa.Descricao;
tarefaBanco.Status = tarefa.Status;
tarefaBanco.Data = tarefa.Data;

_context.Tarefas.Update(tarefaBanco);
_context.SaveChanges();

// TODO: Atualizar a variável tarefaBanco no EF e salvar as mudanças (save changes)
return Ok();
return Ok(tarefaBanco);
}

[HttpDelete("{id}")]
Expand All @@ -90,6 +111,9 @@ public IActionResult Deletar(int id)
return NotFound();

// TODO: Remover a tarefa encontrada através do EF e salvar as mudanças (save changes)
_context.Tarefas.Remove(tarefaBanco);
_context.SaveChanges();

return NoContent();
}
}
Expand Down
32 changes: 32 additions & 0 deletions Controllers/WeatherForecastController.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
using Microsoft.AspNetCore.Mvc;

namespace TrilhaApiDesafio.Controllers;

[ApiController]
[Route("[controller]")]
public class WeatherForecastController : ControllerBase
{
private static readonly string[] Summaries = new[]
{
"Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
};

private readonly ILogger<WeatherForecastController> _logger;

public WeatherForecastController(ILogger<WeatherForecastController> logger)
{
_logger = logger;
}

[HttpGet(Name = "GetWeatherForecast")]
public IEnumerable<WeatherForecast> Get()
{
return Enumerable.Range(1, 5).Select(index => new WeatherForecast
{
Date = DateTime.Now.AddDays(index),
TemperatureC = Random.Shared.Next(-20, 55),
Summary = Summaries[Random.Shared.Next(Summaries.Length)]
})
.ToArray();
}
}
54 changes: 54 additions & 0 deletions Migrations/20250125183531_CriacaoTabelaTarefa.Designer.cs

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

35 changes: 35 additions & 0 deletions Migrations/20250125183531_CriacaoTabelaTarefa.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
using System;
using Microsoft.EntityFrameworkCore.Migrations;

#nullable disable

namespace TrilhaApiDesafio.Migrations
{
public partial class CriacaoTabelaTarefa : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "Tarefas",
columns: table => new
{
Id = table.Column<int>(type: "int", nullable: false)
.Annotation("SqlServer:Identity", "1, 1"),
Titulo = table.Column<string>(type: "nvarchar(max)", nullable: true),
Descricao = table.Column<string>(type: "nvarchar(max)", nullable: true),
Data = table.Column<DateTime>(type: "datetime2", nullable: false),
Status = table.Column<int>(type: "int", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Tarefas", x => x.Id);
});
}

protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "Tarefas");
}
}
}
52 changes: 52 additions & 0 deletions Migrations/OrganizadorContextModelSnapshot.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
// <auto-generated />
using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using TrilhaApiDesafio.Context;

#nullable disable

namespace TrilhaApiDesafio.Migrations
{
[DbContext(typeof(OrganizadorContext))]
partial class OrganizadorContextModelSnapshot : ModelSnapshot
{
protected override void BuildModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "6.0.5")
.HasAnnotation("Relational:MaxIdentifierLength", 128);

SqlServerModelBuilderExtensions.UseIdentityColumns(modelBuilder, 1L, 1);

modelBuilder.Entity("TrilhaApiDesafio.Models.Tarefa", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");

SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"), 1L, 1);

b.Property<DateTime>("Data")
.HasColumnType("datetime2");

b.Property<string>("Descricao")
.HasColumnType("nvarchar(max)");

b.Property<int>("Status")
.HasColumnType("int");

b.Property<string>("Titulo")
.HasColumnType("nvarchar(max)");

b.HasKey("Id");

b.ToTable("Tarefas");
});
#pragma warning restore 612, 618
}
}
}
2 changes: 1 addition & 1 deletion Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -30,4 +30,4 @@

app.MapControllers();

app.Run();
app.Run();
20 changes: 15 additions & 5 deletions Properties/launchSettings.json
Original file line number Diff line number Diff line change
@@ -1,20 +1,30 @@
{
"$schema": "https://json.schemastore.org/launchsettings.json",
"$schema": "http://json.schemastore.org/launchsettings.json",
"iisSettings": {
"windowsAuthentication": false,
"anonymousAuthentication": true,
"iisExpress": {
"applicationUrl": "http://localhost:3076",
"sslPort": 44343
"applicationUrl": "http://localhost:26014",
"sslPort": 44381
}
},
"profiles": {
"TrilhaApiDesafio": {
"http": {
"commandName": "Project",
"dotnetRunMessages": true,
"launchBrowser": true,
"launchUrl": "swagger",
"applicationUrl": "https://localhost:7295;http://localhost:5181",
"applicationUrl": "http://localhost:5204",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
},
"https": {
"commandName": "Project",
"dotnetRunMessages": true,
"launchBrowser": true,
"launchUrl": "swagger",
"applicationUrl": "https://localhost:7004;http://localhost:5204",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
Expand Down
9 changes: 5 additions & 4 deletions TrilhaApiDesafio.csproj
Original file line number Diff line number Diff line change
@@ -1,18 +1,19 @@
<Project Sdk="Microsoft.NET.Sdk.Web">

<PropertyGroup>
<TargetFramework>net6.0</TargetFramework>
<TargetFramework>net8.0</TargetFramework>
<Nullable>disable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="6.0.5">
<PackageReference Include="Microsoft.AspNetCore.OpenApi" Version="8.0.12" />
<PackageReference Include="Microsoft.EntityFrameworkCore.design" Version="6.0.5">
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
<PrivateAssets>all</PrivateAssets>
</PackageReference>
<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="6.0.5" />
<PackageReference Include="Swashbuckle.AspNetCore" Version="6.2.3" />
<PackageReference Include="Microsoft.EntityFrameworkCore.sqlserver" Version="6.0.5" />
<PackageReference Include="Swashbuckle.AspNetCore" Version="6.6.2" />
</ItemGroup>

</Project>
6 changes: 6 additions & 0 deletions TrilhaApiDesafio.http
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
@TrilhaApiDesafio_HostAddress = http://localhost:5204

GET {{TrilhaApiDesafio_HostAddress}}/weatherforecast/
Accept: application/json

###
24 changes: 24 additions & 0 deletions TrilhaApiDesafio.sln
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 17
VisualStudioVersion = 17.5.2.0
MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "TrilhaApiDesafio", "TrilhaApiDesafio.csproj", "{0FA4A2BD-0B92-5E85-E87C-176D79B2DDC0}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{0FA4A2BD-0B92-5E85-E87C-176D79B2DDC0}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{0FA4A2BD-0B92-5E85-E87C-176D79B2DDC0}.Debug|Any CPU.Build.0 = Debug|Any CPU
{0FA4A2BD-0B92-5E85-E87C-176D79B2DDC0}.Release|Any CPU.ActiveCfg = Release|Any CPU
{0FA4A2BD-0B92-5E85-E87C-176D79B2DDC0}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {AEC24498-A0CE-46E2-AC5C-859451D7A2BB}
EndGlobalSection
EndGlobal
Loading