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

Tm 1234 #2

Open
wants to merge 5 commits 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
3 changes: 3 additions & 0 deletions BookManagerApi/BookManagerApi.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
<TargetFramework>net6.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
<UserSecretsId>c38411eb-41d5-49b1-8fa7-961026824723</UserSecretsId>
</PropertyGroup>

<ItemGroup>
Expand All @@ -12,7 +13,9 @@
<PrivateAssets>all</PrivateAssets>
</PackageReference>
<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="6.0.4" />
<PackageReference Include="Microsoft.Extensions.Configuration" Version="6.0.1" />
<PackageReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Design" Version="6.0.3" />
<PackageReference Include="Pomelo.EntityFrameworkCore.MySql" Version="6.0.2" />
<PackageReference Include="Swashbuckle.AspNetCore" Version="6.3.1" />
<PackageReference Include="Microsoft.EntityFrameworkCore.InMemory" Version="6.0.4" />
</ItemGroup>
Expand Down
28 changes: 23 additions & 5 deletions BookManagerApi/Controllers/BookManagerController.cs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
using Microsoft.AspNetCore.Mvc;
using BookManagerApi.Models;
using BookManagerApi.Services;

using BookManagerApi.Services;
namespace BookManagerApi.Controllers
{
[Route("api/v1/book")]
Expand All @@ -27,23 +27,41 @@ public ActionResult<IEnumerable<Book>> GetBooks()
public ActionResult<Book> GetBookById(long id)
{
var book = _bookManagementService.FindBookById(id);
return book;
return Ok(book);
}

// PUT: api/v1/book/5
// To protect from overposting attacks, see https://go.microsoft.com/fwlink/?linkid=2123754
[HttpPut("{id}")]
public IActionResult UpdateBookById(long id, Book book)
{
if (!_bookManagementService.BookExists(id))
return NotFound();

_bookManagementService.Update(id, book);
return NoContent();
return Ok();
}


// Delete: api/v1/book/5
[HttpDelete("{id}")]
public IActionResult DeleteBookById(long id)
{
if (_bookManagementService.Delete(id))
return Ok();
else
return BadRequest();

}


// POST: api/v1/book
// To protect from overposting attacks, see https://go.microsoft.com/fwlink/?linkid=2123754
[HttpPost]
public ActionResult<Book> AddBook(Book book)
{
//if(_bookManagementService.BookExists(book.Id))
// return BadRequest(book);
book.Id = 0;
_bookManagementService.Create(book);
return CreatedAtAction(nameof(GetBookById), new { id = book.Id }, book);
}
Expand Down
51 changes: 51 additions & 0 deletions BookManagerApi/Migrations/20221011153708_InitialCreate.Designer.cs

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

42 changes: 42 additions & 0 deletions BookManagerApi/Migrations/20221011153708_InitialCreate.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Migrations;

#nullable disable

namespace BookManagerApi.Migrations
{
public partial class InitialCreate : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.AlterDatabase()
.Annotation("MySql:CharSet", "utf8mb4");

migrationBuilder.CreateTable(
name: "Books",
columns: table => new
{
Id = table.Column<long>(type: "bigint", nullable: false)
.Annotation("MySql:ValueGenerationStrategy", MySqlValueGenerationStrategy.IdentityColumn),
Title = table.Column<string>(type: "longtext", nullable: false)
.Annotation("MySql:CharSet", "utf8mb4"),
Description = table.Column<string>(type: "longtext", nullable: false)
.Annotation("MySql:CharSet", "utf8mb4"),
Author = table.Column<string>(type: "longtext", nullable: false)
.Annotation("MySql:CharSet", "utf8mb4"),
Genre = table.Column<int>(type: "int", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Books", x => x.Id);
})
.Annotation("MySql:CharSet", "utf8mb4");
}

protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "Books");
}
}
}
49 changes: 49 additions & 0 deletions BookManagerApi/Migrations/BookContextModelSnapshot.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
// <auto-generated />
using BookManagerApi.Models;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;

#nullable disable

namespace BookManagerApi.Migrations
{
[DbContext(typeof(BookContext))]
partial class BookContextModelSnapshot : ModelSnapshot
{
protected override void BuildModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "6.0.7")
.HasAnnotation("Relational:MaxIdentifierLength", 64);

modelBuilder.Entity("BookManagerApi.Models.Book", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("bigint");

b.Property<string>("Author")
.IsRequired()
.HasColumnType("longtext");

b.Property<string>("Description")
.IsRequired()
.HasColumnType("longtext");

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

b.Property<string>("Title")
.IsRequired()
.HasColumnType("longtext");

b.HasKey("Id");

b.ToTable("Books");
});
#pragma warning restore 612, 618
}
}
}
14 changes: 7 additions & 7 deletions BookManagerApi/Models/BookContext.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,13 @@

