Eliseev E.E. LabWork08_Hard #18

Closed
ElEgEv wants to merge 12 commits from LabWork08_Hard into LabWork07_Hard
65 changed files with 1753 additions and 825 deletions

2
.gitignore vendored
View File

@ -14,6 +14,8 @@
# User-specific files (MonoDevelop/Xamarin Studio)
*.userprefs
ImplementationExtensions
# Mono auto generated files
mono_crash.*

View File

@ -17,9 +17,9 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "BlacksmithWorkshopFileImple
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "BlacksmithWorkshopDatabaseImplement", "BlacksmithWorkshopDatabaseImplement\BlacksmithWorkshopDatabaseImplement.csproj", "{EE03BAE3-52EE-4E3B-8992-382D89E61E1A}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "BlacksmithWorkshopRestApi", "BlackmithWorkshopRestApi\BlacksmithWorkshopRestApi.csproj", "{23DBD9A3-2107-44AB-8B87-6982BFD2E69A}"
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "BlacksmithWorkshopRestApi", "BlackmithWorkshopRestApi\BlacksmithWorkshopRestApi.csproj", "{23DBD9A3-2107-44AB-8B87-6982BFD2E69A}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "BlacksmithWorkshopClientApp", "BlacksmithWorkshopClientApp\BlacksmithWorkshopClientApp.csproj", "{FCA95914-11AF-494A-8116-BB7B3253D925}"
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "BlacksmithWorkshopClientApp", "BlacksmithWorkshopClientApp\BlacksmithWorkshopClientApp.csproj", "{FCA95914-11AF-494A-8116-BB7B3253D925}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "BlacksmithWorkshopShopApp", "BlacksmithWorkshopShopApp\BlacksmithWorkshopShopApp.csproj", "{3ADC69D9-EACA-4D59-840E-EB4A7F40BAEE}"
EndProject

View File

@ -0,0 +1,66 @@
using BlacksmithWorkshopContracts.Attributes;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BlacksmithWorkshop
{
public 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;
}
column.DefaultCellStyle.Format = columnAttr.Format;
}
}
}
}
}

View File

