Правки

This commit is contained in:
nikbel2004@outlook.com 2024-05-22 17:31:21 +04:00
parent 9d619f493f
commit 2a2da1c23d
22 changed files with 125 additions and 99 deletions

View File

@ -30,10 +30,12 @@ namespace FurnitureAssemblyBusinessLogic.BussinessLogic
public void CreateBackUp(BackUpSaveBindingModel model)
{
// Проверка наличия данных для бэкапа
if (_backUpInfo == null)
{
return;
}
try
{
_logger.LogDebug("Clear folder");
@ -43,7 +45,7 @@ namespace FurnitureAssemblyBusinessLogic.BussinessLogic
if (dirInfo.Exists)
{
// ЛУЧШЕ ВЫБИРАТЬ ОТДЕЛЬНО СОЗДАННУЮ ПАПКУ (Не брать рабочий стол иначе с него всё удалится)
// ЛУЧШЕ ВЫБИРАТЬ ОТДЕЛЬНО СОЗДАННУЮ ПАПКУ (Рабочий стол не использовать, поскольку с него всё удалится)
foreach (var file in dirInfo.GetFiles())
{
file.Delete();
@ -62,6 +64,7 @@ namespace FurnitureAssemblyBusinessLogic.BussinessLogic
// Берём метод для сохранения
_logger.LogDebug("Get assembly");
// Получение сборки и типов
var typeIId = typeof(IId);
var assembly = typeIId.Assembly;
@ -75,6 +78,7 @@ namespace FurnitureAssemblyBusinessLogic.BussinessLogic
_logger.LogDebug("Find {count} types", types.Length);
// Перебор типов и вызов метода для сохранения данных
foreach (var type in types)
{
// Проверка на то, является ли тип интерфейсом и унаследован ли он от IId
@ -89,7 +93,7 @@ namespace FurnitureAssemblyBusinessLogic.BussinessLogic
_logger.LogDebug("Call SaveToFile method for {name} type", type.Name);
// Вызываем метод на выполнение
// Вызываем метод на выполнение (Вызываем метод типа MethodInfo)
method?.MakeGenericMethod(modelType).Invoke(this, new object[] { model.FolderName });
}
}

View File

@ -19,12 +19,14 @@ namespace FurnitureAssemblyBusinessLogic.BussinessLogic
private readonly IImplementerStorage _implementerStorage;
// Конструктор
public ImplementerLogic(ILogger<ImplementerLogic> logger, IImplementerStorage implementerStorage)
{
_logger = logger;
_implementerStorage = implementerStorage;
}
// Вывод всего отфильтрованного списка
public List<ImplementerViewModel>? ReadList(ImplementerSearchModel? model)
{
_logger.LogInformation("ReadList. ImplementerFIO:{ImplementerFIO}. Id:{Id}", model?.ImplementerFIO, model?.Id);
@ -43,6 +45,7 @@ namespace FurnitureAssemblyBusinessLogic.BussinessLogic
return list;
}
// Вывод конкретного элемента
public ImplementerViewModel? ReadElement(ImplementerSearchModel model)
{
if (model == null)
@ -66,6 +69,7 @@ namespace FurnitureAssemblyBusinessLogic.BussinessLogic
return element;
}
// Создание работника
public bool Create(ImplementerBindingModel model)
{
CheckModel(model);
@ -80,6 +84,7 @@ namespace FurnitureAssemblyBusinessLogic.BussinessLogic
return true;
}
// Обновление данных о работнике
public bool Update(ImplementerBindingModel model)
{
CheckModel(model);
@ -94,6 +99,7 @@ namespace FurnitureAssemblyBusinessLogic.BussinessLogic
return true;
}
// Удаление работника
public bool Delete(ImplementerBindingModel model)
{
CheckModel(model, false);
@ -145,7 +151,7 @@ namespace FurnitureAssemblyBusinessLogic.BussinessLogic
// Проверка на наличие квалификации
if (model.WorkExperience < 0)
{
throw new ArgumentNullException("Указан некоректный стаж работы", nameof(model.WorkExperience));
throw new ArgumentNullException("Указан некорректный стаж работы", nameof(model.WorkExperience));
}
_logger.LogInformation("Implementer. ImplementerFIO:{ImplementerFIO}. Password:{Password}. " +

View File

@ -20,6 +20,7 @@ namespace FurnitureAssemblyBusinessLogic.BussinessLogic
private IOrderLogic? _orderLogic;
// Конструктор
public WorkModeling(ILogger<WorkModeling> logger)
{
_logger = logger;
@ -44,7 +45,7 @@ namespace FurnitureAssemblyBusinessLogic.BussinessLogic
return;
}
_logger.LogDebug("DoWork for {Count} orders", orders.Count);
_logger.LogDebug("DoWork for {сount} orders", orders.Count);
foreach (var implementer in implementers)
{
@ -114,24 +115,26 @@ namespace FurnitureAssemblyBusinessLogic.BussinessLogic
ImplementerId = implementer.Id
});
// делаем работу
// Работу работаем, делаем-делаем
Thread.Sleep(implementer.WorkExperience * order.Count);
_logger.LogDebug("DoWork. Worker {Id} finish order {Order}", implementer.Id, order.Id);
_orderLogic.FinishOrder(new OrderBindingModel
{
Id = order.Id,
Id = order.Id
});
// Отдыхаем
// Усёёё отдыхаем
Thread.Sleep(implementer.Qualification);
}
// Кто-то мог уже перехватить заказ, игнорируем ошибку
// Игнорируем ошибку, если с заказом что-то случится
catch (InvalidOperationException ex)
{
_logger.LogWarning(ex, "Error try get work");
}
// Заканчиваем выполнение имитации в случае иной ошибки
catch (Exception ex)
{
@ -163,9 +166,9 @@ namespace FurnitureAssemblyBusinessLogic.BussinessLogic
return;
}
_logger.LogDebug("DoWork. Worker {Id} back to order {Order}", implementer.Id, runOrder.Id);
_logger.LogDebug("DoWork {Id} back to order {Order}", implementer.Id, runOrder.Id);
// Доделываем работу
// Доделываем работу
Thread.Sleep(implementer.WorkExperience * runOrder.Count);
_logger.LogDebug("DoWork. Worker {Id} finish order {Order}", implementer.Id, runOrder.Id);
@ -175,15 +178,17 @@ namespace FurnitureAssemblyBusinessLogic.BussinessLogic
Id = runOrder.Id
});
// Отдыхаем
// Отдыхаем, хватит работы
Thread.Sleep(implementer.Qualification);
}
// Заказа может не быть, просто игнорируем ошибку
catch (InvalidOperationException ex)
{
_logger.LogWarning(ex, "Error try get work");
}
// Может возникнуть иная ошибка, тогда просто заканчиваем выполнение имитации
// Просто возникнет тупая ошибка, тогда заканчиваем выполнение имитации
catch (Exception ex)
{
_logger.LogError(ex, "Error while do work");

View File

@ -14,7 +14,7 @@ namespace FurnitureAssemblyBusinessLogic.OfficePackage.HelperModels
public string Title { get; set; } = string.Empty;
// Список заготовок для вывода и сохранения
// Cписок заготовок для вывода и сохранения
public List<FurnitureViewModel> Furnitures { get; set; } = new();
// Список магазинов для вывода и сохранения

View File

@ -12,7 +12,7 @@ namespace FurnitureAssemblyBusinessLogic.OfficePackage.HelperModels
// Набор текстов в абзаце (для случая, если в абзаце текст разных стилей)
public List<(string, WordTextProperties)> Texts { get; set; } = new();
// Свойства параграфа, если они есть
// Cвойства параграфа, если они есть
public WordTextProperties? TextProperties { get; set; }
public List<List<(string, WordTextProperties)>> RowTexts { get; set; } = new();

View File

@ -185,7 +185,10 @@ namespace FurnitureAssemblyBusinessLogic.OfficePackage.Implements
var stylesheetExtensionList = new StylesheetExtensionList();
var stylesheetExtension1 = new StylesheetExtension() { Uri = "{EB79DEF2-80B8-43e5-95BD-54CBDDF9020C}" };
var stylesheetExtension1 = new StylesheetExtension()
{
Uri = "{EB79DEF2-80B8-43e5-95BD-54CBDDF9020C}"
};
stylesheetExtension1.AddNamespaceDeclaration("x14", "http://schemas.microsoft.com/office/spreadsheetml/2009/9/main");
stylesheetExtension1.Append(new SlicerStyles()
{
@ -328,7 +331,6 @@ namespace FurnitureAssemblyBusinessLogic.OfficePackage.Implements
};
row.InsertBefore(newCell, refCell);
cell = newCell;
}

View File

@ -9,7 +9,7 @@ namespace FurnitureAssemblyContracts.BusinessLogicsContracts
// Интерфейс для класса, имитирующего работу
public interface IWorkProcess
{
// Запуск работ
// Запуск работы
void DoWork(IImplementerLogic implementerLogic, IOrderLogic orderLogic);
}
}