namespace BookManagerApi.Models
{
public class BookContext : DbContext
{
public BookContext(DbContextOptions<BookContext> options) : base(options)
{
}
public class BookContext : DbContext
{
public BookContext(DbContextOptions<BookContext> options) : base(options)
{
}

public DbSet<Book> Books { get; set; }
}
public DbSet<Book> Books { get; set; }
}
}

17 changes: 14 additions & 3 deletions BookManagerApi/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,20 @@

builder.Services.AddScoped<IBookManagementService, BookManagementService>();
builder.Services.AddControllers();
builder.Services.AddDbContext<BookContext>(option =>
option.UseInMemoryDatabase("BookDb"));

var connectionString = builder.Configuration.GetConnectionString("BookManagerApi");

if (builder.Environment.EnvironmentName == "Testing")
{
// in test environment use a fresh in-memory DB
builder.Services.AddDbContext<BookContext>(option =>
option.UseInMemoryDatabase("BookDb"));
}
else
{
builder.Services.AddDbContext<BookContext>(option =>
option.UseMySql(connectionString, ServerVersion.AutoDetect(connectionString)));
}
// Configure Swagger/OpenAPI Documentation
// You can learn more on this link: https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
Expand All @@ -19,7 +30,7 @@
var app = builder.Build();

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
if (app.Environment.IsDevelopment() || app.Environment.EnvironmentName == "Testing")
{
app.UseSwagger();
app.UseSwaggerUI();
Expand Down
30 changes: 19 additions & 11 deletions BookManagerApi/Properties/launchSettings.json
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
{
{
"$schema": "https://json.schemastore.org/launchsettings.json",
"iisSettings": {
"windowsAuthentication": false,
Expand All @@ -9,25 +9,33 @@
}
},
"profiles": {
"BookManagerApi": {
"commandName": "Project",
"dotnetRunMessages": true,
"IIS Express": {
"commandName": "IISExpress",
"launchBrowser": true,
"launchUrl": "swagger",
"applicationUrl": "https://localhost:7230;http://localhost:5213",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
},
"IIS Express": {
"commandName": "IISExpress",
"Development": {
"commandName": "Project",
"launchBrowser": true,
"launchUrl": "swagger",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
},
"applicationUrl": "https://localhost:7230;http://localhost:5213",
"dotnetRunMessages": true
},
"Testing": {
"commandName": "Project",
"launchBrowser": true,
"launchUrl": "swagger",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Testing"
},
"applicationUrl": "https://localhost:7230;http://localhost:5213",
"dotnetRunMessages": true
}
}
}


}
15 changes: 13 additions & 2 deletions BookManagerApi/Services/BookManagementService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,8 @@

namespace BookManagerApi.Services
{
public class BookManagementService : IBookManagementService
{
public class BookManagementService : IBookManagementService
{
private readonly BookContext _context;

public BookManagementService(BookContext context)
Expand Down Expand Up @@ -38,6 +38,17 @@ public Book Update(long id, Book book)
return book;
}

public bool Delete(long id)
{
var bookToBeRemoved = FindBookById(id);
if (bookToBeRemoved == null)
return false;

_context.Remove(bookToBeRemoved);
_context.SaveChanges();
return true;
}

public Book FindBookById(long id)
{
var book = _context.Books.Find(id);
Expand Down
5 changes: 3 additions & 2 deletions BookManagerApi/Services/IBookManagementService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,12 @@

namespace BookManagerApi.Services
{
public interface IBookManagementService
{
public interface IBookManagementService
{
List<Book> GetAllBooks();
Book Create(Book book);
Book Update(long id, Book book);
bool Delete(long id);
Book FindBookById(long id);
bool BookExists(long id);
}
Expand Down
3 changes: 3 additions & 0 deletions BookManagerApi/appsettings.Development.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,9 @@
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"ConnectionStrings": {
"BookManagerApi": "server=localhost; database=bookshop; user=bookmanagerapi; password=apiuser123"
}
}

5 changes: 5 additions & 0 deletions BookManagerApi/appsettings.Testing.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
{
"ConnectionStrings": {
"DefaultConnection": "Server=(localdb)\\MSSQLLocalDB;Database=_CHANGE_ME;Trusted_Connection=True;MultipleActiveResultSets=true"
}
}