diff --git a/Client.Wasm/Client.Wasm.csproj b/Client.Wasm/Client.Wasm.csproj
index 0ba9f90..1c371bf 100644
--- a/Client.Wasm/Client.Wasm.csproj
+++ b/Client.Wasm/Client.Wasm.csproj
@@ -10,6 +10,10 @@
+
+
+
+
diff --git a/Client.Wasm/Components/StudentCard.razor b/Client.Wasm/Components/StudentCard.razor
index 661f118..07b2938 100644
--- a/Client.Wasm/Components/StudentCard.razor
+++ b/Client.Wasm/Components/StudentCard.razor
@@ -4,10 +4,10 @@
- Номер №X "Название лабораторной"
- Вариант №Х "Название варианта"
- Выполнена Фамилией Именем 65ХХ
- Ссылка на форк
+ Номер № 1
+ Вариант № 52
+ Выполнена Томашайтисом Павлом 6513
+ Ссылка на форк
diff --git a/Client.Wasm/wwwroot/appsettings.json b/Client.Wasm/wwwroot/appsettings.json
index 4dda7c0..57499df 100644
--- a/Client.Wasm/wwwroot/appsettings.json
+++ b/Client.Wasm/wwwroot/appsettings.json
@@ -6,5 +6,5 @@
}
},
"AllowedHosts": "*",
- "BaseAddress": "https://localhost:7170/land-plot"
+ "BaseAddress": "https://localhost:7170/course-management"
}
\ No newline at end of file
diff --git a/CloudDevelopment.sln b/CloudDevelopment.sln
deleted file mode 100644
index cb48241..0000000
--- a/CloudDevelopment.sln
+++ /dev/null
@@ -1,25 +0,0 @@
-
-Microsoft Visual Studio Solution File, Format Version 12.00
-# Visual Studio Version 17
-VisualStudioVersion = 17.14.36811.4
-MinimumVisualStudioVersion = 10.0.40219.1
-Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Client.Wasm", "Client.Wasm\Client.Wasm.csproj", "{AE7EEA74-2FE0-136F-D797-854FD87E022A}"
-EndProject
-Global
- GlobalSection(SolutionConfigurationPlatforms) = preSolution
- Debug|Any CPU = Debug|Any CPU
- Release|Any CPU = Release|Any CPU
- EndGlobalSection
- GlobalSection(ProjectConfigurationPlatforms) = postSolution
- {AE7EEA74-2FE0-136F-D797-854FD87E022A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
- {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
- EndGlobalSection
- GlobalSection(SolutionProperties) = preSolution
- HideSolutionNode = FALSE
- EndGlobalSection
- GlobalSection(ExtensibilityGlobals) = postSolution
- SolutionGuid = {90FE6B04-8381-437E-893A-FEBA1DA10AEE}
- EndGlobalSection
-EndGlobal
diff --git a/CourseManagement.sln b/CourseManagement.sln
new file mode 100644
index 0000000..d90b458
--- /dev/null
+++ b/CourseManagement.sln
@@ -0,0 +1,43 @@
+
+Microsoft Visual Studio Solution File, Format Version 12.00
+# Visual Studio Version 18
+VisualStudioVersion = 18.4.11506.43
+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}") = "CourseManagement.AppHost", "CourseManagement\CourseManagement.AppHost\CourseManagement.AppHost.csproj", "{68D48F1B-1FC5-4FF4-9227-1EEB20CF4B96}"
+EndProject
+Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CourseManagement.ServiceDefaults", "CourseManagement\CourseManagement.ServiceDefaults\CourseManagement.ServiceDefaults.csproj", "{39157B84-72E5-AB3C-22EB-59DEE8C02D29}"
+EndProject
+Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CourseManagement.ApiService", "CourseManagement\CourseManagement.ApiService\CourseManagement.ApiService.csproj", "{15EBA239-9A26-5A00-427D-D957E19F128A}"
+EndProject
+Global
+ GlobalSection(SolutionConfigurationPlatforms) = preSolution
+ Debug|Any CPU = Debug|Any CPU
+ Release|Any CPU = Release|Any CPU
+ EndGlobalSection
+ GlobalSection(ProjectConfigurationPlatforms) = postSolution
+ {AE7EEA74-2FE0-136F-D797-854FD87E022A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
+ {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
+ {68D48F1B-1FC5-4FF4-9227-1EEB20CF4B96}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
+ {68D48F1B-1FC5-4FF4-9227-1EEB20CF4B96}.Debug|Any CPU.Build.0 = Debug|Any CPU
+ {68D48F1B-1FC5-4FF4-9227-1EEB20CF4B96}.Release|Any CPU.ActiveCfg = Release|Any CPU
+ {68D48F1B-1FC5-4FF4-9227-1EEB20CF4B96}.Release|Any CPU.Build.0 = Release|Any CPU
+ {39157B84-72E5-AB3C-22EB-59DEE8C02D29}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
+ {39157B84-72E5-AB3C-22EB-59DEE8C02D29}.Debug|Any CPU.Build.0 = Debug|Any CPU
+ {39157B84-72E5-AB3C-22EB-59DEE8C02D29}.Release|Any CPU.ActiveCfg = Release|Any CPU
+ {39157B84-72E5-AB3C-22EB-59DEE8C02D29}.Release|Any CPU.Build.0 = Release|Any CPU
+ {15EBA239-9A26-5A00-427D-D957E19F128A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
+ {15EBA239-9A26-5A00-427D-D957E19F128A}.Debug|Any CPU.Build.0 = Debug|Any CPU
+ {15EBA239-9A26-5A00-427D-D957E19F128A}.Release|Any CPU.ActiveCfg = Release|Any CPU
+ {15EBA239-9A26-5A00-427D-D957E19F128A}.Release|Any CPU.Build.0 = Release|Any CPU
+ EndGlobalSection
+ GlobalSection(SolutionProperties) = preSolution
+ HideSolutionNode = FALSE
+ EndGlobalSection
+ GlobalSection(ExtensibilityGlobals) = postSolution
+ SolutionGuid = {90FE6B04-8381-437E-893A-FEBA1DA10AEE}
+ EndGlobalSection
+EndGlobal
diff --git a/CourseManagement/CourseManagement.ApiService/Controllers/CourseController.cs b/CourseManagement/CourseManagement.ApiService/Controllers/CourseController.cs
new file mode 100644
index 0000000..cb9b303
--- /dev/null
+++ b/CourseManagement/CourseManagement.ApiService/Controllers/CourseController.cs
@@ -0,0 +1,30 @@
+using Microsoft.AspNetCore.Mvc;
+using CourseManagement.ApiService.Dto;
+using CourseManagement.ApiService.Services;
+
+namespace CourseManagement.ApiService.Controllers;
+
+///
+/// Контроллер для сущности типа Курс
+///
+/// Логгер
+/// Сервис для сущности типа Курс
+[ApiController]
+[Route("course-management")]
+public class CourseController(ILogger logger, CourseService courseService) : ControllerBase
+{
+ ///
+ /// Обработчик GET-запроса на генерацию курса
+ ///
+ /// Идентификатор курса
+ /// Сгенерированный курс
+ [HttpGet]
+ public async Task> GetCourse(int? id)
+ {
+ logger.LogInformation("Processing request for course {ResourceId}", id);
+
+ var course = await courseService.GetCourse(id ?? 0);
+
+ return course != null ? Ok(course) : Problem("Internal server error", statusCode: 500);
+ }
+}
\ No newline at end of file
diff --git a/CourseManagement/CourseManagement.ApiService/CourseManagement.ApiService.csproj b/CourseManagement/CourseManagement.ApiService/CourseManagement.ApiService.csproj
new file mode 100644
index 0000000..cbce22c
--- /dev/null
+++ b/CourseManagement/CourseManagement.ApiService/CourseManagement.ApiService.csproj
@@ -0,0 +1,21 @@
+
+
+
+ net10.0
+ enable
+ enable
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/CourseManagement/CourseManagement.ApiService/DTO/CourseDto.cs b/CourseManagement/CourseManagement.ApiService/DTO/CourseDto.cs
new file mode 100644
index 0000000..eebd509
--- /dev/null
+++ b/CourseManagement/CourseManagement.ApiService/DTO/CourseDto.cs
@@ -0,0 +1,58 @@
+namespace CourseManagement.ApiService.Dto;
+
+
+///
+/// DTO для сущности типа курс
+///
+public class CourseDto
+{
+ ///
+ /// Идентификатор курса
+ ///
+ public int Id { get; set; }
+
+ ///
+ /// Название курса
+ ///
+ public string Title { get; set; } = string.Empty;
+
+ ///
+ /// Лектор
+ ///
+ public string Lector { get; set; } = string.Empty;
+
+ ///
+ /// Дата начала курса
+ ///
+ public DateOnly StartDate { get; set; }
+
+ ///
+ /// Дата окончания курса
+ ///
+ public DateOnly EndDate { get; set; }
+
+ ///
+ /// Максимальное число студентов для курса
+ ///
+ public int MaxStudents { get; set; }
+
+ ///
+ /// Текущее число студентов курса
+ ///
+ public int EnrolledStudents { get; set; }
+
+ ///
+ /// Выдача сертификата
+ ///
+ public bool HasSertificate { get; set; }
+
+ ///
+ /// Стоимость курса
+ ///
+ public decimal Price { get; set; }
+
+ ///
+ /// Рейтинг
+ ///
+ public int Rating { get; set; }
+}
diff --git a/CourseManagement/CourseManagement.ApiService/Program.cs b/CourseManagement/CourseManagement.ApiService/Program.cs
new file mode 100644
index 0000000..ed014ca
--- /dev/null
+++ b/CourseManagement/CourseManagement.ApiService/Program.cs
@@ -0,0 +1,55 @@
+using CourseManagement.ApiService.Dto;
+using CourseManagement.ApiService.Services;
+
+var builder = WebApplication.CreateBuilder(args);
+
+// Add service defaults
+builder.AddServiceDefaults();
+
+// Redis
+builder.AddRedisDistributedCache("course-cache");
+
+// Add services to the container
+builder.Services.AddProblemDetails();
+builder.Services.AddOpenApi();
+
+// Контроллеры
+builder.Services.AddControllers();
+
+// CORS
+builder.Services.AddCors(options =>
+{
+ options.AddPolicy("AllowClient", policy =>
+ {
+ policy.AllowAnyOrigin()
+ .WithMethods("GET")
+ .WithHeaders("Content-Type");
+ });
+});
+
+// Генератор курсов
+builder.Services.AddSingleton();
+
+// Сервис для взаимодействия с кэшем
+builder.Services.AddSingleton>();
+
+// Сервис для сущности типа Курс
+builder.Services.AddSingleton();
+
+var app = builder.Build();
+
+// Configure the HTTP request pipeline
+app.UseExceptionHandler();
+app.UseCors("AllowClient");
+
+// Mapping
+if (app.Environment.IsDevelopment())
+{
+ app.MapOpenApi();
+}
+
+app.MapControllers();
+
+app.MapDefaultEndpoints();
+
+app.Run();
\ No newline at end of file
diff --git a/CourseManagement/CourseManagement.ApiService/Properties/launchSettings.json b/CourseManagement/CourseManagement.ApiService/Properties/launchSettings.json
new file mode 100644
index 0000000..e237496
--- /dev/null
+++ b/CourseManagement/CourseManagement.ApiService/Properties/launchSettings.json
@@ -0,0 +1,23 @@
+{
+ "$schema": "https://json.schemastore.org/launchsettings.json",
+ "profiles": {
+ "http": {
+ "commandName": "Project",
+ "dotnetRunMessages": true,
+ "launchBrowser": false,
+ "applicationUrl": "http://localhost:5329",
+ "environmentVariables": {
+ "ASPNETCORE_ENVIRONMENT": "Development"
+ }
+ },
+ "https": {
+ "commandName": "Project",
+ "dotnetRunMessages": true,
+ "launchBrowser": false,
+ "applicationUrl": "https://localhost:7170;http://localhost:5329",
+ "environmentVariables": {
+ "ASPNETCORE_ENVIRONMENT": "Development"
+ }
+ }
+ }
+}
diff --git a/CourseManagement/CourseManagement.ApiService/Services/CacheService.cs b/CourseManagement/CourseManagement.ApiService/Services/CacheService.cs
new file mode 100644
index 0000000..eb0cc6b
--- /dev/null
+++ b/CourseManagement/CourseManagement.ApiService/Services/CacheService.cs
@@ -0,0 +1,77 @@
+using System.Text.Json;
+using Microsoft.Extensions.Caching.Distributed;
+
+namespace CourseManagement.ApiService.Services;
+
+///
+/// Сервис для взаимодействия с кэшем
+///
+/// Кэш
+/// Логгер
+public class CacheService(IDistributedCache cache, ILogger> logger)
+{
+ ///
+ /// Время жизни данных в кэше
+ ///
+ private static readonly double _cacheDuration = 5;
+
+ ///
+ /// Асинхронный метод для извлечения данных из кэша
+ ///
+ /// Ключ для сущности
+ /// Идентификатор объекта
+ /// Объект или null при его отсутствии
+ public async Task FetchAsync(string key, int id)
+ {
+ var cacheKey = $"{key}:{id}";
+
+ try
+ {
+ var cached = await cache.GetStringAsync(cacheKey);
+ if (cached != null)
+ {
+ var obj = JsonSerializer.Deserialize(cached);
+
+ logger.LogInformation("Cache hit for object {ResourceId}", id);
+
+ return obj;
+ }
+
+ logger.LogInformation("Cache miss for object {ResourceId}", id);
+ }
+ catch (Exception ex)
+ {
+ logger.LogWarning(ex, "Сache is unavailable");
+ }
+
+ return default;
+ }
+
+ ///
+ /// Асинхронный метод для внесения данных в кэш
+ ///
+ /// Ключ для сущности
+ /// Идентификатор объекта
+ /// Объект
+ public async Task StoreAsync(string key, int id, T obj)
+ {
+ var cacheKey = $"{key}:{id}";
+
+ var options = new DistributedCacheEntryOptions
+ {
+ AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(_cacheDuration)
+ };
+
+ try
+ {
+ var serialized = JsonSerializer.Serialize(obj);
+ await cache.SetStringAsync(cacheKey, serialized, options);
+ logger.LogInformation("Object {ResourceId} cached", id);
+ }
+ catch (Exception ex)
+ {
+ logger.LogWarning(ex, "Сache is unavailable");
+ }
+
+ }
+}
diff --git a/CourseManagement/CourseManagement.ApiService/Services/CourseGenerator.cs b/CourseManagement/CourseManagement.ApiService/Services/CourseGenerator.cs
new file mode 100644
index 0000000..0ecedc8
--- /dev/null
+++ b/CourseManagement/CourseManagement.ApiService/Services/CourseGenerator.cs
@@ -0,0 +1,81 @@
+using Bogus;
+using CourseManagement.ApiService.Dto;
+
+namespace CourseManagement.ApiService.Services;
+
+///
+/// Генератор для сущности типа Курс
+///
+/// Логгер
+public class CourseGenerator(ILogger logger)
+{
+ ///
+ /// Список названий курсов
+ ///
+ private static readonly string[] _courseTitles = {
+ "Разработка корпоративных приложений",
+ "Алгоритмы и структуры данных",
+ "Базы данных",
+ "Веб-разработка",
+ "Машинное обучение",
+ "Основы информационной безопасности",
+ "Математический анализ",
+ "Линейная алгебра и геометрия",
+ "Математическая статистика",
+ "Теория вероятностей",
+ "Физика",
+ "Микроэкономика",
+ "Макроэкономика",
+ "Нейронные сети и глубокое обучение",
+ "Сети и системы передачи информации",
+ "Философия",
+ "История России",
+ "Дискретная математика",
+ "Прикладное программирование",
+ "Методы оптимизации",
+ "Теория графов",
+ "Технологии программирования",
+ "Основы веб-приложений",
+ "Безопасность вычислительных сетей",
+ "Низкоуровневое программирование",
+ "Системное программирование",
+ "Криптография",
+ "Криптопротоколы",
+ "Жизненный цикл",
+ "Цифровая обработка сигналов",
+ "Цифровая обработка изображений",
+ "Основы программиования",
+ "Объектно-ориентированное программирование",
+ "Форензика",
+ "Компьютерная алгебра",
+ };
+
+ ///
+ /// Экземпляр генератора данных
+ ///
+ private readonly Faker _courseFaker = new Faker("ru")
+ .RuleFor(c => c.Title, f => f.PickRandom(_courseTitles))
+ .RuleFor(c => c.Lector, f => f.Name.FullName())
+ .RuleFor(c => c.StartDate, f => DateOnly.FromDateTime(f.Date.Future(1)))
+ .RuleFor(c => c.EndDate, (f, c) => c.StartDate.AddMonths(f.Random.Int(1, 6)))
+ .RuleFor(c => c.MaxStudents, f => f.Random.Int(10, 100))
+ .RuleFor(c => c.EnrolledStudents, (f, c) => f.Random.Int(0, c.MaxStudents))
+ .RuleFor(c => c.HasSertificate, f => f.Random.Bool())
+ .RuleFor(c => c.Price, f => f.Finance.Amount(5000, 100000, 2))
+ .RuleFor(c => c.Rating, f => f.Random.Int(1, 5));
+
+ ///
+ /// Метод для генерации одного экземпляра сущности типа Курс
+ ///
+ /// Идентификатор курса
+ /// Курс
+ public CourseDto GenerateOne(int? id = null)
+ {
+ var course = _courseFaker.Generate();
+ course.Id = id ?? new Randomizer().Int(1, 100000);
+
+ logger.LogInformation("Course {ResourceId} generated", id);
+
+ return course;
+ }
+}
\ No newline at end of file
diff --git a/CourseManagement/CourseManagement.ApiService/Services/CourseService.cs b/CourseManagement/CourseManagement.ApiService/Services/CourseService.cs
new file mode 100644
index 0000000..8fae4a6
--- /dev/null
+++ b/CourseManagement/CourseManagement.ApiService/Services/CourseService.cs
@@ -0,0 +1,44 @@
+using CourseManagement.ApiService.Dto;
+
+namespace CourseManagement.ApiService.Services;
+
+///
+/// Сервис для сущности типа Курс
+///
+/// Генератор курсов
+/// Логгер
+/// Сервис для взаимодействия с кэшем
+public class CourseService(CourseGenerator generator, ILogger logger, CacheService cacheService)
+{
+ ///
+ /// Константа для ключа кэша
+ ///
+ private const string CacheKeyPrefix = "course";
+
+ ///
+ /// Метод для получения курса
+ ///
+ /// Идентификатор курса
+ /// Курс или null при ошибке
+ public async Task GetCourse(int id)
+ {
+ try
+ {
+ var course = await cacheService.FetchAsync(CacheKeyPrefix, id);
+ if (course != null)
+ return course;
+
+ var newCourse = generator.GenerateOne(id);
+
+ await cacheService.StoreAsync(CacheKeyPrefix, id, newCourse);
+
+ return newCourse;
+ }
+ catch (Exception ex)
+ {
+ logger.LogError(ex, "Error processing course {ResourceId}", id);
+ }
+
+ return null;
+ }
+}
diff --git a/CourseManagement/CourseManagement.ApiService/appsettings.Development.json b/CourseManagement/CourseManagement.ApiService/appsettings.Development.json
new file mode 100644
index 0000000..0c208ae
--- /dev/null
+++ b/CourseManagement/CourseManagement.ApiService/appsettings.Development.json
@@ -0,0 +1,8 @@
+{
+ "Logging": {
+ "LogLevel": {
+ "Default": "Information",
+ "Microsoft.AspNetCore": "Warning"
+ }
+ }
+}
diff --git a/CourseManagement/CourseManagement.ApiService/appsettings.json b/CourseManagement/CourseManagement.ApiService/appsettings.json
new file mode 100644
index 0000000..10f68b8
--- /dev/null
+++ b/CourseManagement/CourseManagement.ApiService/appsettings.json
@@ -0,0 +1,9 @@
+{
+ "Logging": {
+ "LogLevel": {
+ "Default": "Information",
+ "Microsoft.AspNetCore": "Warning"
+ }
+ },
+ "AllowedHosts": "*"
+}
diff --git a/CourseManagement/CourseManagement.AppHost/AppHost.cs b/CourseManagement/CourseManagement.AppHost/AppHost.cs
new file mode 100644
index 0000000..88ef792
--- /dev/null
+++ b/CourseManagement/CourseManagement.AppHost/AppHost.cs
@@ -0,0 +1,20 @@
+var builder = DistributedApplication.CreateBuilder(args);
+
+// Redis
+var redis = builder.AddRedis("course-cache")
+ .WithRedisCommander(containerName: "redis-commander")
+ .WithDataVolume();
+
+// API service
+var apiService = builder.AddProject("course-insight")
+ .WithReference(redis)
+ .WithHttpHealthCheck("/health");
+
+// Client
+builder.AddProject("course-wasm")
+ .WithExternalHttpEndpoints()
+ .WithHttpHealthCheck("/health")
+ .WithReference(apiService)
+ .WaitFor(apiService);
+
+builder.Build().Run();
diff --git a/CourseManagement/CourseManagement.AppHost/CourseManagement.AppHost.csproj b/CourseManagement/CourseManagement.AppHost/CourseManagement.AppHost.csproj
new file mode 100644
index 0000000..d2a0740
--- /dev/null
+++ b/CourseManagement/CourseManagement.AppHost/CourseManagement.AppHost.csproj
@@ -0,0 +1,20 @@
+
+
+
+ Exe
+ net10.0
+ enable
+ enable
+ 9bbc0bf3-e529-4a0f-833b-49b80c01c009
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/CourseManagement/CourseManagement.AppHost/Properties/launchSettings.json b/CourseManagement/CourseManagement.AppHost/Properties/launchSettings.json
new file mode 100644
index 0000000..8bba3b8
--- /dev/null
+++ b/CourseManagement/CourseManagement.AppHost/Properties/launchSettings.json
@@ -0,0 +1,31 @@
+{
+ "$schema": "https://json.schemastore.org/launchsettings.json",
+ "profiles": {
+ "https": {
+ "commandName": "Project",
+ "dotnetRunMessages": true,
+ "launchBrowser": true,
+ "applicationUrl": "https://localhost:17286;http://localhost:15040",
+ "environmentVariables": {
+ "ASPNETCORE_ENVIRONMENT": "Development",
+ "DOTNET_ENVIRONMENT": "Development",
+ "ASPIRE_DASHBOARD_OTLP_ENDPOINT_URL": "https://localhost:21283",
+ "ASPIRE_DASHBOARD_MCP_ENDPOINT_URL": "https://localhost:23150",
+ "ASPIRE_RESOURCE_SERVICE_ENDPOINT_URL": "https://localhost:22100"
+ }
+ },
+ "http": {
+ "commandName": "Project",
+ "dotnetRunMessages": true,
+ "launchBrowser": true,
+ "applicationUrl": "http://localhost:15040",
+ "environmentVariables": {
+ "ASPNETCORE_ENVIRONMENT": "Development",
+ "DOTNET_ENVIRONMENT": "Development",
+ "ASPIRE_DASHBOARD_OTLP_ENDPOINT_URL": "http://localhost:19011",
+ "ASPIRE_DASHBOARD_MCP_ENDPOINT_URL": "http://localhost:18011",
+ "ASPIRE_RESOURCE_SERVICE_ENDPOINT_URL": "http://localhost:20240"
+ }
+ }
+ }
+}
diff --git a/CourseManagement/CourseManagement.AppHost/appsettings.Development.json b/CourseManagement/CourseManagement.AppHost/appsettings.Development.json
new file mode 100644
index 0000000..0c208ae
--- /dev/null
+++ b/CourseManagement/CourseManagement.AppHost/appsettings.Development.json
@@ -0,0 +1,8 @@
+{
+ "Logging": {
+ "LogLevel": {
+ "Default": "Information",
+ "Microsoft.AspNetCore": "Warning"
+ }
+ }
+}
diff --git a/CourseManagement/CourseManagement.AppHost/appsettings.json b/CourseManagement/CourseManagement.AppHost/appsettings.json
new file mode 100644
index 0000000..31c092a
--- /dev/null
+++ b/CourseManagement/CourseManagement.AppHost/appsettings.json
@@ -0,0 +1,9 @@
+{
+ "Logging": {
+ "LogLevel": {
+ "Default": "Information",
+ "Microsoft.AspNetCore": "Warning",
+ "Aspire.Hosting.Dcp": "Warning"
+ }
+ }
+}
diff --git a/CourseManagement/CourseManagement.ServiceDefaults/CourseManagement.ServiceDefaults.csproj b/CourseManagement/CourseManagement.ServiceDefaults/CourseManagement.ServiceDefaults.csproj
new file mode 100644
index 0000000..eeb71e3
--- /dev/null
+++ b/CourseManagement/CourseManagement.ServiceDefaults/CourseManagement.ServiceDefaults.csproj
@@ -0,0 +1,22 @@
+
+
+
+ net10.0
+ enable
+ enable
+ true
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/CourseManagement/CourseManagement.ServiceDefaults/Extensions.cs b/CourseManagement/CourseManagement.ServiceDefaults/Extensions.cs
new file mode 100644
index 0000000..b72c875
--- /dev/null
+++ b/CourseManagement/CourseManagement.ServiceDefaults/Extensions.cs
@@ -0,0 +1,127 @@
+using Microsoft.AspNetCore.Builder;
+using Microsoft.AspNetCore.Diagnostics.HealthChecks;
+using Microsoft.Extensions.DependencyInjection;
+using Microsoft.Extensions.Diagnostics.HealthChecks;
+using Microsoft.Extensions.Logging;
+using Microsoft.Extensions.ServiceDiscovery;
+using OpenTelemetry;
+using OpenTelemetry.Metrics;
+using OpenTelemetry.Trace;
+
+namespace Microsoft.Extensions.Hosting;
+
+// Adds common Aspire services: service discovery, resilience, health checks, and OpenTelemetry.
+// This project should be referenced by each service project in your solution.
+// To learn more about using this project, see https://aka.ms/dotnet/aspire/service-defaults
+public static class Extensions
+{
+ private const string HealthEndpointPath = "/health";
+ private const string AlivenessEndpointPath = "/alive";
+
+ public static TBuilder AddServiceDefaults(this TBuilder builder) where TBuilder : IHostApplicationBuilder
+ {
+ builder.ConfigureOpenTelemetry();
+
+ builder.AddDefaultHealthChecks();
+
+ builder.Services.AddServiceDiscovery();
+
+ builder.Services.ConfigureHttpClientDefaults(http =>
+ {
+ // Turn on resilience by default
+ http.AddStandardResilienceHandler();
+
+ // Turn on service discovery by default
+ http.AddServiceDiscovery();
+ });
+
+ // Uncomment the following to restrict the allowed schemes for service discovery.
+ // builder.Services.Configure(options =>
+ // {
+ // options.AllowedSchemes = ["https"];
+ // });
+
+ return builder;
+ }
+
+ public static TBuilder ConfigureOpenTelemetry(this TBuilder builder) where TBuilder : IHostApplicationBuilder
+ {
+ builder.Logging.AddOpenTelemetry(logging =>
+ {
+ logging.IncludeFormattedMessage = true;
+ logging.IncludeScopes = true;
+ });
+
+ builder.Services.AddOpenTelemetry()
+ .WithMetrics(metrics =>
+ {
+ metrics.AddAspNetCoreInstrumentation()
+ .AddHttpClientInstrumentation()
+ .AddRuntimeInstrumentation();
+ })
+ .WithTracing(tracing =>
+ {
+ tracing.AddSource(builder.Environment.ApplicationName)
+ .AddAspNetCoreInstrumentation(tracing =>
+ // Exclude health check requests from tracing
+ tracing.Filter = context =>
+ !context.Request.Path.StartsWithSegments(HealthEndpointPath)
+ && !context.Request.Path.StartsWithSegments(AlivenessEndpointPath)
+ )
+ // Uncomment the following line to enable gRPC instrumentation (requires the OpenTelemetry.Instrumentation.GrpcNetClient package)
+ //.AddGrpcClientInstrumentation()
+ .AddHttpClientInstrumentation();
+ });
+
+ builder.AddOpenTelemetryExporters();
+
+ return builder;
+ }
+
+ private static TBuilder AddOpenTelemetryExporters(this TBuilder builder) where TBuilder : IHostApplicationBuilder
+ {
+ var useOtlpExporter = !string.IsNullOrWhiteSpace(builder.Configuration["OTEL_EXPORTER_OTLP_ENDPOINT"]);
+
+ if (useOtlpExporter)
+ {
+ builder.Services.AddOpenTelemetry().UseOtlpExporter();
+ }
+
+ // Uncomment the following lines to enable the Azure Monitor exporter (requires the Azure.Monitor.OpenTelemetry.AspNetCore package)
+ //if (!string.IsNullOrEmpty(builder.Configuration["APPLICATIONINSIGHTS_CONNECTION_STRING"]))
+ //{
+ // builder.Services.AddOpenTelemetry()
+ // .UseAzureMonitor();
+ //}
+
+ return builder;
+ }
+
+ public static TBuilder AddDefaultHealthChecks(this TBuilder builder) where TBuilder : IHostApplicationBuilder
+ {
+ builder.Services.AddHealthChecks()
+ // Add a default liveness check to ensure app is responsive
+ .AddCheck("self", () => HealthCheckResult.Healthy(), ["live"]);
+
+ return builder;
+ }
+
+ public static WebApplication MapDefaultEndpoints(this WebApplication app)
+ {
+ // Adding health checks endpoints to applications in non-development environments has security implications.
+ // See https://aka.ms/dotnet/aspire/healthchecks for details before enabling these endpoints in non-development environments.
+ if (app.Environment.IsDevelopment())
+ {
+ // All health checks must pass for app to be considered ready to accept traffic after starting
+ app.MapHealthChecks(HealthEndpointPath);
+
+ // Only health checks tagged with the "live" tag must pass for app to be considered alive
+ app.MapHealthChecks(AlivenessEndpointPath, new HealthCheckOptions
+ {
+ Predicate = r => r.Tags.Contains("live")
+ });
+ }
+
+ return app;
+ }
+}
diff --git a/README.md b/README.md
index dcaa5eb..5a4130c 100644
--- a/README.md
+++ b/README.md
@@ -1,128 +1,15 @@
-# Современные технологии разработки программного обеспечения
-[Таблица с успеваемостью](https://docs.google.com/spreadsheets/d/1an43o-iqlq4V_kDtkr_y7DC221hY9qdhGPrpII27sH8/edit?usp=sharing)
+# Томашайтис Павел 6513 (вариант 52)
+---
+## Учебный курс
-## Задание
-### Цель
-Реализация проекта микросервисного бекенда.
+**Внесённые изменения:**
+- [x] Cервис генерации контрактов на основе Bogus
+- [x] Кеширование при помощи IDistributedCache и Redis
+- [x] Сервис для взаимодействия с кешем
+- [x] Структурное логирование сервисов
+- [x] Оркестрация Aspire
-### Задачи
-* Реализация межсервисной коммуникации,
-* Изучение работы с брокерами сообщений,
-* Изучение архитектурных паттернов,
-* Изучение работы со средствами оркестрации на примере .NET Aspire,
-* Повторение основ работы с системами контроля версий,
-* Интеграционное тестирование.
+
-### Лабораторные работы
-
-1. «Кэширование» - Реализация сервиса генерации контрактов, кэширование его ответов
-
-
-В рамках первой лабораторной работы необходимо:
-* Реализовать сервис генерации контрактов на основе Bogus,
-* Реализовать кеширование при помощи IDistributedCache и Redis,
-* Реализовать структурное логирование сервиса генерации,
-* Настроить оркестрацию Aspire.
-
-
-
-2. «Балансировка нагрузки» - Реализация апи гейтвея, настройка его работы
-
-
-В рамках второй лабораторной работы необходимо:
-* Настроить оркестрацию на запуск нескольких реплик сервиса генерации,
-* Реализовать апи гейтвей на основе Ocelot,
-* Имплементировать алгоритм балансировки нагрузки согласно варианту.
-
-
-
-
-3. «Интеграционное тестирование» - Реализация файлового сервиса и объектного хранилища, интеграционное тестирование бекенда
-
-
-В рамках третьей лабораторной работы необходимо:
-* Добавить в оркестрацию объектное хранилище,
-* Реализовать файловый сервис, сериализующий сгенерированные данные в файлы и сохраняющий их в объектном хранилище,
-* Реализовать отправку генерируемых данных в файловый сервис посредством брокера,
-* Реализовать интеграционные тесты, проверяющие корректность работы всех сервисов бекенда вместе.
-
-
-
-
-4. (Опционально) «Переход на облачную инфраструктуру» - Перенос бекенда в Yandex Cloud
-
-
-В рамках четвертой лабораторной работы необходимо перенестиервисы на облако все ранее разработанные сервисы:
-* Клиент - в хостинг через отдельный бакет Object Storage,
-* Сервис генерации - в Cloud Function,
-* Апи гейтвей - в Serverless Integration как API Gateway,
-* Брокер сообщений - в Message Queue,
-* Файловый сервис - в Cloud Function,
-* Объектное хранилище - в отдельный бакет Object Storage,
-
-
-
-
-## Задание. Общая часть
-**Обязательно**:
-* Реализация серверной части на [.NET 8](https://learn.microsoft.com/ru-ru/dotnet/core/whats-new/dotnet-8/overview).
-* Оркестрация проектов при помощи [.NET Aspire](https://learn.microsoft.com/ru-ru/dotnet/aspire/get-started/aspire-overview).
-* Реализация сервиса генерации данных при помощи [Bogus](https://github.com/bchavez/Bogus).
-* Реализация тестов с использованием [xUnit](https://xunit.net/?tabs=cs).
-* Создание минимальной документации к проекту: страница на GitHub с информацией о задании, скриншоты приложения и прочая информация.
-
-**Факультативно**:
-* Перенос бекенда на облачную инфраструктуру Yandex Cloud
-
-Внимательно прочитайте [дискуссии](https://github.com/itsecd/cloud-development/discussions/1) о том, как работает автоматическое распределение на ревью.
-Сразу корректно называйте свои pr, чтобы они попали на ревью нужному преподавателю.
-
-По итогу работы в семестре должна получиться следующая информационная система:
-
-C4 диаграмма
-
-
-
-## Варианты заданий
-Номер варианта задания присваивается в начале семестра. Изменить его нельзя. Каждый вариант имеет уникальную комбинацию из предметной области, базы данных и технологии для общения сервиса генерации данных и сервера апи.
-
-[Список вариантов](https://docs.google.com/document/d/1WGmLYwffTTaAj4TgFCk5bUyW3XKbFMiBm-DHZrfFWr4/edit?usp=sharing)
-[Список предметных областей и алгоритмов балансировки](https://docs.google.com/document/d/1PLn2lKe4swIdJDZhwBYzxqFSu0AbY2MFY1SUPkIKOM4/edit?usp=sharing)
-
-## Схема сдачи
-
-На каждую из лабораторных работ необходимо сделать отдельный [Pull Request (PR)](https://docs.github.com/en/pull-requests).
-
-Общая схема:
-1. Сделать форк данного репозитория
-2. Выполнить задание
-3. Сделать PR в данный репозиторий
-4. Исправить замечания после code review
-5. Получить approve
-
-## Критерии оценивания
-
-Конкурентный принцип.
-Так как задания в первой лабораторной будут повторяться между студентами, то выделяются следующие показатели для оценки:
-1. Скорость разработки
-2. Качество разработки
-3. Полнота выполнения задания
-
-Быстрее делаете PR - у вас преимущество.
-Быстрее получаете Approve - у вас преимущество.
-Выполните нечто немного выходящее за рамки проекта - у вас преимущество.
-Не укладываетесь в дедлайн - получаете минимально возможный балл.
-
-### Шкала оценивания
-
-- **3 балла** за качество кода, из них:
- - 2 балла - базовая оценка
- - 1 балл (но не более) можно получить за выполнение любого из следующих пунктов:
- - Реализация факультативного функционала
- - Выполнение работы раньше других: первые 5 человек из каждой группы, которые сделали PR и получили approve, получают дополнительный балл
-
-## Вопросы и обратная связь по курсу
-
-Чтобы задать вопрос по лабораторной, воспользуйтесь [соответствующим разделом дискуссий](https://github.com/itsecd/cloud-development/discussions/categories/questions) или заведите [ишью](https://github.com/itsecd/cloud-development/issues/new).
-Если у вас появились идеи/пожелания/прочие полезные мысли по преподаваемой дисциплине, их можно оставить [здесь](https://github.com/itsecd/cloud-development/discussions/categories/ideas).
+