Tworzysz aplikację .NET 6. Napisz pełną implementację controller, service oraz…
- User
Tworzysz aplikację .NET 6. Napisz pełną implementację controller, service oraz wszystkich koniecznych do ich działania klas dla klasy FiscalPrinterPosnet. Wzoruj się przy tym na plikach NfzContractController.cs oraz OccupationalFactorService.cs. Wygeneruj pełną treść plików.
/// FiscalPrinterPosnet.cs
using Abp.Domain.Entities.Auditing; using Abp.Organizations; using Abp.Domain.Entities; using Medica.Helpers.Database; using System;
namespace Medica.OrganizationUnits;
public class FiscalPrinterPosnet : FullAuditedEntity, IMustHaveOrganizationUnit, IMustHaveTenant, INamedEntity, IPassivable { public string Name { get; set; }
public string Model { get; set; } public string IpAddress { get; set; } public string Port { get; set; } public bool IsActive { get; set; } public int TenantId { get; set; } public long OrganizationUnitId { get; set; } public virtual MedicaOrganizationUnit OrganizationUnit { get; set; }}
/// NfzContractController.cs
#nullable enable
using System; using System.Threading.Tasks; using System.Xml; using Abp.Application.Services.Dto; using Abp.AspNetCore.Mvc.Controllers; using Abp.Auditing; using Abp.Authorization; using Medica.Authorization; using Medica.Extensions; using Medica.Nfz.Contract; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc;
namespace Medica.Nfz;
[AbpAuthorize(PermissionNames.NfzContracts_Manage, PermissionNames.NfzContracts_View)] [Controller] [Route("api/services/app/[controller]")] public class NfzContractController : AbpController { private readonly INfzContractService _nfzContractService;
public NfzContractController(INfzContractService nfzContractService) { _nfzContractService = nfzContractService; } [DisableAuditing] [HttpPost(nameof(Search))] public Task<PagedResultDto<NfzContractDto>> Search([FromBody] NfzContractQueryDto dto) => _nfzContractService.SearchAsync(dto.ToEntity()).MapPagedAsync(NfzContractConverters.ToNfzContractDto); [AbpAuthorize(PermissionNames.NfzContracts_Manage)] [HttpPut("{id:guid}")] public Task<NfzContractDto> Update([FromRoute] Guid id, [FromBody]NfzContractDto dto) { if (dto.Id != id) throw new Exception("Id mismatch"); return _nfzContractService.UpdateAsync(NfzContractConverters.ToNfzContract(dto)) .MapDtoAsync(NfzContractConverters.ToNfzContractDto); } [AbpAuthorize(PermissionNames.NfzContracts_Manage)] [HttpDelete("{id:guid}")] public Task DeleteFactorAsync([FromRoute] Guid id) => _nfzContractService.DeleteAsync(id).OrThrow(); [HttpGet("{id:guid}")] public Task<NfzContractDto> GetAsync(Guid id) => _nfzContractService.GetAsync(id) .MapDtoAsync(NfzContractConverters.ToNfzContractDto); [AbpAuthorize(PermissionNames.NfzContracts_Manage)] [HttpPost] public async Task<NfzContractDto> Import(IFormCollection form) { var description = form["description"]; if (form.Files?.FirstIfSingle() is not {} singleFile) throw new ArgumentException($"Expected single file. Found: {form.Files?.Count}"); var xmlDoc = new XmlDocument(); await using var stream = singleFile.OpenReadStream(); xmlDoc.Load(stream); var importData = new NfzContractImportData(xmlDoc) { Description = description }; var entity = await _nfzContractService.ImportAsync(importData).OrThrow(); return NfzContractConverters.ToNfzContractDto(entity); }}
/// OccupationalFactorService.cs
using System; using System.Linq; using System.Threading.Tasks; using Medica.Commerce.OccupationalMedicine.Repository; using Medica.Extensions; using Medica.Helpers.Services;
namespace Medica.Commerce.OccupationalMedicine;
public class OccupationalFactorService : CrudService<Guid, OccupationalFactor, OccupationalFactorQuery>, IOccupationalFactorService { private readonly IOccupationalFactorDbAdapter _occupationalFactorDbAdapter;
public OccupationalFactorService(IOccupationalFactorDbAdapter dbAdapter) : base(dbAdapter) { _occupationalFactorDbAdapter = dbAdapter; } protected override void UpdateStaticFields(OccupationalFactor target, OccupationalFactor source) { target.Name = source.Name; target.Type = source.Type; target.Options = source.Options; target.SurveyName = source.SurveyName; target.StatementValiditySetup = source.StatementValiditySetup; } protected override Task<Either> ValidateDeleteRequest(Guid id) { return _occupationalFactorDbAdapter.GetWithSets(id).FlatMapAsync(entity => { if (entity.Sets is not { Count: > 0 } sets) return Either.SuccessTask(); return Either.UserFriendlyErrorTask($"Occupational factor is still assigned to sets: {sets.Select(v => v.Id).JoinAsStringWithLimit()}", $"Czynnik jest nadal przypisany do zbiorów: {sets.Select(v => v.Name).JoinAsStringWithLimit()}"); }); }}
/// IOccupationalFactorService.cs
using System; using Medica.Commerce.OccupationalMedicine.Repository; using Medica.Helpers.Services;
namespace Medica.Commerce.OccupationalMedicine;
public interface IOccupationalFactorService : ICrudService<Guid, OccupationalFactor, OccupationalFactorQuery> {
}
- Assistant
Oto pełna implementacja kontrolera, serwisu oraz wszystkich niezbędnych klas dla klasy
FiscalPrinterPosnetw aplikacji .NET 6. Implementacja została wzorowana na plikachNfzContractController.csorazOccupationalFactorService.cs.1.
FiscalPrinterPosnetController.cs#nullable enable using System; using System.Threading.Tasks; using System.Xml; using Abp.Application.Services.Dto; using Abp.AspNetCore.Mvc.Controllers; using Abp.Auditing; using Abp.Authorization; using Medica.Authorization; using Medica.Extensions; using Medica.OrganizationUnits; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; namespace Medica.OrganizationUnits { [AbpAuthorize(PermissionNames.FiscalPrinters_Manage, PermissionNames.FiscalPrinters_View)] [Controller] [Route("api/services/app/[controller]")] public class FiscalPrinterPosnetController : AbpController { private readonly IFiscalPrinterPosnetService _fiscalPrinterPosnetService; public FiscalPrinterPosnetController(IFiscalPrinterPosnetService fiscalPrinterPosnetService) { _fiscalPrinterPosnetService = fiscalPrinterPosnetService; } [DisableAuditing] [HttpPost(nameof(Search))] public Task<PagedResultDto<FiscalPrinterPosnetDto>> Search([FromBody] FiscalPrinterPosnetQueryDto dto) => _fiscalPrinterPosnetService.SearchAsync(dto.ToEntity()).MapPagedAsync(FiscalPrinterPosnetConverters.ToFiscalPrinterPosnetDto); [AbpAuthorize(PermissionNames.FiscalPrinters_Manage)] [HttpPut("{id:guid}")] public Task<FiscalPrinterPosnetDto> Update([FromRoute] Guid id, [FromBody] FiscalPrinterPosnetDto dto) { if (dto.Id != id) throw new Exception("Id mismatch"); return _fiscalPrinterPosnetService.UpdateAsync(FiscalPrinterPosnetConverters.ToFiscalPrinterPosnet(dto)) .MapDtoAsync(FiscalPrinterPosnetConverters.ToFiscalPrinterPosnetDto); } [AbpAuthorize(PermissionNames.FiscalPrinters_Manage)] [HttpDelete("{id:guid}")] public Task DeleteAsync([FromRoute] Guid id) => _fiscalPrinterPosnetService.DeleteAsync(id).OrThrow(); [HttpGet("{id:guid}")] public Task<FiscalPrinterPosnetDto> GetAsync(Guid id) => _fiscalPrinterPosnetService.GetAsync(id) .MapDtoAsync(FiscalPrinterPosnetConverters.ToFiscalPrinterPosnetDto); [AbpAuthorize(PermissionNames.FiscalPrinters_Manage)] [HttpPost] public async Task<FiscalPrinterPosnetDto> Import(IFormCollection form) { var description = form["description"]; if (form.Files?.FirstIfSingle() is not {} singleFile) throw new ArgumentException($"Expected single file. Found: {form.Files?.Count}"); var xmlDoc = new XmlDocument(); await using var stream = singleFile.OpenReadStream(); xmlDoc.Load(stream); var importData = new FiscalPrinterPosnetImportData(xmlDoc) { Description = description }; var entity = await _fiscalPrinterPosnetService.ImportAsync(importData).OrThrow(); return FiscalPrinterPosnetConverters.ToFiscalPrinterPosnetDto(entity); } } }2.
IFiscalPrinterPosnetService.csusing System; using Medica.OrganizationUnits.Repository; using Medica.Helpers.Services; namespace Medica.OrganizationUnits { public interface IFiscalPrinterPosnetService : ICrudService<Guid, FiscalPrinterPosnet, FiscalPrinterPosnetQuery> { } }3.
FiscalPrinterPosnetService.csusing System; using System.Linq; using System.Threading.Tasks; using Medica.OrganizationUnits.Repository; using Medica.Extensions; using Medica.Helpers.Services; namespace Medica.OrganizationUnits { public class FiscalPrinterPosnetService : CrudService<Guid, FiscalPrinterPosnet, FiscalPrinterPosnetQuery>, IFiscalPrinterPosnetService { private readonly IFiscalPrinterPosnetDbAdapter _fiscalPrinterPosnetDbAdapter; public FiscalPrinterPosnetService(IFiscalPrinterPosnetDbAdapter dbAdapter) : base(dbAdapter) { _fiscalPrinterPosnetDbAdapter = dbAdapter; } protected override void UpdateStaticFields(FiscalPrinterPosnet target, FiscalPrinterPosnet source) { target.Name = source.Name; target.Model = source.Model; target.IpAddress = source.IpAddress; target.Port = source.Port; target.IsActive = source.IsActive; target.OrganizationUnitId = source.OrganizationUnitId; target.TenantId = source.TenantId; } protected override Task<Either> ValidateDeleteRequest(Guid id) { return _fiscalPrinterPosnetDbAdapter.GetWithDependencies(id).FlatMapAsync(entity => { // Przykładowa walidacja - dostosuj do rzeczywistych zależności if (!entity.IsActive) return Either.SuccessTask(); return Either.UserFriendlyErrorTask("Cannot delete an active Fiscal Printer.", "Nie można usunąć aktywnego drukarki fiskalnej."); }); } } }4.
FiscalPrinterPosnetDto.csusing System; using Abp.Application.Services.Dto; namespace Medica.OrganizationUnits { public class FiscalPrinterPosnetDto : EntityDto<Guid> { public string Name { get; set; } public string Model { get; set; } public string IpAddress { get; set; } public string Port { get; set; } public bool IsActive { get; set; } public int TenantId { get; set; } public long OrganizationUnitId { get; set; } public string OrganizationUnitName { get; set; } } }5.
FiscalPrinterPosnetQueryDto.csusing Medica.Helpers.Services; namespace Medica.OrganizationUnits { public class FiscalPrinterPosnetQueryDto : QueryDto<FiscalPrinterPosnetQuery> { public string? Name { get; set; } public string? Model { get; set; } public string? IpAddress { get; set; } public bool? IsActive { get; set; } public int? TenantId { get; set; } } }6.
FiscalPrinterPosnetConverters.csusing System; using System.Linq; using Medica.Extensions; namespace Medica.OrganizationUnits { public static class FiscalPrinterPosnetConverters { public static FiscalPrinterPosnetDto ToFiscalPrinterPosnetDto(this FiscalPrinterPosnet entity) { if (entity == null) return null; return new FiscalPrinterPosnetDto { Id = entity.Id, Name = entity.Name, Model = entity.Model, IpAddress = entity.IpAddress, Port = entity.Port, IsActive = entity.IsActive, TenantId = entity.TenantId, OrganizationUnitId = entity.OrganizationUnitId, OrganizationUnitName = entity.OrganizationUnit?.Name }; } public static FiscalPrinterPosnet ToFiscalPrinterPosnet(this FiscalPrinterPosnetDto dto) { if (dto == null) return null; return new FiscalPrinterPosnet { Id = dto.Id != Guid.Empty ? dto.Id : Guid.NewGuid(), Name = dto.Name, Model = dto.Model, IpAddress = dto.IpAddress, Port = dto.Port, IsActive = dto.IsActive, TenantId = dto.TenantId, OrganizationUnitId = dto.OrganizationUnitId }; } public static FiscalPrinterPosnetQuery ToEntity(this FiscalPrinterPosnetQueryDto dto) { if (dto == null) return new FiscalPrinterPosnetQuery(); return new FiscalPrinterPosnetQuery { Name = dto.Name, Model = dto.Model, IpAddress = dto.IpAddress, IsActive = dto.IsActive, TenantId = dto.TenantId }; } } }7.
FiscalPrinterPosnetQuery.csusing Medica.Helpers.Services; namespace Medica.OrganizationUnits { public class FiscalPrinterPosnetQuery : Query { public string? Name { get; set; } public string? Model { get; set; } public string? IpAddress { get; set; } public bool? IsActive { get; set; } public int? TenantId { get; set; } } }8.
IFiscalPrinterPosnetDbAdapter.csusing System; using System.Threading.Tasks; using Medica.Helpers.Database; namespace Medica.OrganizationUnits.Repository { public interface IFiscalPrinterPosnetDbAdapter : ICrudDbAdapter<FiscalPrinterPosnet, FiscalPrinterPosnetQuery> { Task<FiscalPrinterPosnet> GetWithDependencies(Guid id); } }9.
FiscalPrinterPosnetDbAdapter.csusing System; using System.Linq; using System.Threading.Tasks; using Abp.Domain.Repositories; using Microsoft.EntityFrameworkCore; namespace Medica.OrganizationUnits.Repository { public class FiscalPrinterPosnetDbAdapter : CrudDbAdapter<FiscalPrinterPosnet, FiscalPrinterPosnetQuery>, IFiscalPrinterPosnetDbAdapter { private readonly IRepository<FiscalPrinterPosnet, Guid> _repository; public FiscalPrinterPosnetDbAdapter(IRepository<FiscalPrinterPosnet, Guid> repository) : base(repository) { _repository = repository; } public async Task<FiscalPrinterPosnet> GetWithDependencies(Guid id) { return await _repository.GetAll() .Include(fp => fp.OrganizationUnit) .FirstOrDefaultAsync(fp => fp.Id == id); } protected override IQueryable<FiscalPrinterPosnet> ApplyFilters(IQueryable<FiscalPrinterPosnet> query, FiscalPrinterPosnetQuery filter) { if (!string.IsNullOrEmpty(filter.Name)) query = query.Where(fp => fp.Name.Contains(filter.Name)); if (!string.IsNullOrEmpty(filter.Model)) query = query.Where(fp => fp.Model.Contains(filter.Model)); if (!string.IsNullOrEmpty(filter.IpAddress)) query = query.Where(fp => fp.IpAddress.Contains(filter.IpAddress)); if (filter.IsActive.HasValue) query = query.Where(fp => fp.IsActive == filter.IsActive.Value); if (filter.TenantId.HasValue) query = query.Where(fp => fp.TenantId == filter.TenantId.Value); return query; } } }10.
FiscalPrinterPosnetImportData.csusing System.Xml; namespace Medica.OrganizationUnits { public class FiscalPrinterPosnetImportData { public XmlDocument XmlDocument { get; set; } public string Description { get; set; } } }11.
PermissionNames.csZakładam, że posiadasz plik
PermissionNames.cs, w którym definiujesz nazwy uprawnień. Dodaj odpowiednie uprawnienia dlaFiscalPrinterPosnet.namespace Medica.Authorization { public static class PermissionNames { // NFZ Contracts Permissions public const string NfzContracts_Manage = "Permissions.NfzContracts.Manage"; public const string NfzContracts_View = "Permissions.NfzContracts.View"; // Fiscal Printers Permissions public const string FiscalPrinters_Manage = "Permissions.FiscalPrinters.Manage"; public const string FiscalPrinters_View = "Permissions.FiscalPrinters.View"; } }12.
Startup.cslubProgram.csUpewnij się, że zarejestrowałeś wszystkie nowe serwisy w kontenerze DI. Przykład dla
Startup.cs:public class Startup { public void ConfigureServices(IServiceCollection services) { // Inne rejestracje serwisów... services.AddTransient<IFiscalPrinterPosnetService, FiscalPrinterPosnetService>(); services.AddTransient<IFiscalPrinterPosnetDbAdapter, FiscalPrinterPosnetDbAdapter>(); // Rejestracja repozytorium, jeśli jeszcze nie jest zarejestrowane services.AddAbpDbContext<YourDbContext>(options => { options.AddRepository<FiscalPrinterPosnet, Repository<FiscalPrinterPosnet, Guid>>(); }); // Inne konfiguracje... } // ... }Wyjaśnienia:
-
Kontroler (
FiscalPrinterPosnetController.cs): Obsługuje żądania HTTP związane zFiscalPrinterPosnet, takie jak wyszukiwanie, aktualizacja, usuwanie, pobieranie pojedynczego rekordu oraz import danych z pliku XML. -
Serwis (
FiscalPrinterPosnetService.cs): Implementuje logikę biznesową dlaFiscalPrinterPosnet, korzystając z bazowej klasyCrudService. Zawiera metody do aktualizacji pól oraz walidacji przed usunięciem rekordu. -
Interfejs Serwisu (
IFiscalPrinterPosnetService.cs): Definiuje kontrakt dla serwisuFiscalPrinterPosnet. -
DTO (
FiscalPrinterPosnetDto.cs): Definiuje dane transferowe dlaFiscalPrinterPosnet. Możesz dostosować właściwości w zależności od potrzeb. -
DTO zapytania (
FiscalPrinterPosnetQueryDto.cs): Definiuje kryteria wyszukiwania dlaFiscalPrinterPosnet. -
Konwertery (
FiscalPrinterPosnetConverters.cs): Zawiera metody konwertujące między encją a DTO oraz odwrotnie. -
Zapytanie (
FiscalPrinterPosnetQuery.cs): Reprezentuje kryteria wyszukiwania używane w serwisie. -
Adapter bazy danych (
IFiscalPrinterPosnetDbAdapter.csiFiscalPrinterPosnetDbAdapter.cs): Abstrakcyjny interfejs oraz implementacja adaptera bazy danych dlaFiscalPrinterPosnet. Umożliwia to separację logiki dostępu do danych od reszty aplikacji. -
Import Danych (
FiscalPrinterPosnetImportData.cs): Definiuje strukturę danych potrzebnych do importu danychFiscalPrinterPosnetz pliku XML. -
Uprawnienia (
PermissionNames.cs): Definiuje uprawnienia związane z zarządzaniem i przeglądaniemFiscalPrinterPosnet. -
Rejestracja Serwisów: Upewnij się, że wszystkie nowe serwisy i adaptery są zarejestrowane w kontenerze DI, aby mogły być wstrzykiwane tam, gdzie są potrzebne.
Dodatkowe Uwagi:
-
Mapowanie: Zakładam, że posiadasz metody rozszerzające takie jak
MapPagedAsynciMapDtoAsync. Upewnij się, że są one zdefiniowane w Twoim projekcie, podobnie jak w przykładzieNfzContractController. -
Uprawnienia: Upewnij się, że odpowiednie uprawnienia (
Permissions.FiscalPrinters.ManageiPermissions.FiscalPrinters.View) są zdefiniowane i przydzielone odpowiednim użytkownikom w systemie. -
Importując Danych: Klasa
FiscalPrinterPosnetImportDatajest przykładowa. Dostosuj jej strukturę oraz logikę importu danych do swoich potrzeb. -
Walidacja: W metodzie
ValidateDeleteRequestw serwisie możesz dostosować logikę walidacji przed usunięciem rekordu, na przykład sprawdzając zależności lub inne warunki biznesowe. -
Repository Pattern: Jeśli używasz wzorca repository, upewnij się, że masz odpowiednie repozytoria dla
FiscalPrinterPosnet. W powyższym przykładzie użytoIRepository<FiscalPrinterPosnet, Guid>.
Implementując te pliki, powinieneś mieć pełną funkcjonalność CRUD dla klasy
FiscalPrinterPosnetw swojej aplikacji .NET 6, zgodnie z przykładami, które dostarczyłeś. -