This commit is contained in:
danilafilippov7299 2024-06-22 09:32:05 +04:00
parent 722792852e
commit a22c8352bf
46 changed files with 1315 additions and 460 deletions

View File

@ -9,6 +9,10 @@
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="7.0.18">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="Microsoft.Extensions.Logging" Version="8.0.0" />
<PackageReference Include="NLog" Version="5.3.2" />
<PackageReference Include="NLog.Extensions.Logging" Version="5.3.11" />

View File

@ -0,0 +1,44 @@
using BarContracts.Attrubites;
namespace BarView
{
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 СolumnAttr)
{
Column.HeaderText = СolumnAttr.Title;
Column.Visible = СolumnAttr.Visible;
if (СolumnAttr.IsUseAutoSize)
{
Column.AutoSizeMode = (DataGridViewAutoSizeColumnMode)Enum.Parse(typeof(DataGridViewAutoSizeColumnMode), СolumnAttr.GridViewAutoSize.ToString());
}
else
{
Column.Width = СolumnAttr.Width;
}
}
}
}
}
}

View File

@ -44,7 +44,7 @@
this.списокКомпонентовToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.компонентыПоИзделиямToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.списокЗаказовToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.запускРаботToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.StartWorkToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.MailToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
((System.ComponentModel.ISupportInitialize)(this.DataGridView)).BeginInit();
this.menuStrip1.SuspendLayout();
@ -116,7 +116,7 @@
this.menuStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.ToolStripMenu,
this.отчётыToolStripMenuItem,
this.запускРаботToolStripMenuItem,
this.StartWorkToolStripMenuItem,
this.MailToolStripMenuItem});
this.menuStrip1.Location = new System.Drawing.Point(0, 0);
this.menuStrip1.Name = "menuStrip1";
@ -138,28 +138,28 @@
// ComponentsStripMenuItem
//
this.ComponentsStripMenuItem.Name = "ComponentsStripMenuItem";
this.ComponentsStripMenuItem.Size = new System.Drawing.Size(224, 26);
this.ComponentsStripMenuItem.Size = new System.Drawing.Size(185, 26);
this.ComponentsStripMenuItem.Text = "Компоненты";
this.ComponentsStripMenuItem.Click += new System.EventHandler(this.ComponentsStripMenuItem_Click);
//
// CocktailStripMenuItem
//
this.CocktailStripMenuItem.Name = "CocktailStripMenuItem";
this.CocktailStripMenuItem.Size = new System.Drawing.Size(224, 26);
this.CocktailStripMenuItem.Size = new System.Drawing.Size(185, 26);
this.CocktailStripMenuItem.Text = "Коктейль";
this.CocktailStripMenuItem.Click += new System.EventHandler(this.CocktailsStripMenuItem_Click);
//
// ClientsToolStripMenuItem
//
this.ClientsToolStripMenuItem.Name = "ClientsToolStripMenuItem";
this.ClientsToolStripMenuItem.Size = new System.Drawing.Size(224, 26);
this.ClientsToolStripMenuItem.Size = new System.Drawing.Size(185, 26);
this.ClientsToolStripMenuItem.Text = "Клиенты";
this.ClientsToolStripMenuItem.Click += new System.EventHandler(this.ClientsToolStripMenuItem_Click);
//
// EmployersToolStripMenuItem
//
this.EmployersToolStripMenuItem.Name = "EmployersToolStripMenuItem";
this.EmployersToolStripMenuItem.Size = new System.Drawing.Size(224, 26);
this.EmployersToolStripMenuItem.Size = new System.Drawing.Size(185, 26);
this.EmployersToolStripMenuItem.Text = "Исполнители";
this.EmployersToolStripMenuItem.Click += new System.EventHandler(this.EmployersToolStripMenuItem_Click);
//
@ -194,12 +194,12 @@
this.списокЗаказовToolStripMenuItem.Text = "Список заказов";
this.списокЗаказовToolStripMenuItem.Click += new System.EventHandler(this.OrdersToolStripMenuItem_Click);
//
// запускРаботToolStripMenuItem
// StartWorkToolStripMenuItem
//
this.запускРаботToolStripMenuItem.Name = "запускРаботToolStripMenuItem";
this.запускРаботToolStripMenuItem.Size = new System.Drawing.Size(114, 24);
this.запускРаботToolStripMenuItem.Text = "Запуск работ";
this.запускРаботToolStripMenuItem.Click += new System.EventHandler(this.запускРаботToolStripMenuItem_Click);
this.StartWorkToolStripMenuItem.Name = "StartWorkToolStripMenuItem";
this.StartWorkToolStripMenuItem.Size = new System.Drawing.Size(114, 24);
this.StartWorkToolStripMenuItem.Text = "Запуск работ";
this.StartWorkToolStripMenuItem.Click += new System.EventHandler(this.запускРаботToolStripMenuItem_Click);
//
// MailToolStripMenuItem
//
@ -248,7 +248,7 @@
private ToolStripMenuItem компонентыПоИзделиямToolStripMenuItem;
private ToolStripMenuItem списокЗаказовToolStripMenuItem;
private ToolStripMenuItem ClientsToolStripMenuItem;
private ToolStripMenuItem запускРаботToolStripMenuItem;
private ToolStripMenuItem StartWorkToolStripMenuItem;
private ToolStripMenuItem EmployersToolStripMenuItem;
private ToolStripMenuItem MailToolStripMenuItem;
}

View File

