8 Лаба из видео (вроде)

This commit is contained in:
Павел Сорокин 2023-04-28 16:13:32 +04:00
parent a4216eba08
commit c554b0dbec
31 changed files with 701 additions and 168 deletions

2
.gitignore vendored
View File

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

View File

@ -0,0 +1,51 @@
using ShipyardContracts.Attributes;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ShipyardView
{
internal static class DataGridViewExtension
{
public static void FillAndConfigGrid<T>(this DataGridView grid, List<T>? data)
{
if (data == null)
{
return;
}
grid.DataSource = data;
var type = typeof(T);
var properties = type.GetProperties();
foreach (DataGridViewColumn column in grid.Columns)
{
var property = properties.FirstOrDefault(x => x.Name == column.Name);
if (property == null)
{
throw new InvalidOperationException($"В типе {type.Name} не найдено свойство с именем {column.Name}");
}
var attribute = property.GetCustomAttributes(typeof(ColumnAttribute), true)?.SingleOrDefault();
if (attribute == null)
{
throw new InvalidOperationException($"Не найден атрибут типа ColumnAttribute для свойства {property.Name}");
}
// ищем нужный нам атрибут
if (attribute is ColumnAttribute columnAttr)
{
column.HeaderText = columnAttr.Title;
column.Visible = columnAttr.Visible;
if (columnAttr.IsUseAutoSize)
{
column.AutoSizeMode = (DataGridViewAutoSizeColumnMode)Enum.Parse(typeof(DataGridViewAutoSizeColumnMode), columnAttr.GridViewAutoSize.ToString());
}
else
{
column.Width = columnAttr.Width;
}
}
}
}
}
}

View File

@ -35,13 +35,7 @@ namespace ShipyardView
{
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)

View File

@ -2,6 +2,7 @@
using Microsoft.VisualBasic.Logging;
using ShipyardContracts.BindingModels;
using ShipyardContracts.BusinessLogicsContracts;
using ShipyardContracts.DI;
using System;
using System.Collections.Generic;
using System.ComponentModel;
@ -51,13 +52,10 @@ namespace ShipyardView
private void ButtonAdd_Click(object sender, EventArgs e)
{
var service = Program.ServiceProvider?.GetService(typeof(FormDetail));
if (service is FormDetail form)
var form = DependencyManager.Instance.Resolve<FormDetail>();
if (form.ShowDialog() == DialogResult.OK)
{
if (form.ShowDialog() == DialogResult.OK)
{
LoadData();
}
LoadData();
}
}
@ -65,14 +63,11 @@ namespace ShipyardView
{
if (dataGridView.SelectedRows.Count == 1)
{
var service = Program.ServiceProvider?.GetService(typeof(FormDetail));
if (service is FormDetail form)
var form = DependencyManager.Instance.Resolve<FormDetail>();
form.Id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value);
if (form.ShowDialog() == DialogResult.OK)
{
form.Id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value);
if (form.ShowDialog() == DialogResult.OK)
{
LoadData();
}
LoadData();
}
}
}

View File

@ -1,6 +1,7 @@
using Microsoft.Extensions.Logging;
using ShipyardContracts.BindingModels;
using ShipyardContracts.BusinessLogicsContracts;
using ShipyardContracts.DI;
using System;
using System.Collections.Generic;
using System.ComponentModel;
@ -53,13 +54,10 @@ namespace ShipyardView
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<FormImplementer>();
if (form.ShowDialog() == DialogResult.OK)
{
if (form.ShowDialog() == DialogResult.OK)
{
LoadData();
}
LoadData();
}
}
@ -67,14 +65,11 @@ namespace ShipyardView
{
if (dataGridView.SelectedRows.Count == 1)
{
var service = Program.ServiceProvider?.GetService(typeof(FormImplementer));
if (service is FormImplementer form)
var form = DependencyManager.Instance.Resolve<FormImplementer>();
form.Id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value);
if (form.ShowDialog() == DialogResult.OK)
{
form.Id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value);
if (form.ShowDialog() == DialogResult.OK)
{
LoadData();
}
LoadData();
}
}
}