View File

@ -7,7 +7,7 @@ using System.Threading.Tasks;
namespace FurnitureAssemblyContracts.DI
{
/// Менеджер для работы с зависимостями
// Менеджер для работы с зависимостями
public class DependencyManager
{
private readonly IDependencyContainer _dependencyManager;
@ -31,7 +31,7 @@ namespace FurnitureAssemblyContracts.DI
}
}
// Иницализация библиотек, в которых идут установки зависомстей
// Инициализация библиотек, в которых идут установки зависимостей
public static void InitDependency()
{
var ext = ServiceProviderLoader.GetImplementationExtensions();
@ -41,7 +41,7 @@ namespace FurnitureAssemblyContracts.DI
throw new ArgumentNullException("Отсутствуют компоненты для загрузки зависимостей по модулям");
}
// Регистрируем зависимости хранилищ
// Регистрируем зависимости
ext.RegisterServices();
var extBusiness = ServiceProviderLoader.GetBusinessLogicImplementationExtensions();
@ -64,8 +64,7 @@ namespace FurnitureAssemblyContracts.DI
// Добавление зависимости
public void RegisterType<T>(bool isSingle = false) where T : class => _dependencyManager.RegisterType<T>(isSingle);
// Получение класса со всеми зависмостями
// Получение класса со всеми зависимостями
public T Resolve<T>() => _dependencyManager.Resolve<T>();
}
}

