Сделанная 8 лаба

This commit is contained in:
Табеев Александр 2024-05-19 20:03:41 +04:00
parent 47f3126ed9
commit 4429dec0c6
55 changed files with 1603 additions and 540 deletions

View File

@ -0,0 +1,103 @@
using CarpentryWorkshopContracts.BindingModels;
using CarpentryWorkshopContracts.BusinessLogicsContracts;
using CarpentryWorkshopContracts.StoragesContracts;
using CarpentryWorkshopDataModels;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.IO.Compression;
using System.Linq;
using System.Reflection;
using System.Runtime.Serialization.Json;
using System.Text;
using System.Threading.Tasks;
namespace CarpentryWorkshopBusinessLogic.BusinessLogics
{
public class BackUpLogic : IBackUpLogic
{
private readonly ILogger _logger;
private readonly IBackUpInfo _backUpInfo;
public BackUpLogic(ILogger<BackUpLogic> logger, IBackUpInfo backUpInfo)
{
_logger = logger;
_backUpInfo = backUpInfo;
}
public void CreateBackUp(BackUpSaveBindingModel model)
{
if (_backUpInfo == null)
{
return;
}
try
{
_logger.LogDebug("Clear folder");
// зачистка папки и удаление старого архива
var dirInfo = new DirectoryInfo(model.FolderName);
if (dirInfo.Exists)
{
foreach (var file in dirInfo.GetFiles())
{
file.Delete();
}
}
_logger.LogDebug("Delete archive");
string fileName = $"{model.FolderName}.zip";
if (File.Exists(fileName))
{
File.Delete(fileName);
}
// берем метод для сохранения
_logger.LogDebug("Get assembly");
var typeIId = typeof(IId);
var assembly = typeIId.Assembly;
if (assembly == null)
{
throw new ArgumentNullException("Сборка не найдена", nameof(assembly));
}
var types = assembly.GetTypes();
var method = GetType().GetMethod("SaveToFile", BindingFlags.NonPublic | BindingFlags.Instance);
_logger.LogDebug("Find {count} types", types.Length);
foreach (var type in types)
{
if (type.IsInterface && type.GetInterface(typeIId.Name) != null)
{
var modelType = _backUpInfo.GetTypeByModelInterface(type.Name);
if (modelType == null)
{
throw new InvalidOperationException($"Не найден класс-модель для {type.Name}");
}
_logger.LogDebug("Call SaveToFile method for {name} type", type.Name);
// вызываем метод на выполнение
method?.MakeGenericMethod(modelType).Invoke(this, new object[] { model.FolderName });
}
}
_logger.LogDebug("Create zip and remove folder");
// архивируем
ZipFile.CreateFromDirectory(model.FolderName, fileName);
// удаляем папку
dirInfo.Delete(true);
}
catch (Exception)
{
throw;
}
}
private void SaveToFile<T>(string folderName) where T : class, new()
{
var records = _backUpInfo.GetList<T>();
if (records == null)
{
_logger.LogWarning("{type} type get null list", typeof(T).Name);
return;
}
var jsonFormatter = new DataContractJsonSerializer(typeof(List<T>));
using var fs = new FileStream(string.Format("{0}/{1}.json", folderName, typeof(T).Name), FileMode.OpenOrCreate);
jsonFormatter.WriteObject(fs, records);
}
}
}

View File

@ -0,0 +1,31 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CarpentryWorkshopContracts.Attributes
{
[AttributeUsage(AttributeTargets.Property)]
public class ColumnAttribute : Attribute
{
public string Title { get; private set; }
public bool Visible { get; private set; }
public int Width { get; private set; }
public GridViewAutoSize GridViewAutoSize { get; private set; }
public bool IsUseAutoSize { get; private set; }
public ColumnAttribute(string title = "", bool visible = true, int width = 0, GridViewAutoSize gridViewAutoSize = GridViewAutoSize.None, bool isUseAutoSize = false)
{
Title = title;
Visible = visible;
Width = width;
GridViewAutoSize = gridViewAutoSize;
IsUseAutoSize = isUseAutoSize;
}
}
}

View File

@ -0,0 +1,27 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CarpentryWorkshopContracts.Attributes
{
public enum GridViewAutoSize
{
NotSet = 0,
None = 1,
ColumnHeader = 2,
AllCellsExceptHeader = 4,
AllCells = 6,
DisplayedCellsExceptHeader = 8,
DisplayedCells = 10,
Fill = 16
}
}

View File

@ -0,0 +1,13 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CarpentryWorkshopContracts.BindingModels
{
public class BackUpSaveBindingModel
{
public string FolderName { get; set; } = string.Empty;
}
}

View File

@ -20,5 +20,7 @@ namespace CarpentryWorkshopContracts.BindingModels
public string Body { get; set; } = string.Empty; public string Body { get; set; } = string.Empty;
public DateTime DateDelivery { get; set; } public DateTime DateDelivery { get; set; }
}
public int Id => throw new NotImplementedException();
}
} }

View File

@ -0,0 +1,14 @@
using CarpentryWorkshopContracts.BindingModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CarpentryWorkshopContracts.BusinessLogicsContracts
{
public interface IBackUpLogic
{
void CreateBackUp(BackUpSaveBindingModel model);
}
}

View File

@ -6,6 +6,14 @@
<Nullable>enable</Nullable> <Nullable>enable</Nullable>
</PropertyGroup> </PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Logging" Version="7.0.0" />
<PackageReference Include="Unity" Version="5.11.10" />
<PackageReference Include="Unity.Abstractions" Version="5.11.7" />
<PackageReference Include="Unity.Container" Version="5.11.11" />
<PackageReference Include="Unity.Microsoft.Logging" Version="5.11.1" />
</ItemGroup>
<ItemGroup> <ItemGroup>
<ProjectReference Include="..\CarpentryWorkshopDataModels\CarpentryWorkshopDataModels.csproj" /> <ProjectReference Include="..\CarpentryWorkshopDataModels\CarpentryWorkshopDataModels.csproj" />
</ItemGroup> </ItemGroup>

View File

@ -0,0 +1,41 @@
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CarpentryWorkshopContracts.DI
{
public class DependencyManager
{
private readonly IDependencyContainer _dependencyManager;
private static DependencyManager? _manager;
private static readonly object _lockObject = new();
private DependencyManager()
{
_dependencyManager = new ServiceDependencyContainer();
}
public static DependencyManager Instance { get { if (_manager == null) { lock (_lockObject) { _manager = new DependencyManager(); } } return _manager; } }
public static void InitDependency()
{
var ext = ServiceProviderLoader.GetImplementationExtensions();
if (ext == null)
{
throw new ArgumentNullException("Отсутствуют компоненты для загрузки зависимостей по модулям");
}
// регистрируем зависимости
ext.RegisterServices();
}
public void AddLogging(Action<ILoggingBuilder> configure) => _dependencyManager.AddLogging(configure);
public void RegisterType<T, U>(bool isSingle = false) where U : class, T where T : class => _dependencyManager.RegisterType<T, U>(isSingle);
public void RegisterType<T>(bool isSingle = false) where T : class => _dependencyManager.RegisterType<T>(isSingle);
public T Resolve<T>() => _dependencyManager.Resolve<T>();
}
}

View File

@ -0,0 +1,20 @@
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CarpentryWorkshopContracts.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

@ -0,0 +1,14 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CarpentryWorkshopContracts.DI
{
public interface IImplementationExtension
{
public int Priority { get; }
public void RegisterServices();
}
}

View File

@ -0,0 +1,62 @@
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CarpentryWorkshopContracts.DI
{
public class ServiceDependencyContainer : IDependencyContainer
{
private ServiceProvider? _serviceProvider;
private readonly ServiceCollection _serviceCollection;
public ServiceDependencyContainer()
{
_serviceCollection = new ServiceCollection();
}
public void AddLogging(Action<ILoggingBuilder> configure)
{
_serviceCollection.AddLogging(configure);
}
public void RegisterType<T, U>(bool isSingle) where U : class, T where T : class
{
if (isSingle)
{
_serviceCollection.AddSingleton<T, U>();
}
else
{
_serviceCollection.AddTransient<T, U>();
}
_serviceProvider = null;
}
public void RegisterType<T>(bool isSingle) where T : class
{
if (isSingle)
{
_serviceCollection.AddSingleton<T>();
}
else
{
_serviceCollection.AddTransient<T>();
}
_serviceProvider = null;
}
public T Resolve<T>()
{
if (_serviceProvider == null)
{
_serviceProvider = _serviceCollection.BuildServiceProvider();
}
return _serviceProvider.GetService<T>()!;
}
}
}

View File

@ -0,0 +1,51 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
namespace CarpentryWorkshopContracts.DI
{
public class ServiceProviderLoader
{
public static IImplementationExtension? GetImplementationExtensions()
{
IImplementationExtension? source = null;
var files = Directory.GetFiles(TryGetImplementationExtensionsFolder(), "*.dll", SearchOption.AllDirectories);
foreach (var file in files.Distinct())
{
Assembly asm = Assembly.LoadFrom(file);
foreach (var t in asm.GetExportedTypes())
{
if (t.IsClass && typeof(IImplementationExtension).IsAssignableFrom(t))
{
if (source == null)
{
source = (IImplementationExtension)Activator.CreateInstance(t)!;
}
else
{
var newSource = (IImplementationExtension)Activator.CreateInstance(t)!;
if (newSource.Priority > source.Priority)
{
source = newSource;
}
}
}
}
}
return source;
}
private static string TryGetImplementationExtensionsFolder()
{
var directory = new DirectoryInfo(Directory.GetCurrentDirectory());
while (directory != null && !directory.GetDirectories("ImplementationExtensions", SearchOption.AllDirectories).Any(x => x.Name == "ImplementationExtensions"))
{
directory = directory.Parent;
}
return $"{directory?.FullName}\\ImplementationExtensions";
}
}
}

View File

@ -0,0 +1,55 @@
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Unity;
using Unity.Microsoft.Logging;
namespace CarpentryWorkshopContracts.DI
{
public class UnityDependencyContainer : IDependencyContainer
{
private readonly IUnityContainer _container;
public UnityDependencyContainer()
{
_container = new UnityContainer();
}
public void AddLogging(Action<ILoggingBuilder> configure)
{
var logger = LoggerFactory.Create(configure);
_container.AddExtension(new LoggingExtension(logger));
}
public void RegisterType<T, U>(bool isSingle) where U : class, T where T : class
{
if (isSingle)
{
_container.RegisterSingleton<T, U>();
}
else
{
_container.RegisterType<T, U>();
}
}
public void RegisterType<T>(bool isSingle) where T : class
{
if (isSingle)
{
_container.RegisterSingleton<T>();
}
else
{
_container.RegisterType<T>();
}
}
public T Resolve<T>()
{
return _container.Resolve<T>();
}
}
}

