Skip to content

Commit

Permalink
Merge pull request #25 from NiceOneFox/develop
Browse files Browse the repository at this point in the history
Sprint 2
  • Loading branch information
NiceOneFox authored Apr 30, 2022
2 parents b67b392 + b68e618 commit d03820a
Show file tree
Hide file tree
Showing 40 changed files with 508 additions and 68 deletions.
10 changes: 9 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -22,12 +22,20 @@ Input parameters:
* Amount of requests
* Modeling time (max time)
* SimulationType (Type of buffer modeling, FIFO, LIFO etc.)
* Lambda (amount of flow) parameter for Poissonian flow
* Lambda for devices (amount of flow) parameter for Poissonian flow
* Lambda for sources

## Technologies
- ASP .NET 6
- C# 10
- AutoMapper
- FluentValidation
- CORS
- NLog

### For testing
- NUnit
- Moq

## Architecture
N-Layer Web API
Expand Down
9 changes: 8 additions & 1 deletion backend/ServiceSimulation/Api/Api.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,14 @@

<ItemGroup>
<PackageReference Include="AutoMapper" Version="11.0.1" />
<PackageReference Include="Swashbuckle.AspNetCore" Version="6.3.0" />
<PackageReference Include="FluentValidation" Version="10.4.0" />
<PackageReference Include="FluentValidation.AspNetCore" Version="10.4.0" />
<PackageReference Include="FluentValidation.DependencyInjectionExtensions" Version="10.4.0" />
<PackageReference Include="Microsoft.AspNetCore.Cors" Version="2.2.0" />
<PackageReference Include="NLog" Version="4.7.15" />
<PackageReference Include="NLog.Schema" Version="4.7.15" />
<PackageReference Include="NLog.Web.AspNetCore" Version="4.14.0" />
<PackageReference Include="Swashbuckle.AspNetCore" Version="6.3.1" />
</ItemGroup>

<ItemGroup>
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
using Api.Entities;
using AutoMapper;
using Bll.Domain.Entities;
using Bll.Domain.Models;
using Bll.Domain.Interfaces;

namespace Api.Configuration;
Expand Down
23 changes: 23 additions & 0 deletions backend/ServiceSimulation/Api/Configuration/CorsPolicies.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
using Microsoft.AspNetCore.Cors.Infrastructure;

namespace Api.Configuration;

public static class CorsPolicies
{
public static readonly (string Name, Action<CorsPolicyBuilder> ConfigurePolicy) AllowRemoteFrontendWithCredentials =
(
"AllowRemoteFrontendWithCredentials",
builder =>
{
var host = Environment.GetEnvironmentVariable("REMOTE_FRONTEND_HOST");
var port = Environment.GetEnvironmentVariable("REMOTE_FRONTEND_PORT");
var scheme = Environment.GetEnvironmentVariable("REMOTE_FRONTEND_SCHEME");
var origin = $"{scheme}://{host}:{port}";
builder
.WithOrigins(origin)
.AllowAnyHeader()
.AllowAnyMethod()
.AllowCredentials();
}
);
}
7 changes: 5 additions & 2 deletions backend/ServiceSimulation/Api/Controllers/Simulation.cs
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
using Api.Entities;
using Api.enums;
using Api.Validation;
using AutoMapper;
using Bll.Domain.Entities;
using Bll.Domain.Interfaces;
using Bll.Domain.Models;
using FluentValidation;
using Microsoft.AspNetCore.Mvc;

namespace Api.Controllers;
Expand Down Expand Up @@ -31,6 +32,8 @@ public Simulation(ISimulationService simulationService,
[HttpGet("/start")]
public IActionResult Start(InputParameters parameters)
{
new InputParametersValidator().ValidateAndThrow(parameters);

_simulationService.StartSimulation(parameters);
var endResultsOfModeling = _resultManager.CalculateResultsOfModeling();
var apiResults = _mapper.Map<ApiResults>((endResultsOfModeling, _results));
Expand Down
12 changes: 12 additions & 0 deletions backend/ServiceSimulation/Api/Extensions/CorsOptionsExtensions.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
using Microsoft.AspNetCore.Cors.Infrastructure;

namespace Api.Extensions;

public static class CorsOptionsExtensions
{
public static void AddPolicy(this CorsOptions options, (string Name, Action<CorsPolicyBuilder> ConfigurePolicy) arg)
{
options.AddPolicy(arg.Name, arg.ConfigurePolicy);
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
using Api.Middlewares;

namespace Api.Extensions
{
public static class CustomExceptionHandlerMiddlewareExtensions
{
public static IApplicationBuilder UseCustomExceptionHandler(this IApplicationBuilder builder)
{
return builder.UseMiddleware<CustomExceptionHandlerMiddleware>();
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
using System.Net;
using System.Text.Json;
using FluentValidation;

namespace Api.Middlewares
{
public class CustomExceptionHandlerMiddleware
{
private readonly RequestDelegate _next;

private readonly ILogger _logger;
public CustomExceptionHandlerMiddleware(RequestDelegate next,
ILogger<CustomExceptionHandlerMiddleware> logger)
{
_next = next;
_logger = logger;
}

public async Task Invoke(HttpContext context)
{
try
{
await _next(context);
}
catch (Exception ex)
{
await HandleExceptionAsync(context, ex);
}
}

private Task HandleExceptionAsync(HttpContext context, Exception ex)
{
var statusCode = HttpStatusCode.InternalServerError;
var result = string.Empty;

switch (ex)
{
case ValidationException validationException:
statusCode = HttpStatusCode.BadRequest;
result = JsonSerializer.Serialize(validationException.Errors);
_logger.LogDebug(validationException.Message);
break;

default:
statusCode = HttpStatusCode.NotFound;
break;

}
context.Response.ContentType = "application/json";
context.Response.StatusCode = (int)statusCode;

if (result == string.Empty)
{
result = JsonSerializer.Serialize(new { error = ex.Message });
}
return context.Response.WriteAsync(result);
}
}
}
39 changes: 32 additions & 7 deletions backend/ServiceSimulation/Api/Program.cs
Original file line number Diff line number Diff line change
@@ -1,34 +1,57 @@
using Api.Configuration;
using Api.Extensions;
using Api.Validation;
using Bll.Domain.Entities;
using Bll.Domain.Factories;
using Bll.Domain.Interfaces;
using Bll.Domain.Models;
using Bll.Domain.Services;
using FluentValidation;
using FluentValidation.AspNetCore;
using NLog.Web;

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddControllers();
builder.Services.AddControllers().AddFluentValidation(fv =>
{
fv.RegisterValidatorsFromAssemblyContaining<InputParametersValidator>();
});

#region Logger
builder.Logging.ClearProviders();
builder.Logging.SetMinimumLevel(Microsoft.Extensions.Logging.LogLevel.Trace);
builder.Host.UseNLog();
#endregion
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

#region servicesDI
builder.Services.AddTransient<ISimulationService, SimulationService>();

builder.Services.AddScoped<ITimeProvider, TimeProvider>();
builder.Services.AddScoped<IFlowProvider, PoissonianFlowProvider>();

builder.Services.AddScoped<IResults, Bll.Domain.Entities.Results>();
builder.Services.AddScoped<IResultManager, ResultManager>();
builder.Services.AddScoped<IResultManager, ResultManager>();
//builder.Services.AddTransient<IBufferManager, StandardBufferManager>();

builder.Services.AddTransient<IBufferManagerFactory, BufferManagerFactory>();
builder.Services.AddTransient<IDeviceManager, DeviceManager>();
builder.Services.AddTransient<ISourceManager, SourceManager>();
//builder.Services.AddScoped<StandardBufferManager>()
// .AddScoped<IBufferManager, StandardBufferManager>(s => s.GetRequiredService<StandardBufferManager>());

//builder.Services.AddScoped<IBufferManager>(s =>
// ActivatorUtilities.CreateInstance<StandardBufferManager>(s));
builder.Services.AddTransient<IValidator<InputParameters>, InputParametersValidator>();
#endregion

#region Mapper
builder.Services.AddMapper();
#endregion

#region CORS
builder.Services.AddCors(opts =>
{
opts.AddPolicy(CorsPolicies.AllowRemoteFrontendWithCredentials);
});
#endregion


var app = builder.Build();

Expand All @@ -38,6 +61,8 @@
app.UseSwaggerUI();
}

app.UseCustomExceptionHandler();

app.UseHttpsRedirection();

app.UseAuthorization();
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
using FluentValidation;
using Bll.Domain.Models;
using Api.enums;

namespace Api.Validation
{
public class InputParametersValidator : AbstractValidator<InputParameters>
{
public InputParametersValidator()
{
RuleFor(p => p.NumberOfSources).NotEmpty().InclusiveBetween(1, 100);
RuleFor(p => p.NumberOfDevices).NotEmpty().InclusiveBetween(1, 100);
RuleFor(p => p.AmountOfRequests).NotEmpty().InclusiveBetween(1, 5000);
RuleFor(p => p.BufferSize).NotEmpty().InclusiveBetween(1, 100);
RuleFor(p => p.LambdaForDevice).NotEmpty().ExclusiveBetween(0, 10000);
RuleFor(p => p.NumberOfSources).NotEmpty().ExclusiveBetween(0, 10000);
RuleFor(p => p.ModelingTime).NotEmpty().ExclusiveBetween(0, 10000);
RuleFor(p => p.BufferType).IsInEnum();
}
}
}
7 changes: 6 additions & 1 deletion backend/ServiceSimulation/Api/appsettings.Development.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,5 +4,10 @@
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
}
},

"REMOTE_FRONTEND_SCHEME": "https",
"REMOTE_FRONTEND_HOST": "localhost",
"REMOTE_FRONTEND_PORT": "8081",
"DISABLE_SSL_SERVER_CERTIFICATES_VALIDATION": "true"
}
7 changes: 4 additions & 3 deletions backend/ServiceSimulation/Api/appsettings.json
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
"Default": "Trace",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
}
},
"AllowedHosts": "*"
}
}
41 changes: 41 additions & 0 deletions backend/ServiceSimulation/Api/nlog.config
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
<?xml version="1.0" encoding="utf-8" ?>
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
autoReload="true"
internalLogLevel="Info"
internalLogFile="c:\temp\internal-nlog-AspNetCore.txt">

<!-- enable asp.net core layout renderers -->
<extensions>
<add assembly="NLog.Web.AspNetCore"/>
</extensions>

<!-- the targets to write to -->
<targets>
<!-- File Target for all log messages with basic details -->
<target xsi:type="File" name="allfile" fileName="c:\temp\nlog-AspNetCore-all-${shortdate}.log"
layout="${longdate}|${event-properties:item=EventId_Id:whenEmpty=0}|${level:uppercase=true}|${logger}|${message} ${exception:format=tostring}" />

<!-- File Target for own log messages with extra web details using some ASP.NET core renderers -->
<target xsi:type="File" name="ownFile-web" fileName="c:\temp\nlog-AspNetCore-own-${shortdate}.log"
layout="${longdate}|${event-properties:item=EventId_Id:whenEmpty=0}|${level:uppercase=true}|${logger}|${message} ${exception:format=tostring}|url: ${aspnet-request-url}|action: ${aspnet-mvc-action}|${callsite}" />

<!--Console Target for hosting lifetime messages to improve Docker / Visual Studio startup detection -->
<target xsi:type="Console" name="lifetimeConsole" layout="${MicrosoftConsoleLayout}" />
</targets>

<!-- rules to map from logger name to target -->
<rules>
<!--All logs, including from Microsoft-->
<logger name="*" minlevel="Trace" writeTo="allfile" />

<!--Output hosting lifetime messages to console target for faster startup detection -->
<logger name="Microsoft.Hosting.Lifetime" minlevel="Info" writeTo="lifetimeConsole, ownFile-web" final="true" />

<!--Skip non-critical Microsoft logs and so log only own logs (BlackHole) -->
<logger name="Microsoft.*" maxlevel="Info" final="true" />
<logger name="System.Net.Http.*" maxlevel="Info" final="true" />

<logger name="*" minlevel="Trace" writeTo="ownFile-web" />
</rules>
</nlog>
22 changes: 22 additions & 0 deletions backend/ServiceSimulation/Bll.Domain.Tests/Bll.Domain.Tests.csproj
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<TargetFramework>net6.0</TargetFramework>
<Nullable>enable</Nullable>

<IsPackable>false</IsPackable>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="16.11.0" />
<PackageReference Include="Moq" Version="4.17.2" />
<PackageReference Include="NUnit" Version="3.13.2" />
<PackageReference Include="NUnit3TestAdapter" Version="4.0.0" />
<PackageReference Include="coverlet.collector" Version="3.1.0" />
</ItemGroup>

<ItemGroup>
<ProjectReference Include="..\Bll.Domain\Bll.Domain.csproj" />
</ItemGroup>

</Project>
Loading

0 comments on commit d03820a

Please sign in to comment.