View File

@ -10,16 +10,16 @@ namespace FurnitureAssemblyContracts.DI
// Интерфейс установки зависимости между элементами
public interface IDependencyContainer
{
//Регистрация логгера
// Регистрация логгера
void AddLogging(Action<ILoggingBuilder> configure);
//Добавление зависимости
// Добавление зависимости
void RegisterType<T, U>(bool isSingle) where U : class, T where T : class;
//Добавление зависимости
// Добавление зависимости
void RegisterType<T>(bool isSingle) where T : class;
//Получение класса со всеми зависимостями
// Получение класса со всеми зависимостями
T Resolve<T>();
}
}

View File

@ -34,6 +34,7 @@ namespace FurnitureAssemblyContracts.DI
{
_serviceCollection.AddTransient<T, U>();
}
_serviceProvider = null;
}
@ -47,6 +48,7 @@ namespace FurnitureAssemblyContracts.DI
{
_serviceCollection.AddTransient<T>();
}
_serviceProvider = null;
}
@ -56,6 +58,7 @@ namespace FurnitureAssemblyContracts.DI
{
_serviceProvider = _serviceCollection.BuildServiceProvider();
}
return _serviceProvider.GetService<T>()!;
}
}

View File

@ -27,7 +27,6 @@ namespace FurnitureAssemblyContracts.DI
public void RegisterType<T>(bool isSingle) where T : class
{
_container.RegisterType<T>(isSingle ? TypeLifetime.Singleton : TypeLifetime.Transient);
}
public T Resolve<T>()

View File

@ -18,7 +18,7 @@ namespace FurnitureAssemblyContracts.ViewModels
[Column(title: "ФИО клиента", width: 150)]
public string ClientFIO { get; set; } = string.Empty;
[Column(title: "Логин (электронная почта)", gridViewAutoSize: GridViewAutoSize.Fill, isUseAutoSize: true)]
[Column(title: "Логин (эл. почта)", gridViewAutoSize: GridViewAutoSize.Fill, isUseAutoSize: true)]
public string Email { get; set; } = string.Empty;
[Column(title: "Пароль", width: 150)]

View File