View File

@ -1,6 +1,7 @@
using Microsoft.Extensions.Logging;
using ShipyardContracts.BindingModels;
using ShipyardContracts.BusinessLogicsContracts;
using ShipyardContracts.DI;
using ShipyardDataModels.Enums;
using System;
using System.Collections.Generic;
@ -57,30 +58,21 @@ namespace ShipyardView
private void ДеталиToolStripMenuItem_Click(object sender, EventArgs e)
{
var service = Program.ServiceProvider?.GetService(typeof(FormDetails));
if (service is FormDetails form)
{
form.ShowDialog();
}
var form = DependencyManager.Instance.Resolve<FormDetails>();
form.ShowDialog();
}
private void КораблиToolStripMenuItem_Click(object sender, EventArgs e)
{
var service = Program.ServiceProvider?.GetService(typeof(FormShips));
if (service is FormShips form)
{
form.ShowDialog();
}
var form = DependencyManager.Instance.Resolve<FormShips>();
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<FormCreateOrder>();
form.ShowDialog();
LoadData();
}
private void ButtonTakeOrderInWork_Click(object sender, EventArgs e)
@ -172,44 +164,32 @@ namespace ShipyardView
private void shipDetailsToolStripMenuItem_Click(object sender, EventArgs e)
{
var service = Program.ServiceProvider?.GetService(typeof(FormReportShipDetails));
if (service is FormReportShipDetails form)
{
form.ShowDialog();
}
var form = DependencyManager.Instance.Resolve<FormReportShipDetails>();
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<FormReportOrders>();
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<FormClients>();
form.ShowDialog();
}
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<FormImplementers>();
form.ShowDialog();
}
private void ЗапускРаботToolStripMenuItem_Click(object sender, EventArgs e)
{
_workProcess.DoWork((
Program.ServiceProvider?.GetService(typeof(IImplementerLogic)) as IImplementerLogic)!,
DependencyManager.Instance.Resolve<IImplementerLogic>())!,
_orderLogic);
MessageBox.Show("Передано на работу","произведен запуск",
MessageBoxButtons.OK, MessageBoxIcon.Information);
@ -217,11 +197,8 @@ namespace ShipyardView
private void письмаToolStripMenuItem_Click(object sender, EventArgs e)
{
var service = Program.ServiceProvider?.GetService(typeof(FormMails));
if (service is FormMails form)
{
form.ShowDialog();
}
var form = DependencyManager.Instance.Resolve<FormMails>();
form.ShowDialog();
}
}
}

View File

@ -1,6 +1,7 @@
using Microsoft.Extensions.Logging;
using ShipyardContracts.BindingModels;
using ShipyardContracts.BusinessLogicsContracts;
using ShipyardContracts.DI;
using ShipyardContracts.SearchModels;
using ShipyardDataModels.Models;
using System;
@ -81,26 +82,23 @@ namespace ShipyardView
private void ButtonAdd_Click(object sender, EventArgs e)
{
var service = Program.ServiceProvider?.GetService(typeof(FormShipDetail));
if (service is FormShipDetail form)
var form = DependencyManager.Instance.Resolve<FormShipDetail>();
if (form.ShowDialog() == DialogResult.OK)
{
if (form.ShowDialog() == DialogResult.OK)
if (form.DetailModel == null)
{
if (form.DetailModel == null)
{
return;
}
_logger.LogInformation("Добавление нового детали:{ DetailName} - { Count}", form.DetailModel.DetailName, form.Count);
if (_shipDetails.ContainsKey(form.Id))
{
_shipDetails[form.Id] = (form.DetailModel,form.Count);
}
else
{
_shipDetails.Add(form.Id, (form.DetailModel,form.Count));
}
LoadData();
return;
}
_logger.LogInformation("Добавление нового детали:{ DetailName} - { Count}", form.DetailModel.DetailName, form.Count);
if (_shipDetails.ContainsKey(form.Id))
{
_shipDetails[form.Id] = (form.DetailModel,form.Count);
}
else
{
_shipDetails.Add(form.Id, (form.DetailModel,form.Count));
}
LoadData();
}
}
@ -108,22 +106,19 @@ namespace ShipyardView
{
if (dataGridView.SelectedRows.Count == 1)
{
var service = Program.ServiceProvider?.GetService(typeof(FormShipDetail));
if (service is FormShipDetail form)
var form = DependencyManager.Instance.Resolve<FormShipDetail>();
int id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells[0].Value);
form.Id = id;
form.Count = _shipDetails[id].Item2;
if (form.ShowDialog() == DialogResult.OK)
{
int id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells[0].Value);
form.Id = id;
form.Count = _shipDetails[id].Item2;
if (form.ShowDialog() == DialogResult.OK)
if (form.DetailModel == null)
{
if (form.DetailModel == null)
{
return;
}
_logger.LogInformation("Изменение детали: { DetailName} - { Count}", form.DetailModel.DetailName, form.Count);
_shipDetails[form.Id] = (form.DetailModel,form.Count);
LoadData();
return;
}
_logger.LogInformation("Изменение детали: { DetailName} - { Count}", form.DetailModel.DetailName, form.Count);
_shipDetails[form.Id] = (form.DetailModel,form.Count);
LoadData();
}
}
}