@ -1,245 +1,267 @@
using BarContracts.BindingModels;
using BarContracts.BusinessLogicContracts;
using BarContracts.BusinessLogicsContracts;
using BarContracts.DI;
using BarView.Forms;
using Microsoft.Extensions.Logging;
namespace BarView
{
public partial class FormMain : Form
{
private readonly ILogger _logger;
private readonly IOrderLogic _orderLogic;
private readonly IReportLogic _reportLogic;
private readonly IWorkProcess _workProcess;
public FormMain(ILogger<FormMain> Logger, IOrderLogic OrderLogic, IReportLogic ReportLogic, IWorkProcess WorkProcess)
{
InitializeComponent();
public partial class FormMain : Form
{
private readonly ILogger _logger;
private readonly IOrderLogic _orderLogic;
private readonly IReportLogic _reportLogic;
private readonly IWorkProcess _workProcess;
private readonly IBackUpLogic _backUpLogic;
_logger = Logger;
_orderLogic = OrderLogic;
_reportLogic = ReportLogic;
_workProcess = WorkProcess;
}
private void FormMain_Load(object sender, EventArgs e)
{
LoadData();
}
public FormMain(ILogger<FormMain> Logger, IOrderLogic OrderLogic, IReportLogic ReportLogic, IWorkProcess WorkProcess, IBackUpLogic backUpLogic)
{
InitializeComponent();
private void LoadData()
{
_logger.LogInformation("Загрузка заказов");
_logger = Logger;
_orderLogic = OrderLogic;
_reportLogic = ReportLogic;
_workProcess = WorkProcess;
_backUpLogic = backUpLogic;
}
try
{
var List = _orderLogic.ReadList(null);
private void FormMain_Load(object sender, EventArgs e)
{
LoadData();
}
if (List != null)
{
DataGridView.DataSource = List;
DataGridView.Columns["CocktailId"].Visible = false;
DataGridView.Columns["ClientEmail"].Visible = false;
DataGridView.Columns["ClientId"].Visible = false;
DataGridView.Columns["ClientEmail"].Visible = false;
DataGridView.Columns["ImplementerId"].Visible = false;
DataGridView.Columns["CocktailName"].Visible = false;
}
private void LoadData()
{
_logger.LogInformation("Загрузка заказов");
_logger.LogInformation("Загрузка заказов");
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка загрузки заказов");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
try
{
DataGridView.FillAndConfigGrid(_orderLogic.ReadList(null));
_logger.LogInformation("Загрузка заказов");
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка загрузки заказов");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void ComponentsStripMenuItem_Click(object sender, EventArgs e)
{
var Service = Program.ServiceProvider?.GetService(typeof(FormComponents));
private void ComponentsStripMenuItem_Click(object sender, EventArgs e)
{
var Service = DependencyManager.Instance.Resolve<FormComponents>();
if (Service is FormComponents Form)
{
Form.ShowDialog();
}
}
if (Service is FormComponents Form)
{
Form.ShowDialog();
}
}
private void CocktailsStripMenuItem_Click(object sender, EventArgs e)
{
var Service = Program.ServiceProvider?.GetService(typeof(FormCocktails));
private void CocktailsStripMenuItem_Click(object sender, EventArgs e)
{
var Service = DependencyManager.Instance.Resolve<FormCocktails>();
if (Service is FormCocktails Form)
{
Form.ShowDialog();
}
}
if (Service is FormCocktails Form)
{
Form.ShowDialog();
}
}
private void CreateOrderButton_Click(object sender, EventArgs e)
{
var Service = Program.ServiceProvider?.GetService(typeof(FormCreateOrder));
private void CreateOrderButton_Click(object sender, EventArgs e)
{
var Service = DependencyManager.Instance.Resolve<FormCreateOrder>();
if (Service is FormCreateOrder Form)
{
Form.ShowDialog();
LoadData();
}
}
if (Service is FormCreateOrder Form)
{
Form.ShowDialog();
LoadData();
}
}
private void TakeOrderInWorkButton_Click(object sender, EventArgs e)
{
if (DataGridView.SelectedRows.Count == 1)
{
int id = Convert.ToInt32(DataGridView.SelectedRows[0].Cells["Id"].Value);
private void TakeOrderInWorkButton_Click(object sender, EventArgs e)
{
if (DataGridView.SelectedRows.Count == 1)
{
int id = Convert.ToInt32(DataGridView.SelectedRows[0].Cells["Id"].Value);
_logger.LogInformation("Заказ №{id}. Меняется статус на 'В работе'", id);
_logger.LogInformation("Заказ №{id}. Меняется статус на 'В работе'", id);
try
{
var OperationResult = _orderLogic.TakeOrderInWork(new OrderBindingModel { Id = id });
try
{
var OperationResult = _orderLogic.TakeOrderInWork(new OrderBindingModel { Id = id });
if (!OperationResult)
{
throw new Exception("Ошибка при сохранении. Дополнительная информация в логах.");
}
if (!OperationResult)
{
throw new Exception("Ошибка при сохранении. Дополнительная информация в логах.");
}
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 OrderReadyButton_Click(object sender, EventArgs e)
{
if (DataGridView.SelectedRows.Count == 1)
{
int id = Convert.ToInt32(DataGridView.SelectedRows[0].Cells["Id"].Value);
private void OrderReadyButton_Click(object sender, EventArgs e)
{
if (DataGridView.SelectedRows.Count == 1)
{
int id = Convert.ToInt32(DataGridView.SelectedRows[0].Cells["Id"].Value);
_logger.LogInformation("Заказ №{id}. Меняется статус на 'Готов'", id);
_logger.LogInformation("Заказ №{id}. Меняется статус на 'Готов'", id);
try
{
var OperationResult = _orderLogic.FinishOrder(new OrderBindingModel { Id = id });
try
{
var OperationResult = _orderLogic.FinishOrder(new OrderBindingModel { Id = id });
if (!OperationResult)
{
throw new Exception("Ошибка при сохранении. Дополнительная информация в логах.");
}
if (!OperationResult)
{
throw new Exception("Ошибка при сохранении. Дополнительная информация в логах.");
}
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 OrderDeliveredButton_Click(object sender, EventArgs e)
{
if (DataGridView.SelectedRows.Count == 1)
{
int id = Convert.ToInt32(DataGridView.SelectedRows[0].Cells["Id"].Value);
private void OrderDeliveredButton_Click(object sender, EventArgs e)
{
if (DataGridView.SelectedRows.Count == 1)
{
int id = Convert.ToInt32(DataGridView.SelectedRows[0].Cells["Id"].Value);
_logger.LogInformation("Заказ №{id}. Меняется статус на 'Выдан'", id);
_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);
LoadData();
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка отметки о выдачи заказа");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
_logger.LogInformation("Заказ №{id} выдан", id);
LoadData();
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка отметки о выдачи заказа");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
private void RefreshButton_Click(object sender, EventArgs e)
{
LoadData();
}
private void ComponentsToolStripMenuItem_Click(object sender, EventArgs e)
{
using var Dialog = new SaveFileDialog { Filter = "docx|*.docx" };
private void RefreshButton_Click(object sender, EventArgs e)
{
LoadData();
}
if (Dialog.ShowDialog() == DialogResult.OK)
{
_reportLogic.SaveComponentsToWordFile(new ReportBindingModel { FileName = Dialog.FileName });
MessageBox.Show("Выполнено", "Успех", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
private void ComponentsToolStripMenuItem_Click(object sender, EventArgs e)
{
using var Dialog = new SaveFileDialog { Filter = "docx|*.docx" };
private void ComponentCocktailToolStripMenuItem_Click(object sender, EventArgs e)
{
var Service = Program.ServiceProvider?.GetService(typeof(FormReportCocktailComponents));
if (Dialog.ShowDialog() == DialogResult.OK)
{
_reportLogic.SaveComponentsToWordFile(new ReportBindingModel { FileName = Dialog.FileName });
MessageBox.Show("Выполнено", "Успех", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
if (Service is FormReportCocktailComponents Form)
{
Form.ShowDialog();
}
}
private void ComponentCocktailToolStripMenuItem_Click(object sender, EventArgs e)
{
var Service = DependencyManager.Instance.Resolve<FormReportCocktailComponents>();
private void OrdersToolStripMenuItem_Click(object sender, EventArgs e)
{
var Service = Program.ServiceProvider?.GetService(typeof(FormReportOrders));
if (Service is FormReportCocktailComponents Form)
{
Form.ShowDialog();
}
}
if (Service is FormReportOrders Form)
{
Form.ShowDialog();
}
}
private void OrdersToolStripMenuItem_Click(object sender, EventArgs e)
{
var Service = DependencyManager.Instance.Resolve<FormReportOrders>();
private void ClientsToolStripMenuItem_Click(object sender, EventArgs e)
{
var Service = Program.ServiceProvider?.GetService(typeof(FormClients));
if (Service is FormReportOrders Form)
{
Form.ShowDialog();
}
}
if (Service is FormClients Form)
{
Form.ShowDialog();
}
}
private void ClientsToolStripMenuItem_Click(object sender, EventArgs e)
{
var Service = DependencyManager.Instance.Resolve<FormClients>();
private void запускРаботToolStripMenuItem_Click(object sender, EventArgs e)
{
var ImplementerLogic = Program.ServiceProvider?.GetService(typeof(IImplementerLogic));
_workProcess.DoWork((ImplementerLogic as IImplementerLogic)!, _orderLogic);
if (Service is FormClients Form)
{
Form.ShowDialog();
}
}
MessageBox.Show("Процесс обработки запущен", "Сообщение", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
private void EmployersToolStripMenuItem_Click(object sender, EventArgs e)
{
var Service = DependencyManager.Instance.Resolve<FormImplementers>();
private void EmployersToolStripMenuItem_Click(object sender, EventArgs e)
{
var Service = Program.ServiceProvider?.GetService(typeof(FormImplementers));
if (Service is FormImplementers Form)
{
Form.ShowDialog();
}
}
if (Service is FormImplementers Form)
{
Form.ShowDialog();
}
}
private void запускРаботToolStripMenuItem_Click(object sender, EventArgs e)
{
var ImplementerLogic = DependencyManager.Instance.Resolve<IImplementerLogic>();
_workProcess.DoWork(ImplementerLogic, _orderLogic);
private void MailToolStripMenuItem_Click(object sender, EventArgs e)
{
var Service = Program.ServiceProvider?.GetService(typeof(FormMail));
MessageBox.Show("Процесс обработки запущен", "Сообщение", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
if (Service is FormMail Form)
{
Form.ShowDialog();
}
}
}
private void MailToolStripMenuItem_Click(object sender, EventArgs e)
{
var Service = DependencyManager.Instance.Resolve<FormMail>();
if (Service is FormMail Form)
{
Form.ShowDialog();
}
}
private void CreateBackupToolStripMenuItem_Click(object sender, EventArgs e)
{
try
{
if (_backUpLogic != null)
{
var FolderBrowser = new FolderBrowserDialog();
if (FolderBrowser.ShowDialog() == DialogResult.OK)
{
_backUpLogic.CreateBackUp(new BackUpSaveBindingModel
{
FolderName = FolderBrowser.SelectedPath
});
MessageBox.Show("Бекап создан", "Сообщение", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка создания бэкапа", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void CreateBackupToolStripMenuItem_Click_1(object sender, EventArgs e)
{
}
}
}

View File

@ -153,7 +153,7 @@
this.DataGridView.RowTemplate.Height = 29;
this.DataGridView.Size = new System.Drawing.Size(391, 213);
this.DataGridView.TabIndex = 13;
this.DataGridView.CellContentClick += new System.Windows.Forms.DataGridViewCellEventHandler(this.DataGridView_CellContentClick);
//this.DataGridView.CellContentClick += new System.Windows.Forms.DataGridViewCellEventHandler(this.DataGridView_CellContentClick);
//
// IdColumn
//

View File

@ -1,5 +1,6 @@
using BarContracts.BindingModels;
using BarContracts.BusinessLogicContracts;
using BarContracts.DI;
using BarContracts.SearchModels;
using BarDataModels.Models;
using Microsoft.Extensions.Logging;
@ -10,27 +11,27 @@ namespace BarView.Forms
{
private readonly ILogger _logger;
private readonly ICocktailLogic _logic;
private readonly ICocktailLogic _logic;
private int? _id;
private Dictionary<int, (IComponentModel, int)> _CocktailComponents;
private Dictionary<int, (IComponentModel, int)> _cocktailComponents;
public int Id { set { _id = value; } }
public FormCocktail(ILogger<FormCocktail> Logger, ICocktailLogic Logic)
public FormCocktail(ILogger<FormCocktail> Logger, ICocktailLogic Logic)
{
InitializeComponent();
_logger = Logger;
_logic = Logic;
_CocktailComponents = new Dictionary<int, (IComponentModel, int)>();
_cocktailComponents = new Dictionary<int, (IComponentModel, int)>();
}
private void FormCocktail_Load(object sender, EventArgs e)
{
if (_id.HasValue)
{
_logger.LogInformation("Загрузка коктеля");
_logger.LogInformation("Загрузка коктейльа");
try
{
@ -44,13 +45,13 @@ namespace BarView.Forms
NameTextBox.Text = View.CocktailName;
PriceTextBox.Text = View.Price.ToString();
_CocktailComponents = View.CocktailComponents ?? new Dictionary<int, (IComponentModel, int)>();
_cocktailComponents = View.CocktailComponents ?? new Dictionary<int, (IComponentModel, int)>();
LoadData();
}
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка загрузки коктеля");
_logger.LogError(ex, "Ошибка загрузки коктейльа");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
@ -58,14 +59,14 @@ namespace BarView.Forms
private void LoadData()
{
_logger.LogInformation("Загрузка компонентов коктеля");
_logger.LogInformation("Загрузка компонентов коктейльа");
try
{
if (_CocktailComponents != null)
if (_cocktailComponents != null)
{
DataGridView.Rows.Clear();
foreach (var Comp in _CocktailComponents)
foreach (var Comp in _cocktailComponents)
{
DataGridView.Rows.Add(new object[] { Comp.Key, Comp.Value.Item1.ComponentName, Comp.Value.Item2 });
}
@ -75,14 +76,14 @@ namespace BarView.Forms
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка загрузки компонентов коктеля");
_logger.LogError(ex, "Ошибка загрузки компонентов коктейльа");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void AddButton_Click(object sender, EventArgs e)
{
var Service = Program.ServiceProvider?.GetService(typeof(FormCocktailComponent));
var Service = DependencyManager.Instance.Resolve<FormCocktailComponent>();
if (Service is FormCocktailComponent Form)
{
@ -95,13 +96,13 @@ namespace BarView.Forms
_logger.LogInformation("Добавление нового компонента: {ComponentName} - {Count}", Form.ComponentModel.ComponentName, Form.Count);
if (_CocktailComponents.ContainsKey(Form.Id))
if (_cocktailComponents.ContainsKey(Form.Id))
{
_CocktailComponents[Form.Id] = (Form.ComponentModel, Form.Count);
_cocktailComponents[Form.Id] = (Form.ComponentModel, Form.Count);
}
else
{
_CocktailComponents.Add(Form.Id, (Form.ComponentModel, Form.Count));
_cocktailComponents.Add(Form.Id, (Form.ComponentModel, Form.Count));
}
LoadData();
@ -113,12 +114,12 @@ namespace BarView.Forms
{
if (DataGridView.SelectedRows.Count == 1)
{
var service = Program.ServiceProvider?.GetService(typeof(FormCocktailComponent));
var service = DependencyManager.Instance.Resolve<FormCocktailComponent>();
if (service is FormCocktailComponent Form)
{
int id = Convert.ToInt32(DataGridView.SelectedRows[0].Cells[0].Value);
Form.Id = id;
Form.Count = _CocktailComponents[id].Item2;
Form.Count = _cocktailComponents[id].Item2;
if (Form.ShowDialog() == DialogResult.OK)
{
@ -128,7 +129,7 @@ namespace BarView.Forms
}
_logger.LogInformation("Изменение компонента: {ComponentName} - {Count}", Form.ComponentModel.ComponentName, Form.Count);
_CocktailComponents[Form.Id] = (Form.ComponentModel, Form.Count);
_cocktailComponents[Form.Id] = (Form.ComponentModel, Form.Count);
LoadData();
}
@ -147,7 +148,7 @@ namespace BarView.Forms
_logger.LogInformation("Удаление компонента: {ComponentName} - {Count}", DataGridView.SelectedRows[0].Cells[1].Value,
DataGridView.SelectedRows[0].Cells[2].Value);
_CocktailComponents?.Remove(Convert.ToInt32(DataGridView.SelectedRows[0].Cells[0].Value));
_cocktailComponents?.Remove(Convert.ToInt32(DataGridView.SelectedRows[0].Cells[0].Value));
}
catch (Exception ex)
{
@ -179,13 +180,13 @@ namespace BarView.Forms
return;
}
if (_CocktailComponents == null || _CocktailComponents.Count == 0)
if (_cocktailComponents == null || _cocktailComponents.Count == 0)
{
MessageBox.Show("Заполните компоненты", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
_logger.LogInformation("Сохранение коктеля");
_logger.LogInformation("Сохранение коктейльа");
try
{
@ -194,7 +195,7 @@ namespace BarView.Forms
Id = _id ?? 0,
CocktailName = NameTextBox.Text,
Price = Convert.ToDouble(PriceTextBox.Text),
CocktailComponents = _CocktailComponents
CocktailComponents = _cocktailComponents
};
var OperationResult = _id.HasValue ? _logic.Update(Мodel) : _logic.Create(Мodel);
@ -210,7 +211,7 @@ namespace BarView.Forms
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка сохранения коктеля");
_logger.LogError(ex, "Ошибка сохранения коктейльа");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
@ -225,17 +226,12 @@ namespace BarView.Forms
{
double Price = 0;
foreach (var Elem in _CocktailComponents)
foreach (var Elem in _cocktailComponents)
{
Price += ((Elem.Value.Item1?.Cost ?? 0) * Elem.Value.Item2);
}
return Math.Round(Price * 1, 2);
}
private void DataGridView_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
return Math.Round(Price * 1.1, 2);
}
}
}

View File

@ -85,7 +85,7 @@
this.DataGridView.RowTemplate.Height = 29;
this.DataGridView.Size = new System.Drawing.Size(542, 385);
this.DataGridView.TabIndex = 5;
this.DataGridView.SelectionChanged += new System.EventHandler(this.DataGridView_SelectionChanged);
//this.DataGridView.SelectionChanged += new System.EventHandler(this.DataGridView_SelectionChanged);
//
// FormCocktails
//

View File

@ -1,10 +1,11 @@
using BarContracts.BindingModels;
using BarContracts.BusinessLogicContracts;
using BarContracts.DI;
using Microsoft.Extensions.Logging;
namespace BarView.Forms
{
public partial class FormCocktails : Form
public partial class FormCocktails : Form
{
private readonly ILogger _logger;
private readonly ICocktailLogic _logic;
@ -26,28 +27,19 @@ namespace BarView.Forms
{
try
{
var List = _logic.ReadList(null);
if (List != null)
{
DataGridView.DataSource = List;
DataGridView.Columns["Id"].Visible = false;
DataGridView.Columns["CocktailName"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
DataGridView.Columns["CocktailComponents"].Visible = false;
}
_logger.LogInformation("Загрузка коктеля");
DataGridView.FillAndConfigGrid(_logic.ReadList(null));
_logger.LogInformation("Загрузка коктейльа");
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка загрузки коктеля");
_logger.LogError(ex, "Ошибка загрузки коктейльа");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void AddButton_Click(object sender, EventArgs e)
{
var Service = Program.ServiceProvider?.GetService(typeof(FormCocktail));
var Service = DependencyManager.Instance.Resolve<FormCocktail>();
if (Service is FormCocktail Form)
{
@ -62,7 +54,7 @@ namespace BarView.Forms
{
if (DataGridView.SelectedRows.Count == 1)
{
var Service = Program.ServiceProvider?.GetService(typeof(FormCocktail));
var Service = DependencyManager.Instance.Resolve<FormCocktail>();
if (Service is FormCocktail Form)
{
@ -84,7 +76,7 @@ namespace BarView.Forms
if (MessageBox.Show("Удалить запись?", "Вопрос", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
{
int id = Convert.ToInt32(DataGridView.SelectedRows[0].Cells["Id"].Value);
_logger.LogInformation("Удаление коктеля");
_logger.LogInformation("Удаление коктейльа");
try
{
if (!_logic.Delete(new CocktailBindingModel
@ -99,7 +91,7 @@ namespace BarView.Forms
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка удаления коктеля");
_logger.LogError(ex, "Ошибка удаления коктейльа");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
@ -110,9 +102,5 @@ namespace BarView.Forms
{
LoadData();
}
private void DataGridView_SelectionChanged(object sender, EventArgs e)
{
}
}
}

View File

@ -1,5 +1,6 @@
using BarContracts.BindingModels;
using BarContracts.BusinessLogicContracts;
using BarContracts.DI;
using Microsoft.Extensions.Logging;
namespace BarView.Forms
@ -25,15 +26,7 @@ namespace BarView.Forms
{
try
{
var List = _logic.ReadList(null);
if (List != null)
{
DataGridView.DataSource = List;
DataGridView.Columns["Id"].Visible = false;
DataGridView.Columns["ComponentName"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
}
DataGridView.FillAndConfigGrid(_logic.ReadList(null));
_logger.LogInformation("Загрузка компонентов");
}
catch (Exception ex)
@ -45,7 +38,7 @@ namespace BarView.Forms
private void AddButton_Click(object sender, EventArgs e)
{
var Service = Program.ServiceProvider?.GetService(typeof(FormComponent));
var Service = DependencyManager.Instance.Resolve<FormComponent>();
if (Service is FormComponent Form)
{
@ -60,7 +53,7 @@ namespace BarView.Forms
{
if (DataGridView.SelectedRows.Count == 1)
{
var Service = Program.ServiceProvider?.GetService(typeof(FormComponent));
var Service = DependencyManager.Instance.Resolve<FormComponent>();
if (Service is FormComponent Form)
{
Form.Id = Convert.ToInt32(DataGridView.SelectedRows[0].Cells["Id"].Value);
@ -108,7 +101,5 @@ namespace BarView.Forms
{
LoadData();
}
}
}

View File

@ -1,5 +1,6 @@
using BarContracts.BindingModels;
using BarContracts.BusinessLogicsContracts;
using BarContracts.DI;
using Microsoft.Extensions.Logging;
namespace BarView.Forms
@ -12,7 +13,7 @@ namespace BarView.Forms
public FormImplementers(ILogger<FormImplementers> Logger, IImplementerLogic ImplementerLogic)
{
InitializeComponent();
_logger = Logger;
_implementerLogic = ImplementerLogic;
}
@ -21,15 +22,7 @@ namespace BarView.Forms
{
try
{
var List = _implementerLogic.ReadList(null);
if (List != null)
{
DataGridView.DataSource = List;
DataGridView.Columns["Id"].Visible = false;
DataGridView.Columns["ImplementerFIO"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
}
DataGridView.FillAndConfigGrid(_implementerLogic.ReadList(null));
_logger.LogInformation("Загрузка исполнителей");
}
catch (Exception ex)
@ -46,8 +39,8 @@ namespace BarView.Forms
private void AddButton_Click(object sender, EventArgs e)
{
var Service = Program.ServiceProvider?.GetService(typeof(FormImplementer));
var Service = DependencyManager.Instance.Resolve<FormImplementer>();
if (Service is FormImplementer Form)
{
if (Form.ShowDialog() == DialogResult.OK)
@ -61,7 +54,7 @@ namespace BarView.Forms
{
if (DataGridView.SelectedRows.Count == 1)
{
var service = Program.ServiceProvider?.GetService(typeof(FormImplementer));
var service = DependencyManager.Instance.Resolve<FormImplementer>();
if (service is FormImplementer Form)
{
Form.Id = Convert.ToInt32(DataGridView.SelectedRows[0].Cells["Id"].Value);
@ -81,7 +74,7 @@ namespace BarView.Forms
{
int Id = Convert.ToInt32(DataGridView.SelectedRows[0].Cells["Id"].Value);
_logger.LogInformation("Удаление исполнителя");
try
{
if (!_implementerLogic.Delete(new ImplementerBindingModel
@ -91,7 +84,7 @@ namespace BarView.Forms
{
throw new Exception("Ошибка при удалении. Дополнительная информация в логах.");
}
LoadData();
}
catch (Exception ex)
@ -102,7 +95,7 @@ namespace BarView.Forms
}
}
}
private void RefreshButton_Click(object sender, EventArgs e)
{
LoadData();

View File

@ -2,101 +2,87 @@ using BarBusinessLogic.BusinessLogics;
using BarBusinessLogic.OfficePackage.Implements;
using BarBusinessLogic.OfficePackage;
using BarContracts.BusinessLogicContracts;
using BarContracts.StoragesContracts;
using BarDatabaseImplement.Implements;
using BarView.Forms;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using NLog.Extensions.Logging;
using BarContracts.BusinessLogicsContracts;
using BarBusinessLogic.MailWorker;
using BarContracts.BindingModels;
using BarContracts.DI;
namespace BarView
{
internal static class Program
{
private static ServiceProvider? _serviceProvider;
public static ServiceProvider? ServiceProvider => _serviceProvider;
internal static class Program
{
[STAThread]
static void Main()
{
ApplicationConfiguration.Initialize();
InitDependency();
[STAThread]
static void Main()
{
ApplicationConfiguration.Initialize();
try
{
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,
SmtpClientHost = System.Configuration.ConfigurationManager.AppSettings["SmtpClientHost"] ?? string.Empty,
SmtpClientPort = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["SmtpClientPort"]),
PopHost = System.Configuration.ConfigurationManager.AppSettings["PopHost"] ?? string.Empty,
PopPort = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["PopPort"])
});
var Services = new ServiceCollection();
ConfigureServices(Services);
var Timer = new System.Threading.Timer(new TimerCallback(MailCheck!), null, 0, 100000);
}
catch (Exception ex)
{
var Logger = DependencyManager.Instance.Resolve<ILogger>();
Logger?.LogError(ex, "Îøèáêà ðàáîòû ñ ïî÷òîé");
}
_serviceProvider = Services.BuildServiceProvider();
Application.Run(DependencyManager.Instance.Resolve<FormMain>());
}
try
{
var MailSender = _serviceProvider.GetService<AbstractMailWorker>();
MailSender?.MailConfig(new MailConfigBindingModel
{
MailLogin = System.Configuration.ConfigurationManager.AppSettings["MailLogin"] ?? string.Empty,
MailPassword = System.Configuration.ConfigurationManager.AppSettings["MailPassword"] ?? string.Empty,
SmtpClientHost = System.Configuration.ConfigurationManager.AppSettings["SmtpClientHost"] ?? string.Empty,
SmtpClientPort = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["SmtpClientPort"]),
PopHost = System.Configuration.ConfigurationManager.AppSettings["PopHost"] ?? string.Empty,
PopPort = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["PopPort"])
});
private static void MailCheck(object obj) => DependencyManager.Instance.Resolve<AbstractMailWorker>()?.CheckMailAsync();
var Timer = new System.Threading.Timer(new TimerCallback(MailCheck!), null, 0, 5000);
}
catch (Exception ex)
{
var Logger = _serviceProvider.GetService<ILogger>();
Logger?.LogError(ex, "Îøèáêà ðàáîòû ñ ïî÷òîé");
}
private static void InitDependency()
{
DependencyManager.InitDependency();
DependencyManager.Instance.AddLogging(Option =>
{
Option.SetMinimumLevel(LogLevel.Information);
Option.AddNLog("nlog.config");
});
Application.Run(_serviceProvider.GetRequiredService<FormMain>());
}
DependencyManager.Instance.RegisterType<IComponentLogic, ComponentLogic>();
DependencyManager.Instance.RegisterType<IOrderLogic, OrderLogic>();
DependencyManager.Instance.RegisterType<ICocktailLogic, CocktailLogic>();
DependencyManager.Instance.RegisterType<IReportLogic, ReportLogic>();
DependencyManager.Instance.RegisterType<IClientLogic, ClientLogic>();
DependencyManager.Instance.RegisterType<IImplementerLogic, ImplementerLogic>();
DependencyManager.Instance.RegisterType<IWorkProcess, WorkModeling>();
DependencyManager.Instance.RegisterType<IMessageInfoLogic, MessageInfoLogic>();
DependencyManager.Instance.RegisterType<IBackUpLogic, BackUpLogic>();
private static void MailCheck(object obj) => ServiceProvider?.GetService<AbstractMailWorker>()?.CheckMailAsync();
DependencyManager.Instance.RegisterType<AbstractSaveToWord, SaveToWord>();
DependencyManager.Instance.RegisterType<AbstractSaveToExcel, SaveToExcel>();
DependencyManager.Instance.RegisterType<AbstractSaveToPdf, SaveToPdf>();
DependencyManager.Instance.RegisterType<AbstractMailWorker, MailKitWorker>(true);
private static void ConfigureServices(ServiceCollection Services)
{
Services.AddLogging(option =>
{
option.SetMinimumLevel(LogLevel.Information);
option.AddNLog("nlog.config");
});
Services.AddTransient<IComponentStorage, ComponentStorage>();
Services.AddTransient<IOrderStorage, OrderStorage>();
Services.AddTransient<ICocktailStorage, CocktailStorage>();
Services.AddTransient<IClientStorage, ClientStorage>();
Services.AddTransient<IImplementerStorage, ImplementerStorage>();
Services.AddTransient<IMessageInfoStorage, MessageInfoStorage>();
Services.AddTransient<IComponentLogic, ComponentLogic>();
Services.AddTransient<IOrderLogic, OrderLogic>();
Services.AddTransient<ICocktailLogic, CocktailLogic>();
Services.AddTransient<IReportLogic, ReportLogic>();
Services.AddTransient<IClientLogic, ClientLogic>();
Services.AddTransient<IImplementerLogic, ImplementerLogic>();
Services.AddTransient<IWorkProcess, WorkModeling>();
Services.AddTransient<IMessageInfoLogic, MessageInfoLogic>();
Services.AddTransient<AbstractSaveToWord, SaveToWord>();
Services.AddTransient<AbstractSaveToExcel, SaveToExcel>();
Services.AddTransient<AbstractSaveToPdf, SaveToPdf>();
Services.AddSingleton<AbstractMailWorker, MailKitWorker>();
Services.AddTransient<FormMain>();
Services.AddTransient<FormComponent>();
Services.AddTransient<FormComponents>();
Services.AddTransient<FormCreateOrder>();
Services.AddTransient<FormCocktail>();
Services.AddTransient<FormCocktailComponent>();
Services.AddTransient<FormCocktails>();
Services.AddTransient<FormReportCocktailComponents>();
Services.AddTransient<FormReportOrders>();
Services.AddTransient<FormClients>();
Services.AddTransient<FormImplementers>();
Services.AddTransient<FormImplementer>();
Services.AddTransient<FormMail>();
}
}
DependencyManager.Instance.RegisterType<FormMain>();
DependencyManager.Instance.RegisterType<FormComponent>();
DependencyManager.Instance.RegisterType<FormComponents>();
DependencyManager.Instance.RegisterType<FormCreateOrder>();
DependencyManager.Instance.RegisterType<FormCocktail>();
DependencyManager.Instance.RegisterType<FormCocktailComponent>();
DependencyManager.Instance.RegisterType<FormCocktails>();
DependencyManager.Instance.RegisterType<FormReportCocktailComponents>();
DependencyManager.Instance.RegisterType<FormReportOrders>();
DependencyManager.Instance.RegisterType<FormClients>();
DependencyManager.Instance.RegisterType<FormImplementers>();
DependencyManager.Instance.RegisterType<FormImplementer>();
DependencyManager.Instance.RegisterType<FormMail>();
}
}
}

120
Bar/Bar/Program.resx Normal file
View File

@ -0,0 +1,120 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
Version 2.0
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.
Example:
... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader>
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
<value>[base64 mime encoded serialized .NET Framework object]</value>
</data>
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment>
</data>
There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" use="required" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
</root>

View File

@ -0,0 +1,100 @@
using BarContracts.BindingModels;
using BarContracts.BusinessLogicContracts;
using BarContracts.StoragesContracts;
using BarDataModels.Models;
using Microsoft.Extensions.Logging;
using System.IO.Compression;
using System.Reflection;
using System.Runtime.Serialization.Json;
namespace BarBusinessLogic.BusinessLogics
{
public class BackUpLogic : IBackUpLogic
{
private readonly ILogger _logger;
private readonly IBackUpInfo _backUpInfo;
public BackUpLogic(ILogger<BackUpLogic> Logger, IBackUpInfo BackUpInfo)
{
_logger = Logger;
_backUpInfo = BackUpInfo;
}
public void CreateBackUp(BackUpSaveBindingModel Model)
{
if (_backUpInfo == null)
return;
try
{
_logger.LogDebug("Clear folder");
var DirInfo = new DirectoryInfo(Model.FolderName);
if (DirInfo.Exists)
{
foreach (var File in DirInfo.GetFiles())
{
File.Delete();
}
}
_logger.LogDebug("Delete archive");
string FileName = $"{Model.FolderName}.zip";
if (File.Exists(FileName))
{
File.Delete(FileName);
}
_logger.LogDebug("Get assembly");
var TypeIId = typeof(IId);
var Assembly = TypeIId.Assembly;
if (Assembly == null)
{
throw new ArgumentNullException("Сборка не найдена", nameof(Assembly));
}
var Types = Assembly.GetTypes();
var Method = GetType().GetMethod("SaveToFile", BindingFlags.NonPublic | BindingFlags.Instance);
_logger.LogDebug("Found {count} types", Types.Length);
foreach (var Type in Types)
{
if (Type.IsInterface && Type.GetInterface(TypeIId.Name) != null)
{
var ModelType = _backUpInfo.GetTypeByModelInterface(Type.Name);
if (ModelType == null)
{
throw new InvalidOperationException($"Не найден класс - модель для { Type.Name }");
}
_logger.LogDebug("Call SaveToFile method for {name} Type", Type.Name);
Method?.MakeGenericMethod(ModelType).Invoke(this, new object[] { Model.FolderName });
}
}
_logger.LogDebug("Create zip and remove folder");
ZipFile.CreateFromDirectory(Model.FolderName, FileName);
DirInfo.Delete(true);
}
catch (Exception)
{
throw;
}
}
private void SaveToFile<T>(string FolderName) where T : class, new()
{
var Records = _backUpInfo.GetList<T>();
if (Records == null)
{
_logger.LogWarning("{type} type get null list", typeof(T).Name);
return;
}
var JsonFormatter = new DataContractJsonSerializer(typeof(List<T>));
using var fs = new FileStream(string.Format("{0}/{1}.json", FolderName, typeof(T).Name), FileMode.OpenOrCreate);
JsonFormatter.WriteObject(fs, Records);
}
}
}

View File

@ -112,7 +112,7 @@ namespace BarBusinessLogic.BusinessLogics
{
MailAddress = Order.ClientEmail,
Subject = $"Изменение статуса заказа номер {Order.Id}",
Text = $"Ваш заказ номер {Order.Id} на ремонт {Order.CocktailName} от {Order.DateCreate} на сумму {Order.Sum}. Статус изменен на {NewStatus}. {DateInfo}"
Text = $"Ваш заказ номер {Order.Id} на коктейль {Order.CocktailName} от {Order.DateCreate} на сумму {Order.Sum}. Статус изменен на {NewStatus}. {DateInfo}"
}));
return true;
@ -145,7 +145,7 @@ namespace BarBusinessLogic.BusinessLogics
return;
if (Model.Count <= 0)
throw new ArgumentNullException("Количество ремонтов в заказе быть больше 0", nameof(Model.Count));
throw new ArgumentNullException("Количество коктейльов в заказе быть больше 0", nameof(Model.Count));
if (Model.Sum <= 0)
throw new ArgumentNullException("Стоимость заказа должна быть больше 0", nameof(Model.Sum));

View File

@ -7,7 +7,7 @@
</div>
<form method="post">
<div class="row">
<div class="col-4">Ремонт:</div>
<div class="col-4">Коктейль:</div>
<div class="col-8">
<select id="cocktail" name="cocktail" class="form-control" asp-items="@(new SelectList(@ViewBag.Cocktails,"Id", "CocktailName"))"></select>
</div>

View File

@ -23,7 +23,7 @@
Номер
</th>
<th>
Ремонт
Коктейль
</th>
<th>
Дата создания

View File

@ -13,7 +13,7 @@
<header>
<nav class="navbar navbar-expand-sm navbar-toggleable-sm navbar-light bgwhite border-bottom box-shadow mb-3">
<div class="container">
<a class="navbar-brand" asp-area="" asp-controller="Home" aspaction="Index">Магазин ремонтов</a>
<a class="navbar-brand" asp-area="" asp-controller="Home" aspaction="Index">Магазин коктейльов</a>
<button class="navbar-toggler" type="button" datatoggle="collapse" data-target=".navbar-collapse" ariacontrols="navbarSupportedContent"
aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
@ -47,7 +47,7 @@
</div>
<footer class="border-top footer text-muted">
<div class="container">
&copy; 2024 - Магазин ремонтов - <a asp-area="" aspcontroller="Home" asp-action="Privacy">Личные данные</a>
&copy; 2024 - Магазин коктейльов - <a asp-area="" aspcontroller="Home" asp-action="Privacy">Личные данные</a>
</div>
</footer>
<script src="~/js/site.js" asp-append-version="true"></script>

View File

@ -0,0 +1,26 @@
namespace BarContracts.Attrubites
{
[AttributeUsage(AttributeTargets.Property)]
public class ColumnAttribute : Attribute
{
public ColumnAttribute(string Title = "", bool Visible = true, int Width = 0,
GridViewAutoSize GridViewAutoSize = GridViewAutoSize.None, bool IsUseAutoSize = false)
{
this.Title = Title;
this.Visible = Visible;
this.Width = Width;
this.GridViewAutoSize = GridViewAutoSize;
this.IsUseAutoSize = IsUseAutoSize;
}
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; }
}
}

View File

@ -0,0 +1,14 @@
namespace BarContracts.Attrubites
{
public enum GridViewAutoSize
{
NotSet = 0,
None = 1,
ColumnHeader = 2,
AllCellsExceptHeader = 4,
AllCells = 6,
DisplayedCellsExceptHeader = 8,
DisplayedCells = 10,
Fill = 16
}
}

View File

@ -6,6 +6,13 @@
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging" Version="8.0.0" />
<PackageReference Include="Unity" Version="5.11.10" />
<PackageReference Include="Unity.Microsoft.Logging" Version="5.11.1" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\..\BarDataModels\BarDataModels\BarDataModels.csproj" />
</ItemGroup>

View File

@ -0,0 +1,7 @@
namespace BarContracts.BindingModels
{
public class BackUpSaveBindingModel
{
public string FolderName { get; set; } = string.Empty;
}
}

View File

@ -0,0 +1,9 @@
using BarContracts.BindingModels;
namespace BarContracts.BusinessLogicContracts
{
public interface IBackUpLogic
{
void CreateBackUp(BackUpSaveBindingModel Model);
}
}

View File

@ -0,0 +1,48 @@
using Microsoft.Extensions.Logging;
namespace BarContracts.DI
{
public class DependencyManager
{
private readonly IDependencyContainer _dependencyContainer;
private static DependencyManager? _manager;
private static readonly object _lock = new();
private DependencyManager()
{
_dependencyContainer = new ServiceDependencyContainer();
}
public static DependencyManager Instance
{
get
{
if (_manager == null)
{
lock (_lock) { _manager = new DependencyManager(); }
}
return _manager;
}
}
public static void InitDependency()
{
var Ext = ServiceProviderLoader.GetImplementationExtension();
if (Ext == null)
{
throw new ArgumentNullException("Отсутствуют компоненты для загрузки зависимостей по модулям");
}
Ext.RegisterServices();
}
public void AddLogging(Action<ILoggingBuilder> Configure) => _dependencyContainer.AddLogging(Configure);
public void RegisterType<T, U>(bool IsSingleton = false) where U : class, T where T : class => _dependencyContainer.RegisterType<T, U>(IsSingleton);
public void RegisterType<T>(bool IsSingleton = false) where T : class => _dependencyContainer.RegisterType<T>(IsSingleton);
public T Resolve<T>() => _dependencyContainer.Resolve<T>();
}
}

View File

@ -0,0 +1,15 @@
using Microsoft.Extensions.Logging;
namespace BarContracts.DI
{
public interface IDependencyContainer
{
void AddLogging(Action<ILoggingBuilder> Configure);
void RegisterType<T, U>(bool IsSingleton) where U : class, T where T : class;
void RegisterType<T>(bool IsSingleton) where T : class;
T Resolve<T>();
}
}

View File

@ -0,0 +1,9 @@
namespace BarContracts.DI
{
public interface IImplementationExtension
{
public int Priority { get; }
public void RegisterServices();
}
}

View File

@ -0,0 +1,59 @@
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
namespace BarContracts.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 IsSingleton) where U : class, T where T : class
{
if (IsSingleton)
{
_serviceCollection.AddSingleton<T, U>();
}
else
{
_serviceCollection.AddTransient<T, U>();
}
_serviceProvider = null;
}
public void RegisterType<T>(bool IsSingleton) where T : class
{
if (IsSingleton)
{
_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,50 @@
using System.Reflection;
namespace BarContracts.DI
{
public static class ServiceProviderLoader
{
public static IImplementationExtension? GetImplementationExtension()
{
IImplementationExtension? Source = null;
var Files = Directory.GetFiles(TryGetImplementationExtensionsFolder(), "*.dll", SearchOption.AllDirectories);
foreach (var File in Files.Distinct())
{
Assembly Asm = Assembly.LoadFrom(File);
foreach (var Type in Asm.GetExportedTypes())
{
if (Type.IsClass && typeof(IImplementationExtension).IsAssignableFrom(Type))
{
if (Source == null)
{
Source = (IImplementationExtension)Activator.CreateInstance(Type)!;
}
else
{
var NewSource = (IImplementationExtension)Activator.CreateInstance(Type)!;
if (NewSource.Priority > Source.Priority)
{
Source = NewSource;
}
}
}
}
}
return Source;
}
private static string TryGetImplementationExtensionsFolder()
{
var WorkingDirectory = new DirectoryInfo(Directory.GetCurrentDirectory());
while (WorkingDirectory != null && !WorkingDirectory.GetDirectories("ImplementationExtensions", SearchOption.AllDirectories).Any(x => x.Name == "ImplementationExtensions"))
{
WorkingDirectory = WorkingDirectory.Parent;
}
return $"{WorkingDirectory?.FullName}\\ImplementationExtensions";
}
}
}

View File

@ -0,0 +1,38 @@
using Microsoft.Extensions.Logging;
using Unity;
using Unity.Microsoft.Logging;
namespace BarContracts.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 IsSingleton) where T : class
{
_container.RegisterType<T>(IsSingleton ? TypeLifetime.Singleton : TypeLifetime.Transient);
}
public T Resolve<T>()
{
return _container.Resolve<T>();
}
void IDependencyContainer.RegisterType<T, U>(bool IsSingleton)
{
_container.RegisterType<T, U>(IsSingleton ? TypeLifetime.Singleton : TypeLifetime.Transient);
}
}
}

View File

@ -0,0 +1,9 @@
namespace BarContracts.StoragesContracts
{
public interface IBackUpInfo
{
List<T>? GetList<T>() where T : class, new();
Type? GetTypeByModelInterface(string ModelInterfaceName);
}
}

View File

@ -1,19 +1,20 @@
using BarDataModels.Models;
using System.ComponentModel;
using BarContracts.Attrubites;
using BarDataModels.Models;
namespace BarContracts.ViewModels
{
public class ClientViewModel : IClientModel
public class ClientViewModel : IClientModel
{
public int Id { get; set; }
[Column(Visible: false)]
public int Id { get; set; }
[Column(Title: "ФИО клиента", Width: 150)]
public string ClientFIO { get; set; } = string.Empty;
[DisplayName("ФИО клиента")]
public string ClientFIO { get; set; } = string.Empty;
[DisplayName("Логин (эл. почта)")]
public string Email { get; set; } = string.Empty;
[DisplayName("Пароль")]
public string Password { get; set; } = string.Empty;
[Column(Title: "Логин (эл. почта)", GridViewAutoSize: GridViewAutoSize.Fill, IsUseAutoSize: true)]
public string Email { get; set; } = string.Empty;
[Column(Title: "Пароль", Width: 150)]
public string Password { get; set; } = string.Empty;
}
}

View File

@ -1,22 +1,20 @@
using BarDataModels.Models;
using System.ComponentModel;
using BarContracts.Attrubites;
using BarDataModels.Models;
namespace BarContracts.ViewModels
{
public class CocktailViewModel : ICocktailModel
public class CocktailViewModel : ICocktailModel
{
public int Id { get; set; }
[Column(Visible: false)]
public int Id { get; set; }
[DisplayName("Название Коктейльа")]
public string CocktailName { get; set; } = string.Empty;
[Column(Title: "Название коктейльа", GridViewAutoSize: GridViewAutoSize.Fill, IsUseAutoSize: true)]
public string CocktailName { get; set; } = string.Empty;
[DisplayName("Цена")]
public double Price { get; set; }
public Dictionary<int, (IComponentModel, int)> CocktailComponents
{
get;
set;
} = new();
[Column(Title: "Цена", Width: 70)]
public double Price { get; set; }
[Column(Visible: false)]
public Dictionary<int, (IComponentModel, int)> CocktailComponents { get; set; } = new();
}
}

View File

@ -1,16 +1,17 @@
using BarDataModels.Models;
using System.ComponentModel;
using BarContracts.Attrubites;
using BarDataModels.Models;
namespace BarContracts.ViewModels
{
public class ComponentViewModel : IComponentModel
public class ComponentViewModel : IComponentModel
{
public int Id { get; set; }
[Column(Visible: false)]
public int Id { get; set; }
[DisplayName("Название компонента")]
public string ComponentName { get; set; } = string.Empty;
[DisplayName("Цена")]
public double Cost { get; set; }
[Column(Title: "Название компонента", GridViewAutoSize: GridViewAutoSize.Fill, IsUseAutoSize: true)]
public string ComponentName { get; set; } = string.Empty;
[Column(Title: "Цена", Width: 150)]
public double Cost { get; set; }
}
}

View File

@ -1,22 +1,23 @@
using BarDataModels.Models;
using System.ComponentModel;
using BarContracts.Attrubites;
using BarDataModels.Models;
namespace BarContracts.ViewModels
{
public class ImplementerViewModel : IImplementerModel
public class ImplementerViewModel : IImplementerModel
{
public int Id { get; set; }
[Column(Visible: false)]
public int Id { get; set; }
[DisplayName("ФИО исполнителя")]
public string ImplementerFIO { get; set; } = string.Empty;
[Column(Title: "ФИО исполнителя", GridViewAutoSize: GridViewAutoSize.AllCells, IsUseAutoSize: true)]
public string ImplementerFIO { get; set; } = string.Empty;
[DisplayName("Пароль")]
public string Password { get; set; } = string.Empty;
[Column(Title: "Пароль", Width: 100)]
public string Password { get; set; } = string.Empty;
[DisplayName("Стаж работы")]
public int WorkExperience { get; set; }
[Column(Title: "Стаж работы", GridViewAutoSize: GridViewAutoSize.Fill, IsUseAutoSize: true)]
public int WorkExperience { get; set; }
[DisplayName("Квалификация")]
public int Qualification { get; set; }
[Column(Title: "Квалификация", GridViewAutoSize: GridViewAutoSize.Fill, IsUseAutoSize: true)]
public int Qualification { get; set; }
}
}

View File

@ -1,24 +1,29 @@
using BarDataModels.Models;
using System.ComponentModel;
using BarContracts.Attrubites;
using BarDataModels.Models;
namespace BarContracts.ViewModels
{
public class MessageInfoViewModel : IMessageInfoModel
public class MessageInfoViewModel : IMessageInfoModel
{
public string MessageId { get; set; } = string.Empty;
[Column(Visible: false)]
public int Id { get; set; }
public int? ClientId { get; set; }
[Column(Visible: false)]
public string MessageId { get; set; } = string.Empty;
[DisplayName("Отправитель")]
public string SenderName { get; set; } = string.Empty;
[Column(Visible: false)]
public int? ClientId { get; set; }
[DisplayName("Дата доставки")]
public DateTime DateDelivery { get; set; }
[Column(Title: "Отправитель", Width: 150)]
public string SenderName { get; set; } = string.Empty;
[DisplayName("Тема")]
public string Subject { get; set; } = string.Empty;
[Column(Title: "Дата доставки", Width: 120)]
public DateTime DateDelivery { get; set; }
[DisplayName("Содержание")]
public string Body { get; set; } = string.Empty;
[Column(Title: "Тема", Width: 120)]
public string Subject { get; set; } = string.Empty;
[Column(Title: "Содержание", GridViewAutoSize: GridViewAutoSize.Fill, IsUseAutoSize: true)]
public string Body { get; set; } = string.Empty;
}
}

View File

@ -1,45 +1,48 @@
using BarDataModels.Enums;
using BarContracts.Attrubites;
using BarDataModels.Enums;
using BarDataModels.Models;
using System.ComponentModel;
namespace BarContracts.ViewModels
{
public class OrderViewModel : IOrderModel
public class OrderViewModel : IOrderModel
{
[DisplayName("Номер")]
public int Id { get; set; }
[Column(Title: "Номер", GridViewAutoSize: GridViewAutoSize.AllCells, IsUseAutoSize: true)]
public int Id { get; set; }
public int CocktailId { get; set; }
[Column(Visible: false)]
public int CocktailId { get; set; }
[DisplayName("Ремонт")]
public string CocktailName { get; set; } = string.Empty;
[Column(Title: "Коктейль", GridViewAutoSize: GridViewAutoSize.AllCells, IsUseAutoSize: true)]
public string CocktailName { get; set; } = string.Empty;
public int ClientId { get; set; }
[Column(Visible: false)]
public int ClientId { get; set; }
[DisplayName("Клиент")]
public string ClientFIO { get; set; } = string.Empty;
[Column(Title: "Клиент", Width: 120)]
public string ClientFIO { get; set; } = string.Empty;
[DisplayName("Почта клиента")]
public string ClientEmail { get; set; } = string.Empty;
[Column(Title: "Почта клиента", Width: 190)]
public string ClientEmail { get; set; } = string.Empty;
public int? ImplementerId { get; set; }
[Column(Visible: false)]
public int? ImplementerId { get; set; }
[DisplayName("Исполнитель")]
public string? ImplementerFIO { get; set; }
[Column(Title: "Исполнитель", Width: 120)]
public string? ImplementerFIO { get; set; }
[DisplayName("Количество")]
public int Count { get; set; }
[Column(Title: "Количество", Width: 100)]
public int Count { get; set; }
[DisplayName("Сумма")]
public double Sum { get; set; }
[Column(Title: "Сумма", Width: 75)]
public double Sum { get; set; }
[DisplayName("Статус")]
public OrderStatus Status { get; set; } = OrderStatus.Undefined;
[Column(Title: "Статус", Width: 70)]
public OrderStatus Status { get; set; } = OrderStatus.Undefined;
[DisplayName("Дата создания")]
public DateTime DateCreate { get; set; } = DateTime.Now;
[Column(Title: "Дата создания", Width: 120)]
public DateTime DateCreate { get; set; } = DateTime.Now;
[DisplayName("Дата выполнения")]
public DateTime? DateImplement { get; set; }
[Column(Title: "Дата выполнения", Width: 120)]
public DateTime? DateImplement { get; set; }
}
}

View File

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

View File

@ -11,14 +11,21 @@ namespace BarListImplement
public List<Order> Orders { get; set; }
public List<Cocktail> Cocktails { get; set; }
public List<Client> Clients { get; set; }
public List<Implementer> Implementers { get; set; }
public List<MessageInfo> Messages { get; set; }
private DataListSingleton()
{
Components = new List<Component>();
Orders = new List<Order>();
Cocktails = new List<Cocktail>();
Clients = new List<Client>();
Implementers = new List<Implementer>();
Messages = new List<MessageInfo>();
}
public static DataListSingleton GetInstance()

View File

@ -0,0 +1,22 @@
using BarContracts.DI;
using BarContracts.StoragesContracts;
using BarListImplement.Implements;
namespace BarListImplement
{
public class ImplementationExtension : IImplementationExtension
{
public int Priority => 0;
public void RegisterServices()
{
DependencyManager.Instance.RegisterType<IClientStorage, ClientStorage>();
DependencyManager.Instance.RegisterType<IComponentStorage, ComponentStorage>();
DependencyManager.Instance.RegisterType<IImplementerStorage, ImplementerStorage>();
DependencyManager.Instance.RegisterType<IMessageInfoStorage, MessageInfoStorage>();
DependencyManager.Instance.RegisterType<IOrderStorage, OrderStorage>();
DependencyManager.Instance.RegisterType<ICocktailStorage, CocktailStorage>();
DependencyManager.Instance.RegisterType<IBackUpInfo, BackUpInfo>();
}
}
}

View File

@ -0,0 +1,17 @@
using BarContracts.StoragesContracts;
namespace BarListImplement.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,104 @@
using BarContracts.BindingModels;
using BarContracts.SearchModels;
using BarContracts.StoragesContracts;
using BarContracts.ViewModels;
using BarListImplement.Models;
namespace BarListImplement.Implements
{
public class ImplementerStorage : IImplementerStorage
{
private readonly DataListSingleton _source;
public ImplementerStorage()
{
_source = DataListSingleton.GetInstance();
}
public List<ImplementerViewModel> GetFullList()
{
var Result = new List<ImplementerViewModel>();
foreach (var Implementer in _source.Implementers)
{
Result.Add(Implementer.GetViewModel);
}
return Result;
}
public List<ImplementerViewModel> GetFilteredList(ImplementerSearchModel Model)
{
if (string.IsNullOrEmpty(Model.ImplementerFIO))
return new();
return _source.Implementers
.Where(x => (!string.IsNullOrEmpty(Model.ImplementerFIO) && x.ImplementerFIO.Contains(Model.ImplementerFIO)))
.Select(x => x.GetViewModel)
.ToList();
}
public ImplementerViewModel? GetElement(ImplementerSearchModel Model)
{
foreach (var Implementer in _source.Implementers)
{
if ((Model.Id.HasValue && Implementer.Id == Model.Id) ||
(!string.IsNullOrEmpty(Model.ImplementerFIO) && Implementer.ImplementerFIO == Model.ImplementerFIO))
{
return Implementer.GetViewModel;
}
}
return null;
}
public ImplementerViewModel? Insert(ImplementerBindingModel Model)
{
Model.Id = 1;
foreach (var Implementer in _source.Implementers)
{
if (Model.Id <= Implementer.Id)
{
Model.Id = Implementer.Id + 1;
}
}
var NewImplementer = Implementer.Create(Model);
if (NewImplementer == null)
return null;
_source.Implementers.Add(NewImplementer);
return NewImplementer.GetViewModel;
}
public ImplementerViewModel? Update(ImplementerBindingModel Model)
{
foreach (var Implementer in _source.Implementers)
{
if (Implementer.Id == Model.Id)
{
Implementer.Update(Model);
return Implementer.GetViewModel;
}
}
return null;
}
public ImplementerViewModel? Delete(ImplementerBindingModel Model)
{
for (int i = 0; i < _source.Implementers.Count; ++i)
{
if (_source.Implementers[i].Id == Model.Id)
{
var Implementer = _source.Implementers[i];
_source.Implementers.RemoveAt(i);
return Implementer.GetViewModel;
}
}
return null;
}
}
}

View File

@ -0,0 +1,54 @@
using BarContracts.BindingModels;
using BarContracts.SearchModels;
using BarContracts.StoragesContracts;
using BarContracts.ViewModels;
using BarListImplement.Models;
namespace BarListImplement.Implements
{
public class MessageInfoStorage : IMessageInfoStorage
{
private readonly DataListSingleton _source;
public MessageInfoStorage()
{
_source = DataListSingleton.GetInstance();
}
public List<MessageInfoViewModel> GetFullList()
{
return _source.Messages
.Select(x => x.GetViewModel)
.ToList();
}
public List<MessageInfoViewModel> GetFilteredList(MessageInfoSearchModel Model)
{
return _source.Messages
.Where(x => x.ClientId.HasValue && x.ClientId == Model.ClientId)
.Select(x => x.GetViewModel)
.ToList();
}
public MessageInfoViewModel? GetElement(MessageInfoSearchModel Model)
{
if (string.IsNullOrEmpty(Model.MessageId))
return null;
return _source.Messages
.FirstOrDefault(x => x.MessageId == Model.MessageId)?
.GetViewModel;
}
public MessageInfoViewModel? Insert(MessageInfoBindingModel Model)
{
var NewMessageInfo = MessageInfo.Create(Model);
if (NewMessageInfo == null)
return null;
_source.Messages.Add(NewMessageInfo);
return NewMessageInfo.GetViewModel;
}
}
}

View File

@ -0,0 +1,54 @@
using BarContracts.BindingModels;
using BarContracts.ViewModels;
using BarDataModels.Models;
namespace BarListImplement.Models
{
public class Implementer : IImplementerModel
{
public int Id { get; private set; }
public string ImplementerFIO { get; private set; } = string.Empty;
public string Password { get; private set; } = string.Empty;
public int WorkExperience { get; private set; }
public int Qualification { get; private set; }
public static Implementer? Create(ImplementerBindingModel Model)
{
if (Model == null)
{
return null;
}
return new()
{
Id = Model.Id,
Password = Model.Password,
Qualification = Model.Qualification,
ImplementerFIO = Model.ImplementerFIO,
WorkExperience = Model.WorkExperience,
};
}
public void Update(ImplementerBindingModel Model)
{
if (Model == null)
return;
Password = Model.Password;
Qualification = Model.Qualification;
ImplementerFIO = Model.ImplementerFIO;
WorkExperience = Model.WorkExperience;
}
public ImplementerViewModel GetViewModel => new()
{
Id = Id,
Password = Password,
Qualification = Qualification,
ImplementerFIO = ImplementerFIO,
};
}
}

View File

@ -0,0 +1,49 @@
using BarContracts.BindingModels;
using BarContracts.ViewModels;
using BarDataModels.Models;
namespace BarListImplement.Models
{
public class MessageInfo : IMessageInfoModel
{
public int Id { get; set; }
public string MessageId { get; set; } = string.Empty;
public int? ClientId { get; set; }
public string SenderName { get; set; } = string.Empty;
public DateTime DateDelivery { get; set; }
public string Subject { get; set; } = string.Empty;
public string Body { get; set; } = string.Empty;
public static MessageInfo? Create(MessageInfoBindingModel? Model)
{
if (Model == null)
return null;
return new()
{
MessageId = Model.MessageId,
ClientId = Model.ClientId,
SenderName = Model.SenderName,
DateDelivery = Model.DateDelivery,
Subject = Model.Subject,
Body = Model.Body
};
}
public MessageInfoViewModel GetViewModel => new()
{
MessageId = MessageId,
ClientId = ClientId,
SenderName = SenderName,
DateDelivery = DateDelivery,
Subject = Subject,
Body = Body
};
}
}

Binary file not shown.

Binary file not shown.

Binary file not shown.