@ -36,21 +36,12 @@ namespace BlacksmithWorkshop
private void LoadData()
{
_logger.LogInformation("Загрузка клиентов");
try
{
var list = _clientLogic.ReadList(null);
if (list != null)
{
dataGridView.DataSource = list;
dataGridView.Columns["ClientFIO"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
}
_logger.LogInformation("Успешная загрузка клиентов");
}
catch (Exception ex)
try
{
dataGridView.FillandConfigGrid(_clientLogic.ReadList(null));
_logger.LogInformation("Загрузка клиентов");
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка загрузки клиентов");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);

View File

@ -1,5 +1,7 @@
using BlacksmithWorkshopContracts.BindingModels;
using BlacksmithWorkshopBusinessLogic.BusinessLogic;
using BlacksmithWorkshopContracts.BindingModels;
using BlacksmithWorkshopContracts.BusinessLogicsContracts;
using BlacksmithWorkshopContracts.DI;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
@ -34,19 +36,11 @@ namespace BlacksmithWorkshop
private void LoadData()
{
try
{
var list = _logic.ReadList(null);
try
{
dataGridView.FillandConfigGrid(_logic.ReadList(null));
//растягиваем колонку Название на всю ширину, колонку Id скрываем
if (list != null)
{
dataGridView.DataSource = list;
dataGridView.Columns["Id"].Visible = false;
dataGridView.Columns["ImplementerFIO"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
}
_logger.LogInformation("Загрузка исполнителей");
_logger.LogInformation("Загрузка исполнителей");
}
catch (Exception ex)
{
@ -58,14 +52,11 @@ namespace BlacksmithWorkshop
private void ButtonCreate_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();
}
}
@ -73,16 +64,13 @@ namespace BlacksmithWorkshop
{
if (dataGridView.SelectedRows.Count == 1)
{
var service = Program.ServiceProvider?.GetService(typeof(FormImplementer));
var form = DependencyManager.Instance.Resolve<FormImplementer>();
if (service is FormImplementer 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 BlacksmithWorkshopBusinessLogic.BusinessLogic;
using BlacksmithWorkshopContracts.BusinessLogicsContracts;
using BlacksmithWorkshopContracts.DI;
using BlacksmithWorkshopContracts.ViewModels;
using Microsoft.Extensions.Logging;
using System;
@ -45,19 +46,11 @@ namespace BlacksmithWorkshop
try
{
var list = _messageLogic.ReadList(new()
dataGridView.FillandConfigGrid(_messageLogic.ReadList(new()
{
Page = currentPage,
PageSize = pageSize,
});
if (list != null)
{
dataGridView.DataSource = list;
dataGridView.Columns["ClientId"].Visible = false;
dataGridView.Columns["MessageId"].Visible = false;
dataGridView.Columns["Body"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
}
}));
_logger.LogInformation("Загрузка списка писем");
@ -117,16 +110,13 @@ namespace BlacksmithWorkshop
{
if (dataGridView.SelectedRows.Count == 1)
{
var service = Program.ServiceProvider?.GetService(typeof(FormAnswerMail));
var form = DependencyManager.Instance.Resolve<FormAnswerMail>();
if (service is FormAnswerMail form)
form.MessageId = dataGridView.SelectedRows[0].Cells["MessageId"].Value.ToString();
if (form.ShowDialog() == DialogResult.OK)
{
form.MessageId = dataGridView.SelectedRows[0].Cells["MessageId"].Value.ToString();
if (form.ShowDialog() == DialogResult.OK)
{
LoadData();
}
LoadData();
}
}
}

View File

@ -1,295 +1,304 @@
namespace BlacksmithWorkshop
{
partial class FormMain
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
partial class FormMain
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
dataGridView = new DataGridView();
buttonCreateOrder = new Button();
buttonIssuedOrder = new Button();
buttonRef = new Button();
menuStrip = new MenuStrip();
toolStripMenuItem = new ToolStripMenuItem();
workPieceToolStripMenuItem = new ToolStripMenuItem();
manufactureToolStripMenuItem = new ToolStripMenuItem();
shopToolStripMenuItem = new ToolStripMenuItem();
addManufactureToolStripMenuItem = new ToolStripMenuItem();
reportToolStripMenuItem = new ToolStripMenuItem();
groupedOrdersReportToolStripMenuItem = new ToolStripMenuItem();
ordersReportToolStripMenuItem = new ToolStripMenuItem();
workloadStoresReportToolStripMenuItem = new ToolStripMenuItem();
shopsReportToolStripMenuItem = new ToolStripMenuItem();
reportManufactureToolStripMenuItem = new ToolStripMenuItem();
workPieceManufacturesToolStripMenuItem = new ToolStripMenuItem();
workWithImplementerToolStripMenuItem = new ToolStripMenuItem();
implementerToolStripMenuItem = new ToolStripMenuItem();
работаСКлиентамиToolStripMenuItem = new ToolStripMenuItem();
clientsToolStripMenuItem = new ToolStripMenuItem();
startWorkToolStripMenuItem = new ToolStripMenuItem();
buttonSellManufacture = new Button();
messageToolStripMenuItem = new ToolStripMenuItem();
((System.ComponentModel.ISupportInitialize)dataGridView).BeginInit();
menuStrip.SuspendLayout();
SuspendLayout();
//
// dataGridView
//
dataGridView.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize;
dataGridView.Location = new Point(11, 36);
dataGridView.Name = "dataGridView";
dataGridView.RowHeadersWidth = 51;
dataGridView.RowTemplate.Height = 29;
dataGridView.Size = new Size(937, 448);
dataGridView.TabIndex = 0;
//
// buttonCreateOrder
//
buttonCreateOrder.Location = new Point(1014, 67);
buttonCreateOrder.Name = "buttonCreateOrder";
buttonCreateOrder.Size = new Size(235, 29);
buttonCreateOrder.TabIndex = 1;
buttonCreateOrder.Text = "Создать заказ";
buttonCreateOrder.UseVisualStyleBackColor = true;
buttonCreateOrder.Click += ButtonCreateOrder_Click;
//
// buttonIssuedOrder
//
buttonIssuedOrder.Location = new Point(1014, 141);
buttonIssuedOrder.Name = "buttonIssuedOrder";
buttonIssuedOrder.Size = new Size(235, 29);
buttonIssuedOrder.TabIndex = 4;
buttonIssuedOrder.Text = "Заказ выдан";
buttonIssuedOrder.UseVisualStyleBackColor = true;
buttonIssuedOrder.Click += ButtonIssuedOrder_Click;
//
// buttonRef
//
buttonRef.Location = new Point(1014, 214);
buttonRef.Name = "buttonRef";
buttonRef.Size = new Size(235, 29);
buttonRef.TabIndex = 5;
buttonRef.Text = "Обновить";
buttonRef.UseVisualStyleBackColor = true;
buttonRef.Click += ButtonRef_Click;
//
// menuStrip
//
menuStrip.ImageScalingSize = new Size(20, 20);
menuStrip.Items.AddRange(new ToolStripItem[] { toolStripMenuItem, reportToolStripMenuItem, workWithImplementerToolStripMenuItem, работаСКлиентамиToolStripMenuItem, startWorkToolStripMenuItem });
menuStrip.Location = new Point(0, 0);
menuStrip.Name = "menuStrip";
menuStrip.Padding = new Padding(6, 3, 0, 3);
menuStrip.Size = new Size(1297, 30);
menuStrip.TabIndex = 6;
menuStrip.Text = "menuStrip1";
//
// toolStripMenuItem
//
toolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { workPieceToolStripMenuItem, manufactureToolStripMenuItem, shopToolStripMenuItem, addManufactureToolStripMenuItem });
toolStripMenuItem.Name = "toolStripMenuItem";
toolStripMenuItem.Size = new Size(117, 24);
toolStripMenuItem.Text = "Справочники";
//
// workPieceToolStripMenuItem
//
workPieceToolStripMenuItem.Name = "workPieceToolStripMenuItem";
workPieceToolStripMenuItem.Size = new Size(251, 26);
workPieceToolStripMenuItem.Text = "Заготовки";
workPieceToolStripMenuItem.Click += WorkPieceToolStripMenuItem_Click;
//
// manufactureToolStripMenuItem
//
manufactureToolStripMenuItem.Name = "manufactureToolStripMenuItem";
manufactureToolStripMenuItem.Size = new Size(251, 26);
manufactureToolStripMenuItem.Text = "Изделия";
manufactureToolStripMenuItem.Click += ManufactureToolStripMenuItem_Click;
//
// shopToolStripMenuItem
//
shopToolStripMenuItem.Name = "shopToolStripMenuItem";
shopToolStripMenuItem.Size = new Size(251, 26);
shopToolStripMenuItem.Text = "Магазины";
shopToolStripMenuItem.Click += ShopToolStripMenuItem_Click;
//
// addManufactureToolStripMenuItem
//
addManufactureToolStripMenuItem.Name = "addManufactureToolStripMenuItem";
addManufactureToolStripMenuItem.Size = new Size(251, 26);
addManufactureToolStripMenuItem.Text = "Пополнение магазина";
addManufactureToolStripMenuItem.Click += AddManufactureToolStripMenuItem_Click;
//
// reportToolStripMenuItem
//
reportToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { groupedOrdersReportToolStripMenuItem, ordersReportToolStripMenuItem, workloadStoresReportToolStripMenuItem, shopsReportToolStripMenuItem, reportManufactureToolStripMenuItem, workPieceManufacturesToolStripMenuItem });
reportToolStripMenuItem.Name = "reportToolStripMenuItem";
reportToolStripMenuItem.Size = new Size(73, 24);
reportToolStripMenuItem.Text = "Отчёты";
//
// groupedOrdersReportToolStripMenuItem
//
groupedOrdersReportToolStripMenuItem.Name = "groupedOrdersReportToolStripMenuItem";
groupedOrdersReportToolStripMenuItem.Size = new Size(310, 26);
groupedOrdersReportToolStripMenuItem.Text = "Список заказов за весь период";
groupedOrdersReportToolStripMenuItem.Click += GroupedOrdersReportToolStripMenuItem_Click;
//
// ordersReportToolStripMenuItem
//
ordersReportToolStripMenuItem.Name = "ordersReportToolStripMenuItem";
ordersReportToolStripMenuItem.Size = new Size(310, 26);
ordersReportToolStripMenuItem.Text = "Список заказов";
ordersReportToolStripMenuItem.Click += OrdersReportToolStripMenuItem_Click;
//
// workloadStoresReportToolStripMenuItem
//
workloadStoresReportToolStripMenuItem.Name = "workloadStoresReportToolStripMenuItem";
workloadStoresReportToolStripMenuItem.Size = new Size(310, 26);
workloadStoresReportToolStripMenuItem.Text = "Загруженность магазинов";
workloadStoresReportToolStripMenuItem.Click += WorkloadStoresReportToolStripMenuItem_Click;
//
// shopsReportToolStripMenuItem
//
shopsReportToolStripMenuItem.Name = "shopsReportToolStripMenuItem";
shopsReportToolStripMenuItem.Size = new Size(310, 26);
shopsReportToolStripMenuItem.Text = "Таблица магазинов";
shopsReportToolStripMenuItem.Click += ShopsReportToolStripMenuItem_Click;
//
// reportManufactureToolStripMenuItem
//
reportManufactureToolStripMenuItem.Name = "reportManufactureToolStripMenuItem";
reportManufactureToolStripMenuItem.Size = new Size(310, 26);
reportManufactureToolStripMenuItem.Text = "Список изделий";
reportManufactureToolStripMenuItem.Click += ReportManufactureToolStripMenuItem_Click;
//
// workPieceManufacturesToolStripMenuItem
//
workPieceManufacturesToolStripMenuItem.Name = "workPieceManufacturesToolStripMenuItem";
workPieceManufacturesToolStripMenuItem.Size = new Size(310, 26);
workPieceManufacturesToolStripMenuItem.Text = "Заготовки по изделиям";
workPieceManufacturesToolStripMenuItem.Click += WorkPieceManufacturesToolStripMenuItem_Click;
//
// workWithImplementerToolStripMenuItem
//
workWithImplementerToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { implementerToolStripMenuItem });
workWithImplementerToolStripMenuItem.Name = "workWithImplementerToolStripMenuItem";
workWithImplementerToolStripMenuItem.Size = new Size(196, 24);
workWithImplementerToolStripMenuItem.Text = "Работа с исполнителями";
//
// implementerToolStripMenuItem
//
implementerToolStripMenuItem.Name = "implementerToolStripMenuItem";
implementerToolStripMenuItem.Size = new Size(185, 26);
implementerToolStripMenuItem.Text = "Исполнители";
implementerToolStripMenuItem.Click += ImplementerToolStripMenuItem_Click_1;
//
// работаСКлиентамиToolStripMenuItem
//
работаСКлиентамиToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { clientsToolStripMenuItem, messageToolStripMenuItem });
работаСКлиентамиToolStripMenuItem.Name = "работаСКлиентамиToolStripMenuItem";
работаСКлиентамиToolStripMenuItem.Size = new Size(161, 24);
работаСКлиентамиToolStripMenuItem.Text = "Работа с клиентами";
//
// clientsToolStripMenuItem
//
clientsToolStripMenuItem.Name = "clientsToolStripMenuItem";
clientsToolStripMenuItem.Size = new Size(224, 26);
clientsToolStripMenuItem.Text = "Клиенты";
clientsToolStripMenuItem.Click += ClientsToolStripMenuItem_Click_1;
//
// startWorkToolStripMenuItem
//
startWorkToolStripMenuItem.Name = "startWorkToolStripMenuItem";
startWorkToolStripMenuItem.Size = new Size(114, 24);
startWorkToolStripMenuItem.Text = "Запуск работ";
startWorkToolStripMenuItem.Click += StartWorkToolStripMenuItem_Click;
//
// buttonSellManufacture
//
buttonSellManufacture.Location = new Point(1014, 285);
buttonSellManufacture.Name = "buttonSellManufacture";
buttonSellManufacture.Size = new Size(233, 29);
buttonSellManufacture.TabIndex = 7;
buttonSellManufacture.Text = "Продажа изделий";
buttonSellManufacture.UseVisualStyleBackColor = true;
buttonSellManufacture.Click += ButtonSellManufacture_Click;
//
// messageToolStripMenuItem
//
messageToolStripMenuItem.Name = "messageToolStripMenuItem";
messageToolStripMenuItem.Size = new Size(224, 26);
messageToolStripMenuItem.Text = "Письма";
messageToolStripMenuItem.Click += MessageToolStripMenuItem_Click;
//
// FormMain
//
AutoScaleDimensions = new SizeF(8F, 20F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(1297, 496);
Controls.Add(buttonSellManufacture);
Controls.Add(buttonRef);
Controls.Add(buttonIssuedOrder);
Controls.Add(buttonCreateOrder);
Controls.Add(dataGridView);
Controls.Add(menuStrip);
MainMenuStrip = menuStrip;
Name = "FormMain";
Text = "Кузнечная мастерская";
Load += FormMain_Load;
((System.ComponentModel.ISupportInitialize)dataGridView).EndInit();
menuStrip.ResumeLayout(false);
menuStrip.PerformLayout();
ResumeLayout(false);
PerformLayout();
}
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
dataGridView = new DataGridView();
buttonCreateOrder = new Button();
buttonIssuedOrder = new Button();
buttonRef = new Button();
menuStrip = new MenuStrip();
toolStripMenuItem = new ToolStripMenuItem();
workPieceToolStripMenuItem = new ToolStripMenuItem();
manufactureToolStripMenuItem = new ToolStripMenuItem();
shopToolStripMenuItem = new ToolStripMenuItem();
addManufactureToolStripMenuItem = new ToolStripMenuItem();
reportToolStripMenuItem = new ToolStripMenuItem();
groupedOrdersReportToolStripMenuItem = new ToolStripMenuItem();
ordersReportToolStripMenuItem = new ToolStripMenuItem();
workloadStoresReportToolStripMenuItem = new ToolStripMenuItem();
shopsReportToolStripMenuItem = new ToolStripMenuItem();
reportManufactureToolStripMenuItem = new ToolStripMenuItem();
workPieceManufacturesToolStripMenuItem = new ToolStripMenuItem();
workWithImplementerToolStripMenuItem = new ToolStripMenuItem();
implementerToolStripMenuItem = new ToolStripMenuItem();
работаСКлиентамиToolStripMenuItem = new ToolStripMenuItem();
clientsToolStripMenuItem = new ToolStripMenuItem();
messageToolStripMenuItem = new ToolStripMenuItem();
startWorkToolStripMenuItem = new ToolStripMenuItem();
buttonSellManufacture = new Button();
createBackUpToolStripMenuItem = new ToolStripMenuItem();
((System.ComponentModel.ISupportInitialize)dataGridView).BeginInit();
menuStrip.SuspendLayout();
SuspendLayout();
//
// dataGridView
//
dataGridView.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize;
dataGridView.Location = new Point(11, 36);
dataGridView.Name = "dataGridView";
dataGridView.RowHeadersWidth = 51;
dataGridView.RowTemplate.Height = 29;
dataGridView.Size = new Size(937, 448);
dataGridView.TabIndex = 0;
//
// buttonCreateOrder
//
buttonCreateOrder.Location = new Point(1014, 67);
buttonCreateOrder.Name = "buttonCreateOrder";
buttonCreateOrder.Size = new Size(235, 29);
buttonCreateOrder.TabIndex = 1;
buttonCreateOrder.Text = "Создать заказ";
buttonCreateOrder.UseVisualStyleBackColor = true;
buttonCreateOrder.Click += ButtonCreateOrder_Click;
//
// buttonIssuedOrder
//
buttonIssuedOrder.Location = new Point(1014, 141);
buttonIssuedOrder.Name = "buttonIssuedOrder";
buttonIssuedOrder.Size = new Size(235, 29);
buttonIssuedOrder.TabIndex = 4;
buttonIssuedOrder.Text = "Заказ выдан";
buttonIssuedOrder.UseVisualStyleBackColor = true;
buttonIssuedOrder.Click += ButtonIssuedOrder_Click;
//
// buttonRef
//
buttonRef.Location = new Point(1014, 214);
buttonRef.Name = "buttonRef";
buttonRef.Size = new Size(235, 29);
buttonRef.TabIndex = 5;
buttonRef.Text = "Обновить";
buttonRef.UseVisualStyleBackColor = true;
buttonRef.Click += ButtonRef_Click;
//
// menuStrip
//
menuStrip.ImageScalingSize = new Size(20, 20);
menuStrip.Items.AddRange(new ToolStripItem[] { toolStripMenuItem, reportToolStripMenuItem, workWithImplementerToolStripMenuItem, работаСКлиентамиToolStripMenuItem, startWorkToolStripMenuItem, createBackUpToolStripMenuItem });
menuStrip.Location = new Point(0, 0);
menuStrip.Name = "menuStrip";
menuStrip.Padding = new Padding(6, 3, 0, 3);
menuStrip.Size = new Size(1297, 30);
menuStrip.TabIndex = 6;
menuStrip.Text = "menuStrip1";
//
// toolStripMenuItem
//
toolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { workPieceToolStripMenuItem, manufactureToolStripMenuItem, shopToolStripMenuItem, addManufactureToolStripMenuItem });
toolStripMenuItem.Name = "toolStripMenuItem";
toolStripMenuItem.Size = new Size(117, 24);
toolStripMenuItem.Text = "Справочники";
//
// workPieceToolStripMenuItem
//
workPieceToolStripMenuItem.Name = "workPieceToolStripMenuItem";
workPieceToolStripMenuItem.Size = new Size(251, 26);
workPieceToolStripMenuItem.Text = "Заготовки";
workPieceToolStripMenuItem.Click += WorkPieceToolStripMenuItem_Click;
//
// manufactureToolStripMenuItem
//
manufactureToolStripMenuItem.Name = "manufactureToolStripMenuItem";
manufactureToolStripMenuItem.Size = new Size(251, 26);
manufactureToolStripMenuItem.Text = "Изделия";
manufactureToolStripMenuItem.Click += ManufactureToolStripMenuItem_Click;
//
// shopToolStripMenuItem
//
shopToolStripMenuItem.Name = "shopToolStripMenuItem";
shopToolStripMenuItem.Size = new Size(251, 26);
shopToolStripMenuItem.Text = "Магазины";
shopToolStripMenuItem.Click += ShopToolStripMenuItem_Click;
//
// addManufactureToolStripMenuItem
//
addManufactureToolStripMenuItem.Name = "addManufactureToolStripMenuItem";
addManufactureToolStripMenuItem.Size = new Size(251, 26);
addManufactureToolStripMenuItem.Text = "Пополнение магазина";
addManufactureToolStripMenuItem.Click += AddManufactureToolStripMenuItem_Click;
//
// reportToolStripMenuItem
//
reportToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { groupedOrdersReportToolStripMenuItem, ordersReportToolStripMenuItem, workloadStoresReportToolStripMenuItem, shopsReportToolStripMenuItem, reportManufactureToolStripMenuItem, workPieceManufacturesToolStripMenuItem });
reportToolStripMenuItem.Name = "reportToolStripMenuItem";
reportToolStripMenuItem.Size = new Size(73, 24);
reportToolStripMenuItem.Text = "Отчёты";
//
// groupedOrdersReportToolStripMenuItem
//
groupedOrdersReportToolStripMenuItem.Name = "groupedOrdersReportToolStripMenuItem";
groupedOrdersReportToolStripMenuItem.Size = new Size(310, 26);
groupedOrdersReportToolStripMenuItem.Text = "Список заказов за весь период";
groupedOrdersReportToolStripMenuItem.Click += GroupedOrdersReportToolStripMenuItem_Click;
//
// ordersReportToolStripMenuItem
//
ordersReportToolStripMenuItem.Name = "ordersReportToolStripMenuItem";
ordersReportToolStripMenuItem.Size = new Size(310, 26);
ordersReportToolStripMenuItem.Text = "Список заказов";
ordersReportToolStripMenuItem.Click += OrdersReportToolStripMenuItem_Click;
//
// workloadStoresReportToolStripMenuItem
//
workloadStoresReportToolStripMenuItem.Name = "workloadStoresReportToolStripMenuItem";
workloadStoresReportToolStripMenuItem.Size = new Size(310, 26);
workloadStoresReportToolStripMenuItem.Text = "Загруженность магазинов";
workloadStoresReportToolStripMenuItem.Click += WorkloadStoresReportToolStripMenuItem_Click;
//
// shopsReportToolStripMenuItem
//
shopsReportToolStripMenuItem.Name = "shopsReportToolStripMenuItem";
shopsReportToolStripMenuItem.Size = new Size(310, 26);
shopsReportToolStripMenuItem.Text = "Таблица магазинов";
shopsReportToolStripMenuItem.Click += ShopsReportToolStripMenuItem_Click;
//
// reportManufactureToolStripMenuItem
//
reportManufactureToolStripMenuItem.Name = "reportManufactureToolStripMenuItem";
reportManufactureToolStripMenuItem.Size = new Size(310, 26);
reportManufactureToolStripMenuItem.Text = "Список изделий";
reportManufactureToolStripMenuItem.Click += ReportManufactureToolStripMenuItem_Click;
//
// workPieceManufacturesToolStripMenuItem
//
workPieceManufacturesToolStripMenuItem.Name = "workPieceManufacturesToolStripMenuItem";
workPieceManufacturesToolStripMenuItem.Size = new Size(310, 26);
workPieceManufacturesToolStripMenuItem.Text = "Заготовки по изделиям";
workPieceManufacturesToolStripMenuItem.Click += WorkPieceManufacturesToolStripMenuItem_Click;
//
// workWithImplementerToolStripMenuItem
//
workWithImplementerToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { implementerToolStripMenuItem });
workWithImplementerToolStripMenuItem.Name = "workWithImplementerToolStripMenuItem";
workWithImplementerToolStripMenuItem.Size = new Size(196, 24);
workWithImplementerToolStripMenuItem.Text = "Работа с исполнителями";
//
// implementerToolStripMenuItem
//
implementerToolStripMenuItem.Name = "implementerToolStripMenuItem";
implementerToolStripMenuItem.Size = new Size(185, 26);
implementerToolStripMenuItem.Text = "Исполнители";
implementerToolStripMenuItem.Click += ImplementerToolStripMenuItem_Click_1;
//
// работаСКлиентамиToolStripMenuItem
//
работаСКлиентамиToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { clientsToolStripMenuItem, messageToolStripMenuItem });
работаСКлиентамиToolStripMenuItem.Name = "работаСКлиентамиToolStripMenuItem";
работаСКлиентамиToolStripMenuItem.Size = new Size(161, 24);
работаСКлиентамиToolStripMenuItem.Text = "Работа с клиентами";
//
// clientsToolStripMenuItem
//
clientsToolStripMenuItem.Name = "clientsToolStripMenuItem";
clientsToolStripMenuItem.Size = new Size(152, 26);
clientsToolStripMenuItem.Text = "Клиенты";
clientsToolStripMenuItem.Click += ClientsToolStripMenuItem_Click_1;
//
// messageToolStripMenuItem
//
messageToolStripMenuItem.Name = "messageToolStripMenuItem";
messageToolStripMenuItem.Size = new Size(152, 26);
messageToolStripMenuItem.Text = "Письма";
messageToolStripMenuItem.Click += MessageToolStripMenuItem_Click;
//
// startWorkToolStripMenuItem
//
startWorkToolStripMenuItem.Name = "startWorkToolStripMenuItem";
startWorkToolStripMenuItem.Size = new Size(114, 24);
startWorkToolStripMenuItem.Text = "Запуск работ";
startWorkToolStripMenuItem.Click += StartWorkToolStripMenuItem_Click;
//
// buttonSellManufacture
//
buttonSellManufacture.Location = new Point(1014, 285);
buttonSellManufacture.Name = "buttonSellManufacture";
buttonSellManufacture.Size = new Size(233, 29);
buttonSellManufacture.TabIndex = 7;
buttonSellManufacture.Text = "Продажа изделий";
buttonSellManufacture.UseVisualStyleBackColor = true;
buttonSellManufacture.Click += ButtonSellManufacture_Click;
//
// createBackUpToolStripMenuItem
//
createBackUpToolStripMenuItem.Name = "createBackUpToolStripMenuItem";
createBackUpToolStripMenuItem.Size = new Size(122, 24);
createBackUpToolStripMenuItem.Text = "Создать бэкап";
createBackUpToolStripMenuItem.Click += CreateBackUpToolStripMenuItem_Click_1;
//
// FormMain
//
AutoScaleDimensions = new SizeF(8F, 20F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(1297, 496);
Controls.Add(buttonSellManufacture);
Controls.Add(buttonRef);
Controls.Add(buttonIssuedOrder);
Controls.Add(buttonCreateOrder);
Controls.Add(dataGridView);
Controls.Add(menuStrip);
MainMenuStrip = menuStrip;
Name = "FormMain";
Text = "Кузнечная мастерская";
Load += FormMain_Load;
((System.ComponentModel.ISupportInitialize)dataGridView).EndInit();
menuStrip.ResumeLayout(false);
menuStrip.PerformLayout();
ResumeLayout(false);
PerformLayout();
}
#endregion
#endregion
private DataGridView dataGridView;
private Button buttonCreateOrder;
private Button buttonIssuedOrder;
private Button buttonRef;
private MenuStrip menuStrip;
private ToolStripMenuItem toolStripMenuItem;
private ToolStripMenuItem workPieceToolStripMenuItem;
private ToolStripMenuItem manufactureToolStripMenuItem;
private ToolStripMenuItem shopToolStripMenuItem;
private ToolStripMenuItem addManufactureToolStripMenuItem;
private Button buttonSellManufacture;
private ToolStripMenuItem reportToolStripMenuItem;
private ToolStripMenuItem groupedOrdersReportToolStripMenuItem;
private ToolStripMenuItem ordersReportToolStripMenuItem;
private ToolStripMenuItem workloadStoresReportToolStripMenuItem;
private ToolStripMenuItem shopsReportToolStripMenuItem;
private ToolStripMenuItem reportManufactureToolStripMenuItem;
private ToolStripMenuItem workPieceManufacturesToolStripMenuItem;
private ToolStripMenuItem workWithImplementerToolStripMenuItem;
private ToolStripMenuItem implementerToolStripMenuItem;
private ToolStripMenuItem работаСКлиентамиToolStripMenuItem;
private ToolStripMenuItem clientsToolStripMenuItem;
private ToolStripMenuItem startWorkToolStripMenuItem;
private ToolStripMenuItem messageToolStripMenuItem;
}
private DataGridView dataGridView;
private Button buttonCreateOrder;
private Button buttonIssuedOrder;
private Button buttonRef;
private MenuStrip menuStrip;
private ToolStripMenuItem toolStripMenuItem;
private ToolStripMenuItem workPieceToolStripMenuItem;
private ToolStripMenuItem manufactureToolStripMenuItem;
private ToolStripMenuItem shopToolStripMenuItem;
private ToolStripMenuItem addManufactureToolStripMenuItem;
private Button buttonSellManufacture;
private ToolStripMenuItem reportToolStripMenuItem;
private ToolStripMenuItem groupedOrdersReportToolStripMenuItem;
private ToolStripMenuItem ordersReportToolStripMenuItem;
private ToolStripMenuItem workloadStoresReportToolStripMenuItem;
private ToolStripMenuItem shopsReportToolStripMenuItem;
private ToolStripMenuItem reportManufactureToolStripMenuItem;
private ToolStripMenuItem workPieceManufacturesToolStripMenuItem;
private ToolStripMenuItem workWithImplementerToolStripMenuItem;
private ToolStripMenuItem implementerToolStripMenuItem;
private ToolStripMenuItem работаСКлиентамиToolStripMenuItem;
private ToolStripMenuItem clientsToolStripMenuItem;
private ToolStripMenuItem startWorkToolStripMenuItem;
private ToolStripMenuItem messageToolStripMenuItem;
private ToolStripMenuItem createBackUpToolStripMenuItem;
}
}

View File

@ -1,6 +1,7 @@
using BlacksmithWorkshopBusinessLogic.BusinessLogic;
using BlacksmithWorkshopContracts.BindingModels;
using BlacksmithWorkshopContracts.BusinessLogicsContracts;
using BlacksmithWorkshopContracts.DI;
using BlacksmithWorkshopDataModels.Enums;
using Microsoft.Extensions.Logging;
using System;
@ -15,259 +16,239 @@ using System.Windows.Forms;
namespace BlacksmithWorkshop
{
public partial class FormMain : Form
{
private readonly ILogger _logger;
public partial class FormMain : Form
{
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)
{
InitializeComponent();
private readonly IBackUpLogic _backUpLogic;
_logger = logger;
_orderLogic = orderLogic;
_reportLogic = reportLogic;
_workProcess = workProcess;
}
public FormMain(ILogger<FormMain> logger, IOrderLogic orderLogic, IReportLogic reportLogic, IWorkProcess workProcess, IBackUpLogic backUpLogic)
{
InitializeComponent();
private void FormMain_Load(object sender, EventArgs e)
{
LoadData();
}
_logger = logger;
_orderLogic = orderLogic;
_reportLogic = reportLogic;
_workProcess = workProcess;
_backUpLogic = backUpLogic;
}
private void LoadData()
{
_logger.LogInformation("Загрузка заказов");
private void FormMain_Load(object sender, EventArgs e)
{
LoadData();
}
try
{
var list = _orderLogic.ReadList(null);
private void LoadData()
{
_logger.LogInformation("Загрузка заказов");
if (list != null)
{
dataGridView.DataSource = list;
dataGridView.Columns["ManufactureId"].Visible = false;
dataGridView.Columns["ImplementerId"].Visible = false;
dataGridView.Columns["ClientId"].Visible = false;
dataGridView.Columns["ManufactureName"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
dataGridView.Columns["ClientFIO"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
dataGridView.Columns["ImplementerFIO"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
}
try
{
dataGridView.FillandConfigGrid(_orderLogic.ReadList(null));
_logger.LogInformation("Загрузка заказов");
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка загрузки заказов");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
_logger.LogInformation("Загрузка заказов");
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка загрузки заказов");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void WorkPieceToolStripMenuItem_Click(object sender, EventArgs e)
{
var service = Program.ServiceProvider?.GetService(typeof(FormWorkPieces));
private void WorkPieceToolStripMenuItem_Click(object sender, EventArgs e)
{
var form = DependencyManager.Instance.Resolve<FormWorkPieces>();
if (service is FormWorkPieces form)
{
form.ShowDialog();
}
}
form.ShowDialog();
}
private void ManufactureToolStripMenuItem_Click(object sender, EventArgs e)
{
var service = Program.ServiceProvider?.GetService(typeof(FormManufactures));
private void ManufactureToolStripMenuItem_Click(object sender, EventArgs e)
{
var form = DependencyManager.Instance.Resolve<FormManufactures>();
if (service is FormManufactures form)
{
form.ShowDialog();
}
}
form.ShowDialog();
}
private void ButtonCreateOrder_Click(object sender, EventArgs e)
{
var service = Program.ServiceProvider?.GetService(typeof(FormCreateOrder));
private void ButtonCreateOrder_Click(object sender, EventArgs e)
{
var form = DependencyManager.Instance.Resolve<FormCreateOrder>();
if (service is FormCreateOrder form)
{
form.ShowDialog();
LoadData();
}
form.ShowDialog();
LoadData();
}
}
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);
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
});
try
{
var operationResult = _orderLogic.DeliveryOrder(new OrderBindingModel
{
Id = id
});
if (!operationResult)
{
throw new Exception("Ошибка при сохранении. Дополнительная информация в логах.");
}
if (!operationResult)
{
throw new Exception("Ошибка при сохранении. Дополнительная информация в логах.");
}
_logger.LogInformation("Заказ №{id} выдан", id);
_logger.LogInformation("Заказ №{id} выдан", id);
LoadData();
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка отметки о выдачи заказа");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
LoadData();
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка отметки о выдачи заказа");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
private void ButtonRef_Click(object sender, EventArgs e)
{
LoadData();
}
private void ButtonRef_Click(object sender, EventArgs e)
{
LoadData();
}
private void ButtonSellManufacture_Click(object sender, EventArgs e)
{
var form = DependencyManager.Instance.Resolve<FormSellManufacture>();
private void ButtonSellManufacture_Click(object sender, EventArgs e)
{
var service = Program.ServiceProvider?.GetService(typeof(FormSellManufacture));
if (service is FormSellManufacture form)
{
form.ShowDialog();
LoadData();
}
}
form.ShowDialog();
LoadData();
private void ShopToolStripMenuItem_Click(object sender, EventArgs e)
{
var service = Program.ServiceProvider?.GetService(typeof(FormShops));
}
if (service is FormShops form)
{
form.ShowDialog();
}
}
private void ShopToolStripMenuItem_Click(object sender, EventArgs e)
{
var form = DependencyManager.Instance.Resolve<FormShops>();
private void AddManufactureToolStripMenuItem_Click(object sender, EventArgs e)
{
var service = Program.ServiceProvider?.GetService(typeof(FormAddManufacture));
form.ShowDialog();
}
if (service is FormAddManufacture form)
{
form.ShowDialog();
LoadData();
}
}
private void AddManufactureToolStripMenuItem_Click(object sender, EventArgs e)
{
var form = DependencyManager.Instance.Resolve<FormAddManufacture>();
private void GroupedOrdersReportToolStripMenuItem_Click(object sender, EventArgs e)
{
var service = Program.ServiceProvider?.GetService(typeof(FormReportGroupedOrders));
form.ShowDialog();
LoadData();
}
if (service is FormReportGroupedOrders form)
{
form.ShowDialog();
}
}
private void GroupedOrdersReportToolStripMenuItem_Click(object sender, EventArgs e)
{
var form = DependencyManager.Instance.Resolve<FormReportGroupedOrders>();
private void WorkloadStoresReportToolStripMenuItem_Click(object sender, EventArgs e)
{
var service = Program.ServiceProvider?.GetService(typeof(FormReportShopManufactures));
form.ShowDialog();
}
if (service is FormReportShopManufactures form)
{
form.ShowDialog();
}
}
private void WorkloadStoresReportToolStripMenuItem_Click(object sender, EventArgs e)
{
var form = DependencyManager.Instance.Resolve<FormReportShopManufactures>();
private void ShopsReportToolStripMenuItem_Click(object sender, EventArgs e)
{
using var dialog = new SaveFileDialog { Filter = "docx|*.docx" };
form.ShowDialog();
}
if (dialog.ShowDialog() == DialogResult.OK)
{
_reportLogic.SaveShopsToWordFile(new ReportBindingModel { FileName = dialog.FileName });
MessageBox.Show("Выполнено", "Успех", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
private void ShopsReportToolStripMenuItem_Click(object sender, EventArgs e)
{
using var dialog = new SaveFileDialog { Filter = "docx|*.docx" };
private void WorkPieceManufacturesToolStripMenuItem_Click(object sender, EventArgs e)
{
var service = Program.ServiceProvider?.GetService(typeof(FormReportManufactureWorkPieces));
if (dialog.ShowDialog() == DialogResult.OK)
{
_reportLogic.SaveShopsToWordFile(new ReportBindingModel { FileName = dialog.FileName });
MessageBox.Show("Выполнено", "Успех", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
if (service is FormReportManufactureWorkPieces form)
{
form.ShowDialog();
}
}
private void WorkPieceManufacturesToolStripMenuItem_Click(object sender, EventArgs e)
{
var form = DependencyManager.Instance.Resolve<FormReportManufactureWorkPieces>();
private void ImplementerToolStripMenuItem_Click_1(object sender, EventArgs e)
{
var service = Program.ServiceProvider?.GetService(typeof(FormImplementers));
form.ShowDialog();
if (service is FormImplementers form)
{
form.ShowDialog();
}
}
}
private void ClientsToolStripMenuItem_Click_1(object sender, EventArgs e)
{
var service = Program.ServiceProvider?.GetService(typeof(FormClients));
private void ImplementerToolStripMenuItem_Click_1(object sender, EventArgs e)
{
var form = DependencyManager.Instance.Resolve<FormImplementers>();
if (service is FormClients form)
{
form.ShowDialog();
}
}
form.ShowDialog();
}
private void StartWorkToolStripMenuItem_Click(object sender, EventArgs e)
{
_workProcess.DoWork((Program.ServiceProvider?.GetService(typeof(IImplementerLogic)) as IImplementerLogic)!, _orderLogic);
private void ClientsToolStripMenuItem_Click_1(object sender, EventArgs e)
{
var form = DependencyManager.Instance.Resolve<FormClients>();
MessageBox.Show("Процесс обработки запущен", "Сообщение", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
form.ShowDialog();
}
private void ReportManufactureToolStripMenuItem_Click(object sender, EventArgs e)
{
using var dialog = new SaveFileDialog { Filter = "docx|*.docx" };
private void StartWorkToolStripMenuItem_Click(object sender, EventArgs e)
{
_workProcess.DoWork(DependencyManager.Instance.Resolve<IImplementerLogic>()!, _orderLogic);
if (dialog.ShowDialog() == DialogResult.OK)
{
_reportLogic.SaveManufacturesToWordFile(new ReportBindingModel
{
FileName = dialog.FileName
});
MessageBox.Show("Процесс обработки запущен", "Сообщение", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
MessageBox.Show("Выполнено", "Успех", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
private void ReportManufactureToolStripMenuItem_Click(object sender, EventArgs e)
{
using var dialog = new SaveFileDialog { Filter = "docx|*.docx" };
private void OrdersReportToolStripMenuItem_Click(object sender, EventArgs e)
{
var service = Program.ServiceProvider?.GetService(typeof(FormReportOrders));
if (dialog.ShowDialog() == DialogResult.OK)
{
_reportLogic.SaveManufacturesToWordFile(new ReportBindingModel
{
FileName = dialog.FileName
});
if (service is FormReportOrders form)
{
form.ShowDialog();
}
}
MessageBox.Show("Выполнено", "Успех", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
private void MessageToolStripMenuItem_Click(object sender, EventArgs e)
{
var service = Program.ServiceProvider?.GetService(typeof(FormMails));
private void OrdersReportToolStripMenuItem_Click(object sender, EventArgs e)
{
var form = DependencyManager.Instance.Resolve<FormImplementers>();
if (service is FormMails form)
{
form.ShowDialog();
}
}
}
form.ShowDialog();
}
private void MessageToolStripMenuItem_Click(object sender, EventArgs e)
{
var form = DependencyManager.Instance.Resolve<FormMails>();
form.ShowDialog();
}
private void CreateBackUpToolStripMenuItem_Click_1(object sender, EventArgs e)
{
try
{
if (_backUpLogic != null)
{
var fbd = new FolderBrowserDialog();
if (fbd.ShowDialog() == DialogResult.OK)
{
_backUpLogic.CreateBackUp(new BackUpSaveBinidngModel
{
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 BlacksmithWorkshopContracts.BindingModels;
using BlacksmithWorkshopContracts.BusinessLogicsContracts;
using BlacksmithWorkshopContracts.DI;
using BlacksmithWorkshopContracts.SearchModels;
using BlacksmithWorkshopDataModels.Models;
using Microsoft.Extensions.Logging;
@ -89,30 +90,27 @@ namespace BlacksmithWorkshop
private void ButtonAdd_Click(object sender, EventArgs e)
{
var service = Program.ServiceProvider?.GetService(typeof(FormManufactureWorkPiece));
if (service is FormManufactureWorkPiece form)
var form = DependencyManager.Instance.Resolve<FormManufactureWorkPiece>();
if (form.ShowDialog() == DialogResult.OK)
{
if (form.ShowDialog() == DialogResult.OK)
if (form.WorkPieceModel == null)
{
if (form.WorkPieceModel == null)
{
return;
}
_logger.LogInformation("Добавление новой заготовки:{WorkPieceName} - {Count}", form.WorkPieceModel.WorkPieceName, form.Count);
if (_manufactureWorkPieces.ContainsKey(form.Id))
{
_manufactureWorkPieces[form.Id] = (form.WorkPieceModel, form.Count);
}
else
{
_manufactureWorkPieces.Add(form.Id, (form.WorkPieceModel, form.Count));
}
LoadData();
return;
}
_logger.LogInformation("Добавление новой заготовки:{WorkPieceName} - {Count}", form.WorkPieceModel.WorkPieceName, form.Count);
if (_manufactureWorkPieces.ContainsKey(form.Id))
{
_manufactureWorkPieces[form.Id] = (form.WorkPieceModel, form.Count);
}
else
{
_manufactureWorkPieces.Add(form.Id, (form.WorkPieceModel, form.Count));
}
LoadData();
}
}
@ -120,26 +118,23 @@ namespace BlacksmithWorkshop
{
if (dataGridView.SelectedRows.Count == 1)
{
var service = Program.ServiceProvider?.GetService(typeof(FormManufactureWorkPiece));
var form = DependencyManager.Instance.Resolve<FormManufactureWorkPiece>();
if (service is FormManufactureWorkPiece form)
int id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells[0].Value);
form.Id = id;
form.Count = _manufactureWorkPieces[id].Item2;
if (form.ShowDialog() == DialogResult.OK)
{
int id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells[0].Value);
form.Id = id;
form.Count = _manufactureWorkPieces[id].Item2;
if (form.ShowDialog() == DialogResult.OK)
if (form.WorkPieceModel == null)
{
if (form.WorkPieceModel == null)
{
return;
}
_logger.LogInformation("Изменение компонента:{WorkPieceName} - {Count}", form.WorkPieceModel.WorkPieceName, form.Count);
_manufactureWorkPieces[form.Id] = (form.WorkPieceModel, form.Count);
LoadData();
return;
}
_logger.LogInformation("Изменение компонента:{WorkPieceName} - {Count}", form.WorkPieceModel.WorkPieceName, form.Count);
_manufactureWorkPieces[form.Id] = (form.WorkPieceModel, form.Count);
LoadData();
}
}
}

View File

@ -1,5 +1,7 @@
using BlacksmithWorkshopContracts.BindingModels;
using BlacksmithWorkshopBusinessLogic.BusinessLogic;
using BlacksmithWorkshopContracts.BindingModels;
using BlacksmithWorkshopContracts.BusinessLogicsContracts;
using BlacksmithWorkshopContracts.DI;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
@ -37,15 +39,7 @@ namespace BlacksmithWorkshop
{
try
{
var list = _logic.ReadList(null);
if (list != null)
{
dataGridView.DataSource = list;
dataGridView.Columns["Id"].Visible = false;
dataGridView.Columns["ManufactureWorkPieces"].Visible = false;
dataGridView.Columns["ManufactureName"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
}
dataGridView.FillandConfigGrid(_logic.ReadList(null));
_logger.LogInformation("Загрузка изделий");
}
@ -58,14 +52,11 @@ namespace BlacksmithWorkshop
private void ButtonAdd_Click(object sender, EventArgs e)
{
var service = Program.ServiceProvider?.GetService(typeof(FormManufacture));
var form = DependencyManager.Instance.Resolve<FormManufacture>();
if (service is FormManufacture form)
if (form.ShowDialog() == DialogResult.OK)
{
if (form.ShowDialog() == DialogResult.OK)
{
LoadData();
}
LoadData();
}
}
@ -73,16 +64,13 @@ namespace BlacksmithWorkshop
{
if (dataGridView.SelectedRows.Count == 1)
{
var service = Program.ServiceProvider?.GetService(typeof(FormManufacture));
var form = DependencyManager.Instance.Resolve<FormManufacture>();
if (service is FormManufacture form)
{
form.Id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value);
form.Id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value);
if (form.ShowDialog() == DialogResult.OK)
{
LoadData();
}
if (form.ShowDialog() == DialogResult.OK)
{
LoadData();
}
}
}

View File

@ -1,5 +1,7 @@
using BlacksmithWorkshopContracts.BindingModels;
using BlacksmithWorkshopBusinessLogic.BusinessLogic;
using BlacksmithWorkshopContracts.BindingModels;
using BlacksmithWorkshopContracts.BusinessLogicsContracts;
using BlacksmithWorkshopContracts.DI;
using BlacksmithWorkshopContracts.SearchModels;
using BlacksmithWorkshopDataModels.Models;
using Microsoft.Extensions.Logging;
@ -18,6 +20,7 @@ namespace BlacksmithWorkshop
public partial class FormShops : Form
{
private readonly ILogger _logger;
private readonly IShopLogic _logic;
public FormShops(ILogger<FormShops> logger, IShopLogic logic)
@ -33,20 +36,12 @@ namespace BlacksmithWorkshop
}
private void LoadData()
{
try
{
try
{
var list = _logic.ReadList(null);
dataGridView.FillandConfigGrid(_logic.ReadList(null));
if (list != null)
{
dataGridView.DataSource = list;
dataGridView.Columns["Id"].Visible = false;
dataGridView.Columns["ShopManufactures"].Visible = false;
dataGridView.Columns["ShopName"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
}
_logger.LogInformation("Загрузка магазинов");
_logger.LogInformation("Загрузка магазинов");
}
catch (Exception ex)
{
@ -57,13 +52,11 @@ namespace BlacksmithWorkshop
private void ButtonAdd_Click(object sender, EventArgs e)
{
var service = Program.ServiceProvider?.GetService(typeof(FormShop));
if (service is FormShop form)
var form = DependencyManager.Instance.Resolve<FormShop>();
if (form.ShowDialog() == DialogResult.OK)
{
if (form.ShowDialog() == DialogResult.OK)
{
LoadData();
}
LoadData();
}
}
@ -71,14 +64,12 @@ namespace BlacksmithWorkshop
{
if (dataGridView.SelectedRows.Count == 1)
{
var service = Program.ServiceProvider?.GetService(typeof(FormShop));
if (service is FormShop form)
var form = DependencyManager.Instance.Resolve<FormShop>();
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,7 @@
using BlacksmithWorkshopContracts.BindingModels;
using BlacksmithWorkshopBusinessLogic.BusinessLogic;
using BlacksmithWorkshopContracts.BindingModels;
using BlacksmithWorkshopContracts.BusinessLogicsContracts;
using BlacksmithWorkshopContracts.DI;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
@ -35,15 +37,7 @@ namespace BlacksmithWorkshop
{
try
{
var list = _logic.ReadList(null);
//растягиваем колонку Название на всю ширину, колонку Id скрываем
if(list != null)
{
dataGridView.DataSource = list;
dataGridView.Columns["Id"].Visible = false;
dataGridView.Columns["WorkPieceName"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
}
dataGridView.FillandConfigGrid(_logic.ReadList(null));
_logger.LogInformation("Загрузка заготовок");
}
@ -57,14 +51,11 @@ namespace BlacksmithWorkshop
private void ButtonAdd_Click(object sender, EventArgs e)
{
var service = Program.ServiceProvider?.GetService(typeof(FormWorkPiece));
var form = DependencyManager.Instance.Resolve<FormWorkPiece>();
if (service is FormWorkPiece form)
if (form.ShowDialog() == DialogResult.OK)
{
if (form.ShowDialog() == DialogResult.OK)
{
LoadData();
}
LoadData();
}
}
@ -73,15 +64,12 @@ namespace BlacksmithWorkshop
{
if (dataGridView.SelectedRows.Count == 1)
{
var service = Program.ServiceProvider?.GetService(typeof(FormWorkPiece));
if (service is FormWorkPiece form)
var form = DependencyManager.Instance.Resolve<FormWorkPiece>();
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

@ -2,6 +2,7 @@ using BlacksmithWorkshopBusinessLogic.BusinessLogic;
using BlacksmithWorkshopBusinessLogic.OfficePackage.Implements;
using BlacksmithWorkshopBusinessLogic.OfficePackage;
using BlacksmithWorkshopContracts.BusinessLogicsContracts;
using BlacksmithWorkshopContracts.DI;
using BlacksmithWorkshopContracts.StoragesContracts;
using BlacksmithWorkshopDatabaseImplement.Implements;
using Microsoft.Extensions.DependencyInjection;
@ -14,10 +15,6 @@ namespace BlacksmithWorkshop
{
internal static class Program
{
private static ServiceProvider? _serviceProvider;
public static ServiceProvider? ServiceProvider => _serviceProvider;
/// <summary>
/// The main entry point for the application.
/// </summary>
@ -28,13 +25,12 @@ namespace BlacksmithWorkshop
// see https://aka.ms/applicationconfiguration.
ApplicationConfiguration.Initialize();
var services = new ServiceCollection();
ConfigureServices(services);
_serviceProvider = services.BuildServiceProvider();
InitDependency();
try
try
{
var mailSender = _serviceProvider.GetService<AbstractMailWorker>();
mailSender?.MailConfig(new MailConfigBindingModel
var mailSender = DependencyManager.Instance.Resolve<AbstractMailWorker>();
mailSender?.MailConfig(new MailConfigBindingModel
{
MailLogin = System.Configuration.ConfigurationManager.AppSettings["MailLogin"] ?? string.Empty,
MailPassword = System.Configuration.ConfigurationManager.AppSettings["MailPassword"] ?? string.Empty,
@ -49,69 +45,47 @@ namespace BlacksmithWorkshop
}
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.AddNLog("nlog.config");
});
services.AddTransient<IWorkPieceStorage, WorkPieceStorage>();
services.AddTransient<IOrderStorage, OrderStorage>();
services.AddTransient<IManufactureStorage, ManufactureStorage>();
services.AddTransient<IShopStorage, ShopStorage>();
services.AddTransient<IImplementerStorage, ImplementerStorage>();
services.AddTransient<IClientStorage, ClientStorage>();
services.AddTransient<IMessageInfoStorage, MessageInfoStorage>();
DependencyManager.Instance.RegisterType<FormMain>();
DependencyManager.Instance.RegisterType<FormWorkPiece>();
DependencyManager.Instance.RegisterType<FormWorkPieces>();
DependencyManager.Instance.RegisterType<FormCreateOrder>();
DependencyManager.Instance.RegisterType<FormManufacture>();
DependencyManager.Instance.RegisterType<FormManufactureWorkPiece>();
DependencyManager.Instance.RegisterType<FormManufactures>();
DependencyManager.Instance.RegisterType<FormReportManufactureWorkPieces>();
DependencyManager.Instance.RegisterType<FormReportOrders>();
DependencyManager.Instance.RegisterType<FormClients>();
DependencyManager.Instance.RegisterType<FormImplementer>();
DependencyManager.Instance.RegisterType<FormImplementers>();
DependencyManager.Instance.RegisterType<FormMails>();
DependencyManager.Instance.RegisterType<FormAnswerMail>();
DependencyManager.Instance.RegisterType<FormMails>();
DependencyManager.Instance.RegisterType<FormSellManufacture>();
DependencyManager.Instance.RegisterType<FormReportGroupedOrders>();
DependencyManager.Instance.RegisterType<FormReportShopManufactures>();
DependencyManager.Instance.RegisterType<FormShops>();
DependencyManager.Instance.RegisterType<FormShop>();
}
services.AddTransient<IWorkPieceLogic, WorkPieceLogic>();
services.AddTransient<IOrderLogic, OrderLogic>();
services.AddTransient<IManufactureLogic, ManufactureLogic>();
services.AddTransient<IShopLogic, ShopLogic>();
services.AddTransient<IReportLogic, ReportLogic>();
services.AddTransient<IImplementerLogic, ImplementerLogic>();
services.AddTransient<IClientLogic, ClientLogic>();
services.AddTransient<IMessageInfoLogic, MessageInfoLogic>();
services.AddTransient<IWorkProcess, WorkModeling>();
services.AddSingleton<AbstractMailWorker, MailKitWorker>();
services.AddTransient<AbstractSaveToExcel, SaveToExcel>();
services.AddTransient<AbstractSaveToWord, SaveToWord>();
services.AddTransient<AbstractSaveToPdf, SaveToPdf>();
services.AddTransient<FormMain>();
services.AddTransient<FormWorkPiece>();
services.AddTransient<FormWorkPieces>();
services.AddTransient<FormCreateOrder>();
services.AddTransient<FormManufacture>();
services.AddTransient<FormManufactures>();
services.AddTransient<FormManufactureWorkPiece>();
services.AddTransient<FormShop>();
services.AddTransient<FormShops>();
services.AddTransient<FormAddManufacture>();
services.AddTransient<FormSellManufacture>();
services.AddTransient<FormReportManufactureWorkPieces>();
services.AddTransient<FormReportShopManufactures>();
services.AddTransient<FormReportOrders>();
services.AddTransient<FormReportGroupedOrders>();
services.AddTransient<FormClients>();
services.AddTransient<FormImplementers>();
services.AddTransient<FormImplementer>();
services.AddTransient<FormMails>();
services.AddTransient<FormAnswerMail>();
}
private static void MailCheck(object obj) => ServiceProvider?.GetService<AbstractMailWorker>()?.MailCheck();
private static void MailCheck(object obj) => DependencyManager.Instance.Resolve<AbstractMailWorker>()?.MailCheck();
}
}

View File

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

View File

@ -0,0 +1,129 @@
using BlacksmithWorkshopContracts.BindingModels;
using BlacksmithWorkshopContracts.BusinessLogicsContracts;
using BlacksmithWorkshopContracts.StoragesContracts;
using BlacksmithWorkshopDataModels;
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 BlacksmithWorkshopBusinessLogic.BusinessLogic
{
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(BackUpSaveBinidngModel 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)
{
//проверка на то, является ли тип интерфейсом и унаследован ли он от IId
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;
}
//три строчки ниже - сериализация файлов в json
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,40 @@
using BlacksmithWorkshopBusinessLogic.BusinessLogic;
using BlacksmithWorkshopBusinessLogic.MailWorker;
using BlacksmithWorkshopBusinessLogic.OfficePackage.Implements;
using BlacksmithWorkshopBusinessLogic.OfficePackage;
using BlacksmithWorkshopContracts.BusinessLogicsContracts;
using BlacksmithWorkshopContracts.DI;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BlacksmithWorkshopBusinessLogic
{
public class BusinessLogicImplementationExtension : IBusinessLogicImplementationExtension
{
public int Priority => 0;
public void RegisterServices()
{
DependencyManager.Instance.RegisterType<IWorkPieceLogic, WorkPieceLogic>();
DependencyManager.Instance.RegisterType<IOrderLogic, OrderLogic>();
DependencyManager.Instance.RegisterType<IManufactureLogic, ManufactureLogic>();
DependencyManager.Instance.RegisterType<IReportLogic, ReportLogic>();
DependencyManager.Instance.RegisterType<IClientLogic, ClientLogic>();
DependencyManager.Instance.RegisterType<IImplementerLogic, ImplementerLogic>();
DependencyManager.Instance.RegisterType<IMessageInfoLogic, MessageInfoLogic>();
DependencyManager.Instance.RegisterType<IShopLogic, ShopLogic>();
DependencyManager.Instance.RegisterType<AbstractSaveToExcel, SaveToExcel>();
DependencyManager.Instance.RegisterType<AbstractSaveToWord, SaveToWord>();
DependencyManager.Instance.RegisterType<AbstractSaveToPdf, SaveToPdf>();
DependencyManager.Instance.RegisterType<IWorkProcess, WorkModeling>();
DependencyManager.Instance.RegisterType<AbstractMailWorker, MailKitWorker>(true);
DependencyManager.Instance.RegisterType<IBackUpLogic, BackUpLogic>();
}
}
}

View File

@ -0,0 +1,36 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BlacksmithWorkshopContracts.Attributes
{
//указываем, что данный атрибут можно прописать только в Property
[AttributeUsage(AttributeTargets.Property)]
public class ColumnAttribute : Attribute
{
public ColumnAttribute(string title = "", bool visible = true, int width = 0,
GridViewAutoSize gridViewAutoSize = GridViewAutoSize.None, bool isUseAutoSize = false, string format = "")
{
Title = title;
Visible = visible;
Width = width;
GridViewAutoSize = gridViewAutoSize;
IsUseAutoSize = isUseAutoSize;
Format = format;
}
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 string Format { get; private set; }
}
}

View File

@ -0,0 +1,27 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BlacksmithWorkshopContracts.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 BlacksmithWorkshopContracts.BindingModels
{
public class BackUpSaveBinidngModel
{
public string FolderName { get; set; } = string.Empty;
}
}

View File

@ -9,7 +9,9 @@ namespace BlacksmithWorkshopContracts.BindingModels
{
public class MessageInfoBindingModel : IMessageInfoModel
{
public string MessageId { get; set; } = string.Empty;
public int Id { get; set; }
public string MessageId { get; set; } = string.Empty;
public int? ClientId { get; set; }

View File

@ -6,6 +6,12 @@
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Logging" Version="7.0.0" />
<PackageReference Include="Unity" Version="5.11.9" />
<PackageReference Include="Unity.Microsoft.Logging" Version="5.10.0" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\BlacksmithWorkshopDataModels\BlacksmithWorkshopDataModels.csproj" />
</ItemGroup>

View File

@ -0,0 +1,16 @@
using BlacksmithWorkshopContracts.BindingModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BlacksmithWorkshopContracts.BusinessLogicsContracts
{
//интерфейс создания бекапа
public interface IBackUpLogic
{
//путь и имя файла для архивации
void CreateBackUp(BackUpSaveBinidngModel model);
}
}

View File

@ -0,0 +1,73 @@
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BlacksmithWorkshopContracts.DI
{
/// <summary>
/// Менеджер для работы с зависимостями
/// </summary>
public class DependencyManager
{
private readonly IDependencyContainer _dependencyManager;
private static DependencyManager? _manager;
private static readonly object _locjObject = new();
private DependencyManager()
{
_dependencyManager = new UnityDependencyContainer();
}
public static DependencyManager Instance
{
get
{
if (_manager == null) { lock (_locjObject) { _manager = new DependencyManager(); } }
return _manager;
}
}
//Иницализация библиотек, в которых идут установки зависомстей
public static void InitDependency()
{
var ext = ServiceProviderLoader.GetImplementationExtensions();
if (ext == null)
{
throw new ArgumentNullException("Отсутствуют компоненты для загрузки зависимостей по модулям");
}
//регистрируем зависимости хранилищ
ext.RegisterServices();
var extBusiness = ServiceProviderLoader.GetBusinessLogicImplementationExtensions();
if (extBusiness == null)
{
throw new ArgumentNullException("Отсутствуют компоненты для загрузки зависимостей по модулям");
}
//регистрируем зависимости бизнес-логики
extBusiness.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,16 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BlacksmithWorkshopContracts.DI
{
public interface IBusinessLogicImplementationExtension
{
public int Priority { get; }
//Регистрация сервисов
public void RegisterServices();
}
}

View File

@ -0,0 +1,26 @@
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BlacksmithWorkshopContracts.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,20 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BlacksmithWorkshopContracts.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 BlacksmithWorkshopContracts.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,107 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
namespace BlacksmithWorkshopContracts.DI
{
//Загрузчик данных
public static partial class ServiceProviderLoader
{
//Загрузка всех классов-реализаций IImplementationExtension
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";
}
public static IBusinessLogicImplementationExtension? GetBusinessLogicImplementationExtensions()
{
IBusinessLogicImplementationExtension? source = null;
var files = Directory.GetFiles(TryGetBusinessLogicImplementationExtensionsFolder(), "*.dll", SearchOption.AllDirectories);
foreach (var file in files.Distinct())
{
Assembly asm = Assembly.LoadFrom(file);
foreach (var t in asm.GetExportedTypes())
{
if (t.IsClass && typeof(IBusinessLogicImplementationExtension).IsAssignableFrom(t))
{
if (source == null)
{
source = (IBusinessLogicImplementationExtension)Activator.CreateInstance(t)!;
}
else
{
var newSource = (IBusinessLogicImplementationExtension)Activator.CreateInstance(t)!;
if (newSource.Priority > source.Priority)
{
source = newSource;
}
}
}
}
}
return source;
}
private static string TryGetBusinessLogicImplementationExtensionsFolder()
{
var directory = new DirectoryInfo(Directory.GetCurrentDirectory());
while (directory != null && !directory.GetDirectories("BusinessLogicImplementationExtensions", SearchOption.AllDirectories).Any(x => x.Name == "BusinessLogicImplementationExtensions"))
{
directory = directory.Parent;
}
return $"{directory?.FullName}\\BusinessLogicImplementationExtensions";
}
}
}

View File

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

View File

@ -0,0 +1,18 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BlacksmithWorkshopContracts.StoragesContracts
{
//интерфейс получения данных по всем сущностям
public interface IBackUpInfo
{
//метод получения данных по всем сущностям
List<T>? GetList<T>() where T : class, new();
Type? GetTypeByModelInterface(string modelInterfaceName);
}
}

View File

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

View File

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

View File

@ -1,4 +1,5 @@
using BlacksmithWorkshopDataModels.Models;
using BlacksmithWorkshopContracts.Attributes;
using BlacksmithWorkshopDataModels.Models;
using System;
using System.Collections.Generic;
using System.ComponentModel;
@ -11,14 +12,16 @@ namespace BlacksmithWorkshopContracts.ViewModels
//класс для отображения пользователю информаци о продуктах (изделиях)
public class ManufactureViewModel : IManufactureModel
{
[Column(visible: false)]
public int Id { get; set; }
[DisplayName("Навание изделия")]
[Column(title: "Навание изделия", gridViewAutoSize: GridViewAutoSize.Fill, isUseAutoSize: true)]
public string ManufactureName { get; set; } = string.Empty;
[DisplayName("Цена")]
[Column(title: "Цена", width: 150, format: "0.00")]
public double Price { get; set; }
[Column(visible: false)]
public Dictionary<int, (IWorkPieceModel, int)> ManufactureWorkPieces { get; set; } = new();
}
}

View File

@ -1,4 +1,5 @@
using BlacksmithWorkshopDataModels.Models;
using BlacksmithWorkshopContracts.Attributes;
using BlacksmithWorkshopDataModels.Models;
using System;
using System.Collections.Generic;
using System.ComponentModel;
@ -10,26 +11,31 @@ namespace BlacksmithWorkshopContracts.ViewModels
{
public class MessageInfoViewModel : IMessageInfoModel
{
public string MessageId { get; set; } = string.Empty;
[Column(visible: false)]
public int Id { get; set; }
[Column(visible: false)]
public string MessageId { get; set; } = string.Empty;
[Column(visible: false)]
public int? ClientId { get; set; }
[DisplayName("Отправитель")]
[Column(title: "Отправитель", width: 150)]
public string SenderName { get; set; } = string.Empty;
[DisplayName("Дата отправки")]
[Column(title: "Дата отправки", width: 150, format: "D")]
public DateTime DateDelivery { get; set; } = DateTime.Now;
[DisplayName("Заголовок")]
[Column(title: "Заголовок", width: 150)]
public string Subject { get; set; } = string.Empty;
[DisplayName("Текст")]
public string Body { get; set; } = string.Empty;
[Column(title: "Текст", width: 150)]
public string Body { get; set; } = string.Empty;
[DisplayName("Прочитано")]
public bool IsRead { get; set; } = false;
[Column(title: "Прочитано", width: 150)]
public bool IsRead { get; set; } = false;
[DisplayName("Ответ")]
public string? Answer { get; set; }
[Column(title: "Ответ", width: 150)]
public string Answer { get; set; }
}
}

View File

@ -1,4 +1,5 @@
using BlacksmithWorkshopDataModels.Enums;
using BlacksmithWorkshopContracts.Attributes;
using BlacksmithWorkshopDataModels.Enums;
using BlacksmithWorkshopDataModels.Models;
using System;
using System.Collections.Generic;
@ -12,37 +13,40 @@ namespace BlacksmithWorkshopContracts.ViewModels
//класс для отображения пользователю информации о заказах
public class OrderViewModel : IOrderModel
{
[DisplayName("Номер")]
[Column(visible: false)]
public int Id { get; set; }
public int ClientId { get; set; }
[Column(visible: false)]
public int ClientId { get; set; }
public int? ImplementerId { get; set; }
[Column(visible: false)]
public int? ImplementerId { get; set; }
public int ManufactureId { get; set; }
[Column(visible: false)]
public int ManufactureId { get; set; }
[DisplayName("ФИО клиента")]
[Column(title: "ФИО клиента", width: 150)]
public string ClientFIO { get; set; } = string.Empty;
[DisplayName("Изделие")]
[Column(title: "Изделие", width: 150)]
public string ManufactureName { get; set; } = string.Empty;
[DisplayName("ФИО исполнителя")]
[Column(title: "ФИО исполнителя", width: 150)]
public string ImplementerFIO { get; set; } = string.Empty;
[DisplayName("Количество")]
[Column(title: "Количество", width: 150)]
public int Count { get; set; }
[DisplayName("Сумма")]
[Column(title: "Сумма", width: 150, format: "0.00")]
public double Sum { get; set; }
[DisplayName("Статус")]
[Column(title: "Статус", width: 150)]
public OrderStatus Status { get; set; } = OrderStatus.Неизвестен;
[DisplayName("Дата создания")]
[Column(title: "Дата создания", width: 150, format: "D")]
public DateTime DateCreate { get; set; } = DateTime.Now;
[DisplayName("Дата выполнения")]
[Column(title: "Дата выполнения", width: 150, format: "f")]
public DateTime? DateImplement { get; set; }
}
}

View File

@ -1,4 +1,5 @@
using BlacksmithWorkshopDataModels.Models;
using BlacksmithWorkshopContracts.Attributes;
using BlacksmithWorkshopDataModels.Models;
using System;
using System.Collections.Generic;
using System.ComponentModel;
@ -10,22 +11,25 @@ namespace BlacksmithWorkshopContracts.ViewModels
{
public class ShopViewModel
{
public int Id { get; set; }
[Column(visible: false)]
public int Id { get; set; }
[DisplayName("Название магазина")]
public string ShopName { get; set; } = string.Empty;
[Column(title: "Название магазина", gridViewAutoSize: GridViewAutoSize.AllCells, isUseAutoSize: true)]
public string ShopName { get; set; } = string.Empty;
[DisplayName("Адрес магазина")]
public string Address { get; set; } = string.Empty;
[Column(title: "Адрес магазина", gridViewAutoSize: GridViewAutoSize.Fill, isUseAutoSize: true)]
public string Address { get; set; } = string.Empty;
[DisplayName("Дата открытия")]
public DateTime DateOpen { get; set; } = DateTime.Now;
[Column(title: "Время открытия", gridViewAutoSize: GridViewAutoSize.AllCells, isUseAutoSize: true, format: "f")]
public DateTime DateOpen { get; set; } = DateTime.Now;
public Dictionary<int, (IManufactureModel, int)> ShopManufactures { get; set; } = new();
[Column(visible: false)]
public Dictionary<int, (IManufactureModel, int)> ShopManufactures { get; set; } = new();
[DisplayName("Вместимость магазина")]
public int MaxCountManufactures { get; set; }
[Column(title:"Вместимость магазина", gridViewAutoSize: GridViewAutoSize.DisplayedCells, isUseAutoSize: true)]
public int MaxCountManufactures { get; set; }
public List<Tuple<ManufactureViewModel, int>> ShopManufactureList { get; set; } = new();
[Column(visible: false)]
public List<Tuple<ManufactureViewModel, int>> ShopManufactureList { get; set; } = new();
}
}

View File

@ -5,18 +5,20 @@ using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using BlacksmithWorkshopContracts.Attributes;
namespace BlacksmithWorkshopContracts.ViewModels
{
//класс для отображения пользователю данных о заготовких (заготовках)
public class WorkPieceViewModel : IWorkPieceModel
{
[Column(visible: false)]
public int Id { get; set; }
[DisplayName("Название заготовки")]
[Column(title: "Название заготовки", width: 150, format: "0.00")]
public string WorkPieceName { get; set; } = string.Empty;
[DisplayName("Цена")]
[Column(title: "Цена", width: 150)]
public double Cost { get; set; }
}
}

View File

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

View File

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

View File

@ -0,0 +1,35 @@
using BlacksmithWorkshopContracts.DI;
using BlacksmithWorkshopContracts.StoragesContracts;
using BlacksmithWorkshopDatabaseImplement.Implements;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BlacksmithWorkshopDatabaseImplement
{
public class DataBaseImplementationExtension : IImplementationExtension
{
public int Priority => 2;
public void RegisterServices()
{
DependencyManager.Instance.RegisterType<IClientStorage, ClientStorage>();
DependencyManager.Instance.RegisterType<IWorkPieceStorage, WorkPieceStorage>();
DependencyManager.Instance.RegisterType<IImplementerStorage, ImplementerStorage>();
DependencyManager.Instance.RegisterType<IMessageInfoStorage, MessageInfoStorage>();
DependencyManager.Instance.RegisterType<IOrderStorage, OrderStorage>();
DependencyManager.Instance.RegisterType<IManufactureStorage, ManufactureStorage>();
DependencyManager.Instance.RegisterType<IShopStorage, ShopStorage>();
DependencyManager.Instance.RegisterType<IBackUpInfo, BackUpInfo>();
}
}
}

View File

@ -0,0 +1,36 @@
using BlacksmithWorkshopContracts.StoragesContracts;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BlacksmithWorkshopDatabaseImplement.Implements
{
public class BackUpInfo : IBackUpInfo
{
public List<T>? GetList<T>() where T : class, new()
{
using var context = new BlacksmithWorkshopDatabase();
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

@ -6,23 +6,29 @@ using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
namespace BlacksmithWorkshopDatabaseImplement.Models
{
public class Client : IClientModel
[DataContract]
public class Client : IClientModel
{
public int Id { get; set; }
[DataMember]
public int Id { get; set; }
[Required]
[DataMember]
public string ClientFIO { get; set; } = string.Empty;
[Required]
public string ClientFIO { get; set; } = string.Empty;
[DataMember]
public string Email { get; set; } = string.Empty;
[Required]
public string Email { get; set; } = string.Empty;
[Required]
public string Password { get; set; } = string.Empty;
[DataMember]
public string Password { get; set; } = string.Empty;
//для реализации связи многие ко многим с заказами (так как клиенты могу сделать одинаковый заказ)
[ForeignKey("ClientId")]

View File

@ -6,26 +6,33 @@ using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
namespace BlacksmithWorkshopDatabaseImplement.Models
{
public class Implementer : IImplementerModel
[DataContract]
public class Implementer : IImplementerModel
{
public int Id { get; set; }
[DataMember]
public int Id { get; set; }
[Required]
public string ImplementerFIO { get; set; } = string.Empty;
[DataMember]
public string ImplementerFIO { get; set; } = string.Empty;
[Required]
public string Password { get; set; } = string.Empty;
[DataMember]
public string Password { get; set; } = string.Empty;
[Required]
public int WorkExperience { get; set; }
[DataMember]
public int WorkExperience { get; set; }
[Required]
public int Qualification { get; set; }
[DataMember]
public int Qualification { get; set; }
//для реализации связи один ко многим с заказами
[ForeignKey("ImplementerId")]

View File

@ -7,25 +7,31 @@ using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
namespace BlacksmithWorkshopDatabaseImplement.Models
{
[DataContract]
public class Manufacture : IManufactureModel
{
[DataMember]
public int Id { get; set; }
[Required]
[DataMember]
public string ManufactureName { get; set; } = string.Empty;
[Required]
[DataMember]
public double Price { get; set; }
public Dictionary<int, (IWorkPieceModel, int)>? _manufactureWorkPieces = null;
//это поле не будет "мапиться" в бд
[NotMapped]
[DataMember]
public Dictionary<int, (IWorkPieceModel, int)> ManufactureWorkPieces
{
get

View File

@ -2,11 +2,13 @@
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
namespace BlacksmithWorkshopDatabaseImplement.Models
{
[DataContract]
public class ManufactureWorkPiece
{
public int Id { get; set; }

View File

@ -5,33 +5,40 @@ using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
namespace BlacksmithWorkshopDatabaseImplement.Models
{
[DataContract]
public class MessageInfo : IMessageInfoModel
{
[Key]
public string MessageId { get; set; } = string.Empty;
public int Id => throw new NotImplementedException();
[Key]
[DataMember]
public string MessageId { get; set; } = string.Empty;
[DataMember]
public int? ClientId { get; set; }
public bool IsRead { get; private set; } = false;
[Required]
[DataMember]
public string SenderName { get; set; } = string.Empty;
[Required]
[DataMember]
public DateTime DateDelivery { get; set; } = DateTime.Now;
[Required]
[DataMember]
public string Subject { get; set; } = string.Empty;
[Required]
[DataMember]
public string Body { get; set; } = string.Empty;
public string? Answer { get; private set; } = string.Empty;
public string? Answer { get; private set; } = string.Empty;
public virtual Client? Client { get; set; }

View File

@ -6,36 +6,47 @@ using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;
namespace BlacksmithWorkshopDatabaseImplement.Models
{
[DataContract]
public class Order : IOrderModel
{
[DataMember]
public int Id { get; private set; }
[Required]
[DataMember]
public int ManufactureId { get; private set; }
[Required]
public int ClientId { get; private set; }
[DataMember]
public int ClientId { get; private set; }
public int? ImplementerId { get; private set; }
[DataMember]
public int? ImplementerId { get; private set; }
[Required]
[DataMember]
public int Count { get; private set; }
[Required]
[DataMember]
public double Sum { get; private set; }
[Required]
public OrderStatus Status { get; private set; }
[DataMember]
public OrderStatus Status { get; private set; } = OrderStatus.Неизвестен;
[Required]
public DateTime DateCreate { get; private set; }
[DataMember]
public DateTime DateCreate { get; private set; } = DateTime.Now;
[DataMember]
public DateTime? DateImplement { get; private set; }
//для передачи названия изделия

View File

@ -7,19 +7,24 @@ using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Data;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
namespace BlacksmithWorkshopDatabaseImplement.Models
{
[DataContract]
public class WorkPiece : IWorkPieceModel
{
[DataMember]
public int Id { get; private set; }
[Required]
[DataMember]
public string WorkPieceName { get; private set; } = string.Empty;
[Required]
[DataMember]
public double Cost { get; set; }
//для реализации связи многие ко многим с изделиями

View File

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

View File

@ -0,0 +1,36 @@
using BlacksmithWorkshopContracts.DI;
using BlacksmithWorkshopContracts.StoragesContracts;
using BlacksmithWorkshopFileImplement.Implements;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BlacksmithWorkshopFileImplement
{
//для реализации нужных нам зависимостей в данном варианте хранения информации
public class FileImplementationExtension : IImplementationExtension
{
public int Priority => 1;
public void RegisterServices()
{
DependencyManager.Instance.RegisterType<IClientStorage, ClientStorage>();
DependencyManager.Instance.RegisterType<IWorkPieceStorage, WorkPieceStorage>();
DependencyManager.Instance.RegisterType<IImplementerStorage, ImplementerStorage>();
DependencyManager.Instance.RegisterType<IMessageInfoStorage, MessageInfoStorage>();
DependencyManager.Instance.RegisterType<IOrderStorage, OrderStorage>();
DependencyManager.Instance.RegisterType<IManufactureStorage, ManufactureStorage>();
DependencyManager.Instance.RegisterType<IShopStorage, ShopStorage>();
DependencyManager.Instance.RegisterType<IBackUpInfo, BackUpInfo>();
}
}
}

View File

@ -0,0 +1,37 @@
using BlacksmithWorkshopContracts.StoragesContracts;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BlacksmithWorkshopFileImplement.Implements
{
public class BackUpInfo : IBackUpInfo
{
public List<T>? GetList<T>() where T : class, new()
{
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

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

View File

@ -5,23 +5,30 @@ using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;
namespace BlacksmithWorkshopFileImplement.Models
{
[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; }
public static Implementer? Create(ImplementerBindingModel model)
{

View File

@ -4,6 +4,7 @@ using BlacksmithWorkshopDataModels.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;
@ -11,19 +12,23 @@ using System.Xml.Linq;
namespace BlacksmithWorkshopFileImplement.Models
{
//класс реализующий интерфейс модели изделия
[DataContract]
public class Manufacture : IManufactureModel
{
[DataMember]
public int Id { get; private set; }
[DataMember]
public string ManufactureName { get; private set; } = string.Empty;
[DataMember]
public double Price { get; private set; }
public Dictionary<int, int> WorkPieces { get; private set; } = new();
private Dictionary<int, (IWorkPieceModel, int)>? _manufactureWorkPieces = null;
[DataMember]
public Dictionary<int, (IWorkPieceModel, int)> ManufactureWorkPieces
{
get

View File

@ -6,27 +6,37 @@ using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;
namespace BlacksmithWorkshopFileImplement.Models
{
[DataContract]
public class MessageInfo : IMessageInfoModel
{
public string MessageId { get; private set; } = string.Empty;
public int Id { get; private set; }
public int? ClientId { get; private set; }
[DataMember]
public string MessageId { get; private set; } = string.Empty;
[DataMember]
public int? ClientId { get; private set; }
[DataMember]
public string SenderName { get; private set; } = string.Empty;
public bool IsRead { get; private set; } = false;
public string SenderName { get; private set; } = string.Empty;
[DataMember]
public DateTime DateDelivery { get; private set; } = DateTime.Now;
public DateTime DateDelivery { get; private set; } = DateTime.Now;
[DataMember]
public string Subject { get; private set; } = string.Empty;
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 string? Answer { get; private set; } = string.Empty;

View File

@ -6,6 +6,7 @@ using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;
@ -13,24 +14,34 @@ using System.Xml.Linq;
namespace BlacksmithWorkshopFileImplement.Models
{
//класс, реализующий интерфейс модели заказа
[DataContract]
public class Order : IOrderModel
{
[DataMember]
public int Id { get; private set; }
public int ClientId { get; private set; }
[DataMember]
public int ClientId { get; private set; }
public int? ImplementerId { get; private set; }
[DataMember]
public int? ImplementerId { get; private set; }
public int ManufactureId { get; private set; }
[DataMember]
public int ManufactureId { 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 static Order? Create(OrderBindingModel model)

View File

@ -5,6 +5,7 @@ using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;
@ -12,12 +13,16 @@ using System.Xml.Linq;
namespace BlacksmithWorkshopFileImplement.Models
{
//реализация интерфейса модели заготовки
[DataContract]
public class WorkPiece : IWorkPieceModel
{
[DataMember]
public int Id { get; private set; }
[DataMember]
public string WorkPieceName { get; private set; } = string.Empty;
[DataMember]
public double Cost { get; set; }
public static WorkPiece? Create(WorkPieceBindingModel model)

View File

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

View File

@ -0,0 +1,22 @@
using BlacksmithWorkshopContracts.StoragesContracts;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BlacksmithWorkshopListImplement.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,36 @@
using BlacksmithWorkshopContracts.DI;
using BlacksmithWorkshopContracts.StoragesContracts;
using BlacksmithWorkshopListImplement.Implements;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BlacksmithWorkshopListImplement
{
public class ListImplementationExtension : IImplementationExtension
{
public int Priority => 0;
public void RegisterServices()
{
DependencyManager.Instance.RegisterType<IClientStorage, ClientStorage>();
DependencyManager.Instance.RegisterType<IWorkPieceStorage, WorkPieceStorage>();
DependencyManager.Instance.RegisterType<IImplementerStorage, ImplementerStorage>();
DependencyManager.Instance.RegisterType<IMessageInfoStorage, MessageInfoStorage>();
DependencyManager.Instance.RegisterType<IOrderStorage, OrderStorage>();
DependencyManager.Instance.RegisterType<IManufactureStorage, ManufactureStorage>();
DependencyManager.Instance.RegisterType<IShopStorage, ShopStorage>();
DependencyManager.Instance.RegisterType<IBackUpInfo, BackUpInfo>();
}
}
}

View File

@ -12,7 +12,9 @@ namespace BlacksmithWorkshopListImplement.Models
{
public class MessageInfo : IMessageInfoModel
{
public string MessageId { get; private set; } = string.Empty;
public int Id { get; private set; }
public string MessageId { get; private set; } = string.Empty;
public int? ClientId { get; private set; }

BIN
Бэкап.zip Normal file

Binary file not shown.