смена public на internal

This commit is contained in:
2025-04-26 11:22:30 +04:00
parent 22b9ea1bc2
commit 3791fac299
34 changed files with 621 additions and 152 deletions

View File

@@ -7,7 +7,7 @@ using System.Threading.Tasks;
namespace MagicCarpetContracts.BuisnessLogicContracts;
public interface IClientBusinessLogicContract
internal interface IClientBusinessLogicContract
{
List<ClientDataModel> GetAllClients();

View File

@@ -7,7 +7,7 @@ using System.Threading.Tasks;
namespace MagicCarpetContracts.BuisnessLogicContracts;
public interface IEmployeeBusinessLogicContract
internal interface IEmployeeBusinessLogicContract
{
List<EmployeeDataModel> GetAllEmployees(bool onlyActive = true);

View File

@@ -7,7 +7,7 @@ using System.Threading.Tasks;
namespace MagicCarpetContracts.BuisnessLogicContracts;
public interface IPostBusinessLogicContract
internal interface IPostBusinessLogicContract
{
List<PostDataModel> GetAllPosts();

View File

@@ -7,7 +7,7 @@ using System.Threading.Tasks;
namespace MagicCarpetContracts.BusinessLogicContracts;
public interface IReportContract
internal interface IReportContract
{
Task<List<TourAndTourHistoryDataModel>> GetDataToursHistoryAsync(CancellationToken ct);
Task<Stream> CreateDocumentToursHistoryAsync(CancellationToken ct);

View File

@@ -7,7 +7,7 @@ using System.Threading.Tasks;
namespace MagicCarpetContracts.BuisnessLogicContracts;
public interface ISalaryBusinessLogicContract
internal interface ISalaryBusinessLogicContract
{
List<SalaryDataModel> GetAllSalariesByPeriod(DateTime fromDate, DateTime toDate);

View File

@@ -7,7 +7,7 @@ using System.Threading.Tasks;
namespace MagicCarpetContracts.BuisnessLogicContracts;
public interface ISaleBusinessLogicContract
internal interface ISaleBusinessLogicContract
{
List<SaleDataModel> GetAllSalesByPeriod(DateTime fromDate, DateTime toDate);

View File

@@ -7,7 +7,7 @@ using System.Threading.Tasks;
namespace MagicCarpetContracts.BuisnessLogicContracts;
public interface ITourBusinessLogicContract
internal interface ITourBusinessLogicContract
{
List<TourDataModel> GetAllTours();

View File

@@ -9,10 +9,12 @@ using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using ValidationException = MagicCarpetContracts.Exceptions.ValidationException;
using MagicCarpetContracts.Resources;
using Microsoft.Extensions.Localization;
namespace MagicCarpetContracts.DataModels;
public class ClientDataModel(string id, string fIO, string phoneNumber, double discountSize) : IValidation
internal class ClientDataModel(string id, string fIO, string phoneNumber, double discountSize) : IValidation
{
public string Id { get; private set; } = id;
@@ -22,21 +24,21 @@ public class ClientDataModel(string id, string fIO, string phoneNumber, double d
public double DiscountSize { get; private set; } = discountSize;
public void Validate()
public void Validate(IStringLocalizer<Messages> localizer)
{
if (Id.IsEmpty())
throw new ValidationException("Field Id is empty");
throw new ValidationException(string.Format(localizer["ValidationExceptionMessageEmptyField"], "Id"));
if (!Id.IsGuid())
throw new ValidationException("The value in the field Id is not a unique identifier");
throw new ValidationException(string.Format(localizer["ValidationExceptionMessageNotAId"], "Id"));
if (FIO.IsEmpty())
throw new ValidationException("Field FIO is empty");
throw new ValidationException(string.Format(localizer["ValidationExceptionMessageEmptyField"], "FIO"));
if (PhoneNumber.IsEmpty())
throw new ValidationException("Field PhoneNumber is empty");
throw new ValidationException(string.Format(localizer["ValidationExceptionMessageEmptyField"], "PhoneNumber"));
if (!Regex.IsMatch(PhoneNumber, @"^((8|\+7)[\- ]?)?(\(?\d{3}\)?[\- ]?)?[\d\- ]{7,10}$"))
throw new ValidationException("Field PhoneNumber is not a phone number");
throw new ValidationException(localizer["ValidationExceptionIncorrectPhoneNumber"]);
}
}

View File

@@ -1,7 +1,9 @@
using MagicCarpetContracts.Exceptions;
using MagicCarpetContracts.Extensions;
using MagicCarpetContracts.Infrastructure;
using MagicCarpetContracts.Resources;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Localization;
using System;
using System.Collections.Generic;
using System.Linq;
@@ -11,7 +13,7 @@ using System.Threading.Tasks;
namespace MagicCarpetContracts.DataModels;
public class EmployeeDataModel(string id, string fio, string email, string postId, DateTime birthDate, DateTime employmentDate, bool isDeleted) : IValidation
internal class EmployeeDataModel(string id, string fio, string email, string postId, DateTime birthDate, DateTime employmentDate, bool isDeleted) : IValidation
{
private readonly PostDataModel? _post;
@@ -40,16 +42,16 @@ public class EmployeeDataModel(string id, string fio, string email, string postI
public EmployeeDataModel(string id, string fio, string email, string postId, DateTime birthDate,
DateTime employmentDate) : this(id, fio, email, postId, birthDate, employmentDate, false) { }
public void Validate()
public void Validate(IStringLocalizer<Messages> localizer)
{
if (Id.IsEmpty())
throw new ValidationException("Field Id is empty");
throw new ValidationException(string.Format(localizer["ValidationExceptionMessageEmptyField"], "Id"));
if (!Id.IsGuid())
throw new ValidationException("The value in the field Id is not a unique identifier");
throw new ValidationException(string.Format(localizer["ValidationExceptionMessageNotAId"], "Id"));
if (FIO.IsEmpty())
throw new ValidationException("Field FIO is empty");
throw new ValidationException(string.Format(localizer["ValidationExceptionMessageEmptyField"], "FIO"));
if (Email.IsEmpty())
throw new ValidationException("Field Email is empty");
@@ -58,18 +60,20 @@ public class EmployeeDataModel(string id, string fio, string email, string postI
throw new ValidationException("Field Email is not a valid email address");
if (PostId.IsEmpty())
throw new ValidationException("Field PostId is empty");
throw new ValidationException(string.Format(localizer["ValidationExceptionMessageEmptyField"], "PostId"));
if (!PostId.IsGuid())
throw new ValidationException("The value in the field PostId is not a unique identifier");
throw new ValidationException(string.Format(localizer["ValidationExceptionMessageNotAId"], "PostId"));
if (BirthDate.Date > DateTime.Now.AddYears(-18).Date)
throw new ValidationException($"Only adults can be hired (BirthDate = {BirthDate.ToShortDateString()})");
throw new ValidationException(string.Format(localizer["ValidationExceptionMessageMinorsBirthDate"], BirthDate.ToShortDateString()));
if (EmploymentDate.Date < BirthDate.Date)
throw new ValidationException("The date of employment cannot be less than the date of birth");
throw new ValidationException(string.Format(localizer["ValidationExceptionMessageEmploymentDateAndBirthDate"],
EmploymentDate.ToShortDateString(), BirthDate.ToShortDateString()));
if ((EmploymentDate - BirthDate).TotalDays / 365 < 18)
throw new ValidationException($"Only adults can be hired (EmploymentDate - {EmploymentDate.ToShortDateString()}, BirthDate - {BirthDate.ToShortDateString()})");
throw new ValidationException(string.Format(localizer["ValidationExceptionMessageMinorsEmploymentDate"],
EmploymentDate.ToShortDateString(), BirthDate.ToShortDateString()));
}
}

View File

@@ -11,10 +11,12 @@ using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using MagicCarpetContracts.Resources;
using Microsoft.Extensions.Localization;
namespace MagicCarpetContracts.DataModels;
public class PostDataModel(string postId, string postName, PostType postType, PostConfiguration configuration) : IValidation
internal class PostDataModel(string postId, string postName, PostType postType, PostConfiguration configuration) : IValidation
{
public string Id { get; private set; } = postId;
public string PostName { get; private set; } = postName;
@@ -35,19 +37,24 @@ public class PostDataModel(string postId, string postName, PostType postType, Po
}
}
public void Validate()
public void Validate(IStringLocalizer<Messages> localizer)
{
if (Id.IsEmpty())
throw new ValidationException("Field Id is empty");
throw new ValidationException(string.Format(localizer["ValidationExceptionMessageEmptyField"], "Id"));
if (!Id.IsGuid())
throw new ValidationException("The value in the field Id is not a unique identifier");
throw new ValidationException(string.Format(localizer["ValidationExceptionMessageNotAId"], "Id"));
if (PostName.IsEmpty())
throw new ValidationException("Field PostName is empty");
throw new ValidationException(string.Format(localizer["ValidationExceptionMessageEmptyField"], "PostName"));
if (PostType == PostType.None)
throw new ValidationException("Field PostType is empty");
throw new ValidationException(string.Format(localizer["ValidationExceptionMessageEmptyField"], "PostType"));
if (ConfigurationModel is null)
throw new ValidationException("Field ConfigurationModel is not initialized");
throw new ValidationException(string.Format(localizer["ValidationExceptionMessageNotInitialized"], "ConfigurationModel"));
if (ConfigurationModel!.Rate <= 0)
throw new ValidationException("Field Rate is less or equal zero");
throw new ValidationException(string.Format(localizer["ValidationExceptionMessageLessOrEqualZero"], "Rate"));
}
}

View File

@@ -1,6 +1,8 @@
using MagicCarpetContracts.Exceptions;
using MagicCarpetContracts.Extensions;
using MagicCarpetContracts.Infrastructure;
using MagicCarpetContracts.Resources;
using Microsoft.Extensions.Localization;
using System;
using System.Collections.Generic;
using System.Linq;
@@ -9,7 +11,7 @@ using System.Threading.Tasks;
namespace MagicCarpetContracts.DataModels;
public class SalaryDataModel(string employeeId, DateTime salaryDate, double employeeSalary) : IValidation
internal class SalaryDataModel(string employeeId, DateTime salaryDate, double employeeSalary) : IValidation
{
private readonly EmployeeDataModel? _employee;
public string EmployeeId { get; private set; } = employeeId;
@@ -25,15 +27,15 @@ public class SalaryDataModel(string employeeId, DateTime salaryDate, double empl
_employee = employee;
}
public void Validate()
public void Validate(IStringLocalizer<Messages> localizer)
{
if (EmployeeId.IsEmpty())
throw new ValidationException("Field EmployeeId is empty");
throw new ValidationException(string.Format(localizer["ValidationExceptionMessageEmptyField"], "EmployeeId"));
if (!EmployeeId.IsGuid())
throw new ValidationException("The value in the field EmployeeId is not a unique identifier");
throw new ValidationException(string.Format(localizer["ValidationExceptionMessageNotAId"], "EmployeeId"));
if (Salary <= 0)
throw new ValidationException("Field Salary is less than or equal to 0");
throw new ValidationException(string.Format(localizer["ValidationExceptionMessageLessOrEqualZero"], "Salary"));
}
}

View File

@@ -2,6 +2,8 @@
using MagicCarpetContracts.Exceptions;
using MagicCarpetContracts.Extensions;
using MagicCarpetContracts.Infrastructure;
using MagicCarpetContracts.Resources;
using Microsoft.Extensions.Localization;
using System;
using System.Collections.Generic;
using System.Linq;
@@ -10,7 +12,7 @@ using System.Threading.Tasks;
namespace MagicCarpetContracts.DataModels;
public class SaleDataModel : IValidation
internal class SaleDataModel : IValidation
{
private readonly ClientDataModel? _client;
@@ -83,27 +85,32 @@ public class SaleDataModel : IValidation
public SaleDataModel(string id, string employeeId, string? clientId, int discountType,
List<SaleTourDataModel> tours) : this(id, employeeId, clientId, (DiscountType)discountType, false, tours) { }
public void Validate()
public void Validate(IStringLocalizer<Messages> localizer)
{
if (Id.IsEmpty())
throw new ValidationException("Field Id is empty");
throw new ValidationException(string.Format(localizer["ValidationExceptionMessageEmptyField"], "Id"));
if (!Id.IsGuid())
throw new ValidationException("The value in the field Id is not a unique identifier");
throw new ValidationException(string.Format(localizer["ValidationExceptionMessageNotAId"], "Id"));
if (EmployeeId.IsEmpty())
throw new ValidationException("Field EmployeeId is empty");
throw new ValidationException(string.Format(localizer["ValidationExceptionMessageEmptyField"], "WorkerId"));
if (!EmployeeId.IsGuid())
throw new ValidationException("The value in the field EmployeeId is not a unique identifier");
throw new ValidationException(string.Format(localizer["ValidationExceptionMessageNotAId"], "WorkerId"));
if (!ClientId?.IsGuid() ?? !ClientId?.IsEmpty() ?? false)
throw new ValidationException("The value in the field BuyerId is not a unique identifier");
throw new ValidationException(string.Format(localizer["ValidationExceptionMessageNotAId"], "BuyerId"));
if (Sum <= 0)
throw new ValidationException("Field Sum is less than or equal to 0");
throw new ValidationException(string.Format(localizer["ValidationExceptionMessageLessOrEqualZero"], "Sum"));
if ((Tours?.Count ?? 0) == 0)
throw new ValidationException("The sale must include tours");
if (Tours is null)
throw new ValidationException(string.Format(localizer["ValidationExceptionMessageNotInitialized"], "Tours"));
if (Tours.Count == 0)
throw new ValidationException(localizer["ValidationExceptionMessageNoProductsInSale"]);
Tours.ForEach(x => x.Validate(localizer));
}
}

View File

@@ -1,6 +1,8 @@
using MagicCarpetContracts.Exceptions;
using MagicCarpetContracts.Extensions;
using MagicCarpetContracts.Infrastructure;
using MagicCarpetContracts.Resources;
using Microsoft.Extensions.Localization;
using System;
using System.Collections.Generic;
using System.Diagnostics;
@@ -10,7 +12,7 @@ using System.Threading.Tasks;
namespace MagicCarpetContracts.DataModels;
public class SaleTourDataModel(string saleId, string tourId, int count, double price) : IValidation
internal class SaleTourDataModel(string saleId, string tourId, int count, double price) : IValidation
{
private readonly TourDataModel? _tour;
@@ -29,24 +31,24 @@ public class SaleTourDataModel(string saleId, string tourId, int count, double p
_tour = tour;
}
public void Validate()
public void Validate(IStringLocalizer<Messages> localizer)
{
if (SaleId.IsEmpty())
throw new ValidationException("Field SaleId is empty");
throw new ValidationException(string.Format(localizer["ValidationExceptionMessageEmptyField"], "SaleId"));
if (!SaleId.IsGuid())
throw new ValidationException("The value in the field SaleId is not a unique identifier");
throw new ValidationException(string.Format(localizer["ValidationExceptionMessageNotAId"], "SaleId"));
if (TourId.IsEmpty())
throw new ValidationException("Field ProductId is empty");
throw new ValidationException(string.Format(localizer["ValidationExceptionMessageEmptyField"], "ITourIdd"));
if (!TourId.IsGuid())
throw new ValidationException("The value in the field ProductId is not a unique identifier");
throw new ValidationException(string.Format(localizer["ValidationExceptionMessageNotAId"], "TourId"));
if (Count <= 0)
throw new ValidationException("Field Count is less than or equal to 0");
throw new ValidationException(string.Format(localizer["ValidationExceptionMessageLessOrEqualZero"], "Count"));
if (Price <= 0)
throw new ValidationException("Field Price is less than or equal to 0");
throw new ValidationException(string.Format(localizer["ValidationExceptionMessageLessOrEqualZero"], "Price"));
}
}

View File

@@ -2,6 +2,8 @@
using MagicCarpetContracts.Exceptions;
using MagicCarpetContracts.Extensions;
using MagicCarpetContracts.Infrastructure;
using MagicCarpetContracts.Resources;
using Microsoft.Extensions.Localization;
using System;
using System.Collections.Generic;
using System.Diagnostics;
@@ -12,7 +14,7 @@ using System.Xml.Linq;
namespace MagicCarpetContracts.DataModels;
public class TourDataModel(string id, string tourName, string tourCountry, double price, TourType tourType) : IValidation
internal class TourDataModel(string id, string tourName, string tourCountry, double price, TourType tourType) : IValidation
{
public string Id { get; private set; } = id;
public string TourName { get; private set; } = tourName;
@@ -20,19 +22,19 @@ public class TourDataModel(string id, string tourName, string tourCountry, doubl
public double Price { get; private set; } = price;
public TourType TourType { get; private set; } = tourType;
public void Validate()
public void Validate(IStringLocalizer<Messages> localizer)
{
if (Id.IsEmpty())
throw new ValidationException("Field Id is empty");
throw new ValidationException(string.Format(localizer["ValidationExceptionMessageEmptyField"], "Id"));
if (!Id.IsGuid())
throw new ValidationException("The value in the field Id is not a unique identifier");
throw new ValidationException(string.Format(localizer["ValidationExceptionMessageNotAId"], "Id"));
if (TourName.IsEmpty())
throw new ValidationException("Field TourName is empty");
throw new ValidationException(string.Format(localizer["ValidationExceptionMessageEmptyField"], "TourName"));
if (TourCountry.IsEmpty())
throw new ValidationException("Field TourCountry is empty");
throw new ValidationException(string.Format(localizer["ValidationExceptionMessageEmptyField"], "TourCountry"));
if (Price <= 0)
throw new ValidationException("Field Price is less than or equal to 0");
throw new ValidationException(string.Format(localizer["ValidationExceptionMessageLessOrEqualZero"], "Price"));
if (TourType == TourType.None)
throw new ValidationException("Field Type is empty");
throw new ValidationException(string.Format(localizer["ValidationExceptionMessageEmptyField"], "TourType"));
}
}

View File

@@ -1,6 +1,8 @@
using MagicCarpetContracts.Exceptions;
using MagicCarpetContracts.Extensions;
using MagicCarpetContracts.Infrastructure;
using MagicCarpetContracts.Resources;
using Microsoft.Extensions.Localization;
using System;
using System.Collections.Generic;
using System.Linq;
@@ -9,7 +11,7 @@ using System.Threading.Tasks;
namespace MagicCarpetContracts.DataModels;
public class TourHistoryDataModel(string tourId, double oldPrice) : IValidation
internal class TourHistoryDataModel(string tourId, double oldPrice) : IValidation
{
private readonly TourDataModel? _tour;
@@ -27,15 +29,15 @@ public class TourHistoryDataModel(string tourId, double oldPrice) : IValidation
_tour = tour;
}
public void Validate()
public void Validate(IStringLocalizer<Messages> localizer)
{
if (TourId.IsEmpty())
throw new ValidationException("Field TourId is empty");
throw new ValidationException(string.Format(localizer["ValidationExceptionMessageEmptyField"], "TourId"));
if (!TourId.IsGuid())
throw new ValidationException("The value in the field TourId is not a unique identifier");
throw new ValidationException(string.Format(localizer["ValidationExceptionMessageNotAId"], "TourId"));
if (OldPrice <= 0)
throw new ValidationException("Field OldPrice is less than or equal to 0");
throw new ValidationException(string.Format(localizer["ValidationExceptionMessageLessOrEqualZero"], "OldPrice"));
}
}

View File

@@ -1,4 +1,6 @@
using System;
using MagicCarpetContracts.Resources;
using Microsoft.Extensions.Localization;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
@@ -6,7 +8,6 @@ using System.Threading.Tasks;
namespace MagicCarpetContracts.Exceptions;
public class ElementDeletedException : Exception
{
public ElementDeletedException(string id) : base($"Cannot modify a deleted item (id: {id})") { }
}
internal class ElementDeletedException(string id, IStringLocalizer<Messages> localizer)
: Exception(string.Format(localizer["ElementDeletedExceptionMessage"], id))
{ }

View File

@@ -1,4 +1,6 @@
using System;
using MagicCarpetContracts.Resources;
using Microsoft.Extensions.Localization;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
@@ -6,15 +8,10 @@ using System.Threading.Tasks;
namespace MagicCarpetContracts.Exceptions;
public class ElementExistsException : Exception
internal class ElementExistsException(string paramName, string paramValue, IStringLocalizer<Messages> localizer) :
Exception(string.Format(localizer["ElementExistsExceptionMessage"], paramValue, paramName))
{
public string ParamName { get; private set; }
public string ParamName { get; private set; } = paramName;
public string ParamValue { get; private set; }
public ElementExistsException(string paramName, string paramValue) : base($"There is already an element with value{paramValue} of parameter {paramName}")
{
ParamName = paramName;
ParamValue = paramValue;
}
public string ParamValue { get; private set; } = paramValue;
}

View File

@@ -1,4 +1,6 @@
using System;
using MagicCarpetContracts.Resources;
using Microsoft.Extensions.Localization;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
@@ -6,12 +8,8 @@ using System.Threading.Tasks;
namespace MagicCarpetContracts.Exceptions;
public class ElementNotFoundException : Exception
internal class ElementNotFoundException(string value, IStringLocalizer<Messages> localizer) :
Exception(string.Format(localizer["ElementNotFoundExceptionMessage"], value))
{
public string Value { get; private set; }
public ElementNotFoundException(string value) : base($"Element not found at value = {value}")
{
Value = value;
}
public string Value { get; private set; } = value;
}

View File

@@ -1,4 +1,6 @@
using System;
using MagicCarpetContracts.Resources;
using Microsoft.Extensions.Localization;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
@@ -6,8 +8,6 @@ using System.Threading.Tasks;
namespace MagicCarpetContracts.Exceptions;
public class IncorrectDatesException : Exception
{
public IncorrectDatesException(DateTime start, DateTime end) : base($"The end date must be later than the start date.. StartDate: " +
$"{start:dd.MM.YYYY}. EndDate: {end:dd.MM.YYYY}") { }
}
internal class IncorrectDatesException(DateTime start, DateTime end, IStringLocalizer<Messages> localizer) :
Exception(string.Format(localizer["IncorrectDatesExceptionMessage"], start.ToShortDateString(), end.ToShortDateString()))
{ }

View File

@@ -1,12 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MagicCarpetContracts.Exceptions;
public class NullListException : Exception
{
public NullListException() : base("The returned list is null") { }
}

View File

@@ -1,4 +1,6 @@
using System;
using MagicCarpetContracts.Resources;
using Microsoft.Extensions.Localization;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
@@ -6,7 +8,5 @@ using System.Threading.Tasks;
namespace MagicCarpetContracts.Exceptions;
public class StorageException : Exception
{
public StorageException(Exception ex) : base($"Error while working in storage: {ex.Message}", ex) { }
}
internal class StorageException(Exception ex, IStringLocalizer<Messages> localizer) : Exception(string.Format(localizer["StorageExceptionMessage"], ex.Message), ex)
{ }

View File

@@ -1,4 +1,6 @@
using System;
using MagicCarpetContracts.Resources;
using Microsoft.Extensions.Localization;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
@@ -6,8 +8,8 @@ using System.Threading.Tasks;
namespace MagicCarpetContracts.Infrastructure;
public interface IValidation
internal interface IValidation
{
void Validate();
void Validate(IStringLocalizer<Messages> localizer);
}

View File

@@ -10,6 +10,29 @@
<PackageReference Include="Microsoft.AspNetCore.Http.Abstractions" Version="2.3.0" />
<PackageReference Include="Microsoft.AspNetCore.Mvc.Abstractions" Version="2.3.0" />
<PackageReference Include="Microsoft.AspNetCore.Mvc.Core" Version="2.3.0" />
<PackageReference Include="Microsoft.Extensions.Localization.Abstractions" Version="9.0.4" />
</ItemGroup>
<ItemGroup>
<Compile Update="Resources\Messages.Designer.cs">
<DesignTime>True</DesignTime>
<AutoGen>True</AutoGen>
<DependentUpon>Messages.resx</DependentUpon>
</Compile>
</ItemGroup>
<ItemGroup>
<EmbeddedResource Update="Resources\Messages.resx">
<Generator>ResXFileCodeGenerator</Generator>
<LastGenOutput>Messages.Designer.cs</LastGenOutput>
</EmbeddedResource>
</ItemGroup>
<ItemGroup>
<InternalsVisibleTo Include="MagicCarpetDatabase" />
<InternalsVisibleTo Include="MagicCarpetTests" />
<InternalsVisibleTo Include="MagicCarpetBusinessLogic" />
<InternalsVisibleTo Include="MagicCarpetWebApi" />
<InternalsVisibleTo Include="DynamicProxyGenAssembly2" />
</ItemGroup>
</Project>

View File

@@ -0,0 +1,225 @@
//------------------------------------------------------------------------------
// <auto-generated>
// Этот код создан программой.
// Исполняемая версия:4.0.30319.42000
//
// Изменения в этом файле могут привести к неправильной работе и будут потеряны в случае
// повторной генерации кода.
// </auto-generated>
//------------------------------------------------------------------------------
namespace MagicCarpetContracts.Resources {
using System;
/// <summary>
/// Класс ресурса со строгой типизацией для поиска локализованных строк и т.д.
/// </summary>
// Этот класс создан автоматически классом StronglyTypedResourceBuilder
// с помощью такого средства, как ResGen или Visual Studio.
// Чтобы добавить или удалить член, измените файл .ResX и снова запустите ResGen
// с параметром /str или перестройте свой проект VS.
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "17.0.0.0")]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
internal class Messages {
private static global::System.Resources.ResourceManager resourceMan;
private static global::System.Globalization.CultureInfo resourceCulture;
[global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
internal Messages() {
}
/// <summary>
/// Возвращает кэшированный экземпляр ResourceManager, использованный этим классом.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Resources.ResourceManager ResourceManager {
get {
if (object.ReferenceEquals(resourceMan, null)) {
global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("MagicCarpetContracts.Resources.Messages", typeof(Messages).Assembly);
resourceMan = temp;
}
return resourceMan;
}
}
/// <summary>
/// Перезаписывает свойство CurrentUICulture текущего потока для всех
/// обращений к ресурсу с помощью этого класса ресурса со строгой типизацией.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Globalization.CultureInfo Culture {
get {
return resourceCulture;
}
set {
resourceCulture = value;
}
}
/// <summary>
/// Ищет локализованную строку, похожую на Нельзя изменить удаленный элемент (идентификатор: {0}).
/// </summary>
internal static string ElementDeletedExceptionMessage {
get {
return ResourceManager.GetString("ElementDeletedExceptionMessage", resourceCulture);
}
}
/// <summary>
/// Ищет локализованную строку, похожую на Уже существует элемент со значением {0} параметра {1}.
/// </summary>
internal static string ElementExistsExceptionMessage {
get {
return ResourceManager.GetString("ElementExistsExceptionMessage", resourceCulture);
}
}
/// <summary>
/// Ищет локализованную строку, похожую на Элемент не найден по значению = {0}.
/// </summary>
internal static string ElementNotFoundExceptionMessage {
get {
return ResourceManager.GetString("ElementNotFoundExceptionMessage", resourceCulture);
}
}
/// <summary>
/// Ищет локализованную строку, похожую на Дата окончания должна быть позже даты начала. Дата начала: {0}. ​​Дата окончания: {1}.
/// </summary>
internal static string IncorrectDatesExceptionMessage {
get {
return ResourceManager.GetString("IncorrectDatesExceptionMessage", resourceCulture);
}
}
/// <summary>
/// Ищет локализованную строку, похожую на Недостаточно данных для обработки: {0}.
/// </summary>
internal static string NotEnoughDataToProcessExceptionMessage {
get {
return ResourceManager.GetString("NotEnoughDataToProcessExceptionMessage", resourceCulture);
}
}
/// <summary>
/// Ищет локализованную строку, похожую на Не найдены данные.
/// </summary>
internal static string NotFoundDataMessage {
get {
return ResourceManager.GetString("NotFoundDataMessage", resourceCulture);
}
}
/// <summary>
/// Ищет локализованную строку, похожую на Ошибка при работе в хранилище: {0}.
/// </summary>
internal static string StorageExceptionMessage {
get {
return ResourceManager.GetString("StorageExceptionMessage", resourceCulture);
}
}
/// <summary>
/// Ищет локализованную строку, похожую на Дата трудоустройства не может быть раньше даты рождения ({0}, {1}).
/// </summary>
internal static string ValidationExceptionMessageEmploymentDateAndBirthDate {
get {
return ResourceManager.GetString("ValidationExceptionMessageEmploymentDateAndBirthDate", resourceCulture);
}
}
/// <summary>
/// Ищет локализованную строку, похожую на Значение в поле {0} пусто.
/// </summary>
internal static string ValidationExceptionMessageEmptyField {
get {
return ResourceManager.GetString("ValidationExceptionMessageEmptyField", resourceCulture);
}
}
/// <summary>
/// Ищет локализованную строку, похожую на Некорректный формат ФИО.
/// </summary>
internal static string ValidationExceptionMessageIncorrectFIO {
get {
return ResourceManager.GetString("ValidationExceptionMessageIncorrectFIO", resourceCulture);
}
}
/// <summary>
/// Ищет локализованную строку, похожую на Значение в поле Телефонный номер не является телефонным номером.
/// </summary>
internal static string ValidationExceptionMessageIncorrectPhoneNumber {
get {
return ResourceManager.GetString("ValidationExceptionMessageIncorrectPhoneNumber", resourceCulture);
}
}
/// <summary>
/// Ищет локализованную строку, похожую на Значение в поле {0} меньше или равно 0.
/// </summary>
internal static string ValidationExceptionMessageLessOrEqualZero {
get {
return ResourceManager.GetString("ValidationExceptionMessageLessOrEqualZero", resourceCulture);
}
}
/// <summary>
/// Ищет локализованную строку, похожую на Несовершеннолетние не могут быть приняты на работу (Дата рождения: {0}).
/// </summary>
internal static string ValidationExceptionMessageMinorsBirthDate {
get {
return ResourceManager.GetString("ValidationExceptionMessageMinorsBirthDate", resourceCulture);
}
}
/// <summary>
/// Ищет локализованную строку, похожую на Несовершеннолетние не могут быть приняты на работу (Дата трудоустройства: {0}, Дата рождения: {1}).
/// </summary>
internal static string ValidationExceptionMessageMinorsEmploymentDate {
get {
return ResourceManager.GetString("ValidationExceptionMessageMinorsEmploymentDate", resourceCulture);
}
}
/// <summary>
/// Ищет локализованную строку, похожую на Отсутствуют компоненты.
/// </summary>
internal static string ValidationExceptionMessageNoComponents {
get {
return ResourceManager.GetString("ValidationExceptionMessageNoComponents", resourceCulture);
}
}
/// <summary>
/// Ищет локализованную строку, похожую на В продаже должен быть хотя бы один товар.
/// </summary>
internal static string ValidationExceptionMessageNoProductsInSale {
get {
return ResourceManager.GetString("ValidationExceptionMessageNoProductsInSale", resourceCulture);
}
}
/// <summary>
/// Ищет локализованную строку, похожую на Значение в поле {0} не является типом уникального идентификатора.
/// </summary>
internal static string ValidationExceptionMessageNotAId {
get {
return ResourceManager.GetString("ValidationExceptionMessageNotAId", resourceCulture);
}
}
/// <summary>
/// Ищет локализованную строку, похожую на Значение в поле {0} не проинициализировано.
/// </summary>
internal static string ValidationExceptionMessageNotInitialized {
get {
return ResourceManager.GetString("ValidationExceptionMessageNotInitialized", resourceCulture);
}
}
}
}

View File

@@ -0,0 +1,174 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
Version 2.0
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.
Example:
... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader>
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
<value>[base64 mime encoded serialized .NET Framework object]</value>
</data>
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment>
</data>
There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" use="required" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<data name="ElementDeletedExceptionMessage" xml:space="preserve">
<value>Нельзя изменить удаленный элемент (идентификатор: {0})</value>
</data>
<data name="ElementExistsExceptionMessage" xml:space="preserve">
<value>Уже существует элемент со значением {0} параметра {1}</value>
</data>
<data name="ElementNotFoundExceptionMessage" xml:space="preserve">
<value>Элемент не найден по значению = {0}</value>
</data>
<data name="IncorrectDatesExceptionMessage" xml:space="preserve">
<value>Дата окончания должна быть позже даты начала. Дата начала: {0}. ​​Дата окончания: {1}</value>
</data>
<data name="NotEnoughDataToProcessExceptionMessage" xml:space="preserve">
<value>Недостаточно данных для обработки: {0}</value>
</data>
<data name="NotFoundDataMessage" xml:space="preserve">
<value>Не найдены данные</value>
</data>
<data name="StorageExceptionMessage" xml:space="preserve">
<value>Ошибка при работе в хранилище: {0}</value>
</data>
<data name="ValidationExceptionMessageEmploymentDateAndBirthDate" xml:space="preserve">
<value>Дата трудоустройства не может быть раньше даты рождения ({0}, {1})</value>
</data>
<data name="ValidationExceptionMessageEmptyField" xml:space="preserve">
<value>Значение в поле {0} пусто</value>
</data>
<data name="ValidationExceptionMessageIncorrectFIO" xml:space="preserve">
<value>Некорректный формат ФИО</value>
</data>
<data name="ValidationExceptionMessageIncorrectPhoneNumber" xml:space="preserve">
<value>Значение в поле Телефонный номер не является телефонным номером</value>
</data>
<data name="ValidationExceptionMessageLessOrEqualZero" xml:space="preserve">
<value>Значение в поле {0} меньше или равно 0</value>
</data>
<data name="ValidationExceptionMessageMinorsBirthDate" xml:space="preserve">
<value>Несовершеннолетние не могут быть приняты на работу (Дата рождения: {0})</value>
</data>
<data name="ValidationExceptionMessageMinorsEmploymentDate" xml:space="preserve">
<value>Несовершеннолетние не могут быть приняты на работу (Дата трудоустройства: {0}, Дата рождения: {1})</value>
</data>
<data name="ValidationExceptionMessageNoComponents" xml:space="preserve">
<value>Отсутствуют компоненты</value>
</data>
<data name="ValidationExceptionMessageNoProductsInSale" xml:space="preserve">
<value>В продаже должен быть хотя бы один товар</value>
</data>
<data name="ValidationExceptionMessageNotAId" xml:space="preserve">
<value>Значение в поле {0} не является типом уникального идентификатора</value>
</data>
<data name="ValidationExceptionMessageNotInitialized" xml:space="preserve">
<value>Значение в поле {0} не проинициализировано</value>
</data>
</root>

View File

@@ -7,7 +7,7 @@ using System.Threading.Tasks;
namespace MagicCarpetContracts.StoragesContracts;
public interface IClientStorageContract
internal interface IClientStorageContract
{
List<ClientDataModel> GetList();

View File

@@ -7,7 +7,7 @@ using System.Threading.Tasks;
namespace MagicCarpetContracts.StoragesContracts;
public interface IEmployeeStorageContract
internal interface IEmployeeStorageContract
{
List<EmployeeDataModel> GetList(bool onlyActive = true, string? postId = null, DateTime? fromBirthDate = null,
DateTime? toBirthDate = null, DateTime? fromEmploymentDate = null, DateTime? toEmploymentDate = null);

View File

@@ -7,7 +7,7 @@ using System.Threading.Tasks;
namespace MagicCarpetContracts.StoragesContracts;
public interface IPostStorageContract
internal interface IPostStorageContract
{
List<PostDataModel> GetList();
List<PostDataModel> GetPostWithHistory(string postId);

View File

@@ -7,7 +7,7 @@ using System.Threading.Tasks;
namespace MagicCarpetContracts.StoragesContracts;
public interface ISalaryStorageContract
internal interface ISalaryStorageContract
{
List<SalaryDataModel> GetList(DateTime? startDate, DateTime? endDate, string? employeeId = null);

View File

@@ -7,7 +7,7 @@ using System.Threading.Tasks;
namespace MagicCarpetContracts.StoragesContracts;
public interface ISaleStorageContract
internal interface ISaleStorageContract
{
List<SaleDataModel> GetList(DateTime? startDate = null, DateTime? endDate = null, string? employeeId = null,
string? clientId = null, string? tourId = null);

View File

@@ -7,7 +7,7 @@ using System.Threading.Tasks;
namespace MagicCarpetContracts.StoragesContracts;
public interface ITourStorageContract
internal interface ITourStorageContract
{
List<TourDataModel> GetList();
List<TourHistoryDataModel> GetHistoryByTourId(string tourId);

View File

@@ -1,9 +1,11 @@
using AutoMapper;
using MagicCarpetContracts.DataModels;
using MagicCarpetContracts.Exceptions;
using MagicCarpetContracts.Resources;
using MagicCarpetContracts.StoragesContracts;
using MagicCarpetDatabase.Models;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Localization;
using Npgsql;
using System;
using System.Collections.Generic;
@@ -13,11 +15,12 @@ using System.Threading.Tasks;
namespace MagicCarpetDatabase.Implementations;
public class ClientStorageContract : IClientStorageContract
internal class ClientStorageContract : IClientStorageContract
{
private readonly MagicCarpetDbContext _dbContext;
private readonly Mapper _mapper;
public ClientStorageContract(MagicCarpetDbContext magicCarpetDbContext)
private readonly IStringLocalizer<Messages> _localizer;
public ClientStorageContract(MagicCarpetDbContext magicCarpetDbContext, IStringLocalizer<Messages> localizer)
{
_dbContext = magicCarpetDbContext;
var config = new MapperConfiguration(cfg =>
@@ -25,6 +28,7 @@ public class ClientStorageContract : IClientStorageContract
cfg.AddMaps(typeof(MagicCarpetDbContext).Assembly);
});
_mapper = new Mapper(config);
_localizer = localizer;
}
public List<ClientDataModel> GetList()
{
@@ -35,7 +39,7 @@ public class ClientStorageContract : IClientStorageContract
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
throw new StorageException(ex, _localizer);
}
}
public ClientDataModel? GetElementById(string id)
@@ -47,7 +51,7 @@ public class ClientStorageContract : IClientStorageContract
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
throw new StorageException(ex, _localizer);
}
}
public ClientDataModel? GetElementByFIO(string fio)
@@ -59,7 +63,7 @@ public class ClientStorageContract : IClientStorageContract
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
throw new StorageException(ex, _localizer);
}
}
public ClientDataModel? GetElementByPhoneNumber(string phoneNumber)
@@ -71,7 +75,7 @@ public class ClientStorageContract : IClientStorageContract
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
throw new StorageException(ex, _localizer);
}
}
public void AddElement(ClientDataModel clientDataModel)
@@ -84,24 +88,24 @@ public class ClientStorageContract : IClientStorageContract
catch (InvalidOperationException ex) when (ex.TargetSite?.Name == "ThrowIdentityConflict")
{
_dbContext.ChangeTracker.Clear();
throw new ElementExistsException("Id", clientDataModel.Id);
throw new ElementExistsException("Id", clientDataModel.Id, _localizer);
}
catch (DbUpdateException ex) when (ex.InnerException is PostgresException { ConstraintName: "IX_Clients_PhoneNumber" })
{
_dbContext.ChangeTracker.Clear();
throw new ElementExistsException("PhoneNumber", clientDataModel.PhoneNumber);
throw new ElementExistsException("PhoneNumber", clientDataModel.PhoneNumber, _localizer);
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
throw new StorageException(ex, _localizer);
}
}
public void UpdElement(ClientDataModel clientDataModel)
{
try
{
var element = GetClientById(clientDataModel.Id) ?? throw new ElementNotFoundException(clientDataModel.Id);
var element = GetClientById(clientDataModel.Id) ?? throw new ElementNotFoundException(clientDataModel.Id, _localizer);
_dbContext.Clients.Update(_mapper.Map(clientDataModel, element));
_dbContext.SaveChanges();
}
@@ -113,19 +117,19 @@ public class ClientStorageContract : IClientStorageContract
catch (DbUpdateException ex) when (ex.InnerException is PostgresException { ConstraintName: "IX_Clients_PhoneNumber" })
{
_dbContext.ChangeTracker.Clear();
throw new ElementExistsException("PhoneNumber", clientDataModel.PhoneNumber);
throw new ElementExistsException("PhoneNumber", clientDataModel.PhoneNumber, _localizer);
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
throw new StorageException(ex, _localizer);
}
}
public void DelElement(string id)
{
try
{
var element = GetClientById(id) ?? throw new ElementNotFoundException(id);
var element = GetClientById(id) ?? throw new ElementNotFoundException(id, _localizer);
_dbContext.Clients.Remove(element);
_dbContext.SaveChanges();
}
@@ -137,7 +141,7 @@ public class ClientStorageContract : IClientStorageContract
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
throw new StorageException(ex, _localizer);
}
}
private Client? GetClientById(string id) => _dbContext.Clients.FirstOrDefault(x => x.Id == id);

View File

@@ -1,8 +1,10 @@
using AutoMapper;
using MagicCarpetContracts.DataModels;
using MagicCarpetContracts.Exceptions;
using MagicCarpetContracts.Resources;
using MagicCarpetContracts.StoragesContracts;
using MagicCarpetDatabase.Models;
using Microsoft.Extensions.Localization;
using System;
using System.Collections.Generic;
using System.Linq;
@@ -11,12 +13,12 @@ using System.Threading.Tasks;
namespace MagicCarpetDatabase.Implementations;
public class EmployeeStorageContract : IEmployeeStorageContract
internal class EmployeeStorageContract : IEmployeeStorageContract
{
private readonly MagicCarpetDbContext _dbContext;
private readonly Mapper _mapper;
public EmployeeStorageContract(MagicCarpetDbContext dbContext)
private readonly IStringLocalizer<Messages> _localizer;
public EmployeeStorageContract(MagicCarpetDbContext dbContext, IStringLocalizer<Messages> localizer)
{
_dbContext = dbContext;
var config = new MapperConfiguration(cfg =>
@@ -27,6 +29,7 @@ public class EmployeeStorageContract : IEmployeeStorageContract
cfg.CreateMap<EmployeeDataModel, Employee>();
});
_mapper = new Mapper(config);
_localizer = localizer;
}
public List<EmployeeDataModel> GetList(bool onlyActive = true, string? postId = null, DateTime? fromBirthDate = null, DateTime? toBirthDate = null, DateTime? fromEmploymentDate = null, DateTime? toEmploymentDate = null)
@@ -55,7 +58,7 @@ public class EmployeeStorageContract : IEmployeeStorageContract
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
throw new StorageException(ex, _localizer);
}
}
@@ -68,7 +71,7 @@ public class EmployeeStorageContract : IEmployeeStorageContract
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
throw new StorageException(ex, _localizer);
}
}
@@ -81,7 +84,7 @@ public class EmployeeStorageContract : IEmployeeStorageContract
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
throw new StorageException(ex, _localizer);
}
}
@@ -94,7 +97,7 @@ public class EmployeeStorageContract : IEmployeeStorageContract
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
throw new StorageException(ex, _localizer);
}
}
@@ -108,12 +111,12 @@ public class EmployeeStorageContract : IEmployeeStorageContract
catch (InvalidOperationException ex) when (ex.TargetSite?.Name == "ThrowIdentityConflict")
{
_dbContext.ChangeTracker.Clear();
throw new ElementExistsException("Id", employeeDataModel.Id);
throw new ElementExistsException("Id", employeeDataModel.Id, _localizer);
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
throw new StorageException(ex, _localizer);
}
}
@@ -121,7 +124,7 @@ public class EmployeeStorageContract : IEmployeeStorageContract
{
try
{
var element = GetEmployeeById(employeeDataModel.Id) ?? throw new ElementNotFoundException(employeeDataModel.Id);
var element = GetEmployeeById(employeeDataModel.Id) ?? throw new ElementNotFoundException(employeeDataModel.Id, _localizer);
_dbContext.Employees.Update(_mapper.Map(employeeDataModel, element));
_dbContext.SaveChanges();
}
@@ -133,7 +136,7 @@ public class EmployeeStorageContract : IEmployeeStorageContract
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
throw new StorageException(ex, _localizer);
}
}
@@ -141,7 +144,7 @@ public class EmployeeStorageContract : IEmployeeStorageContract
{
try
{
var element = GetEmployeeById(id) ?? throw new ElementNotFoundException(id);
var element = GetEmployeeById(id) ?? throw new ElementNotFoundException(id, _localizer);
element.IsDeleted = true;
_dbContext.SaveChanges();
}
@@ -153,7 +156,7 @@ public class EmployeeStorageContract : IEmployeeStorageContract
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
throw new StorageException(ex, _localizer);
}
}
@@ -168,7 +171,7 @@ public class EmployeeStorageContract : IEmployeeStorageContract
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
throw new StorageException(ex, _localizer);
}
}