@ -30,13 +30,13 @@ namespace FurnitureAssemblyContracts.ViewModels
[Column(title: "Заголовок", width: 150)]
public string Subject { get; set; } = string.Empty;
[DisplayName("Текст")]
[Column(title: "Текст", width: 150)]
public string Body { get; set; } = string.Empty;
[DisplayName("Прочитано")]
[Column(title: "Прочитано", width: 150)]
public bool IsRead { get; set; } = false;
[DisplayName("Ответ")]
[Column(title: "Ответ", width: 150)]
public string? Answer { get; set; }
}
}

View File

@ -1,27 +1,27 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net6.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
<PropertyGroup>
<TargetFramework>net6.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="7.0.16" />
<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="7.0.16" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="7.0.16">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
</ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="7.0.16" />
<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="7.0.16" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="7.0.16">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\FurnitureAssemblyContracts\FurnitureAssemblyContracts.csproj" />
<ProjectReference Include="..\FurnitureAssemblyDataModels\FurnitureAssemblyDataModels.csproj" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\FurnitureAssemblyContracts\FurnitureAssemblyContracts.csproj" />
<ProjectReference Include="..\FurnitureAssemblyDataModels\FurnitureAssemblyDataModels.csproj" />
</ItemGroup>
<Target Name="PostBuild" AfterTargets="PostBuildEvent">
<Exec Command="copy /Y &quot;$(TargetDir)*.dll&quot; &quot;$(SolutionDir)ImplementationExtensions\*.dll&quot;" />
</Target>
<Target Name="PostBuild" AfterTargets="PostBuildEvent">
<Exec Command="copy /Y &quot;$(TargetDir)*.dll&quot; &quot;$(SolutionDir)ImplementationExtensions\*.dll&quot;" />
</Target>
</Project>

View File

@ -1,18 +1,18 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net6.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
<PropertyGroup>
<TargetFramework>net6.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\FurnitureAssemblyContracts\FurnitureAssemblyContracts.csproj" />
<ProjectReference Include="..\FurnitureAssemblyDataModels\FurnitureAssemblyDataModels.csproj" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\FurnitureAssemblyContracts\FurnitureAssemblyContracts.csproj" />
<ProjectReference Include="..\FurnitureAssemblyDataModels\FurnitureAssemblyDataModels.csproj" />
</ItemGroup>
<Target Name="PostBuild" AfterTargets="PostBuildEvent">
<Exec Command="copy /Y &quot;$(TargetDir)*.dll&quot; &quot;$(SolutionDir)ImplementationExtensions\*.dll&quot;" />
</Target>
<Target Name="PostBuild" AfterTargets="PostBuildEvent">
<Exec Command="copy /Y &quot;$(TargetDir)*.dll&quot; &quot;$(SolutionDir)ImplementationExtensions\*.dll&quot;" />
</Target>
</Project>

View File

