Skip to content
Snippets Groups Projects
Commit 49d30a80 authored by Abdelsamad, Mouaz R (UG - SISC)'s avatar Abdelsamad, Mouaz R (UG - SISC)
Browse files

Booking Service with Dockerfile

parent 0a931a09
No related branches found
No related tags found
No related merge requests found
Showing
with 574 additions and 0 deletions
**/.classpath
**/.dockerignore
**/.env
**/.git
**/.gitignore
**/.project
**/.settings
**/.toolstarget
**/.vs
**/.vscode
**/*.*proj.user
**/*.dbmdl
**/*.jfm
**/azds.yaml
**/bin
**/charts
**/docker-compose*
**/Dockerfile*
**/node_modules
**/npm-debug.log
**/obj
**/secrets.dev.yaml
**/values.dev.yaml
LICENSE
README.md
!**/.gitignore
!.git/HEAD
!.git/config
!.git/packed-refs
!.git/refs/heads/**
\ No newline at end of file
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
<UserSecretsId>1b0c76fc-55fe-4ae7-9921-1d071955c125</UserSecretsId>
<DockerDefaultTargetOS>Linux</DockerDefaultTargetOS>
<DockerfileContext>.</DockerfileContext>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="8.0.3" />
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="8.0.3" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="8.0.3">
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
<PrivateAssets>all</PrivateAssets>
</PackageReference>
<PackageReference Include="Microsoft.VisualStudio.Azure.Containers.Tools.Targets" Version="1.19.6" />
<PackageReference Include="Pomelo.EntityFrameworkCore.MySql" Version="8.0.2" />
<PackageReference Include="Swashbuckle.AspNetCore" Version="6.4.0" />
</ItemGroup>
</Project>
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="Current" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<ActiveDebugProfile>http</ActiveDebugProfile>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|AnyCPU'">
<DebuggerFlavor>ProjectDebugger</DebuggerFlavor>
</PropertyGroup>
</Project>
\ No newline at end of file
@BookingMicroservice_HostAddress = http://localhost:5207
GET {{BookingMicroservice_HostAddress}}/weatherforecast/
Accept: application/json
###

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 17
VisualStudioVersion = 17.9.34622.214
MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "BookingMicroservice", "BookingMicroservice.csproj", "{FF90ADFD-EC0A-4189-B734-59CD531D1FD6}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{FF90ADFD-EC0A-4189-B734-59CD531D1FD6}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{FF90ADFD-EC0A-4189-B734-59CD531D1FD6}.Debug|Any CPU.Build.0 = Debug|Any CPU
{FF90ADFD-EC0A-4189-B734-59CD531D1FD6}.Release|Any CPU.ActiveCfg = Release|Any CPU
{FF90ADFD-EC0A-4189-B734-59CD531D1FD6}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {1F564B53-A9C7-46CC-8ADD-A2CB5381ADB7}
EndGlobalSection
EndGlobal
namespace BookingMicroservice.Clients
{
public class FlightServiceClient : IFlightServiceClient
{
private readonly HttpClient httpClient;
private const string FLIGHT_API_PATH = "api/Flight";
private const string SEAT_API_PATH = "api/Seat";
public FlightServiceClient(HttpClient httpClient)
{
this.httpClient = httpClient;
}
public async Task<HttpResponseMessage> GetFlightCapacityAsync(int flightId, int classType)
{
return await httpClient.GetAsync($"{FLIGHT_API_PATH}/{flightId}/capacity?classType={classType}");
}
public async Task<HttpResponseMessage> IsSeatAvailableAsync(int seatId)
{
return await httpClient.GetAsync($"{SEAT_API_PATH}/{seatId}/isAvailable");
}
public async Task<HttpResponseMessage> BookSeatAsync(int seatId)
{
return await httpClient.PutAsync($"{SEAT_API_PATH}/{seatId}", null);
}
}
}
namespace BookingMicroservice.Clients
{
public interface IFlightServiceClient
{
Task<HttpResponseMessage> GetFlightCapacityAsync(int flightId, int classType);
Task<HttpResponseMessage> IsSeatAvailableAsync(int seatId);
Task<HttpResponseMessage> BookSeatAsync(int seatId);
}
}
using BookingMicroservice.Exceptions;
using BookingMicroservice.Models;
using BookingMicroservice.Services;
using Microsoft.AspNetCore.Mvc;
using System.Security.Claims;
namespace BookingMicroservice.Controllers
{
[ApiController]
[Route("api/[Controller]")]
public class BookingController : ControllerBase
{
private readonly IReservationComplianceService reservationComplianceService;
private readonly IBookingService bookingService;
public BookingController(IReservationComplianceService reservationComplianceService, IBookingService bookingService)
{
this.reservationComplianceService = reservationComplianceService;
this.bookingService = bookingService;
}
[HttpGet()]
public IActionResult GetBookings(int? flightId = null, int? userId = null, BookingClass? bookingClass = null)
{
List<Booking> bookings = bookingService.GetBookings(flightId, userId, bookingClass);
if (bookings == null)
return BadRequest("Unable to get bookings");
return Ok(bookings);
}
[HttpGet("{id}")]
public IActionResult GetBooking([FromRoute] int id)
{
Booking? booking = bookingService.GetBooking(id);
if(booking == null)
return NotFound($"Could not find booking with id: {id}");
return Ok(booking);
}
[HttpPost()]
public async Task<IActionResult> MakeBooking([FromBody] BookingCreation bookingCreationModel)
{
// TODO: add stripe handling
string? userIdValue = User.FindFirst(ClaimTypes.NameIdentifier)?.Value;
if (!int.TryParse(userIdValue, out int userId))
return BadRequest("Unable to get User Id from Token");
Booking booking = await reservationComplianceService.TryCreateBookingAsync(bookingCreationModel.FlightId, userId, bookingCreationModel.BookingClass, bookingCreationModel.SeatId);
if (booking == null)
return BadRequest("Error in creating booking");
return Ok(booking);
}
[HttpPut("{bookingId}")]
public async Task<IActionResult> UpdatedBookingSeat([FromRoute] int bookingId, [FromBody] BookingUpdate bookingUpdateModel)
{
try
{
await reservationComplianceService.TryBookSeatAsync(bookingId, bookingUpdateModel.SeatId);
return Ok();
}
catch (InvalidOperationException exception)
{
return BadRequest(exception.Message);
}
catch (BookingException exception)
{
return BadRequest(exception.Message);
}
}
}
}
FROM mcr.microsoft.com/dotnet/aspnet:8.0 AS base
USER app
WORKDIR /app
EXPOSE 8080
EXPOSE 8081
FROM mcr.microsoft.com/dotnet/sdk:8.0 AS build
ARG BUILD_CONFIGURATION=Release
WORKDIR /src
COPY ["BookingMicroservice.csproj", "."]
RUN dotnet restore "./BookingMicroservice.csproj"
COPY . .
WORKDIR "/src/."
RUN dotnet build "./BookingMicroservice.csproj" -c $BUILD_CONFIGURATION -o /app/build
FROM build AS publish
ARG BUILD_CONFIGURATION=Release
RUN dotnet publish "./BookingMicroservice.csproj" -c $BUILD_CONFIGURATION -o /app/publish /p:UseAppHost=false
FROM base AS final
WORKDIR /app
COPY --from=publish /app/publish .
ENTRYPOINT ["dotnet", "BookingMicroservice.dll"]
\ No newline at end of file
namespace BookingMicroservice.Exceptions
{
public class BookingException : Exception
{
public BookingException(string message) : base(message) { }
}
}
using System.Net;
using System.Text.Json;
namespace BookingMicroservice.Handlers
{
public class ExceptionHandler
{
private readonly RequestDelegate next;
public ExceptionHandler(RequestDelegate next)
{
this.next = next;
}
public async Task Invoke(HttpContext context)
{
try
{
await next(context);
}
catch (Exception ex)
{
if (!context.Response.HasStarted)
{
var response = context.Response;
response.ContentType = "application/json";
response.StatusCode = (int)HttpStatusCode.InternalServerError;
var result = JsonSerializer.Serialize(new
{
response.StatusCode,
ex.Message
});
await response.WriteAsync(result);
}
}
}
}
}
using Microsoft.EntityFrameworkCore;
namespace BookingMicroservice.Models
{
public class ApplicationDbContext : DbContext
{
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
: base(options)
{
}
public DbSet<Booking> Bookings { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
}
}
}
namespace BookingMicroservice.Models
{
public class Booking
{
public int Id { get; private set; }
public int FlightId { get; private set; }
public int UserId { get; private set; }
public BookingClass BookingClass { get; private set; }
public int? SeatId { get; private set; }
public Booking(int flightId, int userId, BookingClass bookingClass, int? seatId)
{
FlightId = flightId;
UserId = userId;
BookingClass = bookingClass;
SeatId = seatId;
}
public Booking() { }
public void SetSeatNumber(int seatId)
{
SeatId = seatId;
}
}
public enum BookingClass
{
BUSINESS = 0,
ECONOMY = 1
}
}
namespace BookingMicroservice.Models
{
public class BookingCreation
{
public required int FlightId { get; set; }
public required BookingClass BookingClass { get; set; }
public int? SeatId { get; set; }
}
}
namespace BookingMicroservice.Models
{
public class BookingUpdate
{
public required int SeatId { get; set; }
}
}
using BookingMicroservice.Clients;
using BookingMicroservice.Handlers;
using BookingMicroservice.Models;
using BookingMicroservice.Services;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.EntityFrameworkCore;
using Microsoft.IdentityModel.Tokens;
using System.Text;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddControllers();
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
builder.Services.AddDbContext<ApplicationDbContext>(options =>
options.UseMySql(builder.Configuration.GetConnectionString("DefaultConnection"),
new MariaDbServerVersion(new Version(10, 4, 20))));
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options =>
{
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuerSigningKey = true,
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(builder.Configuration["Jwt:Key"] ?? throw new InvalidOperationException("JWT Key is not configured."))),
ValidateIssuer = true,
ValidateAudience = true,
ValidIssuer = builder.Configuration["Jwt:Issuer"] ?? throw new InvalidOperationException("JWT Issuer is not configured."),
ValidAudience = builder.Configuration["Jwt:Audience"] ?? throw new InvalidOperationException("JWT Audience is not configured.")
};
});
builder.Services.AddHttpClient<IFlightServiceClient, FlightServiceClient>(client =>
{
string baseURL = builder.Configuration["FlightMicroservice:BaseUrl"] ?? throw new InvalidOperationException("FlightMicroservice BaseUrl is not configured.");
baseURL = baseURL.EndsWith("/") ? baseURL : baseURL + "/";
client.BaseAddress = new Uri(baseURL);
});
builder.Services.AddScoped<IBookingService, BookingService>();
builder.Services.AddScoped<IReservationComplianceService, ReservationComplianceService>();
var app = builder.Build();
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
app.UseMiddleware<ExceptionHandler>();
app.UseHttpsRedirection();
// Middleware to check for the access token in cookies
app.Use(async (context, next) =>
{
var accessToken = context.Request.Cookies["AccessToken"];
if (!string.IsNullOrEmpty(accessToken))
{
context.Request.Headers.Append("Authorization", "Bearer " + accessToken);
}
await next();
});
app.UseAuthorization();
app.MapControllers();
app.Run();
{
"profiles": {
"http": {
"commandName": "Project",
"launchBrowser": true,
"launchUrl": "swagger",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
},
"dotnetRunMessages": true,
"applicationUrl": "http://localhost:5207"
},
"https": {
"commandName": "Project",
"launchBrowser": true,
"launchUrl": "swagger",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
},
"dotnetRunMessages": true,
"applicationUrl": "https://localhost:7116;http://localhost:5207"
},
"IIS Express": {
"commandName": "IISExpress",
"launchBrowser": true,
"launchUrl": "swagger",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
},
"Container (Dockerfile)": {
"commandName": "Docker",
"launchBrowser": true,
"launchUrl": "{Scheme}://{ServiceHost}:{ServicePort}/swagger",
"environmentVariables": {
"ASPNETCORE_HTTPS_PORTS": "8081",
"ASPNETCORE_HTTP_PORTS": "8080"
},
"publishAllPorts": true,
"useSSL": true
}
},
"$schema": "http://json.schemastore.org/launchsettings.json",
"iisSettings": {
"windowsAuthentication": false,
"anonymousAuthentication": true,
"iisExpress": {
"applicationUrl": "http://localhost:4639",
"sslPort": 44398
}
}
}
\ No newline at end of file
using BookingMicroservice.Models;
using Microsoft.EntityFrameworkCore;
using System.Diagnostics.CodeAnalysis;
namespace BookingMicroservice.Services
{
public class BookingService : IBookingService
{
private readonly ApplicationDbContext dbContext;
public BookingService(ApplicationDbContext dbContext)
{
this.dbContext = dbContext;
}
public List<Booking> GetBookings(int? flightId = null, int? userId = null, BookingClass? bookingClass = null)
{
IQueryable<Booking> query = dbContext.Bookings.AsQueryable();
if (flightId.HasValue)
query = query.Where(booking => booking.FlightId == flightId.Value);
if (userId.HasValue)
query = query.Where(booking => booking.UserId == userId.Value);
if (bookingClass.HasValue)
query = query.Where(booking => booking.BookingClass == bookingClass.Value);
List<Booking> bookings = query.ToList();
return bookings;
}
public Booking CreateBooking(int flightId, int userId, BookingClass bookingClass, int? seatId)
{
Booking booking = new Booking(flightId, userId, bookingClass, seatId);
dbContext.Bookings.Add(booking);
dbContext.SaveChanges();
return booking;
}
public Booking? GetBooking(int bookingId)
{
Booking? booking = dbContext.Bookings.SingleOrDefault(booking => booking.Id == bookingId);
return booking;
}
public void DeleteBooking(int bookingId)
{
Booking? booking = GetBooking(bookingId);
if (booking == null)
throw new KeyNotFoundException($"A Booking with the provided Id: {bookingId} doesnt exist");
dbContext.Bookings.Remove(booking);
dbContext.SaveChanges();
}
public Booking UpdateBooking(int bookingId, int seatId)
{
Booking? booking = GetBooking(bookingId);
if (booking == null)
throw new KeyNotFoundException($"A Booking with the provided Id: {bookingId} doesnt exist");
booking.SetSeatNumber(seatId);
int affectedRows = dbContext.Bookings
.Where(booking => booking.Id == bookingId)
.ExecuteUpdate(setters => setters
.SetProperty(booking => booking.SeatId, seatId));
dbContext.SaveChanges();
if (affectedRows == 0)
throw new DbUpdateException("Operation was not able to update the Database");
return booking;
}
}
}
using BookingMicroservice.Models;
namespace BookingMicroservice.Services
{
public interface IBookingService
{
Booking CreateBooking(int flightId, int userId, BookingClass bookingClass, int? seatId);
List<Booking> GetBookings(int? flightId = null, int? userId = null, BookingClass? bookingClass = null);
Booking? GetBooking(int bookingId);
void DeleteBooking(int bookingId);
Booking UpdateBooking(int bookingId, int seatId);
}
}
using BookingMicroservice.Models;
namespace BookingMicroservice.Services
{
public interface IReservationComplianceService
{
Task<Booking> TryCreateBookingAsync(int flightId, int userId, BookingClass bookingClass, int? seatId);
Task TryBookSeatAsync(int bookingId, int seatId);
}
}
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment