Skip to content
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
8 changes: 4 additions & 4 deletions Client.Wasm/Components/StudentCard.razor
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,10 @@
</CardHeader>
<CardBody>
<UnorderedList Unstyled>
<UnorderedListItem>Номер <Strong>№X "Название лабораторной"</Strong></UnorderedListItem>
<UnorderedListItem>Вариант <Strong>№Х "Название варианта"</Strong></UnorderedListItem>
<UnorderedListItem>Выполнена <Strong>Фамилией Именем 65ХХ</Strong> </UnorderedListItem>
<UnorderedListItem><Link To="https://puginarug.com/">Ссылка на форк</Link></UnorderedListItem>
<UnorderedListItem>Номер <Strong>№1 Кэширование</Strong></UnorderedListItem>
<UnorderedListItem>Вариант <Strong>№50 "Учебный курс"</Strong></UnorderedListItem>
<UnorderedListItem>Выполнена <Strong>Сахаровой Дарьей 6513</Strong> </UnorderedListItem>
<UnorderedListItem><Link To="https://github.com/daryaskhrv/cloud-development">Ссылка на форк</Link></UnorderedListItem>
</UnorderedList>
</CardBody>
</Card>
2 changes: 1 addition & 1 deletion Client.Wasm/wwwroot/appsettings.json
Original file line number Diff line number Diff line change
Expand Up @@ -6,5 +6,5 @@
}
},
"AllowedHosts": "*",
"BaseAddress": ""
"BaseAddress": "https://localhost:7068/api/course"
}
28 changes: 26 additions & 2 deletions CloudDevelopment.sln
Original file line number Diff line number Diff line change
@@ -1,10 +1,18 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 17
VisualStudioVersion = 17.14.36811.4
# Visual Studio Version 18
VisualStudioVersion = 18.3.11505.172 d18.3
MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Client.Wasm", "Client.Wasm\Client.Wasm.csproj", "{AE7EEA74-2FE0-136F-D797-854FD87E022A}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CourseApp.Domain", "CourseApp.Domain\CourseApp.Domain.csproj", "{8DB96A31-4C80-448B-8E97-33930E7DD01C}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CourseApp.Api", "CourseApp.Api\CourseApp.Api.csproj", "{3E70AD66-1A84-425D-8EAA-23B820F3A292}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CourseApp.ServiceDefaults", "CourseApp.ServiceDefaults\CourseApp.ServiceDefaults.csproj", "{FA3F9ED2-E039-4168-AA5E-1E49E771AD99}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CourseApp.AppHost", "CourseApp.AppHost\CourseApp.AppHost.csproj", "{8874AAD8-BCC8-4E48-B7AB-C39E7B5F0F53}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Expand All @@ -15,6 +23,22 @@ Global
{AE7EEA74-2FE0-136F-D797-854FD87E022A}.Debug|Any CPU.Build.0 = Debug|Any CPU
{AE7EEA74-2FE0-136F-D797-854FD87E022A}.Release|Any CPU.ActiveCfg = Release|Any CPU
{AE7EEA74-2FE0-136F-D797-854FD87E022A}.Release|Any CPU.Build.0 = Release|Any CPU
{8DB96A31-4C80-448B-8E97-33930E7DD01C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{8DB96A31-4C80-448B-8E97-33930E7DD01C}.Debug|Any CPU.Build.0 = Debug|Any CPU
{8DB96A31-4C80-448B-8E97-33930E7DD01C}.Release|Any CPU.ActiveCfg = Release|Any CPU
{8DB96A31-4C80-448B-8E97-33930E7DD01C}.Release|Any CPU.Build.0 = Release|Any CPU
{3E70AD66-1A84-425D-8EAA-23B820F3A292}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{3E70AD66-1A84-425D-8EAA-23B820F3A292}.Debug|Any CPU.Build.0 = Debug|Any CPU
{3E70AD66-1A84-425D-8EAA-23B820F3A292}.Release|Any CPU.ActiveCfg = Release|Any CPU
{3E70AD66-1A84-425D-8EAA-23B820F3A292}.Release|Any CPU.Build.0 = Release|Any CPU
{FA3F9ED2-E039-4168-AA5E-1E49E771AD99}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{FA3F9ED2-E039-4168-AA5E-1E49E771AD99}.Debug|Any CPU.Build.0 = Debug|Any CPU
{FA3F9ED2-E039-4168-AA5E-1E49E771AD99}.Release|Any CPU.ActiveCfg = Release|Any CPU
{FA3F9ED2-E039-4168-AA5E-1E49E771AD99}.Release|Any CPU.Build.0 = Release|Any CPU
{8874AAD8-BCC8-4E48-B7AB-C39E7B5F0F53}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{8874AAD8-BCC8-4E48-B7AB-C39E7B5F0F53}.Debug|Any CPU.Build.0 = Debug|Any CPU
{8874AAD8-BCC8-4E48-B7AB-C39E7B5F0F53}.Release|Any CPU.ActiveCfg = Release|Any CPU
{8874AAD8-BCC8-4E48-B7AB-C39E7B5F0F53}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
Expand Down
22 changes: 22 additions & 0 deletions CourseApp.Api/Controllers/CourseController.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
using CourseApp.Api.Services;
using CourseApp.Domain.Entity;
using Microsoft.AspNetCore.Mvc;

namespace CourseApp.Api.Controllers;

[ApiController]
[Route("api/[controller]")]
public class CourseController(CourseService _courseService) : ControllerBase
{
/// <summary>
/// Получить курс по идентификатору
/// </summary>
/// <param name="id">Идентификатор курса</param>
/// <returns>Информация о курсе</returns>
[HttpGet]
public async Task<ActionResult<Course>> Get(int id)
{
var course = await _courseService.GetCourseAsync(id);
return Ok(course);
}
}
20 changes: 20 additions & 0 deletions CourseApp.Api/CourseApp.Api.csproj
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
<Project Sdk="Microsoft.NET.Sdk.Web">

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

<ItemGroup>
<PackageReference Include="Aspire.StackExchange.Redis.DistributedCaching" Version="13.1.1" />
<PackageReference Include="Bogus" Version="35.6.5" />
<PackageReference Include="Swashbuckle.AspNetCore" Version="6.6.2" />
</ItemGroup>

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

</Project>
39 changes: 39 additions & 0 deletions CourseApp.Api/Program.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
using CourseApp.Api.Services;
using CourseApp.ServiceDefaults;

var builder = WebApplication.CreateBuilder(args);

builder.AddServiceDefaults();
builder.AddRedisDistributedCache("redis");

builder.Services.AddControllers();
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

builder.Services.AddCors(options =>
{
options.AddPolicy("wasm", policy =>
{
policy.AllowAnyOrigin()
.WithMethods("GET", "POST")
.WithHeaders("Content-Type");
});
});

builder.Services.AddScoped<CourseGenerator>();
builder.Services.AddScoped<CourseService>();

var app = builder.Build();

if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}

app.MapDefaultEndpoints();
app.UseHttpsRedirection();
app.UseCors("wasm");
app.UseAuthorization();
app.MapControllers();
app.Run();
41 changes: 41 additions & 0 deletions CourseApp.Api/Properties/launchSettings.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
{
"$schema": "http://json.schemastore.org/launchsettings.json",
"iisSettings": {
"windowsAuthentication": false,
"anonymousAuthentication": true,
"iisExpress": {
"applicationUrl": "http://localhost:19002",
"sslPort": 44340
}
},
"profiles": {
"http": {
"commandName": "Project",
"dotnetRunMessages": true,
"launchBrowser": true,
"launchUrl": "swagger",
"applicationUrl": "http://localhost:5083",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
},
"https": {
"commandName": "Project",
"dotnetRunMessages": true,
"launchBrowser": true,
"launchUrl": "swagger",
"applicationUrl": "https://localhost:7068;http://localhost:5083",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
},
"IIS Express": {
"commandName": "IISExpress",
"launchBrowser": true,
"launchUrl": "swagger",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
}
}
}
40 changes: 40 additions & 0 deletions CourseApp.Api/Services/CourseGenerator.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
using Bogus;
using CourseApp.Domain.Entity;

namespace CourseApp.Api.Services;

public class CourseGenerator
{
private static readonly string[] _courseNames =
[
"C# для начинающих",
"Python для анализа данных",
"Микросервисная архитектура",
"Docker",
"Алгоритмы и структуры данных",
"SQL и базы данных",
"Автоматизированное тестирование",
"HTML+CSS Вёрстка сайтов"
];

public Course Generate(int id)
{
var faker = new Faker<Course>("ru")
.RuleFor(c => c.Id, _ => id)
.RuleFor(c => c.Name, f => f.PickRandom(_courseNames))
.RuleFor(c => c.TeacherFullName, f => f.Name.FullName())
//f => $"{f.Name.LastName()} {f.Name.FirstName()} {f.Name.}")
.RuleFor(c => c.StartDate, f => f.Date.SoonDateOnly(30))
.RuleFor(c => c.EndDate, (f, c) =>
c.StartDate.AddDays(f.Random.Int(30, 180)))
.RuleFor(c => c.MaxStudents, f => f.Random.Int(10, 50))
.RuleFor(c => c.CurrentStudents, (f, c) =>
f.Random.Int(0, c.MaxStudents))
.RuleFor(c => c.HasCertificate, f => f.Random.Bool())
.RuleFor(c => c.Price,
f => Math.Round(f.Random.Decimal(5000, 10000), 2))
.RuleFor(c => c.Rating, f => f.Random.Int(1, 5));

return faker.Generate();
}
}
51 changes: 51 additions & 0 deletions CourseApp.Api/Services/CourseService.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
using System.Text.Json;
using CourseApp.Domain.Entity;
using Microsoft.Extensions.Caching.Distributed;

namespace CourseApp.Api.Services;

public class CourseService(IDistributedCache _cache, IConfiguration _configuration,
ILogger<CourseService> _logger, CourseGenerator _generator)
{
public async Task<Course> GetCourseAsync(int id)
{

var cacheKey = $"course-{id}";
_logger.LogInformation("Попытка получить курс {CourseId} из кэша",id);
var cachedData = await _cache.GetStringAsync(cacheKey);

if (!string.IsNullOrEmpty(cachedData))
{
try
{
var cachedCourse = JsonSerializer.Deserialize<Course>(cachedData);

if (cachedCourse != null)
{
_logger.LogInformation("Курс {CourseId} успешно получен из кэша", id);
return cachedCourse;
}
_logger.LogWarning("Курс {CourseId} найден в кэше, но десериализация вернула null", id);
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка десериализации курса {CourseId} из кэша", id);
}
}

_logger.LogInformation("Курс {CourseId} отсутствует в кэше. Начинаем генерацию", id);

var course = _generator.Generate(id);
var expirationMinutes = _configuration.GetValue("CacheSettings:ExpirationMinutes", 5);

var cacheOptions = new DistributedCacheEntryOptions
{
AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(expirationMinutes)
};

await _cache.SetStringAsync(cacheKey, JsonSerializer.Serialize(course), cacheOptions);
_logger.LogInformation("Курс {CourseId} сгенерирован и сохранён в кэш", id);

return course;
}
}
8 changes: 8 additions & 0 deletions CourseApp.Api/appsettings.Development.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
}
}
12 changes: 12 additions & 0 deletions CourseApp.Api/appsettings.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"CacheSettings": {
"ExpirationMinutes": 10
},
"AllowedHosts": "*"
}
21 changes: 21 additions & 0 deletions CourseApp.AppHost/AppHost.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
var builder = DistributedApplication.CreateBuilder(args);

var redis = builder.AddRedis("redis");

var redisCommander = builder.AddContainer(
name: "redis-commander",
image: "rediscommander/redis-commander")
.WithEnvironment("REDIS_HOSTS", "local:redis:6379")
.WithReference(redis)
.WaitFor(redis)
.WithEndpoint(port: 8081, targetPort: 8081);

var api = builder.AddProject<Projects.CourseApp_Api>("courseapp-api")
.WithReference(redis)
.WaitFor(redis);

builder.AddProject<Projects.Client_Wasm>("client")
.WithReference(api)
.WaitFor(api);

builder.Build().Run();
22 changes: 22 additions & 0 deletions CourseApp.AppHost/CourseApp.AppHost.csproj
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
<Project Sdk="Aspire.AppHost.Sdk/13.1.0">

<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net8.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<UserSecretsId>c086dba3-3e81-4540-916e-ccad1674fa30</UserSecretsId>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Aspire.Hosting.AppHost" Version="13.1.1" />
<PackageReference Include="Aspire.Hosting.Redis" Version="13.1.1" />
</ItemGroup>

<ItemGroup>
<ProjectReference Include="..\Client.Wasm\Client.Wasm.csproj" />
<ProjectReference Include="..\CourseApp.Api\CourseApp.Api.csproj" />
</ItemGroup>


</Project>
31 changes: 31 additions & 0 deletions CourseApp.AppHost/Properties/launchSettings.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
{
"$schema": "https://json.schemastore.org/launchsettings.json",
"profiles": {
"https": {
"commandName": "Project",
"dotnetRunMessages": true,
"launchBrowser": true,
"applicationUrl": "https://localhost:17164;http://localhost:15271",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development",
"DOTNET_ENVIRONMENT": "Development",
"ASPIRE_DASHBOARD_OTLP_ENDPOINT_URL": "https://localhost:21251",
"ASPIRE_DASHBOARD_MCP_ENDPOINT_URL": "https://localhost:23029",
"ASPIRE_RESOURCE_SERVICE_ENDPOINT_URL": "https://localhost:22151"
}
},
"http": {
"commandName": "Project",
"dotnetRunMessages": true,
"launchBrowser": true,
"applicationUrl": "http://localhost:15271",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development",
"DOTNET_ENVIRONMENT": "Development",
"ASPIRE_DASHBOARD_OTLP_ENDPOINT_URL": "http://localhost:19248",
"ASPIRE_DASHBOARD_MCP_ENDPOINT_URL": "http://localhost:18141",
"ASPIRE_RESOURCE_SERVICE_ENDPOINT_URL": "http://localhost:20080"
}
}
}
}
8 changes: 8 additions & 0 deletions CourseApp.AppHost/appsettings.Development.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
}
}
Loading