@ -24,7 +24,7 @@ namespace FurnitureAssemblyListImplement
// Список для хранения Магазинов
public List<Shop> Shops { get; set; }
// Список для хранения Клиентов
// Список для хранения клиентов
public List<Client> Clients { get; set; }
// Список для хранения исполнителей
@ -46,7 +46,7 @@ namespace FurnitureAssemblyListImplement
public static DataListSingleton GetInstance()
{
if(_instance == null)
if (_instance == null)
{
_instance = new DataListSingleton();
}

View File

@ -1,18 +1,18 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net6.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
<PropertyGroup>
<TargetFramework>net6.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\FurnitureAssemblyContracts\FurnitureAssemblyContracts.csproj" />
<ProjectReference Include="..\FurnitureAssemblyDataModels\FurnitureAssemblyDataModels.csproj" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\FurnitureAssemblyContracts\FurnitureAssemblyContracts.csproj" />
<ProjectReference Include="..\FurnitureAssemblyDataModels\FurnitureAssemblyDataModels.csproj" />
</ItemGroup>
<Target Name="PostBuild" AfterTargets="PostBuildEvent">
<Exec Command="copy /Y &quot;$(TargetDir)*.dll&quot; &quot;$(SolutionDir)ImplementationExtensions\*.dll&quot;" />
</Target>
<Target Name="PostBuild" AfterTargets="PostBuildEvent">
<Exec Command="copy /Y &quot;$(TargetDir)*.dll&quot; &quot;$(SolutionDir)ImplementationExtensions\*.dll&quot;" />
</Target>
</Project>

View File

@ -13,7 +13,9 @@ namespace FurnitureAssemblyListImplement.Implements
{
public class MessageInfoStorage : IMessageInfoStorage
{
// Поле для работы со списком изделий
private readonly DataListSingleton _source;
public MessageInfoStorage()
{
_source = DataListSingleton.GetInstance();
@ -26,6 +28,7 @@ namespace FurnitureAssemblyListImplement.Implements
if (model.MessageId != null && model.MessageId.Equals(message.MessageId))
return message.GetViewModel;
}
return null;
}
@ -44,15 +47,18 @@ namespace FurnitureAssemblyListImplement.Implements
{
return result;
}
if (model.Page * model.PageSize >= result.Count)
{
return null;
}
List<MessageInfoViewModel> filteredResult = new();
for (var i = (model.Page.Value - 1) * model.PageSize.Value; i < model.Page.Value * model.PageSize.Value; i++)
{
filteredResult.Add(result[i]);
}
return filteredResult;
}
@ -63,17 +69,21 @@ namespace FurnitureAssemblyListImplement.Implements
{
result.Add(item.GetViewModel);
}
return result;
}
public MessageInfoViewModel? Insert(MessageInfoBindingModel model)
{
var newMessage = MessageInfo.Create(model);
if (newMessage == null)
{
return null;
}
_source.MessageInfos.Add(newMessage);
return newMessage.GetViewModel;
}
@ -87,6 +97,7 @@ namespace FurnitureAssemblyListImplement.Implements
return message.GetViewModel;
}
}
return null;
}
}

View File

@ -88,7 +88,7 @@ namespace FurnitureAssemblyListImplement.Implements
return result;
}
// Получение элемента из списка заказов
// Получение элемента из списка заказов и исполнителя
public OrderViewModel? GetElement(OrderSearchModel model)
{
if (!model.Id.HasValue)

View File

@ -52,7 +52,6 @@ namespace FurnitureAssemblyView
textBoxName.Text = view.FurnitureName;
textBoxPrice.Text = view.Price.ToString();
_furnitureWorkPieces = view.FurnitureWorkPieces ?? new Dictionary<int, (IWorkPieceModel, int)>();
LoadData();
}
}

View File

@ -52,7 +52,7 @@ namespace FurnitureAssemblyView
{
dataGridView.FillandConfigGrid(_orderLogic.ReadList(null));
_logger.LogInformation("Загрузка заказов");
_logger.LogInformation("Успешная загрузка заказов");
}
catch (Exception ex)
{
@ -99,7 +99,7 @@ namespace FurnitureAssemblyView
if (!operationResult)
{
throw new Exception("Ошибка при сохранении. Дополнительная информация в логах.");
throw new Exception("Заказ не в статусе готовности. Дополнительная информация в логах.");
}
_logger.LogInformation("Заказ №{id} выдан", id);

View File

@ -9,6 +9,19 @@
</PropertyGroup>
<ItemGroup>
<None Update="App.config">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
<None Update="nlog.config">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
<None Update="ReportGroupedOrders.rdlc">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
<None Update="ReportOrders.rdlc">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
<PackageReference Include="Microsoft.Data.SqlClient" Version="5.2.0" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="7.0.16">
<PrivateAssets>all</PrivateAssets>
@ -22,21 +35,6 @@
<PackageReference Include="ReportViewerCore.WinForms" Version="15.1.17" />
</ItemGroup>
<ItemGroup>
<None Update="App.config">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
<None Update="nlog.config">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
<None Update="ReportGroupedOrders.rdlc">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
<None Update="ReportOrders.rdlc">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\FurnitureAssemblyBusinessLogic\FurnitureAssemblyBusinessLogic.csproj" />
<ProjectReference Include="..\FurnitureAssemblyContracts\FurnitureAssemblyContracts.csproj" />
@ -46,9 +44,9 @@
</ItemGroup>
<ItemGroup>
<Compile Update="FormReportOrders.cs">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</Compile>
<Compile Update="FormReportOrders.cs">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</Compile>
</ItemGroup>
</Project>