рабочий бекап

This commit is contained in:
Максим Яковлев 2024-05-19 01:10:58 +04:00
parent d284548070
commit 59c04ccfa3
4 changed files with 135 additions and 2 deletions

View File

@ -0,0 +1,97 @@
using CarRepairShopContracts.BindingModels;
using CarRepairShopContracts.BusinessLogicsContracts;
using CarRepairShopContracts.StoragesContracts;
using CarRepairShopDataModels;
using DocumentFormat.OpenXml.Office.CustomUI;
using DocumentFormat.OpenXml.Wordprocessing;
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 CarRepairShopBusinessLogic.BusinessLogics
{
public class BackUpLogic : IBackUpLogic
{
private readonly ILogger _logger;
private readonly IBackUpInfo _backUpInfo;
public BackUpLogic(ILogger<BackUpLogic> logger, IBackUpInfo backUpInfo)
{
_logger = logger;
_backUpInfo = backUpInfo;
}
public void CreateBackUp(BackUpSaveBindingModel model)
{
if (_backUpInfo == null) return;
try
{
_logger.LogDebug("Clear folder");
var dirInfo = new DirectoryInfo(model.FolderName);
if (dirInfo.Exists)
{
foreach(var file in dirInfo.GetFiles())
{
file.Delete();
}
}
_logger.LogDebug("Delete archive");
string fileName = $"{model.FolderName}.zip";
if(File.Exists(fileName))
{
File.Delete(fileName);
}
_logger.LogDebug("Get assembly");
var typeIId = typeof(IId);
var assembly = typeIId.Assembly;
if(assembly == null)
{
throw new ArgumentNullException("Сборка не найдена", nameof(assembly));
}
var types = assembly.GetTypes();
var method = GetType().GetMethod("SaveToFile", BindingFlags.NonPublic | BindingFlags.Instance);
_logger.LogDebug("Find {count} types", types.Length);
foreach( var type in types)
{
if(type.IsInterface && type.GetInterface(typeIId.Name) != null)
{
var modelType = _backUpInfo.GetTypeByModelInterface(type.Name);
if(modelType == null)
{
throw new InvalidOperationException($"Не найден класс-модель для {type.Name}");
}
_logger.LogDebug("Call SaveToFile method for {name} type", type.Name);
method?.MakeGenericMethod(modelType).Invoke(this, new object[] { model.FolderName });
}
}
_logger.LogDebug("Create zip and remove folder");
ZipFile.CreateFromDirectory(model.FolderName, fileName);
dirInfo.Delete(true);
}
catch
{
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

@ -44,13 +44,14 @@
buttonCreateOrder = new Button();
buttonIssuedOrder = new Button();
buttonRef = new Button();
CreateBackUpToolStripMenuItem = new ToolStripMenuItem();
menuStrip1.SuspendLayout();
((System.ComponentModel.ISupportInitialize)dataGridView).BeginInit();
SuspendLayout();
//
// menuStrip1
//
menuStrip1.Items.AddRange(new ToolStripItem[] { справочникиToolStripMenuItem, отчетыToolStripMenuItem, ClientsToolStripMenuItem, workStartToolStripMenuItem, implementersToolStripMenuItem, почтаToolStripMenuItem });
menuStrip1.Items.AddRange(new ToolStripItem[] { справочникиToolStripMenuItem, отчетыToolStripMenuItem, ClientsToolStripMenuItem, workStartToolStripMenuItem, implementersToolStripMenuItem, почтаToolStripMenuItem, CreateBackUpToolStripMenuItem });
menuStrip1.Location = new Point(0, 0);
menuStrip1.Name = "menuStrip1";
menuStrip1.Size = new Size(1256, 24);
@ -182,6 +183,13 @@
buttonRef.UseVisualStyleBackColor = true;
buttonRef.Click += buttonRef_Click;
//
// CreateBackUpToolStripMenuItem
//
CreateBackUpToolStripMenuItem.Name = "CreateBackUpToolStripMenuItem";
CreateBackUpToolStripMenuItem.Size = new Size(97, 20);
CreateBackUpToolStripMenuItem.Text = "Создать бекап";
CreateBackUpToolStripMenuItem.Click += CreateBackUpToolStripMenuItem_Click;
//
// FormMain
//
AutoScaleDimensions = new SizeF(7F, 15F);
@ -221,5 +229,6 @@
private ToolStripMenuItem workStartToolStripMenuItem;
private ToolStripMenuItem implementersToolStripMenuItem;
private ToolStripMenuItem почтаToolStripMenuItem;
private ToolStripMenuItem CreateBackUpToolStripMenuItem;
}
}

View File

@ -20,13 +20,15 @@ namespace CarRepairShopView
private readonly IOrderLogic _orderLogic;
private readonly IReportLogic _reportLogic;
private readonly IWorkProcess _workProcess;
public FormMain(ILogger<FormMain> logger, IOrderLogic orderLogic, IReportLogic reportLogic, IWorkProcess workProcess)
private readonly IBackUpLogic _backUpLogic;
public FormMain(ILogger<FormMain> logger, IOrderLogic orderLogic, IReportLogic reportLogic, IWorkProcess workProcess, IBackUpLogic backUpLogic)
{
InitializeComponent();
_logger = logger;
_orderLogic = orderLogic;
_reportLogic = reportLogic;
_workProcess = workProcess;
_backUpLogic = backUpLogic;
}
private void FormMain_Load(object sender, EventArgs e)
@ -215,5 +217,28 @@ namespace CarRepairShopView
form.ShowDialog();
}
}
private void CreateBackUpToolStripMenuItem_Click(object sender, EventArgs e)
{
try
{
if(_backUpLogic != null)
{
var fbd = new FolderBrowserDialog();
if(fbd.ShowDialog() == DialogResult.OK)
{
_backUpLogic.CreateBackUp(new BackUpSaveBindingModel
{
FolderName = fbd.SelectedPath
});
MessageBox.Show("Бекап создан", "Сообщение", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
}
catch(Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
}

View File

@ -67,6 +67,7 @@ namespace CarRepairShopView
services.AddTransient<IClientStorage, ClientStorage>();
services.AddTransient<IImplementerStorage, ImplementerStorage>();
services.AddTransient<IMessageInfoStorage, MessageInfoStorage>();
services.AddTransient<IBackUpInfo, BackUpInfo>();
services.AddTransient<IComponentLogic, ComponentLogic>();
services.AddTransient<IOrderLogic, OrderLogic>();
@ -75,6 +76,7 @@ namespace CarRepairShopView
services.AddTransient<IClientLogic, ClientLogic>();
services.AddTransient<IImplementerLogic, ImplementerLogic>();
services.AddTransient<IMessageInfoLogic, MessageInfoLogic>();
services.AddTransient<IBackUpLogic, BackUpLogic>();
services.AddTransient<IWorkProcess, WorkModeling>();
services.AddSingleton<AbstractMailWorker, MailKitWorker>();