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
1 change: 1 addition & 0 deletions Client.Wasm/Components/DataCard.razor
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,7 @@
private async Task RequestNewData()
{
var baseAddress = Configuration["BaseAddress"] ?? throw new KeyNotFoundException("Конфигурация клиента не содержит параметра BaseAddress");
Console.WriteLine($"{baseAddress}?id={Id}");
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Для отладки в блазорном клиенте можно пользоваться брейкпоинтами, как и в любом другом дотнетном проекте. А это позорище надо убрать

Value = await Client.GetFromJsonAsync<JsonObject>($"{baseAddress}?id={Id}", new JsonSerializerOptions { });
StateHasChanged();
}
Expand Down
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>№41 "Кредитная заявка "</Strong></UnorderedListItem>
<UnorderedListItem>Выполнена <Strong>Кадниковым Егором 6513</Strong> </UnorderedListItem>
<UnorderedListItem><Link To="https://github.com/acebiscuits/cloud-development">Ссылка на форк</Link></UnorderedListItem>
</UnorderedList>
</CardBody>
</Card>
16 changes: 8 additions & 8 deletions Client.Wasm/wwwroot/appsettings.json
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*",
"BaseAddress": "https://localhost:7170/land-plot"
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*",
"BaseAddress": "https://localhost:7240/credit-orders"
}
11 changes: 11 additions & 0 deletions CloudDevelopment.AppHost/AppHost.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
using Projects;

var builder = DistributedApplication.CreateBuilder(args);

var redis = builder.AddRedis("redis");
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Добавить контейнер с вебмордой к редису


var generator = builder.AddProject<Projects.Generator>("generator").WithReference(redis);

var client = builder.AddProject<Projects.Client_Wasm>("client").WithReference(generator);
Comment on lines +7 to +9
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Добавить WaitFor() в конфигурации служб. Кому кого надо ждать, думаю, догадаешься самостоятельно


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

<Sdk Name="Aspire.AppHost.Sdk" Version="9.5.0" />

<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net8.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<UserSecretsId>2f419979-4dcb-43a3-bf86-3b5579f994b9</UserSecretsId>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Aspire.Hosting.AppHost" Version="13.1.1" />
<PackageReference Include="Aspire.Hosting.Redis" Version="13.1.1" />
Comment on lines +14 to +15
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Я бы посоветовал на всякий случай синхронизировать версию сдк и версию нугет пакетов

</ItemGroup>

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

</Project>
29 changes: 29 additions & 0 deletions CloudDevelopment.AppHost/Properties/launchSettings.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
{
"$schema": "https://json.schemastore.org/launchsettings.json",
"profiles": {
"https": {
"commandName": "Project",
"dotnetRunMessages": true,
"launchBrowser": true,
"applicationUrl": "https://localhost:17129;http://localhost:15221",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development",
"DOTNET_ENVIRONMENT": "Development",
"ASPIRE_DASHBOARD_OTLP_ENDPOINT_URL": "https://localhost:21101",
"ASPIRE_RESOURCE_SERVICE_ENDPOINT_URL": "https://localhost:22255"
}
},
"http": {
"commandName": "Project",
"dotnetRunMessages": true,
"launchBrowser": true,
"applicationUrl": "http://localhost:15221",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development",
"DOTNET_ENVIRONMENT": "Development",
"ASPIRE_DASHBOARD_OTLP_ENDPOINT_URL": "http://localhost:19083",
"ASPIRE_RESOURCE_SERVICE_ENDPOINT_URL": "http://localhost:20274"
}
}
}
}
8 changes: 8 additions & 0 deletions CloudDevelopment.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"
}
}
}
9 changes: 9 additions & 0 deletions CloudDevelopment.AppHost/appsettings.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning",
"Aspire.Hosting.Dcp": "Warning"
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
<Project Sdk="Microsoft.NET.Sdk">

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

<ItemGroup>
<FrameworkReference Include="Microsoft.AspNetCore.App" />

<PackageReference Include="Microsoft.Extensions.Http.Resilience" Version="9.9.0" />
<PackageReference Include="Microsoft.Extensions.ServiceDiscovery" Version="9.5.0" />
<PackageReference Include="OpenTelemetry.Exporter.OpenTelemetryProtocol" Version="1.9.0" />
<PackageReference Include="OpenTelemetry.Extensions.Hosting" Version="1.9.0" />
<PackageReference Include="OpenTelemetry.Instrumentation.AspNetCore" Version="1.9.0" />
<PackageReference Include="OpenTelemetry.Instrumentation.Http" Version="1.9.0" />
<PackageReference Include="OpenTelemetry.Instrumentation.Runtime" Version="1.9.0" />
</ItemGroup>

</Project>
128 changes: 128 additions & 0 deletions CloudDevelopment.ServiceDefaults/Extensions.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,128 @@
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Diagnostics.HealthChecks;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Diagnostics.HealthChecks;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.ServiceDiscovery;
using OpenTelemetry;
using OpenTelemetry.Metrics;
using OpenTelemetry.Trace;

namespace CloudDevelopment.ServiceDefaults;

// 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<TBuilder>(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<ServiceDiscoveryOptions>(options =>
// {
// options.AllowedSchemes = ["https"];
// });

return builder;
}