View File

@ -0,0 +1,14 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CarpentryWorkshopContracts.StoragesContracts
{
public interface IBackUpInfo
{
List<T>? GetList<T>() where T : class, new();
Type? GetTypeByModelInterface(string modelInterfaceName);
}
}

View File

@ -1,4 +1,5 @@
using CarpentryWorkshopDataModels.Models; using CarpentryWorkshopContracts.Attributes;
using CarpentryWorkshopDataModels.Models;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.ComponentModel; using System.ComponentModel;
@ -10,15 +11,16 @@ namespace CarpentryWorkshopContracts.ViewModels
{ {
public class ClientViewModel : IClientModel public class ClientViewModel : IClientModel
{ {
public int Id { get; set; } [Column(visible: false)]
public int Id { get; set; }
[DisplayName("ФИО клиента")] [Column(title: "ФИО клиента", width:150)]
public string ClientFIO { get; set; } = string.Empty; public string ClientFIO { get; set; } = string.Empty;
[DisplayName("Логин (эл. почта)")] [Column(title: "Логин (эл. почта)", gridViewAutoSize: GridViewAutoSize.Fill, isUseAutoSize: true)]
public string Email { get; set; } = string.Empty; public string Email { get; set; } = string.Empty;
[DisplayName("Пароль")] [Column(title: "Пароль", width: 150)]
public string Password { get; set; } = string.Empty; public string Password { get; set; } = string.Empty;
} }
} }

View File

@ -1,4 +1,5 @@
using CarpentryWorkshopDataModels.Models; using CarpentryWorkshopContracts.Attributes;
using CarpentryWorkshopDataModels.Models;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.ComponentModel; using System.ComponentModel;
@ -10,10 +11,11 @@ namespace CarpentryWorkshopContracts.ViewModels
{ {
public class ComponentViewModel : IComponentModel public class ComponentViewModel : IComponentModel
{ {
public int Id { get; set; } [Column(visible: false)]
[DisplayName("Название компонента")] public int Id { get; set; }
public string ComponentName { get; set; } = string.Empty; [Column(title: "Название компонента", gridViewAutoSize: GridViewAutoSize.Fill, isUseAutoSize: true)]
[DisplayName("Цена")] public string ComponentName { get; set; } = string.Empty;
public double Cost { get; set; } [Column(title: "Цена", width: 100)]
public double Cost { get; set; }
} }
} }

View File

@ -1,4 +1,5 @@
using CarpentryWorkshopDataModels.Models; using CarpentryWorkshopContracts.Attributes;
using CarpentryWorkshopDataModels.Models;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.ComponentModel; using System.ComponentModel;
@ -10,18 +11,19 @@ namespace CarpentryWorkshopContracts.ViewModels
{ {
public class ImplementerViewModel : IImplementerModel public class ImplementerViewModel : IImplementerModel
{ {
public int Id { get; set; } [Column(visible: false)]
public int Id { get; set; }
[DisplayName("ФИО")] [Column(title: "ФИО", gridViewAutoSize: GridViewAutoSize.Fill, isUseAutoSize: true)]
public string ImplementerFIO { get; set; } = string.Empty; public string ImplementerFIO { get; set; } = string.Empty;
[DisplayName("Пароль")] [Column(title: "Пароль", width: 150)]
public string Password { get; set; } = string.Empty; public string Password { get; set; } = string.Empty;
[DisplayName("Стаж работы")] [Column(title: "Стаж работы", gridViewAutoSize: GridViewAutoSize.AllCells, isUseAutoSize: true)]
public int WorkExperience { get; set; } public int WorkExperience { get; set; }
[DisplayName("Квалификация")] [Column(title: "Квалификация", gridViewAutoSize: GridViewAutoSize.AllCells, isUseAutoSize: true)]
public int Qualification { get; set; } public int Qualification { get; set; }
} }
} }

View File

@ -1,4 +1,5 @@
using CarpentryWorkshopDataModels.Models; using CarpentryWorkshopContracts.Attributes;
using CarpentryWorkshopDataModels.Models;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.ComponentModel; using System.ComponentModel;
@ -10,20 +11,25 @@ namespace CarpentryWorkshopContracts.ViewModels
{ {
public class MessageInfoViewModel : IMessageInfoModel public class MessageInfoViewModel : IMessageInfoModel
{ {
public string MessageId { get; set; } = string.Empty; [Column(visible: false)]
public string MessageId { get; set; } = string.Empty;
public int? ClientId { get; set; } [Column(visible: false)]
public int? ClientId { get; set; }
[DisplayName("Отправитель")] [Column(title: "Отправитель", gridViewAutoSize: GridViewAutoSize.DisplayedCells, isUseAutoSize: true)]
public string SenderName { get; set; } = string.Empty; public string SenderName { get; set; } = string.Empty;
[DisplayName("Дата письма")] [Column(title: "Дата письма", width: 100)]
public DateTime DateDelivery { get; set; } public DateTime DateDelivery { get; set; }
[DisplayName("Заголовок")] [Column(title: "Заголовок", width: 150)]
public string Subject { get; set; } = string.Empty; public string Subject { get; set; } = string.Empty;
[DisplayName("Текст")] [Column(title: "Текст", gridViewAutoSize: GridViewAutoSize.Fill, isUseAutoSize: true)]
public string Body { get; set; } = string.Empty; public string Body { get; set; } = string.Empty;
}
[Column(visible: false)]
public int Id => throw new NotImplementedException();
}
} }

View File

@ -1,4 +1,5 @@
using CarpentryWorkshopDataModels.Enums; using CarpentryWorkshopContracts.Attributes;
using CarpentryWorkshopDataModels.Enums;
using CarpentryWorkshopDataModels.Models; using CarpentryWorkshopDataModels.Models;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
@ -11,34 +12,37 @@ namespace CarpentryWorkshopContracts.ViewModels
{ {
public class OrderViewModel : IOrderModel public class OrderViewModel : IOrderModel
{ {
[DisplayName("Номер")] [Column(title: "Номер", gridViewAutoSize: GridViewAutoSize.AllCells, isUseAutoSize: true)]
public int Id { get; set; } public int Id { get; set; }
public int WoodId { get; set; } [Column(visible: false)]
public int ClientId { get; set; } public int WoodId { get; set; }
public int? ImplementerId { get; set; } [Column(visible: false)]
public int ClientId { get; set; }
[Column(visible: false)]
public int? ImplementerId { get; set; }
[DisplayName("ФИО исполнителя")] [Column(title: "ФИО исполнителя", gridViewAutoSize: GridViewAutoSize.Fill, isUseAutoSize: true)]
public string ImplementerFIO { get; set; } = string.Empty; public string ImplementerFIO { get; set; } = string.Empty;
[DisplayName("ФИО клиента")] [Column(title: "ФИО клиента", gridViewAutoSize: GridViewAutoSize.Fill, isUseAutoSize: true)]
public string ClientFIO { get; set; } = string.Empty; public string ClientFIO { get; set; } = string.Empty;
[DisplayName("Изделие")] [Column(title: "Изделие", gridViewAutoSize: GridViewAutoSize.AllCells, isUseAutoSize: true)]
public string WoodName { get; set; } = string.Empty; public string WoodName { get; set; } = string.Empty;
[DisplayName("Количество")] [Column(title: "Количество", gridViewAutoSize: GridViewAutoSize.AllCells, isUseAutoSize: true)]
public int Count { get; set; } public int Count { get; set; }
[DisplayName("Сумма")] [Column(title: "Сумма", gridViewAutoSize: GridViewAutoSize.AllCells, isUseAutoSize: true)]
public double Sum { get; set; } public double Sum { get; set; }
[DisplayName("Статус")] [Column(title: "Статус", gridViewAutoSize: GridViewAutoSize.AllCells, isUseAutoSize: true)]
public OrderStatus Status { get; set; } = OrderStatus.Неизвестен; public OrderStatus Status { get; set; } = OrderStatus.Неизвестен;
[DisplayName("Дата создания")] [Column(title: "Дата создания", width: 100)]
public DateTime DateCreate { get; set; } = DateTime.Now; public DateTime DateCreate { get; set; } = DateTime.Now;
[DisplayName("Дата выполнения")] [Column(title: "Дата выполнения", width: 100)]
public DateTime? DateImplement { get; set; } public DateTime? DateImplement { get; set; }
} }
} }

View File

@ -1,4 +1,5 @@
using CarpentryWorkshopDataModels.Models; using CarpentryWorkshopContracts.Attributes;
using CarpentryWorkshopDataModels.Models;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.ComponentModel; using System.ComponentModel;
@ -10,11 +11,13 @@ namespace CarpentryWorkshopContracts.ViewModels
{ {
public class WoodViewModel : IWoodModel public class WoodViewModel : IWoodModel
{ {
public int Id { get; set; } [Column(visible: false)]
[DisplayName("Название изделия")] public int Id { get; set; }
public string WoodName { get; set; } = string.Empty; [Column(title: "Название изделия", gridViewAutoSize: GridViewAutoSize.Fill, isUseAutoSize: true)]
[DisplayName("Цена")] public string WoodName { get; set; } = string.Empty;
public double Price { get; set; } [Column(title: "Цена", width: 100)]
public Dictionary<int, (IComponentModel, int)> WoodComponents { get; set; } = new(); public double Price { get; set; }
[Column(visible: false)]
public Dictionary<int, (IComponentModel, int)> WoodComponents { get; set; } = new();
} }
} }

View File

@ -6,7 +6,7 @@ using System.Threading.Tasks;
namespace CarpentryWorkshopDataModels.Models namespace CarpentryWorkshopDataModels.Models
{ {
public interface IMessageInfoModel public interface IMessageInfoModel : IId
{ {
string MessageId { get; } string MessageId { get; }

View File

@ -20,4 +20,8 @@
<ProjectReference Include="..\CarpentryWorkshopDataModels\CarpentryWorkshopDataModels.csproj" /> <ProjectReference Include="..\CarpentryWorkshopDataModels\CarpentryWorkshopDataModels.csproj" />
</ItemGroup> </ItemGroup>
<Target Name="PostBuild" AfterTargets="PostBuildEvent">
<Exec Command="copy /Y &quot;$(TargetDir)*.dll&quot; &quot;$(SolutionDir)ImplementationExtensions\*.dll&quot;" />
</Target>
</Project> </Project>

View File

@ -0,0 +1,27 @@
using CarpentryWorkshopContracts.DI;
using CarpentryWorkshopContracts.StoragesContracts;
using CarpentryWorkshopDatabaseImplement.Implements;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CarpentryWorkshopDatabaseImplement
{
public class DatabaseImplementationExtension : IImplementationExtension
{
public int Priority => 2;
public void RegisterServices()
{
DependencyManager.Instance.RegisterType<IClientStorage, ClientStorage>();
DependencyManager.Instance.RegisterType<IComponentStorage, ComponentStorage>();
DependencyManager.Instance.RegisterType<IImplementerStorage, ImplementerStorage>();
DependencyManager.Instance.RegisterType<IMessageInfoStorage, MessageInfoStorage>();
DependencyManager.Instance.RegisterType<IOrderStorage, OrderStorage>();
DependencyManager.Instance.RegisterType<IWoodStorage, WoodStorage>();
DependencyManager.Instance.RegisterType<IBackUpInfo, BackUpInfo>();
}
}
}

View File

@ -0,0 +1,31 @@
using CarpentryWorkshopContracts.StoragesContracts;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CarpentryWorkshopDatabaseImplement.Implements
{
public class BackUpInfo : IBackUpInfo
{
public List<T>? GetList<T>() where T : class, new()
{
using var context = new CarpentryWorkshopDatabase();
return context.Set<T>().ToList();
}
public Type? GetTypeByModelInterface(string modelInterfaceName)
{
var assembly = typeof(BackUpInfo).Assembly;
var types = assembly.GetTypes();
foreach (var type in types)
{
if (type.IsClass && type.GetInterface(modelInterfaceName) != null)
{
return type;
}
}
return null;
}
}
}

View File

@ -0,0 +1,298 @@
// <auto-generated />
using System;
using CarpentryWorkshopDatabaseImplement;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
#nullable disable
namespace CarpentryWorkshopDatabaseImplement.Migrations
{
[DbContext(typeof(CarpentryWorkshopDatabase))]
[Migration("20240519151003_FourthMigration")]
partial class FourthMigration
{
/// <inheritdoc />
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "7.0.17")
.HasAnnotation("Relational:MaxIdentifierLength", 128);
SqlServerModelBuilderExtensions.UseIdentityColumns(modelBuilder);
modelBuilder.Entity("CarpentryWorkshopDatabaseImplement.Models.Client", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<string>("ClientFIO")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<string>("Email")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<string>("Password")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.HasKey("Id");
b.ToTable("Clients");
});
modelBuilder.Entity("CarpentryWorkshopDatabaseImplement.Models.Component", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<string>("ComponentName")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<double>("Cost")
.HasColumnType("float");
b.HasKey("Id");
b.ToTable("Components");
});
modelBuilder.Entity("CarpentryWorkshopDatabaseImplement.Models.Implementer", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<string>("ImplementerFIO")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<string>("Password")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<int>("Qualification")
.HasColumnType("int");
b.Property<int>("WorkExperience")
.HasColumnType("int");
b.HasKey("Id");
b.ToTable("Implementers");
});
modelBuilder.Entity("CarpentryWorkshopDatabaseImplement.Models.MessageInfo", b =>
{
b.Property<string>("MessageId")
.HasColumnType("nvarchar(450)");
b.Property<string>("Body")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<int?>("ClientId")
.HasColumnType("int");
b.Property<DateTime>("DateDelivery")
.HasColumnType("datetime2");
b.Property<string>("SenderName")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<string>("Subject")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.HasKey("MessageId");
b.HasIndex("ClientId");
b.ToTable("Messages");
});
modelBuilder.Entity("CarpentryWorkshopDatabaseImplement.Models.Order", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<int>("ClientId")
.HasColumnType("int");
b.Property<int>("Count")
.HasColumnType("int");
b.Property<DateTime>("DateCreate")
.HasColumnType("datetime2");
b.Property<DateTime?>("DateImplement")
.HasColumnType("datetime2");
b.Property<int?>("ImplementerId")
.HasColumnType("int");
b.Property<int>("Status")
.HasColumnType("int");
b.Property<double>("Sum")
.HasColumnType("float");
b.Property<int>("WoodId")
.HasColumnType("int");
b.HasKey("Id");
b.HasIndex("ClientId");
b.HasIndex("ImplementerId");
b.HasIndex("WoodId");
b.ToTable("Orders");
});
modelBuilder.Entity("CarpentryWorkshopDatabaseImplement.Models.Wood", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<double>("Price")
.HasColumnType("float");
b.Property<string>("WoodName")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.HasKey("Id");
b.ToTable("Woods");
});
modelBuilder.Entity("CarpentryWorkshopDatabaseImplement.Models.WoodComponent", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<int>("ComponentId")
.HasColumnType("int");
b.Property<int>("Count")
.HasColumnType("int");
b.Property<int>("WoodId")
.HasColumnType("int");
b.HasKey("Id");
b.HasIndex("ComponentId");
b.HasIndex("WoodId");
b.ToTable("WoodComponents");
});
modelBuilder.Entity("CarpentryWorkshopDatabaseImplement.Models.MessageInfo", b =>
{
b.HasOne("CarpentryWorkshopDatabaseImplement.Models.Client", "Client")
.WithMany("Messages")
.HasForeignKey("ClientId");
b.Navigation("Client");
});
modelBuilder.Entity("CarpentryWorkshopDatabaseImplement.Models.Order", b =>
{
b.HasOne("CarpentryWorkshopDatabaseImplement.Models.Client", "Client")
.WithMany("Orders")
.HasForeignKey("ClientId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("CarpentryWorkshopDatabaseImplement.Models.Implementer", "Implementer")
.WithMany("Orders")
.HasForeignKey("ImplementerId");
b.HasOne("CarpentryWorkshopDatabaseImplement.Models.Wood", "Wood")
.WithMany("Orders")
.HasForeignKey("WoodId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Client");
b.Navigation("Implementer");
b.Navigation("Wood");
});
modelBuilder.Entity("CarpentryWorkshopDatabaseImplement.Models.WoodComponent", b =>
{
b.HasOne("CarpentryWorkshopDatabaseImplement.Models.Component", "Component")
.WithMany("WoodComponents")
.HasForeignKey("ComponentId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("CarpentryWorkshopDatabaseImplement.Models.Wood", "Wood")
.WithMany("Components")
.HasForeignKey("WoodId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Component");
b.Navigation("Wood");
});
modelBuilder.Entity("CarpentryWorkshopDatabaseImplement.Models.Client", b =>
{
b.Navigation("Messages");
b.Navigation("Orders");
});
modelBuilder.Entity("CarpentryWorkshopDatabaseImplement.Models.Component", b =>
{
b.Navigation("WoodComponents");
});
modelBuilder.Entity("CarpentryWorkshopDatabaseImplement.Models.Implementer", b =>
{
b.Navigation("Orders");
});
modelBuilder.Entity("CarpentryWorkshopDatabaseImplement.Models.Wood", b =>
{
b.Navigation("Components");
b.Navigation("Orders");
});
#pragma warning restore 612, 618
}
}
}

View File

@ -0,0 +1,22 @@
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace CarpentryWorkshopDatabaseImplement.Migrations
{
/// <inheritdoc />
public partial class FourthMigration : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
}
}
}

View File