View File

@@ -11,9 +11,12 @@ using MagicCarpetWebApi;
using MagicCarpetWebApi.Adapters;
using MagicCarpetWebApi.Infrastructure;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Localization;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Options;
using Microsoft.IdentityModel.Tokens;
using Serilog;
using System.Globalization;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
@@ -50,6 +53,22 @@ builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
};
});
builder.Services.AddLocalization();
builder.Services.Configure<RequestLocalizationOptions>(
options =>
{
var supportedCultures = new List<CultureInfo>
{
new("en-US"),
new("ru-RU"),
new("zh-CN")
};
options.DefaultRequestCulture = new RequestCulture(culture: "ru-RU", uiCulture: "ru-RU");
options.SupportedCultures = supportedCultures;
options.SupportedUICultures = supportedCultures;
});
builder.Services.AddSingleton<IConfigurationDatabase, ConfigurationDatabase>();
builder.Services.AddSingleton<IConfigurationSalary, ConfigurationSalary>();
@@ -116,4 +135,11 @@ app.Map("/login/{username}", (string username) =>
app.MapControllers();
var localizeOptions =
app.Services.GetService<IOptions<RequestLocalizationOptions>>();
if (localizeOptions is not null)
{
app.UseRequestLocalization(localizeOptions.Value);
}
app.Run();