implement CreateBackup in MainForm

This commit is contained in:
ShabOl 2024-06-21 01:06:04 +04:00
parent 69e0aa3313
commit 1adb6bb874
12 changed files with 243 additions and 236 deletions

View File

@ -20,7 +20,7 @@ namespace AutoWorkshopBusinessLogic.BusinessLogics
_backUpInfo = BackUpInfo;
}
public void CreateBackUp(BackUpSaveBinidngModel Model)
public void CreateBackUp(BackUpSaveBindingModel Model)
{
if (_backUpInfo == null)
return;
@ -28,9 +28,7 @@ namespace AutoWorkshopBusinessLogic.BusinessLogics
try
{
_logger.LogDebug("Clear folder");
var DirInfo = new DirectoryInfo(Model.FolderName);
if (DirInfo.Exists)
{
foreach (var File in DirInfo.GetFiles())
@ -40,17 +38,15 @@ namespace AutoWorkshopBusinessLogic.BusinessLogics
}
_logger.LogDebug("Delete archive");
string FileName = $"{Model.FolderName}.zip";
if (File.Exists(FileName))
File.Delete(FileName);
{
File.Delete(FileName);
}
_logger.LogDebug("Get assembly");
var TypeIId = typeof(IId);
var Assembly = TypeIId.Assembly;
if (Assembly == null)
{
throw new ArgumentNullException("Сборка не найдена", nameof(Assembly));
@ -66,7 +62,6 @@ namespace AutoWorkshopBusinessLogic.BusinessLogics
if (Type.IsInterface && Type.GetInterface(TypeIId.Name) != null)
{
var ModelType = _backUpInfo.GetTypeByModelInterface(Type.Name);
if (ModelType == null)
{
throw new InvalidOperationException($"Не найден класс - модель для { Type.Name }");

View File

@ -1,6 +1,6 @@
namespace AutoWorkshopContracts.BindingModels
{
public class BackUpSaveBinidngModel
public class BackUpSaveBindingModel
{
public string FolderName { get; set; } = string.Empty;
}

View File

@ -4,6 +4,6 @@ namespace AutoWorkshopContracts.BusinessLogicContracts
{
public interface IBackUpLogic
{
void CreateBackUp(BackUpSaveBinidngModel model);
void CreateBackUp(BackUpSaveBindingModel Model);
}
}

View File

@ -4,32 +4,12 @@ namespace AutoWorkshopContracts.DI
{
public interface IDependencyContainer
{
/// <summary>
/// Регистрация логгера
/// </summary>
/// <param name="Configure"></param>
void AddLogging(Action<ILoggingBuilder> Configure);
/// <summary>
/// Добавление зависимости
/// </summary>
/// <typeparam name="T"></typeparam>
/// <typeparam name="U"></typeparam>
/// <param name="IsSingle"></param>
void RegisterType<T, U>(bool IsSingle) where U : class, T where T : class;
void RegisterType<T, U>(bool IsSingleton) where U : class, T where T : class;
/// <summary>
/// Добавление зависимости
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="IsSingle"></param>
void RegisterType<T>(bool IsSingle) where T : class;
void RegisterType<T>(bool IsSingleton) where T : class;
/// <summary>
/// Получение класса со всеми зависмостями
/// </summary>
/// <typeparam name="T"></typeparam>
/// <returns></returns>
T Resolve<T>();
}
}

View File

@ -6,7 +6,6 @@ namespace AutoWorkshopContracts.DI
public class ServiceDependencyContainer : IDependencyContainer
{
private ServiceProvider? _serviceProvider;
private readonly ServiceCollection _serviceCollection;
public ServiceDependencyContainer()
@ -19,9 +18,9 @@ namespace AutoWorkshopContracts.DI
_serviceCollection.AddLogging(Configure);
}
public void RegisterType<T, U>(bool IsSingle) where U : class, T where T : class
public void RegisterType<T, U>(bool IsSingleton) where U : class, T where T : class
{
if (IsSingle)
if (IsSingleton)
{
_serviceCollection.AddSingleton<T, U>();
}
@ -33,9 +32,9 @@ namespace AutoWorkshopContracts.DI
_serviceProvider = null;
}
public void RegisterType<T>(bool IsSingle) where T : class
public void RegisterType<T>(bool IsSingleton) where T : class
{
if (IsSingle)
if (IsSingleton)
{
_serviceCollection.AddSingleton<T>();
}

View File

@ -4,6 +4,6 @@
{
List<T>? GetList<T>() where T : class, new();
Type? GetTypeByModelInterface(string modelInterfaceName);
Type? GetTypeByModelInterface(string ModelInterfaceName);
}
}

View File

@ -6,11 +6,8 @@ namespace AutoWorkshopDatabaseImplement.Implements
{
public List<T>? GetList<T>() where T : class, new()
{
using var Context = new AutoWorkshopDatabase();
return Context
.Set<T>()
.ToList();
using var Context = new AutoWorkshopDatabase();
return Context.Set<T>().ToList();
}
public Type? GetTypeByModelInterface(string ModelInterfaceName)

View File

@ -2,6 +2,7 @@
using AutoWorkshopContracts.ViewModels;
using AutoWorkshopDataModels.Models;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Runtime.Serialization;
namespace AutoWorkshopDatabaseImplement.Models
@ -9,7 +10,7 @@ namespace AutoWorkshopDatabaseImplement.Models
[DataContract]
public class MessageInfo : IMessageInfoModel
{
[DataMember]
[NotMapped]
public int Id { get; set; }
[DataMember]

View File

@ -16,10 +16,10 @@ namespace AutoWorkshopFileImplement.Implements
public List<T>? GetList<T>() where T : class, new()
{
var RequredType = typeof(T);
var RequiredType = typeof(T);
return (List<T>?)_sourceProperties
.FirstOrDefault(x => x.PropertyType.IsGenericType && x.PropertyType.GetGenericArguments()[0] == RequredType)
.FirstOrDefault(x => x.PropertyType.IsGenericType && x.PropertyType.GetGenericArguments()[0] == RequiredType)
?.GetValue(_source);
}

View File

@ -16,11 +16,11 @@ namespace AutoWorkshopView
foreach (DataGridViewColumn Column in Grid.Columns)
{
var Property = Properties.FirstOrDefault(x => x.Name == Column.Name);
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();
var Attribute = Property.GetCustomAttributes(typeof(ColumnAttribute), true)?.SingleOrDefault();
if (Attribute == null)
throw new InvalidOperationException($"Не найден атрибут типа ColumnAttribute для свойства {Property.Name}");

View File

@ -44,6 +44,7 @@
CreateOrderButton = new Button();
IssuedButton = new Button();
RefreshButton = new Button();
CreateBackupToolStripMenuItem = new ToolStripMenuItem();
MenuStrip.SuspendLayout();
((System.ComponentModel.ISupportInitialize)DataGridView).BeginInit();
SuspendLayout();
@ -51,7 +52,7 @@
// MenuStrip
//
MenuStrip.ImageScalingSize = new Size(20, 20);
MenuStrip.Items.AddRange(new ToolStripItem[] { ToolStripMenu, ReportsToolStripMenuItem, WorkStartToolStripMenuItem, MailToolStripMenuItem });
MenuStrip.Items.AddRange(new ToolStripItem[] { ToolStripMenu, ReportsToolStripMenuItem, WorkStartToolStripMenuItem, MailToolStripMenuItem, CreateBackupToolStripMenuItem });
MenuStrip.Location = new Point(0, 0);
MenuStrip.Name = "MenuStrip";
MenuStrip.Padding = new Padding(5, 2, 0, 2);
@ -69,28 +70,28 @@
// ComponentsStripMenuItem
//
ComponentsStripMenuItem.Name = "ComponentsStripMenuItem";
ComponentsStripMenuItem.Size = new Size(149, 22);
ComponentsStripMenuItem.Size = new Size(180, 22);
ComponentsStripMenuItem.Text = "Компоненты";
ComponentsStripMenuItem.Click += ComponentsStripMenuItem_Click;
//
// RepairStripMenuItem
//
RepairStripMenuItem.Name = "RepairStripMenuItem";
RepairStripMenuItem.Size = new Size(149, 22);
RepairStripMenuItem.Size = new Size(180, 22);
RepairStripMenuItem.Text = "Ремонты";
RepairStripMenuItem.Click += RepairsStripMenuItem_Click;
//
// ClientsToolStripMenuItem
//
ClientsToolStripMenuItem.Name = "ClientsToolStripMenuItem";
ClientsToolStripMenuItem.Size = new Size(149, 22);
ClientsToolStripMenuItem.Size = new Size(180, 22);
ClientsToolStripMenuItem.Text = "Клиенты";
ClientsToolStripMenuItem.Click += ClientsToolStripMenuItem_Click;
//
// ImplementersToolStripMenuItem
//
ImplementersToolStripMenuItem.Name = "ImplementersToolStripMenuItem";
ImplementersToolStripMenuItem.Size = new Size(149, 22);
ImplementersToolStripMenuItem.Size = new Size(180, 22);
ImplementersToolStripMenuItem.Text = "Исполнители";
ImplementersToolStripMenuItem.Click += EmployersToolStripMenuItem_Click;
//
@ -179,6 +180,13 @@
RefreshButton.UseVisualStyleBackColor = true;
RefreshButton.Click += RefreshButton_Click;
//
// CreateBackupToolStripMenuItem
//
CreateBackupToolStripMenuItem.Name = "CreateBackupToolStripMenuItem";
CreateBackupToolStripMenuItem.Size = new Size(97, 20);
CreateBackupToolStripMenuItem.Text = "Создать бэкап";
CreateBackupToolStripMenuItem.Click += CreateBackupToolStripMenuItem_Click;
//
// MainForm
//
AutoScaleDimensions = new SizeF(7F, 15F);
@ -219,5 +227,6 @@
private ToolStripMenuItem ImplementersToolStripMenuItem;
private ToolStripMenuItem WorkStartToolStripMenuItem;
private ToolStripMenuItem MailToolStripMenuItem;
private ToolStripMenuItem CreateBackupToolStripMenuItem;
}
}

View File

@ -7,229 +7,255 @@ using Microsoft.Extensions.Logging;
namespace AutoWorkshopView
{
public partial class MainForm : Form
{
private readonly ILogger _logger;
private readonly IOrderLogic _orderLogic;
private readonly IReportLogic _reportLogic;
private readonly IWorkProcess _workProcess;
{
private readonly ILogger _logger;
private readonly IOrderLogic _orderLogic;
private readonly IReportLogic _reportLogic;
private readonly IWorkProcess _workProcess;
private readonly IBackUpLogic _backUpLogic;
public MainForm(ILogger<MainForm> Logger, IOrderLogic OrderLogic, IReportLogic ReportLogic, IWorkProcess WorkProcess)
{
InitializeComponent();
_logger = Logger;
_orderLogic = OrderLogic;
_reportLogic = ReportLogic;
_workProcess = WorkProcess;
}
public MainForm(ILogger<MainForm> Logger, IOrderLogic OrderLogic, IReportLogic ReportLogic, IWorkProcess WorkProcess, IBackUpLogic backUpLogic)
{
InitializeComponent();
private void MainForm_Load(object sender, EventArgs e)
{
LoadData();
}
_logger = Logger;
_orderLogic = OrderLogic;
_reportLogic = ReportLogic;
_workProcess = WorkProcess;
_backUpLogic = backUpLogic;
}
private void LoadData()
{
_logger.LogInformation("Загрузка заказов");
try
{
private void MainForm_Load(object sender, EventArgs e)
{
LoadData();
}
private void LoadData()
{
_logger.LogInformation("Загрузка заказов");
try
{
DataGridView.FillAndConfigGrid(_orderLogic.ReadList(null));
_logger.LogInformation("Загрузка заказов");
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка загрузки заказов");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
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));
if (Service is FormComponents Form)
{
Form.ShowDialog();
}
}
private void ComponentsStripMenuItem_Click(object sender, EventArgs e)
{
var Service = Program.ServiceProvider?.GetService(typeof(FormComponents));
private void RepairsStripMenuItem_Click(object sender, EventArgs e)
{
var Service = Program.ServiceProvider?.GetService(typeof(FormRepairs));
if (Service is FormComponents Form)
{
Form.ShowDialog();
}
}
if (Service is FormRepairs Form)
{
Form.ShowDialog();
}
}
private void RepairsStripMenuItem_Click(object sender, EventArgs e)
{
var Service = Program.ServiceProvider?.GetService(typeof(FormRepairs));
private void CreateOrderButton_Click(object sender, EventArgs e)
{
var Service = Program.ServiceProvider?.GetService(typeof(FormCreateOrder));
if (Service is FormCreateOrder Form)
{
Form.ShowDialog();
LoadData();
}
}
if (Service is FormRepairs Form)
{
Form.ShowDialog();
}
}
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);
try
{
var OperationResult = _orderLogic.TakeOrderInWork(new OrderBindingModel { Id = id });
if (!OperationResult)
{
throw new Exception("Ошибка при сохранении. Дополнительная информация в логах.");
}
private void CreateOrderButton_Click(object sender, EventArgs e)
{
var Service = Program.ServiceProvider?.GetService(typeof(FormCreateOrder));
LoadData();
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка передачи заказа в работу");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
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 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.TakeOrderInWork(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);
}
_logger.LogInformation("Заказ №{id}. Меняется статус на 'Выдан'", id);
private void OrderReadyButton_Click(object sender, EventArgs e)
{
if (DataGridView.SelectedRows.Count == 1)
{
int id = Convert.ToInt32(DataGridView.SelectedRows[0].Cells["Id"].Value);
try
{
var OperationResult = _orderLogic.DeliveryOrder(new OrderBindingModel { Id = id });
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);
private void RefreshButton_Click(object sender, EventArgs e)
{
LoadData();
}
try
{
var OperationResult = _orderLogic.FinishOrder(new OrderBindingModel { Id = id });
private void ComponentsToolStripMenuItem_Click(object sender, EventArgs e)
{
using var Dialog = new SaveFileDialog { Filter = "docx|*.docx" };
if (Dialog.ShowDialog() == DialogResult.OK)
{
_reportLogic.SaveRepairsToWordFile(new ReportBindingModel { FileName = Dialog.FileName });
MessageBox.Show("Выполнено", "Успех", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
if (!OperationResult)
{
throw new Exception("Ошибка при сохранении. Дополнительная информация в логах.");
}
private void ComponentRepairToolStripMenuItem_Click(object sender, EventArgs e)
{
var Service = Program.ServiceProvider?.GetService(typeof(FormReportRepairComponents));
if (Service is FormReportRepairComponents Form)
{
Form.ShowDialog();
}
}
LoadData();
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка отметки о готовности заказа");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
private void OrdersToolStripMenuItem_Click(object sender, EventArgs e)
{
var Service = Program.ServiceProvider?.GetService(typeof(FormReportOrders));
if (Service is FormReportOrders Form)
{
Form.ShowDialog();
}
}
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);
try
{
var OperationResult = _orderLogic.DeliveryOrder(new OrderBindingModel { Id = id });
if (!OperationResult)
{
throw new Exception("Ошибка при сохранении. Дополнительная информация в логах.");
}
_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" };
if (Dialog.ShowDialog() == DialogResult.OK)
{
_reportLogic.SaveRepairsToWordFile(new ReportBindingModel { FileName = Dialog.FileName });
MessageBox.Show("Выполнено", "Успех", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
private void ComponentRepairToolStripMenuItem_Click(object sender, EventArgs e)
{
var Service = Program.ServiceProvider?.GetService(typeof(FormReportRepairComponents));
if (Service is FormReportRepairComponents Form)
{
Form.ShowDialog();
}
}
private void OrdersToolStripMenuItem_Click(object sender, EventArgs e)
{
var Service = Program.ServiceProvider?.GetService(typeof(FormReportOrders));
if (Service is FormReportOrders Form)
{
Form.ShowDialog();
}
}
private void ClientsToolStripMenuItem_Click(object sender, EventArgs e)
{
var Service = Program.ServiceProvider?.GetService(typeof(FormClients));
if (Service is FormClients Form)
if (Service is FormClients Form)
{
Form.ShowDialog();
}
}
private void EmployersToolStripMenuItem_Click(object sender, EventArgs e)
{
var Service = Program.ServiceProvider?.GetService(typeof(FormImplementers));
if (Service is FormImplementers Form)
{
Form.ShowDialog();
}
}
private void EmployersToolStripMenuItem_Click(object sender, EventArgs e)
{
var Service = Program.ServiceProvider?.GetService(typeof(FormImplementers));
private void StartWorkToolStripMenuItem_Click(object sender, EventArgs e)
{
var ImplementerLogic = Program.ServiceProvider?.GetService(typeof(IImplementerLogic));
_workProcess.DoWork((ImplementerLogic as IImplementerLogic)!, _orderLogic);
MessageBox.Show("Процесс обработки запущен", "Сообщение", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
if (Service is FormImplementers Form)
{
Form.ShowDialog();
}
}
private void StartWorkToolStripMenuItem_Click(object sender, EventArgs e)
{
var ImplementerLogic = Program.ServiceProvider?.GetService(typeof(IImplementerLogic));
_workProcess.DoWork((ImplementerLogic as IImplementerLogic)!, _orderLogic);
MessageBox.Show("Процесс обработки запущен", "Сообщение", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
private void MailToolStripMenuItem_Click(object sender, EventArgs e)
{
var Service = Program.ServiceProvider?.GetService(typeof(FormMail));
if (Service is FormMail Form)
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);
}
}
}
}