@ -8,21 +8,27 @@ using System.ComponentModel.DataAnnotations;
using System.Linq; using System.Linq;
using System.Text; using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
using System.Runtime.Serialization;
namespace CarpentryWorkshopDatabaseImplement.Models namespace CarpentryWorkshopDatabaseImplement.Models
{ {
public class Client : IClientModel [DataContract]
public class Client : IClientModel
{ {
public int Id { get; private set; } [DataMember]
public int Id { get; private set; }
[Required] [Required]
public string ClientFIO { get; private set; } = string.Empty; [DataMember]
public string ClientFIO { get; private set; } = string.Empty;
[Required] [Required]
public string Email { get; private set; } = string.Empty; [DataMember]
public string Email { get; private set; } = string.Empty;
[Required] [Required]
public string Password { get; private set; } = string.Empty; [DataMember]
public string Password { get; private set; } = string.Empty;
[ForeignKey("ClientId")] [ForeignKey("ClientId")]
public virtual List<Order> Orders { get; set; } = new(); public virtual List<Order> Orders { get; set; } = new();

View File

@ -6,20 +6,25 @@ using System.Collections.Generic;
using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema; using System.ComponentModel.DataAnnotations.Schema;
using System.Linq; using System.Linq;
using System.Runtime.Serialization;
using System.Text; using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
namespace CarpentryWorkshopDatabaseImplement.Models namespace CarpentryWorkshopDatabaseImplement.Models
{ {
public class Component : IComponentModel [DataContract]
public class Component : IComponentModel
{ {
public int Id { get; private set; } [DataMember]
public int Id { get; private set; }
[Required] [Required]
public string ComponentName { get; private set; } = string.Empty; [DataMember]
public string ComponentName { get; private set; } = string.Empty;
[Required] [Required]
public double Cost { get; set; } [DataMember]
public double Cost { get; set; }
[ForeignKey("ComponentId")] [ForeignKey("ComponentId")]
public virtual List<WoodComponent> WoodComponents { get; set; } = new(); public virtual List<WoodComponent> WoodComponents { get; set; } = new();

View File

@ -8,20 +8,27 @@ using System.ComponentModel.DataAnnotations;
using System.Linq; using System.Linq;
using System.Text; using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
using System.Runtime.Serialization;
namespace CarpentryWorkshopDatabaseImplement.Models namespace CarpentryWorkshopDatabaseImplement.Models
{ {
public class Implementer : IImplementerModel [DataContract]
public class Implementer : IImplementerModel
{ {
public int Id { get; private set; } [DataMember]
public int Id { get; private set; }
public string ImplementerFIO { get; private set; } = string.Empty; [DataMember]
public string ImplementerFIO { get; private set; } = string.Empty;
public string Password { get; private set; } = string.Empty; [DataMember]
public string Password { get; private set; } = string.Empty;
public int WorkExperience { get; private set; } [DataMember]
public int WorkExperience { get; private set; }
public int Qualification { get; private set; } [DataMember]
public int Qualification { get; private set; }
[ForeignKey("ImplementerId")] [ForeignKey("ImplementerId")]
public virtual List<Order> Orders { get; set; } = new(); public virtual List<Order> Orders { get; set; } = new();

View File

@ -5,15 +5,18 @@ using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations;
using System.Linq; using System.Linq;
using System.Runtime.Serialization;
using System.Text; using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
namespace CarpentryWorkshopDatabaseImplement.Models namespace CarpentryWorkshopDatabaseImplement.Models
{ {
public class MessageInfo : IMessageInfoModel [DataContract]
public class MessageInfo : IMessageInfoModel
{ {
[Key] [Key]
public string MessageId { get; private set; } = string.Empty; [DataMember]
public string MessageId { get; private set; } = string.Empty;
public int? ClientId { get; private set; } public int? ClientId { get; private set; }
@ -53,5 +56,7 @@ namespace CarpentryWorkshopDatabaseImplement.Models
SenderName = SenderName, SenderName = SenderName,
DateDelivery = DateDelivery, DateDelivery = DateDelivery,
}; };
}
public int Id => throw new NotImplementedException();
}
} }

View File

@ -7,35 +7,47 @@ using System.Collections.Generic;
using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations;
using System.Linq; using System.Linq;
using System.Reflection; using System.Reflection;
using System.Runtime.Serialization;
using System.Text; using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
namespace CarpentryWorkshopDatabaseImplement.Models namespace CarpentryWorkshopDatabaseImplement.Models
{ {
public class Order : IOrderModel [DataContract]
public class Order : IOrderModel
{ {
public int Id { get; set; } [DataMember]
public int Id { get; set; }
[Required] [Required]
public int WoodId { get; set; } [DataMember]
public int WoodId { get; set; }
[Required] [Required]
public int ClientId { get; set; } [DataMember]
public int? ImplementerId { get; private set; } public int ClientId { get; set; }
[DataMember]
public int? ImplementerId { get; private set; }
[Required] [Required]
public int Count { get; set; } [DataMember]
public int Count { get; set; }
[Required] [Required]
public double Sum { get; set; } [DataMember]
public double Sum { get; set; }
[Required] [Required]
public OrderStatus Status { get; set; } [DataMember]
public OrderStatus Status { get; set; }
[Required] [Required]
public DateTime DateCreate { get; set; } [DataMember]
public DateTime DateCreate { get; set; }
public DateTime? DateImplement { get; set; } [DataMember]
public DateTime? DateImplement { get; set; }
public virtual Wood Wood { get; set; } public virtual Wood Wood { get; set; }
public virtual Client Client { get; set; } public virtual Client Client { get; set; }

View File

@ -6,25 +6,31 @@ using System.Collections.Generic;
using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema; using System.ComponentModel.DataAnnotations.Schema;
using System.Linq; using System.Linq;
using System.Runtime.Serialization;
using System.Text; using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
namespace CarpentryWorkshopDatabaseImplement.Models namespace CarpentryWorkshopDatabaseImplement.Models
{ {
public class Wood : IWoodModel [DataContract]
public class Wood : IWoodModel
{ {
public int Id { get; set; } [DataMember]
public int Id { get; set; }
[Required] [Required]
public string WoodName { get; set; } = string.Empty; [DataMember]
public string WoodName { get; set; } = string.Empty;
[Required] [Required]
public double Price { get; set; } [DataMember]
public double Price { get; set; }
private Dictionary<int, (IComponentModel, int)>? _woodComponents = null; private Dictionary<int, (IComponentModel, int)>? _woodComponents = null;
[NotMapped] [NotMapped]
public Dictionary<int, (IComponentModel, int)> WoodComponents [DataMember]
public Dictionary<int, (IComponentModel, int)> WoodComponents
{ {
get get
{ {

View File

@ -12,4 +12,8 @@
<ProjectReference Include="..\CarpentryWorkshopListImplement\CarpentryWorkshopListImplement.csproj" /> <ProjectReference Include="..\CarpentryWorkshopListImplement\CarpentryWorkshopListImplement.csproj" />
</ItemGroup> </ItemGroup>
<Target Name="PostBuild" AfterTargets="PostBuildEvent">
<Exec Command="copy /Y &quot;$(TargetDir)*.dll&quot; &quot;$(SolutionDir)ImplementationExtensions\*.dll&quot;" />
</Target>
</Project> </Project>

View File

@ -0,0 +1,27 @@
using CarpentryWorkshopContracts.DI;
using CarpentryWorkshopContracts.StoragesContracts;
using CarpentryWorkshopFileImplement.Implements;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CarpentryWorkshopFileImplement
{
public class FileImplementationExtension : IImplementationExtension
{
public int Priority => 1;
public void RegisterServices()
{
DependencyManager.Instance.RegisterType<IClientStorage, ClientStorage>();
DependencyManager.Instance.RegisterType<IComponentStorage, ComponentStorage>();
DependencyManager.Instance.RegisterType<IImplementerStorage, ImplementerStorage>();
DependencyManager.Instance.RegisterType<IMessageInfoStorage, MessageInfoStorage>();
DependencyManager.Instance.RegisterType<IOrderStorage, OrderStorage>();
DependencyManager.Instance.RegisterType<IWoodStorage, WoodStorage>();
DependencyManager.Instance.RegisterType<IBackUpInfo, BackUpInfo>();
}
}
}

View File

@ -0,0 +1,32 @@
using CarpentryWorkshopContracts.StoragesContracts;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CarpentryWorkshopFileImplement.Implements
{
public class BackUpInfo : IBackUpInfo
{
public List<T>? GetList<T>() where T : class, new()
{
// Получаем значения из singleton-объекта универсального свойства содержащее тип T
var source = DataFileSingleton.GetInstance();
return (List<T>?)source.GetType().GetProperties().FirstOrDefault(x => x.PropertyType.IsGenericType && x.PropertyType.GetGenericArguments()[0] == typeof(T))?.GetValue(source);
}
public Type? GetTypeByModelInterface(string modelInterfaceName)
{
var assembly = typeof(BackUpInfo).Assembly;
var types = assembly.GetTypes();
foreach (var type in types)
{
if (type.IsClass && type.GetInterface(modelInterfaceName) != null)
{
return type;
}
}
return null;
}
}
}

View File

@ -4,18 +4,27 @@ using CarpentryWorkshopDataModels.Models;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Runtime.Serialization;
using System.Text; using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
using System.Xml.Linq; using System.Xml.Linq;
namespace CarpentryWorkshopFileImplement.Models namespace CarpentryWorkshopFileImplement.Models
{ {
public class Client : IClientModel [DataContract]
public class Client : IClientModel
{ {
public int Id { get; private set; } [DataMember]
public string ClientFIO { get; private set; } = string.Empty; public int Id { get; private set; }
public string Email { get; private set; } = string.Empty;
public string Password { get; private set; } = string.Empty; [DataMember]
public string ClientFIO { get; private set; } = string.Empty;
[DataMember]
public string Email { get; private set; } = string.Empty;
[DataMember]
public string Password { get; private set; } = string.Empty;
public static Client? Create(ClientBindingModel model) public static Client? Create(ClientBindingModel model)
{ {

View File

@ -4,17 +4,24 @@ using CarpentryWorkshopDataModels.Models;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Runtime.Serialization;
using System.Text; using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
using System.Xml.Linq; using System.Xml.Linq;
namespace CarpentryWorkshopFileImplement.Models namespace CarpentryWorkshopFileImplement.Models
{ {
public class Component : IComponentModel [DataContract]
public class Component : IComponentModel
{ {
public int Id { get; private set; } [DataMember]
public string ComponentName { get; private set; } = string.Empty; public int Id { get; private set; }
public double Cost { get; set; }
[DataMember]
public string ComponentName { get; private set; } = string.Empty;
[DataMember]
public double Cost { get; set; }
public static Component? Create(ComponentBindingModel? model) public static Component? Create(ComponentBindingModel? model)
{ {

View File

@ -4,19 +4,30 @@ using CarpentryWorkshopDataModels.Models;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Runtime.Serialization;
using System.Text; using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
using System.Xml.Linq; using System.Xml.Linq;
namespace CarpentryWorkshopFileImplement.Models namespace CarpentryWorkshopFileImplement.Models
{ {
public class Implementer : IImplementerModel [DataContract]
public class Implementer : IImplementerModel
{ {
public int Id { get; private set; } [DataMember]
public string ImplementerFIO { get; private set; } = string.Empty; public int Id { get; private set; }
public string Password { get; private set; } = string.Empty;
public int WorkExperience { get; private set; } [DataMember]
public int Qualification { get; private set; } public string ImplementerFIO { get; private set; } = string.Empty;
[DataMember]
public string Password { get; private set; } = string.Empty;
[DataMember]
public int WorkExperience { get; private set; }
[DataMember]
public int Qualification { get; private set; }
public static Implementer? Create(ImplementerBindingModel model) public static Implementer? Create(ImplementerBindingModel model)
{ {

View File

@ -4,25 +4,33 @@ using CarpentryWorkshopDataModels.Models;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Runtime.Serialization;
using System.Text; using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
using System.Xml.Linq; using System.Xml.Linq;
namespace CarpentryWorkshopFileImplement.Models namespace CarpentryWorkshopFileImplement.Models
{ {
public class MessageInfo : IMessageInfoModel [DataContract]
public class MessageInfo : IMessageInfoModel
{ {
public string MessageId { get; private set; } = string.Empty; [DataMember]
public string MessageId { get; private set; } = string.Empty;
public int? ClientId { get; private set; } [DataMember]
public int? ClientId { get; private set; }
public string SenderName { get; private set; } = string.Empty; [DataMember]
public string SenderName { get; private set; } = string.Empty;
public DateTime DateDelivery { get; private set; } = DateTime.Now; [DataMember]
public DateTime DateDelivery { get; private set; } = DateTime.Now;
public string Subject { get; private set; } = string.Empty; [DataMember]
public string Subject { get; private set; } = string.Empty;
public string Body { get; private set; } = string.Empty; [DataMember]
public string Body { get; private set; } = string.Empty;
public static MessageInfo? Create(MessageInfoBindingModel model) public static MessageInfo? Create(MessageInfoBindingModel model)
{ {
@ -75,5 +83,7 @@ namespace CarpentryWorkshopFileImplement.Models
new XAttribute("MessageId", MessageId), new XAttribute("MessageId", MessageId),
new XAttribute("SenderName", SenderName), new XAttribute("SenderName", SenderName),
new XAttribute("DateDelivery", DateDelivery)); new XAttribute("DateDelivery", DateDelivery));
}
public int Id => throw new NotImplementedException();
}
} }

View File

@ -6,23 +6,42 @@ using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Diagnostics; using System.Diagnostics;
using System.Linq; using System.Linq;
using System.Runtime.Serialization;
using System.Text; using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
using System.Xml.Linq; using System.Xml.Linq;
namespace CarpentryWorkshopFileImplement.Models namespace CarpentryWorkshopFileImplement.Models
{ {
public class Order : IOrderModel [DataContract]
public class Order : IOrderModel
{ {
public int Id { get; private set; } [DataMember]
public int WoodId { get; private set; } public int Id { get; private set; }
public int ClientId { get; private set; }
public int? ImplementerId { get; private set; } [DataMember]
public int Count { get; private set; } public int WoodId { get; private set; }
public double Sum { get; private set; }
public OrderStatus Status { get; private set; } = OrderStatus.Неизвестен; [DataMember]
public DateTime DateCreate { get; private set; } = DateTime.Now; public int ClientId { get; private set; }
public DateTime? DateImplement { get; private set; }
[DataMember]
public int? ImplementerId { get; private set; }
[DataMember]
public int Count { get; private set; }
[DataMember]
public double Sum { get; private set; }
[DataMember]
public OrderStatus Status { get; private set; } = OrderStatus.Неизвестен;
[DataMember]
public DateTime DateCreate { get; private set; } = DateTime.Now;
[DataMember]
public DateTime? DateImplement { get; private set; }
public virtual Wood Wood { get; set; } public virtual Wood Wood { get; set; }
public virtual Client Client { get; set; } public virtual Client Client { get; set; }

View File

@ -4,22 +4,30 @@ using CarpentryWorkshopDataModels.Models;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Runtime.Serialization;
using System.Text; using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
using System.Xml.Linq; using System.Xml.Linq;
namespace CarpentryWorkshopFileImplement.Models namespace CarpentryWorkshopFileImplement.Models
{ {
public class Wood : IWoodModel [DataContract]
public class Wood : IWoodModel
{ {
public int Id { get; private set; } [DataMember]
public string WoodName { get; private set; } = string.Empty; public int Id { get; private set; }
public double Price { get; private set; }
[DataMember]
public string WoodName { get; private set; } = string.Empty;
[DataMember]
public double Price { get; private set; }
public Dictionary<int, int> Components { get; private set; } = new(); public Dictionary<int, int> Components { get; private set; } = new();
private Dictionary<int, (IComponentModel, int)>? _woodComponents = null; private Dictionary<int, (IComponentModel, int)>? _woodComponents = null;
public Dictionary<int, (IComponentModel, int)> WoodComponents { [DataMember]
public Dictionary<int, (IComponentModel, int)> WoodComponents {
get { get {
if (_woodComponents == null) if (_woodComponents == null)
{ {

View File

@ -11,4 +11,8 @@
<ProjectReference Include="..\CarpentryWorkshopDataModels\CarpentryWorkshopDataModels.csproj" /> <ProjectReference Include="..\CarpentryWorkshopDataModels\CarpentryWorkshopDataModels.csproj" />
</ItemGroup> </ItemGroup>
<Target Name="PostBuild" AfterTargets="PostBuildEvent">
<Exec Command="copy /Y &quot;$(TargetDir)*.dll&quot; &quot;$(SolutionDir)ImplementationExtensions\*.dll&quot;" />
</Target>
</Project> </Project>

View File

@ -0,0 +1,22 @@
using CarpentryWorkshopContracts.StoragesContracts;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CarpentryWorkshopListImplement.Implements
{
public class BackUpInfo : IBackUpInfo
{
public List<T>? GetList<T>() where T : class, new()
{
throw new NotImplementedException();
}
public Type? GetTypeByModelInterface(string modelInterfaceName)
{
throw new NotImplementedException();
}
}
}

View File

@ -0,0 +1,27 @@
using CarpentryWorkshopContracts.DI;
using CarpentryWorkshopContracts.StoragesContracts;
using CarpentryWorkshopListImplement.Implements;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CarpentryWorkshopListImplement
{
public class ListImplementationExtension
{
public int Priority => 0;
public void RegisterServices()
{
DependencyManager.Instance.RegisterType<IClientStorage, ClientStorage>();
DependencyManager.Instance.RegisterType<IComponentStorage, ComponentStorage>();
DependencyManager.Instance.RegisterType<IImplementerStorage, ImplementerStorage>();
DependencyManager.Instance.RegisterType<IMessageInfoStorage, MessageInfoStorage>();
DependencyManager.Instance.RegisterType<IOrderStorage, OrderStorage>();
DependencyManager.Instance.RegisterType<IWoodStorage, WoodStorage>();
DependencyManager.Instance.RegisterType<IBackUpInfo, BackUpInfo>();
}
}
}

View File

@ -49,5 +49,7 @@ namespace CarpentryWorkshopListImplement.Models
SenderName = SenderName, SenderName = SenderName,
DateDelivery = DateDelivery, DateDelivery = DateDelivery,
}; };
}
public int Id => throw new NotImplementedException();
}
} }

View File

@ -0,0 +1,51 @@
using CarpentryWorkshopContracts.Attributes;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CarpentryWorkshopView
{
internal static class DataGridViewExtension
{
public static void FillAndConfigGrid<T>(this DataGridView grid, List<T>? data)
{
if (data == null)
{
return;
}
grid.DataSource = data;
var type = typeof(T);
var properties = type.GetProperties();
foreach (DataGridViewColumn column in grid.Columns)
{
var property = properties.FirstOrDefault(x => x.Name == column.Name);
if (property == null)
{
throw new InvalidOperationException($"В типе {type.Name} не найдено свойство с именем {column.Name}");
}
var attribute = property.GetCustomAttributes(typeof(ColumnAttribute), true)?.SingleOrDefault();
if (attribute == null)
{
throw new InvalidOperationException($"Не найден атрибут типа ColumnAttribute для свойства { property.Name }");
}
// ищем нужный нам атрибут
if (attribute is ColumnAttribute columnAttr)
{
column.HeaderText = columnAttr.Title;
column.Visible = columnAttr.Visible;
if (columnAttr.IsUseAutoSize)
{
column.AutoSizeMode = (DataGridViewAutoSizeColumnMode)Enum.Parse(typeof(DataGridViewAutoSizeColumnMode), columnAttr.GridViewAutoSize.ToString());
}
else
{
column.Width = columnAttr.Width;
}
}
}
}
}
}

View File

@ -33,14 +33,8 @@ namespace CarpentryWorkshopView
{ {
try try
{ {
var list = _logic.ReadList(null); dataGridView.FillAndConfigGrid(_logic.ReadList(null));
if (list != null) _logger.LogInformation("Загрузка клиентов");
{
dataGridView.DataSource = list;
dataGridView.Columns["Id"].Visible = false;
dataGridView.Columns["ClientFIO"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
}
_logger.LogInformation("Загрузка клиентов");
} }
catch (Exception ex) catch (Exception ex)
{ {

View File

@ -1,5 +1,6 @@
using CarpentryWorkshopContracts.BindingModels; using CarpentryWorkshopContracts.BindingModels;
using CarpentryWorkshopContracts.BusinessLogicsContracts; using CarpentryWorkshopContracts.BusinessLogicsContracts;
using CarpentryWorkshopContracts.DI;
using CarpentryWorkshopContracts.SearchModels; using CarpentryWorkshopContracts.SearchModels;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
using System; using System;
@ -33,14 +34,8 @@ namespace CarpentryWorkshopView
{ {
try try
{ {
var list = _logic.ReadList(null); dataGridView.FillAndConfigGrid(_logic.ReadList(null));
if (list != null) _logger.LogInformation("Загрузка компонентов");
{
dataGridView.DataSource = list;
dataGridView.Columns["Id"].Visible = false;
dataGridView.Columns["ComponentName"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
}
_logger.LogInformation("Загрузка компонентов");
} }
catch (Exception ex) catch (Exception ex)
{ {
@ -51,13 +46,10 @@ namespace CarpentryWorkshopView
private void ButtonAdd_Click(object sender, EventArgs e) private void ButtonAdd_Click(object sender, EventArgs e)
{ {
var service = Program.ServiceProvider?.GetService(typeof(FormComponent)); var form = DependencyManager.Instance.Resolve<FormComponent>();
if (service is FormComponent form) if (form.ShowDialog() == DialogResult.OK)
{ {
if (form.ShowDialog() == DialogResult.OK) LoadData();
{
LoadData();
}
} }
} }
@ -65,14 +57,11 @@ namespace CarpentryWorkshopView
{ {
if (dataGridView.SelectedRows.Count == 1) if (dataGridView.SelectedRows.Count == 1)
{ {
var service = Program.ServiceProvider?.GetService(typeof(FormComponent)); var form = DependencyManager.Instance.Resolve<FormComponent>();
if (service is FormComponent form) form.Id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value);
{ if (form.ShowDialog() == DialogResult.OK)
form.Id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value); {
if (form.ShowDialog() == DialogResult.OK) LoadData();
{
LoadData();
}
} }
} }
} }

View File

@ -1,5 +1,6 @@
using CarpentryWorkshopContracts.BindingModels; using CarpentryWorkshopContracts.BindingModels;
using CarpentryWorkshopContracts.BusinessLogicsContracts; using CarpentryWorkshopContracts.BusinessLogicsContracts;
using CarpentryWorkshopContracts.DI;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
@ -33,14 +34,8 @@ namespace CarpentryWorkshopView
{ {
try try
{ {
var list = _logic.ReadList(null); dataGridView.FillAndConfigGrid(_logic.ReadList(null));
if (list != null) _logger.LogInformation("Загрузка исполнителей");
{
dataGridView.DataSource = list;
dataGridView.Columns["Id"].Visible = false;
dataGridView.Columns["ImplementerFIO"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
}
_logger.LogInformation("Загрузка исполнителей");
} }
catch (Exception ex) catch (Exception ex)
{ {
@ -52,31 +47,22 @@ namespace CarpentryWorkshopView
private void buttonAdd_Click(object sender, EventArgs e) private void buttonAdd_Click(object sender, EventArgs e)
{ {
var service = Program.ServiceProvider?.GetService(typeof(FormImplementer)); var form = DependencyManager.Instance.Resolve<FormImplementer>();
if (service is FormImplementer form) if (form.ShowDialog() == DialogResult.OK)
{ {
if (form.ShowDialog() == DialogResult.OK) LoadData();
{ }
LoadData(); }
}
}
}
private void buttonUpd_Click(object sender, EventArgs e) private void buttonUpd_Click(object sender, EventArgs e)
{ {
if (dataGridView.SelectedRows.Count == 1) var form = DependencyManager.Instance.Resolve<FormImplementer>();
{ form.Id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value);
var service = Program.ServiceProvider?.GetService(typeof(FormImplementer)); if (form.ShowDialog() == DialogResult.OK)
if (service is FormImplementer form) {
{ LoadData();
form.Id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value); }
if (form.ShowDialog() == DialogResult.OK) }
{
LoadData();
}
}
}
}
private void buttonDel_Click(object sender, EventArgs e) private void buttonDel_Click(object sender, EventArgs e)
{ {

View File

@ -27,14 +27,7 @@ namespace CarpentryWorkshopView
{ {
try try
{ {
var list = _logic.ReadList(null); dataGridView.FillAndConfigGrid(_logic.ReadList(null));
if (list != null)
{
dataGridView.DataSource = list;
dataGridView.Columns["ClientId"].Visible = false;
dataGridView.Columns["MessageId"].Visible = false;
dataGridView.Columns["Body"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
}
_logger.LogInformation("Загрузка списка писем"); _logger.LogInformation("Загрузка списка писем");
} }
catch (Exception ex) catch (Exception ex)

View File

@ -44,13 +44,14 @@
ButtonCreateOrder = new Button(); ButtonCreateOrder = new Button();
ButtonIssuedOrder = new Button(); ButtonIssuedOrder = new Button();
ButtonRef = new Button(); ButtonRef = new Button();
создатьБекапToolStripMenuItem = new ToolStripMenuItem();
menuStrip1.SuspendLayout(); menuStrip1.SuspendLayout();
((System.ComponentModel.ISupportInitialize)dataGridView).BeginInit(); ((System.ComponentModel.ISupportInitialize)dataGridView).BeginInit();
SuspendLayout(); SuspendLayout();
// //
// menuStrip1 // menuStrip1
// //
menuStrip1.Items.AddRange(new ToolStripItem[] { справочникиToolStripMenuItem, отчетыToolStripMenuItem, запускРаботToolStripMenuItem, письмаToolStripMenuItem }); menuStrip1.Items.AddRange(new ToolStripItem[] { справочникиToolStripMenuItem, отчетыToolStripMenuItem, запускРаботToolStripMenuItem, письмаToolStripMenuItem, создатьБекапToolStripMenuItem });
menuStrip1.Location = new Point(0, 0); menuStrip1.Location = new Point(0, 0);
menuStrip1.Name = "menuStrip1"; menuStrip1.Name = "menuStrip1";
menuStrip1.Size = new Size(1389, 24); menuStrip1.Size = new Size(1389, 24);
@ -67,28 +68,28 @@
// компонентыToolStripMenuItem // компонентыToolStripMenuItem
// //
компонентыToolStripMenuItem.Name = омпонентыToolStripMenuItem"; компонентыToolStripMenuItem.Name = омпонентыToolStripMenuItem";
компонентыToolStripMenuItem.Size = new Size(149, 22); компонентыToolStripMenuItem.Size = new Size(180, 22);
компонентыToolStripMenuItem.Text = "Компоненты"; компонентыToolStripMenuItem.Text = "Компоненты";
компонентыToolStripMenuItem.Click += компонентыToolStripMenuItem_Click; компонентыToolStripMenuItem.Click += компонентыToolStripMenuItem_Click;
// //
// изделияToolStripMenuItem // изделияToolStripMenuItem
// //
изделияToolStripMenuItem.Name = "изделияToolStripMenuItem"; изделияToolStripMenuItem.Name = "изделияToolStripMenuItem";
изделияToolStripMenuItem.Size = new Size(149, 22); изделияToolStripMenuItem.Size = new Size(180, 22);
изделияToolStripMenuItem.Text = "Изделия"; изделияToolStripMenuItem.Text = "Изделия";
изделияToolStripMenuItem.Click += изделияToolStripMenuItem_Click; изделияToolStripMenuItem.Click += изделияToolStripMenuItem_Click;
// //
// клиентыToolStripMenuItem // клиентыToolStripMenuItem
// //
клиентыToolStripMenuItem.Name = "клиентыToolStripMenuItem"; клиентыToolStripMenuItem.Name = "клиентыToolStripMenuItem";
клиентыToolStripMenuItem.Size = new Size(149, 22); клиентыToolStripMenuItem.Size = new Size(180, 22);
клиентыToolStripMenuItem.Text = "Клиенты"; клиентыToolStripMenuItem.Text = "Клиенты";
клиентыToolStripMenuItem.Click += ClientsToolStripMenuItem_Click; клиентыToolStripMenuItem.Click += ClientsToolStripMenuItem_Click;
// //
// исполнителиToolStripMenuItem // исполнителиToolStripMenuItem
// //
исполнителиToolStripMenuItem.Name = сполнителиToolStripMenuItem"; исполнителиToolStripMenuItem.Name = сполнителиToolStripMenuItem";
исполнителиToolStripMenuItem.Size = new Size(149, 22); исполнителиToolStripMenuItem.Size = new Size(180, 22);
исполнителиToolStripMenuItem.Text = "Исполнители"; исполнителиToolStripMenuItem.Text = "Исполнители";
исполнителиToolStripMenuItem.Click += исполнителиToolStripMenuItem_Click; исполнителиToolStripMenuItem.Click += исполнителиToolStripMenuItem_Click;
// //
@ -183,6 +184,13 @@
ButtonRef.UseVisualStyleBackColor = true; ButtonRef.UseVisualStyleBackColor = true;
ButtonRef.Click += ButtonRef_Click; ButtonRef.Click += ButtonRef_Click;
// //
// создатьБекапToolStripMenuItem
//
создатьБекапToolStripMenuItem.Name = "создатьБекапToolStripMenuItem";
создатьБекапToolStripMenuItem.Size = new Size(97, 20);
создатьБекапToolStripMenuItem.Text = "Создать бекап";
создатьБекапToolStripMenuItem.Click += создатьБекапToolStripMenuItem_Click;
//
// FormMain // FormMain
// //
AutoScaleDimensions = new SizeF(7F, 15F); AutoScaleDimensions = new SizeF(7F, 15F);
@ -222,5 +230,6 @@
private ToolStripMenuItem исполнителиToolStripMenuItem; private ToolStripMenuItem исполнителиToolStripMenuItem;
private ToolStripMenuItem запускРаботToolStripMenuItem; private ToolStripMenuItem запускРаботToolStripMenuItem;
private ToolStripMenuItem письмаToolStripMenuItem; private ToolStripMenuItem письмаToolStripMenuItem;
private ToolStripMenuItem создатьБекапToolStripMenuItem;
} }
} }

View File

@ -1,6 +1,7 @@
using CarpentryWorkshopBusinessLogic.BusinessLogics; using CarpentryWorkshopBusinessLogic.BusinessLogics;
using CarpentryWorkshopContracts.BindingModels; using CarpentryWorkshopContracts.BindingModels;
using CarpentryWorkshopContracts.BusinessLogicsContracts; using CarpentryWorkshopContracts.BusinessLogicsContracts;
using CarpentryWorkshopContracts.DI;
using CarpentryWorkshopDataModels.Enums; using CarpentryWorkshopDataModels.Enums;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
using System; using System;
@ -15,235 +16,227 @@ using System.Windows.Forms;
namespace CarpentryWorkshopView namespace CarpentryWorkshopView
{ {
public partial class FormMain : Form public partial class FormMain : Form
{ {
private readonly ILogger _logger; private readonly ILogger _logger;
private readonly IOrderLogic _orderLogic; private readonly IOrderLogic _orderLogic;
private readonly IReportLogic _reportLogic; private readonly IReportLogic _reportLogic;
private readonly IWorkProcess _workProcess; private readonly IWorkProcess _workProcess;
public FormMain(ILogger<FormMain> logger, IOrderLogic orderLogic, IReportLogic reportLogic, IWorkProcess workProcess) private readonly IBackUpLogic _backUpLogic;
{
InitializeComponent();
_logger = logger;
_orderLogic = orderLogic;
_reportLogic = reportLogic;
_workProcess = workProcess;
}
private void FormMain_Load(object sender, EventArgs e) public FormMain(ILogger<FormMain> logger, IOrderLogic orderLogic, IReportLogic reportLogic, IWorkProcess workProcess, IBackUpLogic backUpLogic)
{
LoadData();
}
private void LoadData()
{
_logger.LogInformation("Загрузка заказов");
try
{
var list = _orderLogic.ReadList(null);
if (list != null)
{
dataGridView.DataSource = list;
dataGridView.Columns["WoodId"].Visible = false;
dataGridView.Columns["ClientId"].Visible = false;
dataGridView.Columns["ImplementerId"].Visible = false;
}
_logger.LogInformation("Загрузка заказов");
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка загрузки заказов");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void исполнителиToolStripMenuItem_Click(object sender, EventArgs e)
{
var service = Program.ServiceProvider?.GetService(typeof(FormImplementers));
if (service is FormImplementers form)
{
form.ShowDialog();
}
}
private void запускРаботToolStripMenuItem_Click(object sender, EventArgs e)
{
_workProcess.DoWork((Program.ServiceProvider?.GetService(typeof(IImplementerLogic)) as IImplementerLogic)!, _orderLogic);
MessageBox.Show("Процесс обработки запущен", "Сообщение", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
private void компонентыToolStripMenuItem_Click(object sender, EventArgs e)
{
var service = Program.ServiceProvider?.GetService(typeof(FormComponents));
if (service is FormComponents form)
{
form.ShowDialog();
}
}
private void изделияToolStripMenuItem_Click(object sender, EventArgs e)
{
var service = Program.ServiceProvider?.GetService(typeof(FormWoods));
if (service is FormWoods form)
{
form.ShowDialog();
}
}
private void письмаToolStripMenuItem_Click(object sender, EventArgs e)
{ {
var service = Program.ServiceProvider?.GetService(typeof(FormMails)); InitializeComponent();
if (service is FormMails form) _logger = logger;
_orderLogic = orderLogic;
_reportLogic = reportLogic;
_workProcess = workProcess;
_backUpLogic = backUpLogic;
}
private void FormMain_Load(object sender, EventArgs e)
{
LoadData();
}
private void LoadData()
{
try
{ {
form.ShowDialog(); dataGridView.FillAndConfigGrid(_orderLogic.ReadList(null));
_logger.LogInformation("Загрузка заказов");
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка загрузки заказов");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
} }
} }
private void исполнителиToolStripMenuItem_Click(object sender, EventArgs e)
{
var form = DependencyManager.Instance.Resolve<FormImplementers>();
form.ShowDialog();
}
private void запускРаботToolStripMenuItem_Click(object sender, EventArgs e)
{
_workProcess.DoWork(DependencyManager.Instance.Resolve<IImplementerLogic>(), _orderLogic);
MessageBox.Show("Процесс обработки запущен", "Сообщение", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
private void компонентыToolStripMenuItem_Click(object sender, EventArgs e)
{
var form = DependencyManager.Instance.Resolve<FormComponents>();
form.ShowDialog();
}
private void изделияToolStripMenuItem_Click(object sender, EventArgs e)
{
var form = DependencyManager.Instance.Resolve<FormWoods>();
form.ShowDialog();
}
private void письмаToolStripMenuItem_Click(object sender, EventArgs e)
{
var form = DependencyManager.Instance.Resolve<FormMails>();
form.ShowDialog();
}
private void ButtonCreateOrder_Click(object sender, EventArgs e) private void ButtonCreateOrder_Click(object sender, EventArgs e)
{ {
var service = Program.ServiceProvider?.GetService(typeof(FormCreateOrder)); var form = DependencyManager.Instance.Resolve<FormCreateOrder>();
if (service is FormCreateOrder form) form.ShowDialog();
{ LoadData();
form.ShowDialog(); }
LoadData();
}
}
private void ButtonTakeOrderInWork_Click(object sender, EventArgs e) private void ButtonTakeOrderInWork_Click(object sender, EventArgs e)
{ {
if (dataGridView.SelectedRows.Count == 1) if (dataGridView.SelectedRows.Count == 1)
{ {
int id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value); int id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value);
_logger.LogInformation("Заказ №{id}. Меняется статус на 'В работе'", id); _logger.LogInformation("Заказ №{id}. Меняется статус на 'В работе'", id);
try try
{ {
var operationResult = _orderLogic.TakeOrderInWork(new OrderBindingModel var operationResult = _orderLogic.TakeOrderInWork(new OrderBindingModel
{ {
Id = id, Id = id,
Status = Enum.Parse<OrderStatus>(dataGridView.SelectedRows[0].Cells["Status"].Value.ToString()), Status = Enum.Parse<OrderStatus>(dataGridView.SelectedRows[0].Cells["Status"].Value.ToString()),
}); });
if (!operationResult) if (!operationResult)
{ {
throw new Exception("Ошибка при сохранении. Дополнительная информация в логах."); throw new Exception("Ошибка при сохранении. Дополнительная информация в логах.");
} }
LoadData(); LoadData();
} }
catch (Exception ex) catch (Exception ex)
{ {
_logger.LogError(ex, "Ошибка передачи заказа в работу"); _logger.LogError(ex, "Ошибка передачи заказа в работу");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
} }
} }
} }
private void ButtonOrderReady_Click(object sender, EventArgs e) private void ButtonOrderReady_Click(object sender, EventArgs e)
{ {
if (dataGridView.SelectedRows.Count == 1) if (dataGridView.SelectedRows.Count == 1)
{ {
int id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value); int id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value);
_logger.LogInformation("Заказ №{id}. Меняется статус на 'Выдан'", id); _logger.LogInformation("Заказ №{id}. Меняется статус на 'Выдан'", id);
try try
{ {
var operationResult = _orderLogic.DeliveryOrder(new OrderBindingModel var operationResult = _orderLogic.DeliveryOrder(new OrderBindingModel
{ {
Id = id, Id = id,
Status = Enum.Parse<OrderStatus>(dataGridView.SelectedRows[0].Cells["Status"].Value.ToString()), Status = Enum.Parse<OrderStatus>(dataGridView.SelectedRows[0].Cells["Status"].Value.ToString()),
DateCreate = DateTime.Parse(dataGridView.SelectedRows[0].Cells["DateCreate"].Value.ToString()), DateCreate = DateTime.Parse(dataGridView.SelectedRows[0].Cells["DateCreate"].Value.ToString()),
}); });
if (!operationResult) if (!operationResult)
{ {
throw new Exception("Ошибка при сохранении. Дополнительная информация в логах."); throw new Exception("Ошибка при сохранении. Дополнительная информация в логах.");
} }
_logger.LogInformation("Заказ №{id} выдан", id); _logger.LogInformation("Заказ №{id} выдан", id);
LoadData(); LoadData();
} }
catch (Exception ex) catch (Exception ex)
{ {
_logger.LogError(ex, "Ошибка отметки о выдачи заказа"); _logger.LogError(ex, "Ошибка отметки о выдачи заказа");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
} }
} }
}
private void ButtonIssuedOrder_Click(object sender, EventArgs e) }
{
if (dataGridView.SelectedRows.Count == 1)
{
int id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value);
_logger.LogInformation("Заказ №{id}. Меняется статус на 'Выдан'", id);
try
{
var operationResult = _orderLogic.DeliveryOrder(new OrderBindingModel
{
Id = id,
Status = Enum.Parse<OrderStatus>(dataGridView.SelectedRows[0].Cells["Status"].Value.ToString()),
});
if (!operationResult)
{
throw new Exception("Ошибка при сохранении. Дополнительная информация в логах.");
}
LoadData();
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка отметки о готовности заказа");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
private void ButtonRef_Click(object sender, EventArgs e) private void ButtonIssuedOrder_Click(object sender, EventArgs e)
{ {
LoadData(); if (dataGridView.SelectedRows.Count == 1)
} {
int id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value);
_logger.LogInformation("Заказ №{id}. Меняется статус на 'Выдан'", id);
try
{
var operationResult = _orderLogic.DeliveryOrder(new OrderBindingModel
{
Id = id,
Status = Enum.Parse<OrderStatus>(dataGridView.SelectedRows[0].Cells["Status"].Value.ToString()),
});
if (!operationResult)
{
throw new Exception("Ошибка при сохранении. Дополнительная информация в логах.");
}
LoadData();
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка отметки о готовности заказа");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
private void ComponentsToolStripMenuItem_Click(object sender, EventArgs e) private void ButtonRef_Click(object sender, EventArgs e)
{ {
using var dialog = new SaveFileDialog { Filter = "docx|*.docx" }; LoadData();
if (dialog.ShowDialog() == DialogResult.OK) }
{
_reportLogic.SaveComponentsToWordFile(new ReportBindingModel
{
FileName = dialog.FileName
});
MessageBox.Show("Выполнено", "Успех", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
private void ComponentWoodsToolStripMenuItem_Click(object sender, EventArgs e) private void ComponentsToolStripMenuItem_Click(object sender, EventArgs e)
{ {
var service = Program.ServiceProvider?.GetService(typeof(FormReportWoodComponents)); using var dialog = new SaveFileDialog { Filter = "docx|*.docx" };
if (service is FormReportWoodComponents form) if (dialog.ShowDialog() == DialogResult.OK)
{ {
form.ShowDialog(); _reportLogic.SaveComponentsToWordFile(new ReportBindingModel
} {
} FileName = dialog.FileName
});
MessageBox.Show("Выполнено", "Успех", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
private void OrdersToolStripMenuItem_Click(object sender, EventArgs e) private void ComponentWoodsToolStripMenuItem_Click(object sender, EventArgs e)
{ {
var service = Program.ServiceProvider?.GetService(typeof(FormReportOrders)); var form = DependencyManager.Instance.Resolve<FormReportWoodComponents>();
if (service is FormReportOrders form) form.ShowDialog();
{ }
form.ShowDialog();
}
}
private void ClientsToolStripMenuItem_Click(object sender, EventArgs e) private void OrdersToolStripMenuItem_Click(object sender, EventArgs e)
{ {
var service = Program.ServiceProvider?.GetService(typeof(FormClients)); var form = DependencyManager.Instance.Resolve<FormReportOrders>();
if (service is FormClients form) form.ShowDialog();
{ }
form.ShowDialog();
} private void ClientsToolStripMenuItem_Click(object sender, EventArgs e)
} {
} var form = DependencyManager.Instance.Resolve<FormClients>();
form.ShowDialog();
}
private void создатьБекапToolStripMenuItem_Click(object sender, EventArgs e)
{
try
{
if (_backUpLogic != null)
{
var fbd = new FolderBrowserDialog();
if (fbd.ShowDialog() == DialogResult.OK)
{
_backUpLogic.CreateBackUp(new BackUpSaveBindingModel
{
FolderName = fbd.SelectedPath
});
MessageBox.Show("Бекап создан", "Сообщение",
MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK,
MessageBoxIcon.Error);
}
}
}
} }

View File

@ -1,5 +1,6 @@
using CarpentryWorkshopContracts.BindingModels; using CarpentryWorkshopContracts.BindingModels;
using CarpentryWorkshopContracts.BusinessLogicsContracts; using CarpentryWorkshopContracts.BusinessLogicsContracts;
using CarpentryWorkshopContracts.DI;
using CarpentryWorkshopContracts.SearchModels; using CarpentryWorkshopContracts.SearchModels;
using CarpentryWorkshopDataModels.Models; using CarpentryWorkshopDataModels.Models;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
@ -80,27 +81,23 @@ namespace CarpentryWorkshopView
private void ButtonAdd_Click(object sender, EventArgs e) private void ButtonAdd_Click(object sender, EventArgs e)
{ {
var service = Program.ServiceProvider?.GetService(typeof(FormWoodComponent)); var form = DependencyManager.Instance.Resolve<FormWoodComponent>();
if (service is FormWoodComponent form) if (form.ShowDialog() == DialogResult.OK)
{ {
if (form.ShowDialog() == DialogResult.OK) if (form.ComponentModel == null)
{ {
if (form.ComponentModel == null) return;
{
return;
}
_logger.LogInformation("Добавление нового компонента: { ComponentName} - { Count} ", form.ComponentModel.ComponentName, form.Count);
if (_woodComponents.ContainsKey(form.Id))
{
_woodComponents[form.Id] = (form.ComponentModel, form.Count);
}
else
{
_woodComponents.Add(form.Id, (form.ComponentModel, form.Count));
}
LoadData();
} }
_logger.LogInformation("Добавление нового компонента: { ComponentName} - { Count} ", form.ComponentModel.ComponentName, form.Count);
if (_woodComponents.ContainsKey(form.Id))
{
_woodComponents[form.Id] = (form.ComponentModel, form.Count);
}
else
{
_woodComponents.Add(form.Id, (form.ComponentModel, form.Count));
}
LoadData();
} }
} }
@ -108,23 +105,20 @@ namespace CarpentryWorkshopView
{ {
if (dataGridView.SelectedRows.Count == 1) if (dataGridView.SelectedRows.Count == 1)
{ {
var service = Program.ServiceProvider?.GetService(typeof(FormWoodComponent)); var form = DependencyManager.Instance.Resolve<FormWoodComponent>();
if (service is FormWoodComponent form) int id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells[0].Value);
{ form.Id = id;
int id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells[0].Value); form.Count = _woodComponents[id].Item2;
form.Id = id; if (form.ShowDialog() == DialogResult.OK)
form.Count = _woodComponents[id].Item2; {
if (form.ShowDialog() == DialogResult.OK) if (form.ComponentModel == null)
{ {
if (form.ComponentModel == null) return;
{
return;
}
_logger.LogInformation("Изменение компонента: { ComponentName} - { Count} ", form.ComponentModel.ComponentName, form.Count);
_woodComponents[form.Id] = (form.ComponentModel, form.Count);
LoadData();
} }
} _logger.LogInformation("Изменение компонента: { ComponentName} - { Count} ", form.ComponentModel.ComponentName, form.Count);
_woodComponents[form.Id] = (form.ComponentModel, form.Count);
LoadData();
}
} }
} }

View File

@ -1,5 +1,6 @@
using CarpentryWorkshopContracts.BindingModels; using CarpentryWorkshopContracts.BindingModels;
using CarpentryWorkshopContracts.BusinessLogicsContracts; using CarpentryWorkshopContracts.BusinessLogicsContracts;
using CarpentryWorkshopContracts.DI;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
@ -33,15 +34,8 @@ namespace CarpentryWorkshopView
{ {
try try
{ {
var list = _logic.ReadList(null); dataGridView.FillAndConfigGrid(_logic.ReadList(null));
if (list != null) _logger.LogInformation("Загрузка изделий");
{
dataGridView.DataSource = list;
dataGridView.Columns["Id"].Visible = false;
dataGridView.Columns["WoodComponents"].Visible = false;
dataGridView.Columns["WoodName"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
}
_logger.LogInformation("Загрузка изделий");
} }
catch (Exception ex) catch (Exception ex)
{ {
@ -52,13 +46,10 @@ namespace CarpentryWorkshopView
private void ButtonAdd_Click(object sender, EventArgs e) private void ButtonAdd_Click(object sender, EventArgs e)
{ {
var service = Program.ServiceProvider?.GetService(typeof(FormWood)); var form = DependencyManager.Instance.Resolve<FormWood>();
if (service is FormWood form) if (form.ShowDialog() == DialogResult.OK)
{ {
if (form.ShowDialog() == DialogResult.OK) LoadData();
{
LoadData();
}
} }
} }
@ -66,14 +57,11 @@ namespace CarpentryWorkshopView
{ {
if (dataGridView.SelectedRows.Count == 1) if (dataGridView.SelectedRows.Count == 1)
{ {
var service = Program.ServiceProvider?.GetService(typeof(FormWood)); var form = DependencyManager.Instance.Resolve<FormWood>();
if (service is FormWood form) form.Id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value);
{ if (form.ShowDialog() == DialogResult.OK)
form.Id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value); {
if (form.ShowDialog() == DialogResult.OK) LoadData();
{
LoadData();
}
} }
} }
} }

View File

@ -4,6 +4,7 @@ using CarpentryWorkshopBusinessLogic.OfficePackage;
using CarpentryWorkshopBusinessLogic.OfficePackage.Implements; using CarpentryWorkshopBusinessLogic.OfficePackage.Implements;
using CarpentryWorkshopContracts.BindingModels; using CarpentryWorkshopContracts.BindingModels;
using CarpentryWorkshopContracts.BusinessLogicsContracts; using CarpentryWorkshopContracts.BusinessLogicsContracts;
using CarpentryWorkshopContracts.DI;
using CarpentryWorkshopContracts.StoragesContracts; using CarpentryWorkshopContracts.StoragesContracts;
using CarpentryWorkshopDatabaseImplement.Implements; using CarpentryWorkshopDatabaseImplement.Implements;
using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection;
@ -15,26 +16,17 @@ namespace CarpentryWorkshopView
{ {
internal static class Program internal static class Program
{ {
private static ServiceProvider? _serviceProvider;
public static ServiceProvider? ServiceProvider => _serviceProvider;
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread] [STAThread]
static void Main() static void Main()
{ {
// To customize application configuration such as set high DPI settings or default font,
// see https://aka.ms/applicationconfiguration.
ApplicationConfiguration.Initialize(); ApplicationConfiguration.Initialize();
var services = new ServiceCollection(); InitDependency();
ConfigureServices(services);
_serviceProvider = services.BuildServiceProvider();
try try
{ {
var mailSender = _serviceProvider.GetService<AbstractMailWorker>(); var mailSender = DependencyManager.Instance.Resolve<AbstractMailWorker>();
mailSender?.MailConfig(new MailConfigBindingModel mailSender?.MailConfig(new MailConfigBindingModel
{ {
MailLogin = System.Configuration.ConfigurationManager.AppSettings["MailLogin"] ?? string.Empty, MailLogin = System.Configuration.ConfigurationManager.AppSettings["MailLogin"] ?? string.Empty,
MailPassword = System.Configuration.ConfigurationManager.AppSettings["MailPassword"] ?? string.Empty, MailPassword = System.Configuration.ConfigurationManager.AppSettings["MailPassword"] ?? string.Empty,
SmtpClientHost = System.Configuration.ConfigurationManager.AppSettings["SmtpClientHost"] ?? string.Empty, SmtpClientHost = System.Configuration.ConfigurationManager.AppSettings["SmtpClientHost"] ?? string.Empty,
@ -44,58 +36,53 @@ namespace CarpentryWorkshopView
}); });
// ñîçäàåì òàéìåð // ñîçäàåì òàéìåð
var timer = new System.Threading.Timer(new TimerCallback(MailCheck!), null, 0, 100000); var timer = new System.Threading.Timer(new TimerCallback(MailCheck!), null, 0, 100000);
} }
catch (Exception ex) catch (Exception ex)
{ {
var logger = _serviceProvider.GetService<ILogger>(); var logger = DependencyManager.Instance.Resolve<ILogger>();
logger?.LogError(ex, "Îøèáêà ðàáîòû ñ ïî÷òîé"); logger?.LogError(ex, "Îøèáêà ðàáîòû ñ ïî÷òîé");
} }
Application.Run(_serviceProvider.GetRequiredService<FormMain>()); Application.Run(DependencyManager.Instance.Resolve<FormMain>());
} }
private static void ConfigureServices(ServiceCollection services) private static void InitDependency()
{ {
services.AddLogging(option => DependencyManager.InitDependency();
{
DependencyManager.Instance.AddLogging(option =>
{
option.SetMinimumLevel(LogLevel.Information); option.SetMinimumLevel(LogLevel.Information);
option.AddNLog("nlog.config"); option.AddNLog("nlog.config");
}); });
services.AddTransient<IClientStorage, ClientStorage>(); DependencyManager.Instance.RegisterType<IComponentLogic, ComponentLogic>();
services.AddTransient<IImplementerStorage, ImplementerStorage>(); DependencyManager.Instance.RegisterType<IOrderLogic, OrderLogic>();
services.AddTransient<IComponentStorage, ComponentStorage>(); DependencyManager.Instance.RegisterType<IWoodLogic, WoodLogic>();
services.AddTransient<IOrderStorage, OrderStorage>(); DependencyManager.Instance.RegisterType<IReportLogic, ReportLogic>();
services.AddTransient<IWoodStorage, WoodStorage>(); DependencyManager.Instance.RegisterType<IClientLogic, ClientLogic>();
services.AddTransient<IMessageInfoStorage, MessageInfoStorage>(); DependencyManager.Instance.RegisterType<IImplementerLogic, ImplementerLogic>();
DependencyManager.Instance.RegisterType<IMessageInfoLogic, MessageInfoLogic>();
DependencyManager.Instance.RegisterType<IWorkProcess, WorkModeling>();
DependencyManager.Instance.RegisterType<IBackUpLogic, BackUpLogic>();
services.AddTransient<IClientLogic, ClientLogic>(); DependencyManager.Instance.RegisterType<AbstractSaveToExcel, SaveToExcel>();
services.AddTransient<IImplementerLogic, ImplementerLogic>(); DependencyManager.Instance.RegisterType<AbstractSaveToWord, SaveToWord>();
services.AddTransient<IComponentLogic, ComponentLogic>(); DependencyManager.Instance.RegisterType<AbstractSaveToPdf, SaveToPdf>();
services.AddTransient<IOrderLogic, OrderLogic>(); DependencyManager.Instance.RegisterType<AbstractMailWorker, MailKitWorker>(true);
services.AddTransient<IWoodLogic, WoodLogic>();
services.AddTransient<IReportLogic, ReportLogic>();
services.AddTransient<IWorkProcess, WorkModeling>();
services.AddTransient<IMessageInfoLogic, MessageInfoLogic>();
services.AddTransient<AbstractSaveToExcel, SaveToExcel>();
services.AddTransient<AbstractSaveToWord, SaveToWord>();
services.AddTransient<AbstractSaveToPdf, SaveToPdf>();
services.AddSingleton<AbstractMailWorker, MailKitWorker>();
services.AddTransient<FormMain>(); DependencyManager.Instance.RegisterType<FormMain>();
services.AddTransient<FormClients>(); DependencyManager.Instance.RegisterType<FormComponent>();
services.AddTransient<FormComponent>(); DependencyManager.Instance.RegisterType<FormComponents>();
services.AddTransient<FormComponents>(); DependencyManager.Instance.RegisterType<FormCreateOrder>();
services.AddTransient<FormCreateOrder>(); DependencyManager.Instance.RegisterType<FormWood>();
services.AddTransient<FormWood>(); DependencyManager.Instance.RegisterType<FormWoodComponent>();
services.AddTransient<FormWoodComponent>(); DependencyManager.Instance.RegisterType<FormWoods>();
services.AddTransient<FormWoods>(); DependencyManager.Instance.RegisterType<FormReportWoodComponents>();
services.AddTransient<FormReportWoodComponents>(); DependencyManager.Instance.RegisterType<FormReportOrders>();
services.AddTransient<FormReportOrders>(); DependencyManager.Instance.RegisterType<FormClients>();
services.AddTransient<FormImplementers>(); DependencyManager.Instance.RegisterType<FormImplementers>();
services.AddTransient<FormImplementer>(); DependencyManager.Instance.RegisterType<FormImplementer>();
services.AddTransient<FormMails>(); DependencyManager.Instance.RegisterType<FormMails>();
} }
private static void MailCheck(object obj) => DependencyManager.Instance.Resolve<AbstractMailWorker>()?.MailCheck();
private static void MailCheck(object obj) => ServiceProvider?.GetService<AbstractMailWorker>()?.MailCheck(); }
}
} }