-
Notifications
You must be signed in to change notification settings - Fork 52
Абанин Иван Лаб. 1 Группа 6512 #56
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Closed
Closed
Changes from 1 commit
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,13 +1,17 @@ | ||
| <Card> | ||
| <CardHeader> | ||
| <Heading Size="HeadingSize.Is5"><Icon Name="IconName.User" /> Лабораторная работа</Heading> | ||
| <Heading Size="HeadingSize.Is5"> | ||
| <Icon Name="IconName.User" /> Лабораторная работа | ||
| </Heading> | ||
| </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>№19 "Объект жилого строительства"</Strong></UnorderedListItem> | ||
| <UnorderedListItem>Выполнена <Strong>Абаниным Иваном 6512</Strong> </UnorderedListItem> | ||
| <UnorderedListItem> | ||
| <Link To="https://github.com/UselessMiva/cloud-development">Ссылка на форк</Link> | ||
| </UnorderedListItem> | ||
| </UnorderedList> | ||
| </CardBody> | ||
| </Card> | ||
| </Card> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -6,5 +6,6 @@ | |
| } | ||
| }, | ||
| "AllowedHosts": "*", | ||
| "BaseAddress": "" | ||
|
|
||
| "BaseAddress": "https://localhost:7159/api/ResidentialProperty" | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
28 changes: 28 additions & 0 deletions
28
ResidentialProperty.Api/Controllers/ResidentialPropertyController.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,28 @@ | ||
| using ResidentialProperty.Api.Services.ResidentialPropertyGeneratorService; | ||
| using ResidentialProperty.Domain.Entities; | ||
| using Microsoft.AspNetCore.Mvc; | ||
|
|
||
| namespace ResidentialProperty.Api.Controllers; | ||
|
|
||
| [Route("api/[controller]")] | ||
| [ApiController] | ||
| public class ResidentialPropertyController( | ||
| IResidentialPropertyGeneratorService generatorService, | ||
| ILogger<ResidentialPropertyController> logger) : ControllerBase | ||
| { | ||
| /// <summary> | ||
| /// Получить объект жилого строительства по ID, если не найден в кэше — сгенерировать новый | ||
| /// </summary> | ||
| /// <param name="id">ID объекта</param> | ||
| /// <param name="cancellationToken">Токен отмены операции</param> | ||
| /// <returns>Объект жилого строительства</returns> | ||
| [HttpGet] | ||
| public async Task<ActionResult<ResidentialPropertyEntity>> GetById([FromQuery] int id, CancellationToken cancellationToken) | ||
| { | ||
| logger.LogInformation("Received request to retrieve/generate property {Id}", id); | ||
|
|
||
| var property = await generatorService.GetByIdAsync(id, cancellationToken); | ||
|
|
||
| return Ok(property); | ||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,63 @@ | ||
| using ResidentialProperty.Api.Services.ResidentialPropertyGeneratorService; | ||
| using ResidentialProperty.ServiceDefaults; | ||
|
|
||
| var builder = WebApplication.CreateBuilder(args); | ||
|
|
||
| builder.AddServiceDefaults(); | ||
| builder.AddRedisDistributedCache("redis"); | ||
|
|
||
| builder.Services.AddCors(options => | ||
| { | ||
| options.AddDefaultPolicy(policy => | ||
| { | ||
| policy.SetIsOriginAllowed(origin => | ||
| new Uri(origin).Host == "localhost") | ||
| .WithMethods("GET") | ||
| .WithHeaders("Content-Type") | ||
| .AllowCredentials(); | ||
| }); | ||
| }); | ||
|
|
||
| // Регистрация сервисов | ||
| builder.Services.AddSingleton<ResidentialPropertyGenerator>(); | ||
| builder.Services.AddScoped<IResidentialPropertyGeneratorService, ResidentialPropertyGeneratorService>(); | ||
|
|
||
| builder.Services.AddControllers(); | ||
| builder.Services.AddEndpointsApiExplorer(); | ||
| builder.Services.AddSwaggerGen(options => | ||
| { | ||
| options.SwaggerDoc("v1", new Microsoft.OpenApi.OpenApiInfo | ||
| { | ||
| Title = "Residential Property Generator API", | ||
| Description = "API для генерации объектов жилого строительства", | ||
| Version = "v1" | ||
| }); | ||
|
|
||
| var xmlFilename = $"{System.Reflection.Assembly.GetExecutingAssembly().GetName().Name}.xml"; | ||
| var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFilename); | ||
| if (File.Exists(xmlPath)) | ||
| { | ||
| options.IncludeXmlComments(xmlPath); | ||
| } | ||
|
|
||
| var domainXmlPath = Path.Combine(AppContext.BaseDirectory, "ResidentialProperty.Domain.xml"); | ||
| if (File.Exists(domainXmlPath)) | ||
| { | ||
| options.IncludeXmlComments(domainXmlPath); | ||
| } | ||
| }); | ||
|
|
||
| var app = builder.Build(); | ||
|
|
||
| if (app.Environment.IsDevelopment()) | ||
| { | ||
| app.UseSwagger(); | ||
| app.UseSwaggerUI(); | ||
| } | ||
|
|
||
| app.UseHttpsRedirection(); | ||
| app.UseCors(); | ||
| app.MapControllers(); | ||
| app.MapDefaultEndpoints(); | ||
|
|
||
| app.Run(); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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:32342", | ||
| "sslPort": 44362 | ||
| } | ||
| }, | ||
| "profiles": { | ||
| "http": { | ||
| "commandName": "Project", | ||
| "dotnetRunMessages": true, | ||
| "launchBrowser": true, | ||
| "launchUrl": "swagger", | ||
| "applicationUrl": "http://localhost:5187", | ||
| "environmentVariables": { | ||
| "ASPNETCORE_ENVIRONMENT": "Development" | ||
| } | ||
| }, | ||
| "https": { | ||
| "commandName": "Project", | ||
| "dotnetRunMessages": true, | ||
| "launchBrowser": true, | ||
| "launchUrl": "swagger", | ||
| "applicationUrl": "https://localhost:7159;http://localhost:5187", | ||
| "environmentVariables": { | ||
| "ASPNETCORE_ENVIRONMENT": "Development" | ||
| } | ||
| }, | ||
| "IIS Express": { | ||
| "commandName": "IISExpress", | ||
| "launchBrowser": true, | ||
| "launchUrl": "swagger", | ||
| "environmentVariables": { | ||
| "ASPNETCORE_ENVIRONMENT": "Development" | ||
| } | ||
| } | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,23 @@ | ||
| <Project Sdk="Microsoft.NET.Sdk.Web"> | ||
|
|
||
| <PropertyGroup> | ||
| <TargetFramework>net8.0</TargetFramework> | ||
| <Nullable>enable</Nullable> | ||
| <ImplicitUsings>enable</ImplicitUsings> | ||
| <GenerateDocumentationFile>true</GenerateDocumentationFile> | ||
| <NoWarn>$(NoWarn);1591</NoWarn> | ||
| </PropertyGroup> | ||
|
|
||
| <ItemGroup> | ||
| <PackageReference Include="Aspire.StackExchange.Redis.DistributedCaching" Version="9.5.2" /> | ||
| <PackageReference Include="Bogus" Version="35.6.5" /> | ||
| <PackageReference Include="Microsoft.AspNetCore.OpenApi" Version="8.0.24" /> | ||
| <PackageReference Include="Swashbuckle.AspNetCore" Version="10.1.4" /> | ||
| </ItemGroup> | ||
|
|
||
| <ItemGroup> | ||
| <ProjectReference Include="..\ResidentialProperty.Domain\ResidentialProperty.Domain.csproj" /> | ||
| <ProjectReference Include="..\ResidentialProperty.ServiceDefaults\ResidentialProperty.ServiceDefaults.csproj" /> | ||
| </ItemGroup> | ||
|
|
||
| </Project> |
11 changes: 11 additions & 0 deletions
11
....Api/Services/ResidentialPropertyGeneratorService/IResidentialPropertyGeneratorService.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,11 @@ | ||
| using ResidentialProperty.Domain.Entities; | ||
|
|
||
| namespace ResidentialProperty.Api.Services.ResidentialPropertyGeneratorService; | ||
|
|
||
| /// <summary> | ||
| /// Сервис получения объекта жилого строительства | ||
| /// </summary> | ||
| public interface IResidentialPropertyGeneratorService | ||
| { | ||
| public Task<ResidentialPropertyEntity> GetByIdAsync(int id, CancellationToken cancellationToken = default); | ||
| } |
39 changes: 39 additions & 0 deletions
39
...Property.Api/Services/ResidentialPropertyGeneratorService/ResidentialPropertyGenerator.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,39 @@ | ||
| using Bogus; | ||
| using ResidentialProperty.Domain.Entities; | ||
|
|
||
| namespace ResidentialProperty.Api.Services.ResidentialPropertyGeneratorService; | ||
|
|
||
| /// <summary> | ||
| /// Генератор случайных объектов жилого строительства с использованием Bogus | ||
| /// </summary> | ||
| public class ResidentialPropertyGenerator | ||
| { | ||
| private readonly Faker<ResidentialPropertyEntity> _faker; | ||
| private int _idCounter = 1; | ||
|
|
||
| public ResidentialPropertyGenerator() | ||
| { | ||
| var propertyTypes = new[] { "Квартира", "ИЖС", "Апартаменты", "Офис", "Коммерческая" }; | ||
|
Gwymlas marked this conversation as resolved.
Outdated
|
||
| var currentYear = DateTime.Now.Year; | ||
|
Gwymlas marked this conversation as resolved.
Outdated
|
||
|
|
||
| _faker = new Faker<ResidentialPropertyEntity>("ru") | ||
| .RuleFor(p => p.Id, f => _idCounter++) | ||
| .RuleFor(p => p.Address, f => $"{f.Address.City()}, ул. {f.Address.StreetName()}, д. {f.Random.Number(1, 100)}") | ||
| .RuleFor(p => p.PropertyType, f => f.PickRandom(propertyTypes)) | ||
| .RuleFor(p => p.YearBuilt, f => f.Random.Number(1950, currentYear)) | ||
| .RuleFor(p => p.TotalArea, f => Math.Round(f.Random.Double(30, 200), 2)) | ||
| .RuleFor(p => p.LivingArea, (f, p) => Math.Round(p.TotalArea * f.Random.Double(0.5, 0.9), 2)) | ||
| .RuleFor(p => p.TotalFloors, f => f.Random.Number(1, 25)) | ||
| .RuleFor(p => p.Floor, (f, p) => | ||
| p.PropertyType == "ИЖС" ? null : f.Random.Number(1, p.TotalFloors)) | ||
| .RuleFor(p => p.CadastralNumber, f => | ||
| $"{f.Random.Number(1, 99):D2}.{f.Random.Number(1, 99):D2}.{f.Random.Number(1, 99):D2}.{f.Random.Number(1, 999999):D6}.{f.Random.Number(1, 9999):D4}") | ||
|
Gwymlas marked this conversation as resolved.
Outdated
|
||
| .RuleFor(p => p.CadastralValue, (f, p) => | ||
| Math.Round((decimal)(p.TotalArea * f.Random.Double(50000, 150000)), 2)); | ||
| } | ||
|
|
||
| /// <summary> | ||
| /// Генерирует один случайный объект жилого строительства | ||
| /// </summary> | ||
| public ResidentialPropertyEntity Generate() => _faker.Generate(); | ||
| } | ||
92 changes: 92 additions & 0 deletions
92
...y.Api/Services/ResidentialPropertyGeneratorService/ResidentialPropertyGeneratorService.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,92 @@ | ||
| using Microsoft.Extensions.Caching.Distributed; | ||
| using ResidentialProperty.Api.Services.ResidentialPropertyGeneratorService; | ||
|
Gwymlas marked this conversation as resolved.
Outdated
|
||
| using ResidentialProperty.Domain.Entities; | ||
| using System.Text.Json; | ||
|
|
||
| namespace ResidentialProperty.Api.Services.ResidentialPropertyGeneratorService; | ||
|
|
||
| /// <summary> | ||
| /// Сервис получения объекта жилого строительства: сначала ищет в кэше, при промахе — генерирует новый и сохраняет | ||
| /// </summary> | ||
| public class ResidentialPropertyGeneratorService( | ||
|
Gwymlas marked this conversation as resolved.
|
||
| IDistributedCache cache, | ||
| ResidentialPropertyGenerator generator, | ||
| IConfiguration configuration, | ||
| ILogger<ResidentialPropertyGeneratorService> logger) : IResidentialPropertyGeneratorService | ||
| { | ||
| private readonly int _expirationMinutes = configuration.GetValue("CacheSettings:ExpirationMinutes", 10); | ||
|
|
||
| /// <summary> | ||
| /// Возвращает объект жилого строительства по идентификатору. | ||
| /// Если объект найден в кэше — возвращается из него; иначе генерируется, сохраняется в кэш и возвращается. | ||
| /// </summary> | ||
| /// <param name="id">Идентификатор объекта</param> | ||
| /// <param name="cancellationToken">Токен отмены операции</param> | ||
| /// <returns>Объект жилого строительства</returns> | ||
| public async Task<ResidentialPropertyEntity> GetByIdAsync(int id, CancellationToken cancellationToken = default) | ||
| { | ||
| logger.LogInformation("Attempting to retrieve residential property {Id} from cache", id); | ||
|
|
||
| var cacheKey = $"residential-property-{id}"; | ||
|
|
||
| // Получаем объект из кэша | ||
| ResidentialPropertyEntity? property = null; | ||
| try | ||
| { | ||
| var cachedData = await cache.GetStringAsync(cacheKey, cancellationToken); | ||
|
|
||
| if (!string.IsNullOrEmpty(cachedData)) | ||
| { | ||
| property = JsonSerializer.Deserialize<ResidentialPropertyEntity>(cachedData); | ||
|
|
||
| if (property != null) | ||
| { | ||
| logger.LogInformation("Residential property {Id} found in cache", id); | ||
| return property; | ||
| } | ||
|
|
||
| logger.LogWarning("Property {Id} was found in cache but could not be deserialized. Generating a new one", id); | ||
| } | ||
| } | ||
| catch (Exception ex) | ||
| { | ||
| logger.LogWarning(ex, "Failed to retrieve property {Id} from cache (error ignored)", id); | ||
| } | ||
|
|
||
| // Если в кэше нет или ошибка — генерируем новый объект | ||
| logger.LogInformation("Property {Id} not found in cache or cache unavailable, generating a new one", id); | ||
| property = generator.Generate(); | ||
| property.Id = id; | ||
|
|
||
| // Попытка сохранить в кэш | ||
| try | ||
| { | ||
| logger.LogInformation("Saving property {Id} to cache", id); | ||
|
|
||
| var cacheOptions = new DistributedCacheEntryOptions | ||
| { | ||
| AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(_expirationMinutes) | ||
| }; | ||
|
|
||
| await cache.SetStringAsync( | ||
| cacheKey, | ||
| JsonSerializer.Serialize(property), | ||
| cacheOptions, | ||
| cancellationToken); | ||
|
|
||
| logger.LogInformation( | ||
| "Residential property generated and cached: Id={Id}, Address={Address}, Type={PropertyType}, TotalArea={TotalArea}, CadastralValue={CadastralValue}", | ||
| property.Id, | ||
| property.Address, | ||
| property.PropertyType, | ||
| property.TotalArea, | ||
| property.CadastralValue); | ||
| } | ||
| catch (Exception ex) | ||
| { | ||
| logger.LogWarning(ex, "Failed to save property {Id} to cache (error ignored)", id); | ||
| } | ||
|
|
||
| return property; | ||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,8 @@ | ||
| { | ||
| "Logging": { | ||
| "LogLevel": { | ||
| "Default": "Information", | ||
| "Microsoft.AspNetCore": "Warning" | ||
| } | ||
| } | ||
| } |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.