public static TBuilder ConfigureOpenTelemetry<TBuilder>(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<TBuilder>(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<TBuilder>(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;
}
}
18 changes: 18 additions & 0 deletions CloudDevelopment.sln
Original file line number Diff line number Diff line change
Expand Up @@ -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}") = "Generator", "Generator\Generator.csproj", "{5F162047-71C4-A730-10F2-8456E4D1F966}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CloudDevelopment.AppHost", "CloudDevelopment.AppHost\CloudDevelopment.AppHost.csproj", "{359B77C3-1D6B-4E58-A926-C907812424A8}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CloudDevelopment.ServiceDefaults", "CloudDevelopment.ServiceDefaults\CloudDevelopment.ServiceDefaults.csproj", "{DC017A15-5E73-C618-2A78-CD0D64478DC9}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Expand All @@ -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
{5F162047-71C4-A730-10F2-8456E4D1F966}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{5F162047-71C4-A730-10F2-8456E4D1F966}.Debug|Any CPU.Build.0 = Debug|Any CPU
{5F162047-71C4-A730-10F2-8456E4D1F966}.Release|Any CPU.ActiveCfg = Release|Any CPU
{5F162047-71C4-A730-10F2-8456E4D1F966}.Release|Any CPU.Build.0 = Release|Any CPU
{359B77C3-1D6B-4E58-A926-C907812424A8}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{359B77C3-1D6B-4E58-A926-C907812424A8}.Debug|Any CPU.Build.0 = Debug|Any CPU
{359B77C3-1D6B-4E58-A926-C907812424A8}.Release|Any CPU.ActiveCfg = Release|Any CPU
{359B77C3-1D6B-4E58-A926-C907812424A8}.Release|Any CPU.Build.0 = Release|Any CPU
{DC017A15-5E73-C618-2A78-CD0D64478DC9}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{DC017A15-5E73-C618-2A78-CD0D64478DC9}.Debug|Any CPU.Build.0 = Debug|Any CPU
{DC017A15-5E73-C618-2A78-CD0D64478DC9}.Release|Any CPU.ActiveCfg = Release|Any CPU
{DC017A15-5E73-C618-2A78-CD0D64478DC9}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
Expand Down
32 changes: 32 additions & 0 deletions Generator/Controllers/CreditOrderController.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
using Generator.Dto;
using Generator.Services;
using Microsoft.AspNetCore.Mvc;

namespace Generator.Controllers;


[ApiController]
[Route("credit-orders")]
public sealed class CreditOrderController : ControllerBase
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Это уважаемо, что ты вспомнил про sealed классы, только стратегии я бы выделил две по их использованию:

  • кидать sealed на все подряд, кроме тех сущностей, которые ты явно разрешаешь пользователям твоей библиотеки/апи расширять,
  • не кидать sealed ни на что, потому что код не будет находиться в открытом доступе в принципе.

У тебя как будто по отношению к sealed какие-то полумеры, потому что в коде он встречается ровно два раза.

{
private readonly ILogger<CreditOrderController> _logger;
private readonly CreditOrderService _service;

public CreditOrderController(CreditOrderService service, ILogger<CreditOrderController> logger)
{
_service = service;
_logger = logger;
}
Comment on lines +12 to +19
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Использовать праймари конструктор


[HttpGet]
public async Task<ActionResult<CreditOrderDto>> Get([FromQuery] int id, CancellationToken ct)
{
_logger.LogInformation("HTTP GET /credit-orders requested: {OrderId}", id);

var order = await _service.GetByIdAsync(id, ct);

_logger.LogInformation("HTTP GET /credit-orders completed: {OrderId} {Status}", order.Id, order.OrderStatus);

return Ok(order);
Comment on lines +24 to +30
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Это тело метода могло бы быть в два раза меньше строк кода занимать, но оно дырявое как сыр. Хз, зачем это нужно. Чтобы число строк в pr казалось солиднее?

}
}
15 changes: 15 additions & 0 deletions Generator/Dto/CreditOrderDto.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
namespace Generator.Dto;

public class CreditOrderDto
{
public int Id { get; set; }
public string CreditType { get; set; } = "";
public decimal RequestedSum { get; set; }
public int MonthsDuration { get; set; }
public double InterestRate { get; set; }
public DateOnly FilingDate { get; set; }
public bool IsInsuranceNeeded { get; set; }
public string OrderStatus { get; set; } = "";
public DateOnly? DecisionDate { get; set; }
public decimal? ApprovedSum { get; set; }
}
Comment on lines +3 to +15
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Здесь и далее по коду - саммари к классам/методам/пропертям все еще нужны

19 changes: 19 additions & 0 deletions Generator/Generator.csproj
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
<Project Sdk="Microsoft.NET.Sdk.Web">

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

<ItemGroup>
<PackageReference Include="Bogus" Version="35.6.5" />
<PackageReference Include="Microsoft.Extensions.Caching.StackExchangeRedis" Version="10.0.3" />
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Нужно юзать аспаеровский нугет пакет
У тебя нет телеметрии для клиента редиса. Вот, например твой трейс:
Image
А вот трейс для проекта, в котором используется Aspire.StackExchange.Redis.DistributedCaching
Image

<PackageReference Include="Swashbuckle.AspNetCore" Version="6.6.2" />
</ItemGroup>

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

</Project>
6 changes: 6 additions & 0 deletions Generator/Generator.http
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
@Generator_HostAddress = http://localhost:5291

GET {{Generator_HostAddress}}/weatherforecast/
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Какой такой weatherforecast?

Accept: application/json

###
Loading