diff --git a/Pizzeria/Pizzeria/DataGridViewExtension.cs b/Pizzeria/Pizzeria/DataGridViewExtension.cs new file mode 100644 index 0000000..344c517 --- /dev/null +++ b/Pizzeria/Pizzeria/DataGridViewExtension.cs @@ -0,0 +1,50 @@ +using PizzeriaContracts.Attributes; + +namespace Pizzeria +{ + public static class DataGridViewExtension + { + public static void FillandConfigGrid(this DataGridView grid, List? data) + { + if (data == null) + { + return; + } + grid.DataSource = data; + var type = typeof(T); + var properties = type.GetProperties(); + foreach (DataGridViewColumn column in grid.Columns) + { + var property = properties.FirstOrDefault(x => x.Name == + column.Name); + if (property == null) + { + throw new InvalidOperationException($"В типе {type.Name} не найдено свойство с именем { column.Name }"); + } + var attribute = + property.GetCustomAttributes(typeof(ColumnAttribute), true)?.SingleOrDefault(); + if (attribute == null) + { + throw new InvalidOperationException($"Не найден атрибут типа ColumnAttribute для свойства { property.Name }"); + } + // ищем нужный нам атрибут + if (attribute is ColumnAttribute columnAttr) + { + column.HeaderText = columnAttr.Title; + column.Visible = columnAttr.Visible; + if (columnAttr.IsUseAutoSize) + { + column.AutoSizeMode = + (DataGridViewAutoSizeColumnMode)Enum.Parse(typeof(DataGridViewAutoSizeColumnMode) + , columnAttr.GridViewAutoSize.ToString()); + } + else + { + column.Width = columnAttr.Width; + } + } + } + } + } + +} diff --git a/Pizzeria/Pizzeria/FormClients.cs b/Pizzeria/Pizzeria/FormClients.cs index 1ee26b5..1b8c076 100644 --- a/Pizzeria/Pizzeria/FormClients.cs +++ b/Pizzeria/Pizzeria/FormClients.cs @@ -25,13 +25,7 @@ namespace Pizzeria { try { - var list = _logic.ReadList(null); - if (list != null) - { - dataGridView.DataSource = list; - dataGridView.Columns["Id"].Visible = false; - dataGridView.Columns["ClientFIO"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill; - } + dataGridView.FillandConfigGrid(_logic.ReadList(null)); _logger.LogInformation("Загрузка клиентов"); } catch (Exception ex) diff --git a/Pizzeria/Pizzeria/FormComponents.cs b/Pizzeria/Pizzeria/FormComponents.cs index a07acaa..00ca5c1 100644 --- a/Pizzeria/Pizzeria/FormComponents.cs +++ b/Pizzeria/Pizzeria/FormComponents.cs @@ -1,7 +1,7 @@ using PizzeriaContracts.BindingModels; using PizzeriaContracts.BusinessLogicsContracts; using Microsoft.Extensions.Logging; - +using PizzeriaContracts.DI; namespace Pizzeria { @@ -23,13 +23,8 @@ namespace Pizzeria { 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) @@ -40,28 +35,21 @@ namespace Pizzeria } private void ButtonAdd_Click(object sender, EventArgs e) { - var service = Program.ServiceProvider?.GetService(typeof(FormComponent)); - if (service is FormComponent form) + var form = DependencyManager.Instance.Resolve(); + if (form.ShowDialog() == DialogResult.OK) { - if (form.ShowDialog() == DialogResult.OK) - { - LoadData(); - } + LoadData(); } } private void ButtonUpd_Click(object sender, EventArgs e) { if (dataGridView.SelectedRows.Count == 1) { - var service = Program.ServiceProvider?.GetService(typeof(FormComponent)); - if (service is FormComponent form) + var form = DependencyManager.Instance.Resolve(); + form.Id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value); + if (form.ShowDialog() == DialogResult.OK) { - form.Id = - Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value); - if (form.ShowDialog() == DialogResult.OK) - { - LoadData(); - } + LoadData(); } } } diff --git a/Pizzeria/Pizzeria/FormImplementers.cs b/Pizzeria/Pizzeria/FormImplementers.cs index 91c4bda..b5a4b96 100644 --- a/Pizzeria/Pizzeria/FormImplementers.cs +++ b/Pizzeria/Pizzeria/FormImplementers.cs @@ -1,7 +1,7 @@ using PizzeriaContracts.BindingModels; using PizzeriaContracts.BusinessLogicsContracts; using Microsoft.Extensions.Logging; - +using PizzeriaContracts.DI; namespace Pizzeria { @@ -23,13 +23,7 @@ namespace Pizzeria { try { - var list = _logic.ReadList(null); - if (list != null) - { - dataGridView.DataSource = list; - dataGridView.Columns["Id"].Visible = false; - dataGridView.Columns["ImplementerFIO"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill; - } + dataGridView.FillandConfigGrid(_logic.ReadList(null)); _logger.LogInformation("Загрузка компонентов"); } catch (Exception ex) @@ -40,28 +34,22 @@ namespace Pizzeria } private void ButtonAdd_Click(object sender, EventArgs e) { - var service = Program.ServiceProvider?.GetService(typeof(FormImplementer)); - if (service is FormImplementer form) + var form = DependencyManager.Instance.Resolve(); + if (form.ShowDialog() == DialogResult.OK) { - if (form.ShowDialog() == DialogResult.OK) - { - LoadData(); - } + LoadData(); } } private void ButtonUpd_Click(object sender, EventArgs e) { if (dataGridView.SelectedRows.Count == 1) { - var service = Program.ServiceProvider?.GetService(typeof(FormImplementer)); - if (service is FormImplementer form) + var form = DependencyManager.Instance.Resolve(); + form.Id = + Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value); + if (form.ShowDialog() == DialogResult.OK) { - form.Id = - Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value); - if (form.ShowDialog() == DialogResult.OK) - { - LoadData(); - } + LoadData(); } } } diff --git a/Pizzeria/Pizzeria/FormMails.cs b/Pizzeria/Pizzeria/FormMails.cs index 30c6734..1f90064 100644 --- a/Pizzeria/Pizzeria/FormMails.cs +++ b/Pizzeria/Pizzeria/FormMails.cs @@ -34,14 +34,7 @@ namespace Pizzeria { try { - var list = _logic.ReadList(null); - if (list != null) - { - dataGridView.DataSource = list; - dataGridView.Columns["MessageId"].Visible = false; - dataGridView.Columns["ClientId"].Visible = false; - dataGridView.Columns["Body"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill; - } + dataGridView.FillandConfigGrid(_logic.ReadList(null)); _logger.LogInformation("Загрузка писем"); } catch (Exception ex) diff --git a/Pizzeria/Pizzeria/FormMain.Designer.cs b/Pizzeria/Pizzeria/FormMain.Designer.cs index c8bb969..5d44b27 100644 --- a/Pizzeria/Pizzeria/FormMain.Designer.cs +++ b/Pizzeria/Pizzeria/FormMain.Designer.cs @@ -46,6 +46,7 @@ списокЗаказовToolStripMenuItem = new ToolStripMenuItem(); запускРаботToolStripMenuItem = new ToolStripMenuItem(); письмаToolStripMenuItem = new ToolStripMenuItem(); + создатьБэкапToolStripMenuItem = new ToolStripMenuItem(); ((System.ComponentModel.ISupportInitialize)dataGridView).BeginInit(); menuStrip1.SuspendLayout(); SuspendLayout(); @@ -104,7 +105,7 @@ // menuStrip1 // menuStrip1.ImageScalingSize = new Size(20, 20); - menuStrip1.Items.AddRange(new ToolStripItem[] { справочникиToolStripMenuItem, отчетыToolStripMenuItem, запускРаботToolStripMenuItem, письмаToolStripMenuItem }); + menuStrip1.Items.AddRange(new ToolStripItem[] { справочникиToolStripMenuItem, отчетыToolStripMenuItem, запускРаботToolStripMenuItem, письмаToolStripMenuItem, создатьБэкапToolStripMenuItem }); menuStrip1.Location = new Point(0, 0); menuStrip1.Name = "menuStrip1"; menuStrip1.Size = new Size(1501, 28); @@ -188,6 +189,13 @@ письмаToolStripMenuItem.Text = "Письма"; письмаToolStripMenuItem.Click += письмаToolStripMenuItem_Click; // + // создатьБэкапToolStripMenuItem + // + создатьБэкапToolStripMenuItem.Name = "создатьБэкапToolStripMenuItem"; + создатьБэкапToolStripMenuItem.Size = new Size(122, 24); + создатьБэкапToolStripMenuItem.Text = "Создать бэкап"; + создатьБэкапToolStripMenuItem.Click += создатьБэкапToolStripMenuItem_Click; + // // FormMain // AutoScaleDimensions = new SizeF(8F, 20F); @@ -228,5 +236,6 @@ private ToolStripMenuItem запускРаботToolStripMenuItem; private ToolStripMenuItem исполнителиToolStripMenuItem; private ToolStripMenuItem письмаToolStripMenuItem; + private ToolStripMenuItem создатьБэкапToolStripMenuItem; } } \ No newline at end of file diff --git a/Pizzeria/Pizzeria/FormMain.cs b/Pizzeria/Pizzeria/FormMain.cs index 85ffcc7..35648e5 100644 --- a/Pizzeria/Pizzeria/FormMain.cs +++ b/Pizzeria/Pizzeria/FormMain.cs @@ -2,6 +2,8 @@ using PizzeriaContracts.BindingModels; using PizzeriaContracts.BusinessLogicsContracts; using PizzeriaDataModels; using Microsoft.Extensions.Logging; +using PizzeriaContracts.DI; +using System.Windows.Forms; namespace Pizzeria { @@ -11,13 +13,16 @@ namespace Pizzeria private readonly IOrderLogic _orderLogic; private readonly IReportLogic _reportLogic; private readonly IWorkProcess _workProcess; - public FormMain(ILogger logger, IOrderLogic orderLogic, IReportLogic reportLogic, IWorkProcess workProcess) + private readonly IBackUpLogic _backUpLogic; + + public FormMain(ILogger 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) { @@ -27,15 +32,7 @@ namespace Pizzeria { try { - var list = _orderLogic.ReadList(null); - if (list != null) - { - dataGridView.DataSource = list; - dataGridView.Columns["PizzaId"].Visible = false; - dataGridView.Columns["ClientId"].Visible = false; - dataGridView.Columns["ImplementerId"].Visible = false; - dataGridView.Columns["PizzaName"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill; - } + dataGridView.FillandConfigGrid(_orderLogic.ReadList(null)); _logger.LogInformation(" "); } catch (Exception ex) @@ -46,37 +43,25 @@ namespace Pizzeria } private void ToolStripMenuItem_Click(object sender, EventArgs e) { - var service = Program.ServiceProvider?.GetService(typeof(FormComponents)); - if (service is FormComponents form) - { - form.ShowDialog(); - } + var form = DependencyManager.Instance.Resolve(); + form.ShowDialog(); } private void ToolStripMenuItem_Click(object sender, EventArgs e) { - var service = Program.ServiceProvider?.GetService(typeof(FormPizzas)); - if (service is FormPizzas form) - { - form.ShowDialog(); - } + var form = DependencyManager.Instance.Resolve(); + form.ShowDialog(); } private void ToolStripMenuItem_Click(object sender, EventArgs e) { - var service = Program.ServiceProvider?.GetService(typeof(FormClients)); - if (service is FormClients form) - { - form.ShowDialog(); - } + var form = DependencyManager.Instance.Resolve(); + form.ShowDialog(); } private void ButtonCreateOrder_Click(object sender, EventArgs e) { - var service = Program.ServiceProvider?.GetService(typeof(FormCreateOrder)); - if (service is FormCreateOrder form) - { - form.ShowDialog(); - LoadData(); - } + var form = DependencyManager.Instance.Resolve(); + form.ShowDialog(); + LoadData(); } private OrderBindingModel getBindingModel() @@ -137,44 +122,57 @@ e) } private void ComponentPizzasToolStripMenuItem_Click(object sender, EventArgs e) { - var service = - Program.ServiceProvider?.GetService(typeof(FormReportPizzaComponents)); - if (service is FormReportPizzaComponents form) - { - form.ShowDialog(); - } + var form = DependencyManager.Instance.Resolve(); + form.ShowDialog(); } private void OrdersToolStripMenuItem_Click(object sender, EventArgs e) { - var service = Program.ServiceProvider?.GetService(typeof(FormReportOrders)); - if (service is FormReportOrders form) - { - form.ShowDialog(); - } + var form = DependencyManager.Instance.Resolve(); + form.ShowDialog(); } private void ToolStripMenuItem_Click(object sender, EventArgs e) { - _workProcess.DoWork((Program.ServiceProvider?.GetService(typeof(IImplementerLogic)) as IImplementerLogic)!, _orderLogic); + _workProcess.DoWork((DependencyManager.Instance.Resolve())!, _orderLogic); MessageBox.Show(" ", "", MessageBoxButtons.OK, MessageBoxIcon.Information); } private void ToolStripMenuItem_Click(object sender, EventArgs e) { - var service = Program.ServiceProvider?.GetService(typeof(FormImplementers)); - if (service is FormImplementers form) - { - form.ShowDialog(); - } + var form = DependencyManager.Instance.Resolve(); + form.ShowDialog(); } private void ToolStripMenuItem_Click(object sender, EventArgs e) { - var service = Program.ServiceProvider?.GetService(typeof(FormMails)); - if (service is FormMails form) + var form = DependencyManager.Instance.Resolve(); + form.ShowDialog(); + } + + private void ToolStripMenuItem_Click(object sender, EventArgs e) + { + try { - form.ShowDialog(); + if (_backUpLogic != null) + { + var fbd = new FolderBrowserDialog(); + if (fbd.ShowDialog() == DialogResult.OK) + { + _backUpLogic.CreateBackUp(new BackUpSaveBinidngModel + { + FolderName = fbd.SelectedPath + }); + MessageBox.Show(" ", "", + MessageBoxButtons.OK, MessageBoxIcon.Information); + } + } } + catch (Exception ex) + { + MessageBox.Show(ex.Message, "", MessageBoxButtons.OK, + MessageBoxIcon.Error); + } + } } } \ No newline at end of file diff --git a/Pizzeria/Pizzeria/FormPizza.cs b/Pizzeria/Pizzeria/FormPizza.cs index f21b7ca..da8acec 100644 --- a/Pizzeria/Pizzeria/FormPizza.cs +++ b/Pizzeria/Pizzeria/FormPizza.cs @@ -3,7 +3,7 @@ using PizzeriaContracts.BusinessLogicsContracts; using PizzeriaContracts.SearchModels; using PizzeriaDataModels; using Microsoft.Extensions.Logging; - +using PizzeriaContracts.DI; namespace Pizzeria { @@ -72,48 +72,42 @@ namespace Pizzeria } private void ButtonAdd_Click(object sender, EventArgs e) { - var service = Program.ServiceProvider?.GetService(typeof(FormPizzaComponent)); - if (service is FormPizzaComponent form) + var form = DependencyManager.Instance.Resolve(); + if (form.ShowDialog() == DialogResult.OK) { - if (form.ShowDialog() == DialogResult.OK) + if (form.ComponentModel == null) { - if (form.ComponentModel == null) - { - return; - } - _logger.LogInformation("Добавление нового компонента: { ComponentName} - { Count}", form.ComponentModel.ComponentName, form.Count); - if (_pizzaComponents.ContainsKey(form.Id)) - { - _pizzaComponents[form.Id] = (form.ComponentModel, form.Count); - } - else - { - _pizzaComponents.Add(form.Id, (form.ComponentModel, form.Count)); - } - LoadData(); + return; } + _logger.LogInformation("Добавление нового компонента: { ComponentName} - { Count}", form.ComponentModel.ComponentName, form.Count); + if (_pizzaComponents.ContainsKey(form.Id)) + { + _pizzaComponents[form.Id] = (form.ComponentModel, form.Count); + } + else + { + _pizzaComponents.Add(form.Id, (form.ComponentModel, form.Count)); + } + LoadData(); } } private void ButtonUpd_Click(object sender, EventArgs e) { if (dataGridView.SelectedRows.Count == 1) { - var service = Program.ServiceProvider?.GetService(typeof(FormPizzaComponent)); - if (service is FormPizzaComponent form) + var form = DependencyManager.Instance.Resolve(); + int id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells[0].Value); + form.Id = id; + form.Count = _pizzaComponents[id].Item2; + if (form.ShowDialog() == DialogResult.OK) { - int id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells[0].Value); - form.Id = id; - form.Count = _pizzaComponents[id].Item2; - if (form.ShowDialog() == DialogResult.OK) + if (form.ComponentModel == null) { - if (form.ComponentModel == null) - { - return; - } - _logger.LogInformation("Изменение компонента: { ComponentName} - { Count}", form.ComponentModel.ComponentName, form.Count); - _pizzaComponents[form.Id] = (form.ComponentModel, form.Count); - LoadData(); + return; } + _logger.LogInformation("Изменение компонента: { ComponentName} - { Count}", form.ComponentModel.ComponentName, form.Count); + _pizzaComponents[form.Id] = (form.ComponentModel, form.Count); + LoadData(); } } } diff --git a/Pizzeria/Pizzeria/FormPizzas.cs b/Pizzeria/Pizzeria/FormPizzas.cs index fb84a32..de9e46e 100644 --- a/Pizzeria/Pizzeria/FormPizzas.cs +++ b/Pizzeria/Pizzeria/FormPizzas.cs @@ -1,6 +1,7 @@ using PizzeriaContracts.BindingModels; using PizzeriaContracts.BusinessLogicsContracts; using Microsoft.Extensions.Logging; +using PizzeriaContracts.DI; namespace Pizzeria { @@ -22,14 +23,8 @@ namespace Pizzeria { try { - var list = _logic.ReadList(null); - if (list != null) - { - dataGridView.DataSource = list; - dataGridView.Columns["Id"].Visible = false; - dataGridView.Columns["PizzaName"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill; - dataGridView.Columns["PizzaComponents"].Visible = false; - } + + dataGridView.FillandConfigGrid(_logic.ReadList(null)); _logger.LogInformation("Загрузка компонентов"); } catch (Exception ex) @@ -41,28 +36,21 @@ namespace Pizzeria } private void ButtonAdd_Click(object sender, EventArgs e) { - var service = Program.ServiceProvider?.GetService(typeof(FormPizza)); - if (service is FormPizza form) + var form = DependencyManager.Instance.Resolve(); + if (form.ShowDialog() == DialogResult.OK) { - if (form.ShowDialog() == DialogResult.OK) - { - LoadData(); - } + LoadData(); } } private void ButtonUpd_Click(object sender, EventArgs e) { if (dataGridView.SelectedRows.Count == 1) { - var service = Program.ServiceProvider?.GetService(typeof(FormPizza)); - if (service is FormPizza form) + var form = DependencyManager.Instance.Resolve(); + form.Id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value); + if (form.ShowDialog() == DialogResult.OK) { - form.Id = - Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value); - if (form.ShowDialog() == DialogResult.OK) - { - LoadData(); - } + LoadData(); } } } diff --git a/Pizzeria/Pizzeria/Program.cs b/Pizzeria/Pizzeria/Program.cs index 3e817c6..1564837 100644 --- a/Pizzeria/Pizzeria/Program.cs +++ b/Pizzeria/Pizzeria/Program.cs @@ -7,31 +7,25 @@ using PizzeriaDatabaseImplement.Implements; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using NLog.Extensions.Logging; -using DocumentFormat.OpenXml.Wordprocessing; using PizzeriaBusinessLogic.MailWorker; using PizzeriaContracts.BindingModels; - +using PizzeriaContracts.DI; + namespace Pizzeria { internal static class Program { - private static ServiceProvider? _serviceProvider; - public static ServiceProvider? ServiceProvider => _serviceProvider; - /// - /// The main entry point for the application. - /// [STAThread] static void Main() - { - // To customize application configuration such as set high DPI settings or default font, - // see https://aka.ms/applicationconfiguration. - ApplicationConfiguration.Initialize(); - var services = new ServiceCollection(); - ConfigureServices(services); - _serviceProvider = services.BuildServiceProvider(); + { + // To customize application configuration such as set high DPI settings or default font, + // see https://aka.ms/applicationconfiguration. + ApplicationConfiguration.Initialize(); + var services = new ServiceCollection(); + InitDependency(); try { - var mailSender = _serviceProvider.GetService(); + var mailSender = DependencyManager.Instance.Resolve(); mailSender?.MailConfig(new MailConfigBindingModel { MailLogin = System.Configuration.ConfigurationManager.AppSettings["MailLogin"] ?? string.Empty, @@ -46,52 +40,53 @@ namespace Pizzeria TimerCallback(MailCheck!), null, 0, 100000); } catch (Exception ex) - { - var logger = _serviceProvider.GetService(); - logger?.LogError(ex, " "); + { + var logger = DependencyManager.Instance.Resolve(); + logger?.LogError(ex, " "); } - Application.Run(_serviceProvider.GetRequiredService()); + Application.Run(DependencyManager.Instance.Resolve()); } - private static void ConfigureServices(ServiceCollection services) - { - services.AddLogging(option => - { - option.SetMinimumLevel(LogLevel.Information); - option.AddNLog("nlog.config"); + private static void InitDependency() + { + DependencyManager.InitDependency(); DependencyManager.Instance.AddLogging(option => + { + option.SetMinimumLevel(LogLevel.Information); + option.AddNLog("nlog.config"); }); - services.AddTransient(); - services.AddTransient(); - services.AddTransient(); - services.AddTransient(); - services.AddTransient(); - services.AddTransient(); - services.AddTransient(); - services.AddTransient(); - services.AddTransient(); - services.AddTransient(); - services.AddTransient(); - services.AddTransient(); - services.AddTransient(); - services.AddTransient(); - services.AddTransient(); - services.AddTransient(); - services.AddTransient(); - services.AddSingleton(); - services.AddTransient(); - services.AddTransient(); - services.AddTransient(); - services.AddTransient(); - services.AddTransient(); - services.AddTransient(); - services.AddTransient(); - services.AddTransient(); - services.AddTransient(); - services.AddTransient(); - services.AddTransient(); - services.AddTransient(); - services.AddTransient(); + DependencyManager.Instance.RegisterType(); + DependencyManager.Instance.RegisterType(); + DependencyManager.Instance.RegisterType(); + DependencyManager.Instance.RegisterType(); + DependencyManager.Instance.RegisterType(); + DependencyManager.Instance.RegisterType(); + DependencyManager.Instance.RegisterType(); + DependencyManager.Instance.RegisterType(); + DependencyManager.Instance.RegisterType(); + DependencyManager.Instance.RegisterType(); + DependencyManager.Instance.RegisterType(); + DependencyManager.Instance.RegisterType(); + DependencyManager.Instance.RegisterType(); + DependencyManager.Instance.RegisterType(); + DependencyManager.Instance.RegisterType(); + DependencyManager.Instance.RegisterType(); + DependencyManager.Instance.RegisterType(); + DependencyManager.Instance.RegisterType(true); + DependencyManager.Instance.RegisterType(); + + DependencyManager.Instance.RegisterType(); + DependencyManager.Instance.RegisterType(); + DependencyManager.Instance.RegisterType(); + DependencyManager.Instance.RegisterType(); + DependencyManager.Instance.RegisterType(); + DependencyManager.Instance.RegisterType(); + DependencyManager.Instance.RegisterType(); + DependencyManager.Instance.RegisterType(); + DependencyManager.Instance.RegisterType(); + DependencyManager.Instance.RegisterType(); + DependencyManager.Instance.RegisterType(); + DependencyManager.Instance.RegisterType(); + DependencyManager.Instance.RegisterType(); } - private static void MailCheck(object obj) => - ServiceProvider?.GetService()?.MailCheck(); + private static void MailCheck(object obj) => DependencyManager.Instance.Resolve()?.MailCheck(); } } \ No newline at end of file diff --git a/Pizzeria/PizzeriaBusinessLogic/BackUpLogic.cs b/Pizzeria/PizzeriaBusinessLogic/BackUpLogic.cs new file mode 100644 index 0000000..34e4fe1 --- /dev/null +++ b/Pizzeria/PizzeriaBusinessLogic/BackUpLogic.cs @@ -0,0 +1,98 @@ +using Microsoft.Extensions.Logging; +using PizzeriaContracts.BindingModels; +using PizzeriaContracts.BusinessLogicsContracts; +using PizzeriaContracts.StoragesContracts; +using PizzeriaDataModels; +using System.IO.Compression; +using System.Reflection; +using System.Runtime.Serialization.Json; + +namespace PizzeriaBusinessLogic +{ + public class BackUpLogic : IBackUpLogic + { + private readonly ILogger _logger; + private readonly IBackUpInfo _backUpInfo; + public BackUpLogic(ILogger logger, IBackUpInfo backUpInfo) + { + _logger = logger; + _backUpInfo = backUpInfo; + } + public void CreateBackUp(BackUpSaveBinidngModel model) + { + if (_backUpInfo == null) + { + return; + } + try + { + _logger.LogDebug("Clear folder"); + // зачистка папки и удаление старого архива + var dirInfo = new DirectoryInfo(model.FolderName); + if (dirInfo.Exists) + { + foreach (var file in dirInfo.GetFiles()) + { + file.Delete(); + } + } + _logger.LogDebug("Delete archive"); + string fileName = $"{model.FolderName}.zip"; + if (File.Exists(fileName)) + { + File.Delete(fileName); + } + // берем метод для сохранения + _logger.LogDebug("Get assembly"); + var typeIId = typeof(IId); + var assembly = typeIId.Assembly; + if (assembly == null) + { + throw new ArgumentNullException("Сборка не найдена", + nameof(assembly)); + } + var types = assembly.GetTypes(); + var method = GetType().GetMethod("SaveToFile", BindingFlags.NonPublic | BindingFlags.Instance); + _logger.LogDebug("Find {count} types", types.Length); + foreach (var type in types) + { + 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(string folderName) where T : class, new() + { + var records = _backUpInfo.GetList(); + if (records == null) + { + _logger.LogWarning("{type} type get null list", typeof(T).Name); + return; + } + var jsonFormatter = new DataContractJsonSerializer(typeof(List)); + using var fs = new FileStream(string.Format("{0}/{1}.json", + folderName, typeof(T).Name), FileMode.OpenOrCreate); + jsonFormatter.WriteObject(fs, records); + } + } + +} diff --git a/Pizzeria/PizzeriaClientApp/Views/Shared/_Layout.cshtml b/Pizzeria/PizzeriaClientApp/Views/Shared/_Layout.cshtml index f668b82..f7bda8f 100644 --- a/Pizzeria/PizzeriaClientApp/Views/Shared/_Layout.cshtml +++ b/Pizzeria/PizzeriaClientApp/Views/Shared/_Layout.cshtml @@ -12,7 +12,7 @@