diff --git a/AspireWork.png b/AspireWork.png
new file mode 100644
index 00000000..a20dbaa2
Binary files /dev/null and b/AspireWork.png differ
diff --git a/Client.Wasm/Components/StudentCard.razor b/Client.Wasm/Components/StudentCard.razor
index 661f1181..0d767684 100644
--- a/Client.Wasm/Components/StudentCard.razor
+++ b/Client.Wasm/Components/StudentCard.razor
@@ -4,10 +4,10 @@
- Номер №X "Название лабораторной"
- Вариант №Х "Название варианта"
- Выполнена Фамилией Именем 65ХХ
- Ссылка на форк
+ Номер "№1 "Кэширование"
+ Вариант №16 "Учебный курс"
+ ВыполнилЧугунов Владислав 6511
+ Ссылка на форк
diff --git a/Client.Wasm/Properties/launchSettings.json b/Client.Wasm/Properties/launchSettings.json
index 0d824ea7..dbbac3ff 100644
--- a/Client.Wasm/Properties/launchSettings.json
+++ b/Client.Wasm/Properties/launchSettings.json
@@ -1,4 +1,4 @@
-{
+{
"$schema": "http://json.schemastore.org/launchsettings.json",
"iisSettings": {
"windowsAuthentication": false,
@@ -12,7 +12,7 @@
"http": {
"commandName": "Project",
"dotnetRunMessages": true,
- "launchBrowser": true,
+ "launchBrowser": false,
"inspectUri": "{wsProtocol}://{url.hostname}:{url.port}/_framework/debug/ws-proxy?browser={browserInspectUri}",
"applicationUrl": "http://localhost:5127",
"environmentVariables": {
@@ -22,7 +22,7 @@
"https": {
"commandName": "Project",
"dotnetRunMessages": true,
- "launchBrowser": true,
+ "launchBrowser": false,
"inspectUri": "{wsProtocol}://{url.hostname}:{url.port}/_framework/debug/ws-proxy?browser={browserInspectUri}",
"applicationUrl": "https://localhost:7282;http://localhost:5127",
"environmentVariables": {
@@ -31,7 +31,7 @@
},
"IIS Express": {
"commandName": "IISExpress",
- "launchBrowser": true,
+ "launchBrowser": false,
"inspectUri": "{wsProtocol}://{url.hostname}:{url.port}/_framework/debug/ws-proxy?browser={browserInspectUri}",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
diff --git a/Client.Wasm/wwwroot/appsettings.json b/Client.Wasm/wwwroot/appsettings.json
index d1fe7ab3..c55f31fb 100644
--- a/Client.Wasm/wwwroot/appsettings.json
+++ b/Client.Wasm/wwwroot/appsettings.json
@@ -1,4 +1,4 @@
-{
+{
"Logging": {
"LogLevel": {
"Default": "Information",
@@ -6,5 +6,5 @@
}
},
"AllowedHosts": "*",
- "BaseAddress": ""
+ "BaseAddress": "https://localhost:7231/courses"
}
diff --git a/CloudDevelopment.sln b/CloudDevelopment.sln
index cb48241d..796d636f 100644
--- a/CloudDevelopment.sln
+++ b/CloudDevelopment.sln
@@ -5,6 +5,12 @@ 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
+Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "TrainingCourseApp.AppHost", "TrainingCourseApp\TrainingCourseApp.AppHost\TrainingCourseApp.AppHost.csproj", "{7A240EE1-35E7-4CA8-B387-9D6E6A6C45F5}"
+EndProject
+Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "TrainingCourseApp.ServiceDefaults", "TrainingCourseApp\TrainingCourseApp.ServiceDefaults\TrainingCourseApp.ServiceDefaults.csproj", "{C53C8EE4-EFE3-1A87-4119-EA1F9BA9141D}"
+EndProject
+Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "TrainingCourse.Api", "TrainingCourse.Api\TrainingCourse.Api.csproj", "{91E8399E-D30D-3E51-7F8E-F5AF72E578B5}"
+EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
@@ -15,6 +21,18 @@ 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
+ {7A240EE1-35E7-4CA8-B387-9D6E6A6C45F5}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
+ {7A240EE1-35E7-4CA8-B387-9D6E6A6C45F5}.Debug|Any CPU.Build.0 = Debug|Any CPU
+ {7A240EE1-35E7-4CA8-B387-9D6E6A6C45F5}.Release|Any CPU.ActiveCfg = Release|Any CPU
+ {7A240EE1-35E7-4CA8-B387-9D6E6A6C45F5}.Release|Any CPU.Build.0 = Release|Any CPU
+ {C53C8EE4-EFE3-1A87-4119-EA1F9BA9141D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
+ {C53C8EE4-EFE3-1A87-4119-EA1F9BA9141D}.Debug|Any CPU.Build.0 = Debug|Any CPU
+ {C53C8EE4-EFE3-1A87-4119-EA1F9BA9141D}.Release|Any CPU.ActiveCfg = Release|Any CPU
+ {C53C8EE4-EFE3-1A87-4119-EA1F9BA9141D}.Release|Any CPU.Build.0 = Release|Any CPU
+ {91E8399E-D30D-3E51-7F8E-F5AF72E578B5}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
+ {91E8399E-D30D-3E51-7F8E-F5AF72E578B5}.Debug|Any CPU.Build.0 = Debug|Any CPU
+ {91E8399E-D30D-3E51-7F8E-F5AF72E578B5}.Release|Any CPU.ActiveCfg = Release|Any CPU
+ {91E8399E-D30D-3E51-7F8E-F5AF72E578B5}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
diff --git a/README.md b/README.md
index dcaa5eb7..0449f716 100644
--- a/README.md
+++ b/README.md
@@ -1,128 +1,60 @@
-# Современные технологии разработки программного обеспечения
-[Таблица с успеваемостью](https://docs.google.com/spreadsheets/d/1an43o-iqlq4V_kDtkr_y7DC221hY9qdhGPrpII27sH8/edit?usp=sharing)
-
-## Задание
-### Цель
-Реализация проекта микросервисного бекенда.
-
-### Задачи
-* Реализация межсервисной коммуникации,
-* Изучение работы с брокерами сообщений,
-* Изучение архитектурных паттернов,
-* Изучение работы со средствами оркестрации на примере .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).
+# Лабораторная работа №1 — «Кэширование»
+## Вариант 16 — «Учебный курс»
+
+## Описание
+
+Спроектирован и реализован микросервисный бэкенд для генерации данных учебных курсов. В проекте используется Redis для кэширования запросов, оркестрация микросервисов выполняется средствами .NET Aspire.
+
+## Реализовано
+
+- Сервис генерации данных Учебных курсов на основе Bogus
+- Кэширование ответов при помощи `IDistributedCache` и Redis
+- Структурное логирование сервиса генерации
+- Оркестрация всех компонентов через .NET Aspire
+- Blazor WebAssembly клиент для отображения данных
+
+## Стек технологий
+
+- .NET 8
+- .NET Aspire 9.3.1
+- Bogus (v35.6.5) — генерация данных
+- Redis (v9.3.1) — распределённое кэширование
+- RedisInsight — визуализация данных в Redis
+- Blazor WebAssembly — клиентское приложение
+
+
+## Структура проекта
+
+| Проект | Описание |
+|---|---|
+| `TrainingCourse.Api` | API-сервис генерации курсов |
+| `TrainingCourse.AppHost` | Aspire-оркестратор |
+| `TrainingCourse.ServiceDefaults` | Общие настройки сервисов |
+| `Client.Wasm` | Клиент |
+
+## Характеристики создаваемых курсов
+
+| № | Название | Тип данных | Источник Bogus |
+|---|---|---|---|
+| 1 | Идентификатор в системе | int | Параметр запроса |
+| 2 | Название курса | string | Company.CatchPhrase() + " course" |
+| 3 | ФИО преподавателя | string | Name.FullName() |
+| 4 | Дата начала | DateOnly | f.Date.FutureDateOnly(1) |
+| 5 | Дата окончания | DateOnly | Date.Between(StartDate, StartDate.AddMonths(6)) |
+| 6 | Макс. количество студентов | int | Random.Int(10, 50) |
+| 7 | Текущее количество студентов | int | Random.Int(0, MaxStudents) |
+| 8 | Наличие сертификата | bool | Random.Bool(0.8f) |
+| 9 | Стоимость курса | decimal | Math.Round(Random.Decimal(5000, 50000), 2) |
+| 10 | Рейтинг курса | int | Random.Int(1, 5) |
+
+## Скриншоты
+
+### Aspire Dashboard
+
+
+### Клиент
+
+
+### Кэширование
+
\ No newline at end of file
diff --git a/TrainingCourse.Api/Models/Course.cs b/TrainingCourse.Api/Models/Course.cs
new file mode 100644
index 00000000..a877ac3f
--- /dev/null
+++ b/TrainingCourse.Api/Models/Course.cs
@@ -0,0 +1,57 @@
+namespace TrainingCourse.Api.Models;
+
+///
+/// Модель курса
+///
+public class Course
+{
+ ///
+ /// Идентификатор в системе
+ ///
+ public int Id { get; set; }
+
+ ///
+ /// Наименование курса
+ ///
+ public required string CourseName { get; set; }
+
+ ///
+ /// ФИО преподавателя
+ ///
+ public required string TeacherFullName { get; set; }
+
+ ///
+ /// Дата начала курса
+ ///
+ public required DateOnly StartDate { get; set; }
+
+ ///
+ /// Дата окончания курса
+ ///
+ public required DateOnly EndDate { get; set; }
+
+ ///
+ /// Максимальное число студентов
+ ///
+ public int MaxStudents { get; set; }
+
+ ///
+ /// Текущее число студентов
+ ///
+ public int CurrentStudents { get; set; }
+
+ ///
+ /// Выдача сертификата по окончании
+ ///
+ public bool HasCertificate { get; set; }
+
+ ///
+ /// Стоимость курса
+ ///
+ public decimal Price { get; set; }
+
+ ///
+ /// Рейтинг курса (1-5)
+ ///
+ public int Rating { get; set; }
+}
\ No newline at end of file
diff --git a/TrainingCourse.Api/Program.cs b/TrainingCourse.Api/Program.cs
new file mode 100644
index 00000000..dfaeea6e
--- /dev/null
+++ b/TrainingCourse.Api/Program.cs
@@ -0,0 +1,27 @@
+using TrainingCourse.Api.Services;
+
+
+var builder = WebApplication.CreateBuilder(args);
+
+builder.AddServiceDefaults();
+builder.AddRedisDistributedCache("redis");
+
+builder.Services.AddScoped();
+builder.Services.AddCors(options =>
+ options.AddPolicy("AllowClient", policy =>
+ policy.WithOrigins(builder.Configuration.GetSection("CorsSettings:AllowedOrigins").Get() ?? [])
+ .WithMethods("GET")
+ .AllowAnyHeader()));
+
+var app = builder.Build();
+
+app.UseCors("AllowClient");
+app.MapDefaultEndpoints();
+
+app.MapGet("/courses", async (int id, ICourseService patientService) =>
+{
+ var patient = await patientService.GetCourse(id);
+ return Results.Ok(patient);
+});
+
+app.Run();
\ No newline at end of file
diff --git a/TrainingCourse.Api/Properties/launchSettings.json b/TrainingCourse.Api/Properties/launchSettings.json
new file mode 100644
index 00000000..840df966
--- /dev/null
+++ b/TrainingCourse.Api/Properties/launchSettings.json
@@ -0,0 +1,38 @@
+{
+ "$schema": "http://json.schemastore.org/launchsettings.json",
+ "iisSettings": {
+ "windowsAuthentication": false,
+ "anonymousAuthentication": true,
+ "iisExpress": {
+ "applicationUrl": "http://localhost:14355",
+ "sslPort": 44344
+ }
+ },
+ "profiles": {
+ "http": {
+ "commandName": "Project",
+ "dotnetRunMessages": true,
+ "launchBrowser": true,
+ "applicationUrl": "http://localhost:5153",
+ "environmentVariables": {
+ "ASPNETCORE_ENVIRONMENT": "Development"
+ }
+ },
+ "https": {
+ "commandName": "Project",
+ "dotnetRunMessages": true,
+ "launchBrowser": true,
+ "applicationUrl": "https://localhost:7231;http://localhost:5153",
+ "environmentVariables": {
+ "ASPNETCORE_ENVIRONMENT": "Development"
+ }
+ },
+ "IIS Express": {
+ "commandName": "IISExpress",
+ "launchBrowser": true,
+ "environmentVariables": {
+ "ASPNETCORE_ENVIRONMENT": "Development"
+ }
+ }
+ }
+}
diff --git a/TrainingCourse.Api/Services/CourseGenerator.cs b/TrainingCourse.Api/Services/CourseGenerator.cs
new file mode 100644
index 00000000..a81b3c19
--- /dev/null
+++ b/TrainingCourse.Api/Services/CourseGenerator.cs
@@ -0,0 +1,33 @@
+namespace TrainingCourse.Api.Services;
+
+using Bogus;
+using TrainingCourse.Api.Models;
+
+///
+/// Генератор курсов со случайными свойствами
+///
+public static class CourseGenerator
+{
+ private static readonly Faker _faker = new Faker()
+ .RuleFor(c => c.CourseName, f => f.Company.CatchPhrase() + " course")
+ .RuleFor(c => c.TeacherFullName, f => f.Name.FullName())
+ .RuleFor(c => c.StartDate, f => f.Date.FutureDateOnly(1))
+ .RuleFor(c => c.EndDate, (f, c) => f.Date.BetweenDateOnly(c.StartDate, c.StartDate.AddMonths(6)))
+ .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(0.8f)) // 80% вероятность выдачи сертификата
+ .RuleFor(c => c.Price, f => Math.Round(f.Random.Decimal(5000, 50000), 2))
+ .RuleFor(c => c.Rating, f => f.Random.Int(1, 5));
+
+ ///
+ /// Метод генерации курса
+ ///
+ /// Идентификатор курса
+ /// Курс
+ public static Course GenerateCourse(int id)
+ {
+ var course = _faker.Generate();
+ course.Id = id;
+ return course;
+ }
+}
\ No newline at end of file
diff --git a/TrainingCourse.Api/Services/CourseService.cs b/TrainingCourse.Api/Services/CourseService.cs
new file mode 100644
index 00000000..944dd24f
--- /dev/null
+++ b/TrainingCourse.Api/Services/CourseService.cs
@@ -0,0 +1,60 @@
+namespace TrainingCourse.Api.Services;
+
+using Microsoft.Extensions.Caching.Distributed;
+using System.Text.Json;
+using TrainingCourse.Api.Models;
+
+///
+/// Сервис для получения информации о курсе
+///
+public class CourseService(IDistributedCache cache, IConfiguration configuration,
+ ILogger logger) : ICourseService
+{
+ private readonly int _expirationMinutes = configuration.GetValue("CacheSettings:ExpirationMinutes", 10);
+
+ ///
+ public async Task GetCourse(int id)
+ {
+ var cacheKey = $"course-{id}";
+ logger.LogInformation("Requesting course {CourseId} from cache", id);
+ var cachedData = await cache.GetStringAsync(cacheKey);
+
+ if (!string.IsNullOrEmpty(cachedData))
+ {
+ try
+ {
+ var cachedCourse = JsonSerializer.Deserialize(cachedData);
+
+ if (cachedCourse != null)
+ {
+ logger.LogInformation("Course {CourseId} retrieved from cache", id);
+ return cachedCourse;
+ }
+ logger.LogWarning("Course {CourseId} found in cache but deserialization returned null", id);
+ }
+ catch (Exception ex)
+ {
+ logger.LogError(ex, "Failed to deserialize course {CourseId} from cache", id);
+ }
+ }
+
+ logger.LogInformation("Course {CourseId} not found in cache. Generating", id);
+
+ var course = CourseGenerator.GenerateCourse(id);
+
+ try
+ {
+ var cacheOptions = new DistributedCacheEntryOptions
+ {
+ AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(_expirationMinutes)
+ };
+ await cache.SetStringAsync(cacheKey, JsonSerializer.Serialize(course), cacheOptions);
+ logger.LogInformation("Course {CourseId} generated and cached", id);
+ }
+ catch (Exception ex)
+ {
+ logger.LogWarning(ex, "Failed to cache course {CourseId}. Continuing without cache.", id);
+ }
+ return course;
+ }
+}
\ No newline at end of file
diff --git a/TrainingCourse.Api/Services/ICourseService.cs b/TrainingCourse.Api/Services/ICourseService.cs
new file mode 100644
index 00000000..f447abdc
--- /dev/null
+++ b/TrainingCourse.Api/Services/ICourseService.cs
@@ -0,0 +1,16 @@
+using TrainingCourse.Api.Models;
+
+namespace TrainingCourse.Api.Services;
+
+///
+/// Интерфейс сервиса для работы с курсами
+///
+public interface ICourseService
+{
+ ///
+ /// Получить курс по идентификатору
+ ///
+ /// Идентификатор курса
+ /// Модель курса
+ public Task GetCourse(int id);
+}
\ No newline at end of file
diff --git a/TrainingCourse.Api/TrainingCourse.Api.csproj b/TrainingCourse.Api/TrainingCourse.Api.csproj
new file mode 100644
index 00000000..ff50541f
--- /dev/null
+++ b/TrainingCourse.Api/TrainingCourse.Api.csproj
@@ -0,0 +1,18 @@
+
+
+
+ net8.0
+ enable
+ enable
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/TrainingCourse.Api/appsettings.Development.json b/TrainingCourse.Api/appsettings.Development.json
new file mode 100644
index 00000000..0c208ae9
--- /dev/null
+++ b/TrainingCourse.Api/appsettings.Development.json
@@ -0,0 +1,8 @@
+{
+ "Logging": {
+ "LogLevel": {
+ "Default": "Information",
+ "Microsoft.AspNetCore": "Warning"
+ }
+ }
+}
diff --git a/TrainingCourse.Api/appsettings.json b/TrainingCourse.Api/appsettings.json
new file mode 100644
index 00000000..18745097
--- /dev/null
+++ b/TrainingCourse.Api/appsettings.json
@@ -0,0 +1,21 @@
+{
+ "Logging": {
+ "LogLevel": {
+ "Default": "Information",
+ "Microsoft.AspNetCore": "Warning"
+ }
+ },
+ "AllowedHosts": "*",
+ "CorsSettings": {
+ "AllowedOrigins": [
+ "https://localhost:5127",
+ "https://localhost:7282",
+ "http://localhost:5127",
+ "http://localhost:7282",
+ "https://localhost:7089"
+ ]
+ },
+ "CacheSettings": {
+ "ExpirationMinutes": 10
+ }
+}
diff --git a/TrainingCourseApp/TrainingCourseApp.AppHost/AppHost.cs b/TrainingCourseApp/TrainingCourseApp.AppHost/AppHost.cs
new file mode 100644
index 00000000..65dab036
--- /dev/null
+++ b/TrainingCourseApp/TrainingCourseApp.AppHost/AppHost.cs
@@ -0,0 +1,14 @@
+var builder = DistributedApplication.CreateBuilder(args);
+
+var redis = builder.AddRedis("redis")
+ .WithRedisInsight();
+
+var api = builder.AddProject("training-course-api")
+ .WithReference(redis)
+ .WaitFor(redis);
+
+builder.AddProject("client-wasm")
+ .WithReference(api)
+ .WaitFor(api);
+
+builder.Build().Run();
\ No newline at end of file
diff --git a/TrainingCourseApp/TrainingCourseApp.AppHost/Properties/launchSettings.json b/TrainingCourseApp/TrainingCourseApp.AppHost/Properties/launchSettings.json
new file mode 100644
index 00000000..5fbbf440
--- /dev/null
+++ b/TrainingCourseApp/TrainingCourseApp.AppHost/Properties/launchSettings.json
@@ -0,0 +1,29 @@
+{
+ "$schema": "https://json.schemastore.org/launchsettings.json",
+ "profiles": {
+ "https": {
+ "commandName": "Project",
+ "dotnetRunMessages": true,
+ "launchBrowser": true,
+ "applicationUrl": "https://localhost:17150;http://localhost:15019",
+ "environmentVariables": {
+ "ASPNETCORE_ENVIRONMENT": "Development",
+ "DOTNET_ENVIRONMENT": "Development",
+ "ASPIRE_DASHBOARD_OTLP_ENDPOINT_URL": "https://localhost:21075",
+ "ASPIRE_RESOURCE_SERVICE_ENDPOINT_URL": "https://localhost:22190"
+ }
+ },
+ "http": {
+ "commandName": "Project",
+ "dotnetRunMessages": true,
+ "launchBrowser": true,
+ "applicationUrl": "http://localhost:15019",
+ "environmentVariables": {
+ "ASPNETCORE_ENVIRONMENT": "Development",
+ "DOTNET_ENVIRONMENT": "Development",
+ "ASPIRE_DASHBOARD_OTLP_ENDPOINT_URL": "http://localhost:19229",
+ "ASPIRE_RESOURCE_SERVICE_ENDPOINT_URL": "http://localhost:20092"
+ }
+ }
+ }
+}
diff --git a/TrainingCourseApp/TrainingCourseApp.AppHost/TrainingCourseApp.AppHost.csproj b/TrainingCourseApp/TrainingCourseApp.AppHost/TrainingCourseApp.AppHost.csproj
new file mode 100644
index 00000000..a3ff3cba
--- /dev/null
+++ b/TrainingCourseApp/TrainingCourseApp.AppHost/TrainingCourseApp.AppHost.csproj
@@ -0,0 +1,23 @@
+
+
+
+
+
+ Exe
+ net8.0
+ enable
+ enable
+ 58fecc7f-bf3d-43e2-867c-8457c65da978
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/TrainingCourseApp/TrainingCourseApp.AppHost/appsettings.Development.json b/TrainingCourseApp/TrainingCourseApp.AppHost/appsettings.Development.json
new file mode 100644
index 00000000..0c208ae9
--- /dev/null
+++ b/TrainingCourseApp/TrainingCourseApp.AppHost/appsettings.Development.json
@@ -0,0 +1,8 @@
+{
+ "Logging": {
+ "LogLevel": {
+ "Default": "Information",
+ "Microsoft.AspNetCore": "Warning"
+ }
+ }
+}
diff --git a/TrainingCourseApp/TrainingCourseApp.AppHost/appsettings.json b/TrainingCourseApp/TrainingCourseApp.AppHost/appsettings.json
new file mode 100644
index 00000000..31c092aa
--- /dev/null
+++ b/TrainingCourseApp/TrainingCourseApp.AppHost/appsettings.json
@@ -0,0 +1,9 @@
+{
+ "Logging": {
+ "LogLevel": {
+ "Default": "Information",
+ "Microsoft.AspNetCore": "Warning",
+ "Aspire.Hosting.Dcp": "Warning"
+ }
+ }
+}
diff --git a/TrainingCourseApp/TrainingCourseApp.ServiceDefaults/Extensions.cs b/TrainingCourseApp/TrainingCourseApp.ServiceDefaults/Extensions.cs
new file mode 100644
index 00000000..112c1281
--- /dev/null
+++ b/TrainingCourseApp/TrainingCourseApp.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 .NET 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/TrainingCourseApp/TrainingCourseApp.ServiceDefaults/TrainingCourseApp.ServiceDefaults.csproj b/TrainingCourseApp/TrainingCourseApp.ServiceDefaults/TrainingCourseApp.ServiceDefaults.csproj
new file mode 100644
index 00000000..d808731c
--- /dev/null
+++ b/TrainingCourseApp/TrainingCourseApp.ServiceDefaults/TrainingCourseApp.ServiceDefaults.csproj
@@ -0,0 +1,22 @@
+
+
+
+ net8.0
+ enable
+ enable
+ true
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/WorkApp.png b/WorkApp.png
new file mode 100644
index 00000000..25a57d17
Binary files /dev/null and b/WorkApp.png differ
diff --git "a/WorkCa\321\201he.png" "b/WorkCa\321\201he.png"
new file mode 100644
index 00000000..dcab84af
Binary files /dev/null and "b/WorkCa\321\201he.png" differ