View File

@ -1,6 +1,7 @@
using Microsoft.Extensions.Logging;
using ShipyardContracts.BindingModels;
using ShipyardContracts.BusinessLogicsContracts;
using ShipyardContracts.DI;
using System;
using System.Collections.Generic;
using System.ComponentModel;
@ -51,13 +52,10 @@ namespace ShipyardView
private void ButtonAdd_Click(object sender, EventArgs e)
{
var service = Program.ServiceProvider?.GetService(typeof(FormShip));
if (service is FormShip form)
var form = DependencyManager.Instance.Resolve<FormShip>();
if (form.ShowDialog() == DialogResult.OK)
{
if (form.ShowDialog() == DialogResult.OK)
{
LoadData();
}
LoadData();
}
}
@ -65,14 +63,11 @@ namespace ShipyardView
{
if (dataGridView.SelectedRows.Count == 1)
{
var service = Program.ServiceProvider?.GetService(typeof(FormShip));
if (service is FormShip form)
var form = DependencyManager.Instance.Resolve<FormShip>();
form.Id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value);
if (form.ShowDialog() == DialogResult.OK)
{
form.Id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value);
if (form.ShowDialog() == DialogResult.OK)
{
LoadData();
}
LoadData();
}
}
}

View File

@ -5,17 +5,15 @@ using ShipyardBusinessLogic.BusinessLogics;
using ShipyardBusinessLogic.OfficePackage.Implements;
using ShipyardBusinessLogic.OfficePackage;
using ShipyardContracts.BusinessLogicsContracts;
using ShipyardContracts.StoragesContracts;
using ShipyardDataBaseImplement.Implements;
using ShipyardBusinessLogic.MailWorker;
using ShipyardContracts.BindingModels;
using ShipyardBusinessLogic;
using ShipyardContracts.DI;
namespace ShipyardView
{
internal static class Program
{
private static ServiceProvider? _serviceProvider;
public static ServiceProvider? ServiceProvider => _serviceProvider;
/// <summary>
/// The main entry point for the application.
/// </summary>
@ -26,12 +24,10 @@ namespace ShipyardView
// see https://aka.ms/applicationconfiguration.
ApplicationConfiguration.Initialize();
var services = new ServiceCollection();
ConfigureServices(services);
_serviceProvider = services.BuildServiceProvider();
InitDependency();
try
{
var mailSender = _serviceProvider.GetService<AbstractMailWorker>();
var mailSender = DependencyManager.Instance.Resolve<AbstractMailWorker>();
mailSender?.MailConfig(new MailConfigBindingModel
{
MailLogin = System.Configuration.ConfigurationManager.AppSettings["MailLogin"] ?? string.Empty,
@ -46,56 +42,52 @@ namespace ShipyardView
}
catch (Exception ex)
{
var logger = _serviceProvider.GetService<ILogger>();
var logger = DependencyManager.Instance.Resolve<ILogger>();
logger?.LogError(ex, "Îøèáêà ðàáîòû ñ ïî÷òîé");
}
Application.Run(_serviceProvider.GetRequiredService<FormMain>());
Application.Run(DependencyManager.Instance.Resolve<FormMain>());
}
private static void ConfigureServices(ServiceCollection services)
private static void InitDependency()
{
services.AddLogging(option =>
DependencyManager.InitDependency();
DependencyManager.Instance.AddLogging(option =>
{
option.SetMinimumLevel(LogLevel.Information);
option.AddNLog("nlog.config");
});
services.AddTransient<IClientStorage, ClientStorage>();
services.AddTransient<IDetailStorage, DetailStorage>();
services.AddTransient<IOrderStorage, OrderStorage>();
services.AddTransient<IShipStorage, ShipStorage>();
services.AddTransient<IImplementerStorage, ImplementerStorage>();
services.AddTransient<IMessageInfoStorage, MessageInfoStorage>();
services.AddTransient<IClientLogic, ClientLogic>();
services.AddTransient<IDetailLogic, DetailLogic>();
services.AddTransient<IOrderLogic, OrderLogic>();
services.AddTransient<IShipLogic, ShipLogic>();
services.AddTransient<IReportLogic, ReportLogic>();
services.AddTransient<IImplementerLogic, ImplementerLogic>();
services.AddTransient<IMessageInfoLogic, MessageInfoLogic>();
services.AddTransient<IWorkProcess, WorkModeling>();
DependencyManager.Instance.RegisterType<IDetailLogic, DetailLogic>();
DependencyManager.Instance.RegisterType<IOrderLogic, OrderLogic>();
DependencyManager.Instance.RegisterType<IShipLogic, ShipLogic>();
DependencyManager.Instance.RegisterType<IReportLogic, ReportLogic>();
DependencyManager.Instance.RegisterType<IClientLogic, ClientLogic>();
DependencyManager.Instance.RegisterType<IImplementerLogic, ImplementerLogic>();
DependencyManager.Instance.RegisterType<IMessageInfoLogic, MessageInfoLogic>();
DependencyManager.Instance.RegisterType<AbstractSaveToExcel, SaveToExcel>();
DependencyManager.Instance.RegisterType<AbstractSaveToWord, SaveToWord>();
DependencyManager.Instance.RegisterType<AbstractSaveToPdf, SaveToPdf>();
DependencyManager.Instance.RegisterType<IWorkProcess, WorkModeling>();
DependencyManager.Instance.RegisterType<AbstractMailWorker, MailKitWorker>(true);
DependencyManager.Instance.RegisterType<IBackUpLogic, BackUpLogic>();
services.AddTransient<AbstractSaveToExcel, SaveToExcel>();
services.AddTransient<AbstractSaveToWord, SaveToWord>();
services.AddTransient<AbstractSaveToPdf, SaveToPdf>();
services.AddSingleton<AbstractMailWorker, MailKitWorker>();
services.AddTransient<FormMain>();
services.AddTransient<FormClients>();
services.AddTransient<FormDetail>();
services.AddTransient<FormDetails>();
services.AddTransient<FormImplementer>();
services.AddTransient<FormImplementers>();
services.AddTransient<FormCreateOrder>();
services.AddTransient<FormShip>();
services.AddTransient<FormShipDetail>();
services.AddTransient<FormShips>();
services.AddTransient<FormReportShipDetails>();
services.AddTransient<FormReportOrders>();
services.AddTransient<FormMails>();
DependencyManager.Instance.RegisterType<FormMain>();
DependencyManager.Instance.RegisterType<FormDetail>();
DependencyManager.Instance.RegisterType<FormDetails>();
DependencyManager.Instance.RegisterType<FormCreateOrder>();
DependencyManager.Instance.RegisterType<FormShips>();
DependencyManager.Instance.RegisterType<FormShip>();
DependencyManager.Instance.RegisterType<FormShipDetail>();
DependencyManager.Instance.RegisterType<FormReportShipDetails>();
DependencyManager.Instance.RegisterType<FormReportOrders>();
DependencyManager.Instance.RegisterType<FormClients>();
DependencyManager.Instance.RegisterType<FormMails>();
DependencyManager.Instance.RegisterType<FormImplementer>();
DependencyManager.Instance.RegisterType<FormImplementers>();
}
private static void MailCheck(object obj) => ServiceProvider?.GetService<AbstractMailWorker>()?.MailCheck();
private static void MailCheck(object obj) => DependencyManager.Instance?.Resolve<AbstractMailWorker>()?.MailCheck();
}

View File

@ -0,0 +1,103 @@
using Microsoft.Extensions.Logging;
using ShipyardContracts.BindingModels;
using ShipyardContracts.BusinessLogicsContracts;
using ShipyardContracts.StoragesContracts;
using ShipyardDataModels;
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 ShipyardBusinessLogic
{
public class BackUpLogic : IBackUpLogic
{
private readonly ILogger _logger;
private readonly IBackUpInfo _backUpInfo;
public BackUpLogic(ILogger<BackUpLogic> logger, IBackUpInfo backUpInfo)
{
_logger = logger;
_backUpInfo = backUpInfo;
}
public void CreateBackUp(BackUpSaveBinidngModel model)
{
if (_backUpInfo == null)
{
return;
}
try
{
_logger.LogDebug("Clear folder");
// зачистка папки и удаление старого архива
var dirInfo = new DirectoryInfo(model.FolderName);
if (dirInfo.Exists)
{
foreach (var file in dirInfo.GetFiles())
{
file.Delete();
}
}
_logger.LogDebug("Delete archive");
string fileName = $"{model.FolderName}.zip";
if (File.Exists(fileName))
{
File.Delete(fileName);
}
// берем метод для сохранения
_logger.LogDebug("Get assembly");
var typeIId = typeof(IId);
var assembly = typeIId.Assembly;
if (assembly == null)
{
throw new ArgumentNullException("Сборка не найдена", nameof(assembly));
}
var types = assembly.GetTypes();
var method = GetType().GetMethod("SaveToFile", BindingFlags.NonPublic | BindingFlags.Instance);
_logger.LogDebug("Find {count} types", types.Length);
foreach (var type in types)
{
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

@ -0,0 +1,31 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ShipyardContracts.Attributes
{
[AttributeUsage(AttributeTargets.Property)]
public class ColumnAttribute : Attribute
{
public string Title { get; private set; }
public bool Visible { get; private set; }
public int Width { get; private set; }
public GridViewAutoSize GridViewAutoSize { get; private set; }
public bool IsUseAutoSize { get; private set; }
public ColumnAttribute(string title = "", bool visible = true, int width = 0, GridViewAutoSize gridViewAutoSize = GridViewAutoSize.None, bool isUseAutoSize = false)
{
Title = title;
Visible = visible;
Width = width;
GridViewAutoSize = gridViewAutoSize;
IsUseAutoSize = isUseAutoSize;
}
}
}

View File

@ -0,0 +1,27 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ShipyardContracts.Attributes
{
public enum GridViewAutoSize
{
NotSet = 0,
None = 1,
ColumnHeader = 2,
AllCellsExceptHeader = 4,
AllCells = 6,
DisplayedCellsExceptHeader = 8,
DisplayedCells = 10,
Fill = 16
}
}

View File

@ -0,0 +1,13 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ShipyardContracts.BindingModels
{
public class BackUpSaveBinidngModel
{
public string FolderName { get; set; } = string.Empty;
}
}

View File

@ -20,5 +20,6 @@ namespace ShipyardContracts.BindingModels
public string Body { get; set; } = string.Empty;
public DateTime DateDelivery { get; set; }
public int Id => throw new NotImplementedException();
}
}

View File

@ -0,0 +1,14 @@
using ShipyardContracts.BindingModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ShipyardContracts.BusinessLogicsContracts
{
public interface IBackUpLogic
{
void CreateBackUp(BackUpSaveBinidngModel model);
}
}

View File

@ -0,0 +1,66 @@
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ShipyardContracts.DI
{
public class DependencyManager
{
private readonly IDependencyContainer _dependencyManager;
private static DependencyManager? _manager;
private static readonly object _locjObject = new();
private DependencyManager()
{
_dependencyManager = new ServiceDependencyContainer();
}
public static DependencyManager Instance { get { if (_manager == null) { lock (_locjObject) { _manager = new DependencyManager(); } } return _manager; } }
/// <summary>
/// Иницализация библиотек, в которых идут установки зависомстей
/// </summary>
public static void InitDependency()
{
var ext = ServiceProviderLoader.GetImplementationExtensions();
if (ext == null)
{
throw new ArgumentNullException("Отсутствуют компоненты для загрузки зависимостей по модулям");
}
// регистрируем зависимости
ext.RegisterServices();
}
/// <summary>
/// Регистрация логгера
/// </summary>
/// <param name="configure"></param>
public void AddLogging(Action<ILoggingBuilder> configure) => _dependencyManager.AddLogging(configure);
/// <summary>
/// Добавление зависимости
/// </summary>
/// <typeparam name="T"></typeparam>
/// <typeparam name="U"></typeparam>
public void RegisterType<T, U>(bool isSingle = false) where U : class, T where T : class => _dependencyManager.RegisterType<T, U>(isSingle);
/// <summary>
/// Добавление зависимости
/// </summary>
/// <typeparam name="T"></typeparam>
/// <typeparam name="U"></typeparam>
public void RegisterType<T>(bool isSingle = false) where T : class => _dependencyManager.RegisterType<T>(isSingle);
/// <summary>
/// Получение класса со всеми зависмостями
/// </summary>
/// <typeparam name="T"></typeparam>
/// <returns></returns>
public T Resolve<T>() => _dependencyManager.Resolve<T>();
}
}

View File

@ -0,0 +1,40 @@
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ShipyardContracts.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;
/// <summary>
/// Добавление зависимости
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="isSingle"></param>
void RegisterType<T>(bool isSingle) where T : class;
/// <summary>
/// Получение класса со всеми зависмостями
/// </summary>
/// <typeparam name="T"></typeparam>
/// <returns></returns>
T Resolve<T>();
}
}

View File

@ -0,0 +1,17 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ShipyardContracts.DI
{
public interface IImplementationExtension
{
public int Priority { get; }
/// <summary>
/// Регистрация сервисов
/// </summary>
public void RegisterServices();
}
}

View File

@ -0,0 +1,62 @@
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ShipyardContracts.DI
{
public class ServiceDependencyContainer : IDependencyContainer
{
private ServiceProvider? _serviceProvider;
private readonly ServiceCollection _serviceCollection;
public ServiceDependencyContainer()
{
_serviceCollection = new ServiceCollection();
}
public void AddLogging(Action<ILoggingBuilder> configure)
{
_serviceCollection.AddLogging(configure);
}
public void RegisterType<T, U>(bool isSingle) where U : class, T where T : class
{
if (isSingle)
{
_serviceCollection.AddSingleton<T, U>();
}
else
{
_serviceCollection.AddTransient<T, U>();
}
_serviceProvider = null;
}
public void RegisterType<T>(bool isSingle) where T : class
{
if (isSingle)
{
_serviceCollection.AddSingleton<T>();
}
else
{
_serviceCollection.AddTransient<T>();
}
_serviceProvider = null;
}
public T Resolve<T>()
{
if (_serviceProvider == null)
{
_serviceProvider = _serviceCollection.BuildServiceProvider();
}
return _serviceProvider.GetService<T>()!;
}
}
}

View File

@ -0,0 +1,55 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
namespace ShipyardContracts.DI
{
public class ServiceProviderLoader
{
/// <summary>
/// Загрузка всех классов-реализаций IImplementationExtension
/// </summary>
/// <returns></returns>
public static IImplementationExtension? GetImplementationExtensions()
{
IImplementationExtension? source = null;
var files = Directory.GetFiles(TryGetImplementationExtensionsFolder(), "*.dll", SearchOption.AllDirectories);
foreach (var file in files.Distinct())
{
Assembly asm = Assembly.LoadFrom(file);
foreach (var t in asm.GetExportedTypes())
{
if (t.IsClass && typeof(IImplementationExtension).IsAssignableFrom(t))
{
if (source == null)
{
source = (IImplementationExtension)Activator.CreateInstance(t)!;
}
else
{
var newSource = (IImplementationExtension)Activator.CreateInstance(t)!;
if (newSource.Priority > source.Priority)
{
source = newSource;
}
}
}
}
}
return source;
}
private static string TryGetImplementationExtensionsFolder()
{
var directory = new DirectoryInfo(Directory.GetCurrentDirectory());
while (directory != null && !directory.GetDirectories("ImplementationExtensions", SearchOption.AllDirectories).Any(x => x.Name == "ImplementationExtensions"))
{
directory = directory.Parent;
}
return $"{directory?.FullName}\\ImplementationExtensions";
}
}
}

View File

@ -0,0 +1,15 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ShipyardContracts.StoragesContracts
{
public interface IBackUpInfo
{
List<T>? GetList<T>() where T : class, new();
Type? GetTypeByModelInterface(string modelInterfaceName);
}
}

View File

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

View File

@ -25,5 +25,7 @@ namespace ShipyardContracts.ViewModels
[DisplayName("Текст")]
public string Body { get; set; } = string.Empty;
public int Id => throw new NotImplementedException();
}
}

View File

@ -0,0 +1,32 @@
using ShipyardContracts.StoragesContracts;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ShipyardDataBaseImplement.Implements
{
public class BackUpInfo : IBackUpInfo
{
public List<T>? GetList<T>() where T : class, new()
{
using var context = new ShipyardDataBase();
return context.Set<T>().ToList();
}
public Type? GetTypeByModelInterface(string modelInterfaceName)
{
var assembly = typeof(BackUpInfo).Assembly;
var types = assembly.GetTypes();
foreach (var type in types)
{
if (type.IsClass && type.GetInterface(modelInterfaceName) != null)
{
return type;
}
}
return null;
}
}
}

View File

@ -24,6 +24,7 @@ namespace ShipyardDataBaseImplement.Models
public string Subject { get; private set; } = string.Empty;
public string Body { get; private set; } = string.Empty;
public int Id => throw new NotImplementedException();
public static Message? Create(MessageInfoBindingModel model)
{

View File

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

View File

@ -23,6 +23,7 @@ namespace ShipyardFileImplement.Models
public string Subject { get; private set; } = string.Empty;
public string Body { get; private set; } = string.Empty;
public int Id => throw new NotImplementedException();
public static Message? Create(MessageInfoBindingModel model)
{
if (model == null)

View File

@ -0,0 +1,22 @@
using ShipyardContracts.StoragesContracts;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ShipyardListImplement_.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,28 @@
using ShipyardContracts.DI;
using ShipyardContracts.StoragesContracts;
using ShipyardListImplement.Implements;
using ShipyardListImplement_.Implements;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ShipyardListImplement_
{
public class ListImplementationExtension : IImplementationExtension
{
public int Priority => 0;
public void RegisterServices()
{
DependencyManager.Instance.RegisterType<IClientStorage, ClientStorage>();
DependencyManager.Instance.RegisterType<IDetailStorage, DetailStorage>();
DependencyManager.Instance.RegisterType<IImplementerStorage, ImplementerStorage>();
DependencyManager.Instance.RegisterType<IMessageInfoStorage, MessageInfoStorage>();
DependencyManager.Instance.RegisterType<IOrderStorage, OrderStorage>();
DependencyManager.Instance.RegisterType<IShipStorage, ShipStorage>();
DependencyManager.Instance.RegisterType<IBackUpInfo, BackUpInfo>();
}
}
}

View File

@ -22,6 +22,7 @@ namespace ShipyardListImplement_.Models
public string Subject { get; private set; } = string.Empty;
public string Body { get; private set; } = string.Empty;
public int Id => throw new NotImplementedException();
public static Message? Create(MessageInfoBindingModel model)
{

View File

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