PIbd-22. Stroev V.M. Lab Work 08 #10

Closed
StroevVladimir wants to merge 3 commits from Lab8 into Lab7
45 changed files with 984 additions and 220 deletions
Showing only changes of commit 9f89c83852 - Show all commits

View File

@ -0,0 +1,54 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace PlumbingRepairContracts.Attributes
{
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 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

@ -3,6 +3,7 @@ using PlumbingRepairContracts.BusinessLogicsContracts;
using PlumbingRepairContracts.SearchModels;
using Microsoft.Extensions.Logging;
using System.Windows.Forms;
using PlumbingRepairContracts.Attributes;
namespace PlumbingRepairView
{
@ -28,18 +29,12 @@ namespace PlumbingRepairView
{
try
{
var list = _logic.ReadList(null);
if (list != null)
{
dataGridView.DataSource = list;
dataGridView.Columns["Id"].Visible = false;
dataGridView.Columns["ClientFIO"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
}
_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);
}
}

View File

@ -1,7 +1,7 @@
using Microsoft.Extensions.Logging;
using PlumbingRepairContracts.BusinessLogicsContracts;
using PlumbingRepairContracts.BindingModels;
using PlumbingRepairContracts.SearchModels;
using PlumbingRepairContracts.DI;
using System.Windows.Forms;
namespace PlumbingRepairView
@ -18,70 +18,79 @@ namespace PlumbingRepairView
_logger = logger;
_logic = logic;
}
private void FormComponent_Load(object sender, EventArgs e)
private void FormComponents_Load(object sender, EventArgs e)
{
if (_id.HasValue)
LoadData();
}
private void LoadData()
{
try
{
_logger.LogInformation("Ïîëó÷åíèå êîìïîíåíòà");
var view = _logic.ReadElement(new ComponentSearchModel
{
Id = _id.Value
});
if (view != null)
{
textBoxName.Text = view.ComponentName;
textBoxCost.Text = view.Cost.ToString();
}
DataGridView.FillandConfigGrid(_logic.ReadList(null));
_logger.LogInformation("Çàãðóçêà êîìïîíåíòîâ");
}
catch (Exception ex)
{
_logger.LogError(ex, "Îøèáêà ïîëó÷åíèÿ êîìïîíåíòà");
MessageBox.Show(ex.Message, "Îøèáêà", MessageBoxButtons.OK,
MessageBoxIcon.Error);
_logger.LogError(ex, "Îøèáêà çàãðóçêè êîìïîíåíòîâ");
MessageBox.Show(ex.Message, "Îøèáêà", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
private void ButtonSave_Click(object sender, EventArgs e)
private void AddButton_Click(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(textBoxName.Text))
var form = DependencyManager.Instance.Resolve<FormComponent>();
if (form.ShowDialog() == DialogResult.OK)
{
MessageBox.Show("Çàïîëíèòå íàçâàíèå", "Îøèáêà",
MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
LoadData();
}
_logger.LogInformation("Ñîõðàíåíèå êîìïîíåíòà");
}
private void ChangeButton_Click(object sender, EventArgs e)
{
if (DataGridView.SelectedRows.Count == 1)
{
var form = DependencyManager.Instance.Resolve<FormComponent>();
form.Id = Convert.ToInt32(DataGridView.SelectedRows[0].Cells["Id"].Value);
if (form.ShowDialog() == DialogResult.OK)
{
LoadData();
}
}
}
private void DeleteButton_Click(object sender, EventArgs e)
{
if (DataGridView.SelectedRows.Count == 1)
{
if (MessageBox.Show("Óäàëèòü çàïèñü?", "Âîïðîñ", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
{
int id = Convert.ToInt32(DataGridView.SelectedRows[0].Cells["Id"].Value);
_logger.LogInformation("Óäàëåíèå êîìïîíåíòà");
try
{
var model = new ComponentBindingModel
if (!_logic.Delete(new ComponentBindingModel
{
Id = _id ?? 0,
ComponentName = textBoxName.Text,
Cost = Convert.ToDouble(textBoxCost.Text)
};
var operationResult = _id.HasValue ? _logic.Update(model) :
_logic.Create(model);
if (!operationResult)
Id = id
}))
{
throw new Exception("Îøèáêà ïðè ñîõðàíåíèè. Äîïîëíèòåëüíàÿ èíôîðìàöèÿ â ëîãàõ.");
throw new Exception("Îøèáêà ïðè óäàëåíèè. Äîïîëíèòåëüíàÿ èíôîðìàöèÿ â ëîãàõ.");
}
MessageBox.Show("Ñîõðàíåíèå ïðîøëî óñïåøíî", "Ñîîáùåíèå",
MessageBoxButtons.OK, MessageBoxIcon.Information);
DialogResult = DialogResult.OK;
Close();
LoadData();
}
catch (Exception ex)
{
_logger.LogError(ex, "Îøèáêà ñîõðàíåíèÿ êîìïîíåíòà");
MessageBox.Show(ex.Message, "Îøèáêà", MessageBoxButtons.OK,
MessageBoxIcon.Error);
_logger.LogError(ex, "Îøèáêà óäàëåíèÿ êîìïîíåíòà");
MessageBox.Show(ex.Message, "Îøèáêà", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void ButtonCancel_Click(object sender, EventArgs e)
}
}
private void UpdateButton_Click(object sender, EventArgs e)
{
DialogResult = DialogResult.Cancel;
Close();
LoadData();
}
}
}

View File

@ -1,6 +1,7 @@
using Microsoft.Extensions.Logging;
using PlumbingRepairContracts.BindingModels;
using PlumbingRepairContracts.BusinessLogicsContracts;
using PlumbingRepairContracts.DI;
using PlumbingRepairContracts.SearchModels;
using System;
using System.Collections.Generic;
@ -28,79 +29,83 @@ namespace PlumbingRepair
_logic = logic;
}
private void ButtonSave_Click(object sender, EventArgs e)
private void AddButton_Click(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(PasswordTextBox.Text))
var form = DependencyManager.Instance.Resolve<FormImplementer>();
if (form.ShowDialog() == DialogResult.OK)
{
MessageBox.Show("Заполните пароль", "Ошибка",
MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
if (string.IsNullOrEmpty(FIOTextBox.Text))
{
MessageBox.Show("Заполните фио", "Ошибка",
MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
_logger.LogInformation("Сохранение исполнителя");
try
{
var model = new ImplementerBindingModel
{
Id = _id ?? 0,
ImplementerFIO = FIOTextBox.Text,
Password = PasswordTextBox.Text,
Qualification = (int)QualificationNumericUpDown.Value,
WorkExperience = (int)WorkExpNumericUpDown.Value,
};
var operationResult = _id.HasValue ? _logic.Update(model) : _logic.Create(model);
if (!operationResult)
{
throw new Exception("Ошибка при сохранении. Дополнительная информация в логах.");
}
MessageBox.Show("Сохранение прошло успешно", "Сообщение",
MessageBoxButtons.OK, MessageBoxIcon.Information);
DialogResult = DialogResult.OK;
Close();
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка сохранения исполнителя");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
LoadData();
}
}
private void ButtonCancel_Click(object sender, EventArgs e)
private void ChangeButton_Click(object sender, EventArgs e)
{
DialogResult = DialogResult.Cancel;
Close();
if (DataGridView.SelectedRows.Count == 1)
{
var form = DependencyManager.Instance.Resolve<FormImplementer>();
form.Id = Convert.ToInt32(DataGridView.SelectedRows[0].Cells["Id"].Value);
if (form.ShowDialog() == DialogResult.OK)
{
LoadData();
}
}
}
private void FormImplementer_Load(object sender, EventArgs e)
private void DeleteButton_Click(object sender, EventArgs e)
{
if (_id.HasValue)
if (DataGridView.SelectedRows.Count == 1)
{
if (MessageBox.Show("Удалить запись?", "Вопрос", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
{
int id = Convert.ToInt32(DataGridView.SelectedRows[0].Cells["Id"].Value);
_logger.LogInformation("Удаление исполнителя");
try
{
_logger.LogInformation("Получение исполнителя");
var view = _logic.ReadElement(new ImplementerSearchModel
if (!_logic.Delete(new ImplementerBindingModel
{
Id = _id.Value
});
if (view != null)
Id = id
}))
{
FIOTextBox.Text = view.ImplementerFIO;
PasswordTextBox.Text = view.Password;
QualificationNumericUpDown.Value = view.Qualification;
WorkExpNumericUpDown.Value = view.WorkExperience;
throw new Exception("Ошибка при удалении. Дополнительная информация в логах.");
}
LoadData();
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка получения исполнителя");
_logger.LogError(ex, "Ошибка удаления исполнителя");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
}
private void UpdateButton_Click(object sender, EventArgs e)
{
LoadData();
}
private void FormImplementers_Load(object sender, EventArgs e)
{
LoadData();
}
private void LoadData()
{
try
{
DataGridView.FillandConfigGrid(_logic.ReadList(null));
_logger.LogInformation("Загрузка исполнителей");
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка загрузки исполнителей");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
}

View File

@ -5,35 +5,29 @@ using PlumbingRepairContracts.StoragesContracts;
using PlumbingRepairBusinessLogic.OfficePackage.Implements;
using PlumbingRepairBusinessLogic.OfficePackage;
using PlumbingRepairDataBaseImplement.Implements;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using NLog.Extensions.Logging;
using PlumbingRepairBusinessLogic.BusinessLogics;
using PlumbingRepair;
using PlumbingRepairBusinessLogic.MailWorker;
using PlumbingRepairContracts.BindingModels;
using PlumbingRepairContracts.DI;
using PlumbingRepair;
namespace PlumbingRepairView
{
internal static class Program
{
private static ServiceProvider? _serviceProvider;
public static ServiceProvider? ServiceProvider => _serviceProvider;
/// <summary>
/// The main entry point for the application.
/// </summary>
[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();
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,
@ -48,53 +42,50 @@ namespace PlumbingRepairView
}
catch (Exception ex)
{
var logger = _serviceProvider.GetService<ILogger>();
var logger = DependencyManager.Instance.Resolve<ILogger>();
logger?.LogError(ex, "Error");
}
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<IComponentStorage, ComponentStorage>();
services.AddTransient<IOrderStorage, OrderStorage>();
services.AddTransient<IWorkStorage, WorkStorage>();
services.AddTransient<IClientStorage, ClientStorage>();
services.AddTransient<IImplementerStorage, ImplementerStorage>();
services.AddTransient<IMessageInfoStorage, MessageInfoStorage>();
services.AddTransient<IComponentLogic, ComponentLogic>();
services.AddTransient<IOrderLogic, OrderLogic>();
services.AddTransient<IWorkLogic, WorkLogic>();
services.AddTransient<IReportLogic, ReportLogic>();
services.AddTransient<IClientLogic, ClientLogic>();
services.AddTransient<IImplementerLogic, ImplementerLogic>();
services.AddTransient<IWorkProcess, WorkModeling>();
services.AddTransient<IMessageInfoLogic, MessageInfoLogic>();
services.AddSingleton<AbstractMailWorker, MailKitWorker>();
DependencyManager.Instance.RegisterType<IComponentLogic, ComponentLogic>();
DependencyManager.Instance.RegisterType<IOrderLogic, OrderLogic>();
DependencyManager.Instance.RegisterType<IWorkLogic, WorkLogic>();
DependencyManager.Instance.RegisterType<IReportLogic, ReportLogic>();
DependencyManager.Instance.RegisterType<IClientLogic, ClientLogic>();
DependencyManager.Instance.RegisterType<IImplementerLogic, ImplementerLogic>();
DependencyManager.Instance.RegisterType<IMessageInfoLogic, MessageInfoLogic>();
DependencyManager.Instance.RegisterType<IWorkProcess, WorkModeling>();
DependencyManager.Instance.RegisterType<IBackUpLogic, BackUpLogic>();
services.AddTransient<AbstractSaveToWord, SaveToWord>();
services.AddTransient<AbstractSaveToExcel, SaveToExcel>();
services.AddTransient<AbstractSaveToPdf, SaveToPdf>();
DependencyManager.Instance.RegisterType<AbstractMailWorker, MailKitWorker>(true);
services.AddTransient<FormMain>();
services.AddTransient<FormComponent>();
services.AddTransient<FormComponents>();
services.AddTransient<FormCreateOrder>();
services.AddTransient<FormWork>();
services.AddTransient<FormWorkComponent>();
services.AddTransient<FormWorks>();
services.AddTransient<FormReportWorkComponents>();
services.AddTransient<FormReportOrders>();
services.AddTransient<FormClients>();
services.AddTransient<FormImplementer>();
services.AddTransient<FormImplementers>();
services.AddTransient<FormMails>();
DependencyManager.Instance.RegisterType<AbstractSaveToExcel, SaveToExcel>();
DependencyManager.Instance.RegisterType<AbstractSaveToWord, SaveToWord>();
DependencyManager.Instance.RegisterType<AbstractSaveToPdf, SaveToPdf>();
DependencyManager.Instance.RegisterType<FormMain>();
DependencyManager.Instance.RegisterType<FormComponent>();
DependencyManager.Instance.RegisterType<FormComponents>();
DependencyManager.Instance.RegisterType<FormCreateOrder>();
DependencyManager.Instance.RegisterType<FormWork>();
DependencyManager.Instance.RegisterType<FormWorkComponent>();
DependencyManager.Instance.RegisterType<FormWorks>();
DependencyManager.Instance.RegisterType<FormReportWorkComponents>();
DependencyManager.Instance.RegisterType<FormReportOrders>();
DependencyManager.Instance.RegisterType<FormClients>();
DependencyManager.Instance.RegisterType<FormImplementers>();
DependencyManager.Instance.RegisterType<FormImplementer>();
DependencyManager.Instance.RegisterType<FormMails>();
}
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,112 @@
using Microsoft.Extensions.Logging;
using PlumbingRepairContracts.BindingModels;
using PlumbingRepairContracts.BusinessLogicsContracts;
using PlumbingRepairContracts.StoragesContracts;
using PlumbingRepairDataModels;
using System.IO.Compression;
using System.Reflection;
using System.Runtime.Serialization.Json;
namespace PlumbingRepairBusinessLogic.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 (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,29 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace PlumbingRepairContracts.Attributes
{
[AttributeUsage(AttributeTargets.Property)]
public class ColumnAttribute : Attribute
{
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;
}
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,20 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace PlumbingRepairContracts.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 PlumbingRepairContracts.BindingModels
{
public class BackUpSaveBindingModel
{
public string FolderName { get; set; } = string.Empty;
}
}

View File

@ -15,5 +15,6 @@ namespace PlumbingRepairContracts.BindingModels
public string Subject { get; set; } = string.Empty;
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 PlumbingRepairContracts.BindingModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace PlumbingRepairContracts.BusinessLogicsContracts
{
public interface IBackUpLogic
{
void CreateBackUp(BackUpSaveBindingModel model);
}
}

View File

@ -0,0 +1,43 @@
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace PlumbingRepairContracts.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; } }
public static void InitDependency()
{
var ext = ServiceProviderLoader.GetImplementationExtensions();
if (ext == null)
{
throw new ArgumentNullException("Отсутствуют компоненты для загрузки зависимостей по модулям");
}
// регистрируем зависимости
ext.RegisterServices();
}
public void AddLogging(Action<ILoggingBuilder> configure) => _dependencyManager.AddLogging(configure);
public void RegisterType<T, U>(bool isSingle = false) where U : class, T where T : class => _dependencyManager.RegisterType<T, U>(isSingle);
public void RegisterType<T>(bool isSingle = false) where T : class => _dependencyManager.RegisterType<T>(isSingle);
public T Resolve<T>() => _dependencyManager.Resolve<T>();
}
}

View File

@ -0,0 +1,17 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
namespace PlumbingRepairContracts.DI
{
public interface IDependencyContainer
{
void AddLogging(Action<ILoggingBuilder> configure);
void RegisterType<T, U>(bool isSingle) where U : class, T where T : class;
void RegisterType<T>(bool isSingle) where T : class;
T Resolve<T>();
}
}

View File

@ -0,0 +1,14 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace PlumbingRepairContracts.DI
{
public interface IImplementationExtension
{
public int Priority { get; }
public void RegisterServices();
}
}

View File

@ -0,0 +1,64 @@
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 PlumbingRepairContracts.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,57 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
namespace PlumbingRepairContracts.DI
{
public class ServiceProviderLoader
{
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,44 @@
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using Unity.Microsoft.Logging;
using Unity;
namespace PlumbingRepairContracts.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 isSingle) where T : class
{
_container.RegisterType<T>(isSingle ? TypeLifetime.Singleton : TypeLifetime.Transient);
}
public T Resolve<T>()
{
return _container.Resolve<T>();
}
void IDependencyContainer.RegisterType<T, U>(bool isSingle)
{
_container.RegisterType<T, U>(isSingle ? TypeLifetime.Singleton : TypeLifetime.Transient);
}
}
}

View File

@ -6,6 +6,12 @@
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<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="..\PlumbingRepairDataModels\PlumbingRepairDataModels.csproj" />
</ItemGroup>

View File

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

View File

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

View File

@ -4,16 +4,18 @@ using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using PlumbingRepairContracts.Attributes;
using PlumbingRepairDataModels.Models;
namespace PlumbingRepairContracts.ViewModels
{
public class ComponentViewModel : IComponentModel
{
[Column(visible: false)]
public int Id { get; set; }
[DisplayName("Название компонента")]
[Column("Название компонента", gridViewAutoSize: GridViewAutoSize.Fill, isUseAutoSize: true)]
public string ComponentName { get; set; } = string.Empty;
[DisplayName("Цена")]
[Column("Цена", width: 80)]
public double Cost { get; set; }
}
}

View File

@ -1,4 +1,5 @@
using PlumbingRepairDataModels.Models;
using PlumbingRepairContracts.Attributes;
using PlumbingRepairDataModels.Models;
using System;
using System.Collections.Generic;
using System.ComponentModel;
@ -12,16 +13,16 @@ namespace PlumbingRepairContracts.ViewModels
{
public int Id { get; set; }
[DisplayName("ФИО исполнителя")]
[Column("ФИО исполнителя", gridViewAutoSize: GridViewAutoSize.Fill, isUseAutoSize: true)]
public string ImplementerFIO { get; set; } = string.Empty;
[DisplayName("Пароль")]
[Column("Пароль", width: 150)]
public string Password { get; set; } = string.Empty;
[DisplayName("Стаж работы")]
[Column("Стаж работы", gridViewAutoSize: GridViewAutoSize.AllCells, isUseAutoSize: true)]
public int WorkExperience { get; set; }
[DisplayName("Квалификация")]
[Column("Квалификация", gridViewAutoSize: GridViewAutoSize.AllCells, isUseAutoSize: true)]
public int Qualification { get; set; }
}
}

View File

@ -1,4 +1,5 @@
using PlumbingRepairDataModels.Models;
using PlumbingRepairContracts.Attributes;
using PlumbingRepairDataModels.Models;
using System;
using System.Collections.Generic;
using System.ComponentModel;
@ -10,20 +11,24 @@ namespace PlumbingRepairContracts.ViewModels
{
public class MessageInfoViewModel : IMessageInfoModel
{
[Column(visible: false)]
public string MessageId { get; set; } = string.Empty;
[Column(visible: false)]
public int? ClientId { get; set; }
[DisplayName("Имя отправителя")]
[Column("Имя отправителя", gridViewAutoSize: GridViewAutoSize.DisplayedCells, isUseAutoSize: true)]
public string SenderName { get; set; } = string.Empty;
[DisplayName("Дата отправления")]
[Column("Дата отправления", width: 100)]
public DateTime DateDelivery { get; set; }
[DisplayName("Тема")]
[Column("Тема", width: 150)]
public string Subject { get; set; } = string.Empty;
[DisplayName("Содержание")]
[Column("Содержание", gridViewAutoSize: GridViewAutoSize.Fill, isUseAutoSize: true)]
public string Body { get; set; } = string.Empty;
[Column(visible: false)]
public int Id => throw new NotImplementedException();
}
}

View File

@ -1,4 +1,5 @@
using PlumbingRepairDataModels.Enums;
using PlumbingRepairContracts.Attributes;
using PlumbingRepairDataModels.Enums;
using PlumbingRepairDataModels.Models;
using System;
using System.Collections.Generic;
@ -11,27 +12,29 @@ namespace PlumbingRepairContracts.ViewModels
{
public class OrderViewModel : IOrderModel
{
[DisplayName("Номер")]
[Column("Номер", gridViewAutoSize: GridViewAutoSize.AllCells, isUseAutoSize: true)]
public int Id { get; set; }
[Column(visible: false)]
public int WorkId { get; set; }
[DisplayName("Работа")]
[Column("Название изделия", gridViewAutoSize: GridViewAutoSize.AllCells, isUseAutoSize: true)]
public string WorkName { get; set; } = string.Empty;
[DisplayName("Клиент")]
[Column(visible: false)]
public int ClientId { get; set; }
[DisplayName("ФИО клиента")]
[Column("ФИО клиента", gridViewAutoSize: GridViewAutoSize.AllCells, isUseAutoSize: true)]
public string ClientFIO { get; set; } = string.Empty;
[Column(visible: false)]
public int? ImplementerId { get; set; }
[DisplayName("Исполнитель")]
[Column("ФИО исполнителя", gridViewAutoSize: GridViewAutoSize.AllCells, isUseAutoSize: true)]
public string ImplementerFIO { get; set; } = string.Empty;
[DisplayName("Количество")]
[Column("Количество", gridViewAutoSize: GridViewAutoSize.AllCells, isUseAutoSize: true)]
public int Count { get; set; }
[DisplayName("Сумма")]
[Column("Сумма", gridViewAutoSize: GridViewAutoSize.AllCells, isUseAutoSize: true)]
public double Sum { get; set; }
[DisplayName("Статус")]
[Column("Статус", gridViewAutoSize: GridViewAutoSize.AllCells, isUseAutoSize: true)]
public OrderStatus Status { get; set; } = OrderStatus.Неизвестен;
[DisplayName("Дата создания")]
[Column("Дата создания", width: 130)]
public DateTime DateCreate { get; set; } = DateTime.SpecifyKind(DateTime.Now, DateTimeKind.Utc);
[DisplayName("Дата выполнения")]
[Column("Дата выполнения", width: 130)]
public DateTime? DateImplement { get; set; }
public string ClientEmail { get; set; } = string.Empty;
}

View File

@ -1,4 +1,5 @@
using PlumbingRepairDataModels.Models;
using PlumbingRepairContracts.Attributes;
using PlumbingRepairDataModels.Models;
using System;
using System.Collections.Generic;
using System.ComponentModel;
@ -10,11 +11,13 @@ namespace PlumbingRepairContracts.ViewModels
{
public class WorkViewModel : IWorkModel
{
[Column(visible: false)]
public int Id { get; set; }
[DisplayName("Название работы")]
[Column("Название изделия", gridViewAutoSize: GridViewAutoSize.Fill, isUseAutoSize: true)]
public string WorkName { get; set; } = string.Empty;
[DisplayName("Цена")]
[Column("Цена", width: 100)]
public double Price { get; set; }
[Column(visible: false)]
public Dictionary<int, (IComponentModel, int)> WorkComponents
{ get; set; } = new();
}

View File

@ -0,0 +1,27 @@
using PlumbingRepairContracts.DI;
using PlumbingRepairContracts.StoragesContracts;
using PlumbingRepairDataBaseImplement.Implements;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace PlumbingRepairDataBaseImplement
{
public class DatabaseImplementationExtension : IImplementationExtension
{
public int Priority => 2;
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<IWorkStorage, WorkStorage>();
DependencyManager.Instance.RegisterType<IBackUpInfo, BackUpInfo>();
}
}
}

View File

@ -0,0 +1,33 @@
using PlumbingRepairContracts.StoragesContracts;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace PlumbingRepairDataBaseImplement.Implements
{
public class BackUpInfo : IBackUpInfo
{
public List<T>? GetList<T>() where T : class, new()
{
using var context = new PlumbingRepairDataBase();
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

@ -8,26 +8,29 @@ using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Runtime.Serialization;
namespace PlumbingRepairDataBaseImplement.Models
{
[DataContract]
public class Client : IClientModel
{
[DataMember]
public int Id { get; private set; }
[Required]
[DataMember]
public string ClientFIO { get; private set; } = string.Empty;
[Required]
[DataMember]
public string Email { get; private set; } = string.Empty;
[Required]
[DataMember]
public string Password { get; private set; } = string.Empty;
[ForeignKey("ClientId")]
public virtual List<Order> Orders { get; set; } = new();
[ForeignKey("ClientId")]
public virtual List<Message> Messages { get; set; } = new();
public static Client? Create(ClientBindingModel? model)
{
if (model == null)

View File

@ -3,15 +3,20 @@ using System.ComponentModel.DataAnnotations;
using PlumbingRepairDataModels.Models;
using PlumbingRepairContracts.ViewModels;
using PlumbingRepairContracts.BindingModels;
using System.Runtime.Serialization;
namespace PlumbingRepairDataBaseImplement.Models
{
[DataContract]
public class Component : IComponentModel
{
[DataMember]
public int Id { get; private set; }
[Required]
[DataMember]
public string ComponentName { get; private set; } = string.Empty;
[Required]
[DataMember]
public double Cost { get; set; }
[ForeignKey("ComponentId")]
public virtual List<WorkComponent> WorkComponents { get; set; } = new();

View File

@ -8,23 +8,30 @@ using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Runtime.Serialization;
namespace PlumbingRepairDataBaseImplement.Models
{
[DataContract]
public class Implementer : IImplementerModel
{
[DataMember]
public int Id { get; set; }
[Required]
[DataMember]
public string ImplementerFIO { get; set; } = string.Empty;
[Required]
[DataMember]
public string Password { get; set; } = string.Empty;
[Required]
[DataMember]
public int WorkExperience { get; set; }
[Required]
[DataMember]
public int Qualification { get; set; }
[ForeignKey("ImplementerId")]

View File

@ -5,19 +5,27 @@ using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
namespace PlumbingRepairDataBaseImplement.Models
{
[DataContract]
public class Message : IMessageInfoModel
{
[Key]
[DataMember]
public string MessageId { get; private set; } = string.Empty;
[DataMember]
public int? ClientId { get; private set; }
[DataMember]
public string SenderName { get; private set; } = string.Empty;
[DataMember]
public DateTime DateDelivery { get; private set; } = DateTime.SpecifyKind(DateTime.Now, DateTimeKind.Utc);
[DataMember]
public string Subject { get; private set; } = string.Empty;
[DataMember]
public string Body { get; private set; } = string.Empty;
public virtual Client? Client { get; set; }
@ -48,5 +56,6 @@ namespace PlumbingRepairDataBaseImplement.Models
SenderName = SenderName,
DateDelivery = DateDelivery
};
public int Id => throw new NotImplementedException();
}
}

View File

@ -6,33 +6,39 @@ using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
namespace PlumbingRepairDataBaseImplement.Models
{
[DataContract]
public class Order : IOrderModel
{
[DataMember]
public int Id { get; private set; }
[DataMember]
public int WorkId { get; private set; }
[Required]
[DataMember]
public int ClientId { get; private set; }
[DataMember]
public int? ImplementerId { get; set; }
[DataMember]
public string WorkName { get; private set; } = string.Empty;
[Required]
[DataMember]
public int Count { get; private set; }
[Required]
[DataMember]
public double Sum { get; private set; }
[Required]
[DataMember]
public OrderStatus Status { get; private set; } = OrderStatus.Неизвестен;
[Required]
[DataMember]
public DateTime DateCreate { get; private set; }
[DataMember]
public DateTime? DateImplement { get; private set; }
public virtual Work Work { get; set; }

View File

@ -8,19 +8,25 @@ using System.Text;
using System.Threading.Tasks;
using PlumbingRepairContracts.BindingModels;
using PlumbingRepairContracts.ViewModels;
using System.Runtime.Serialization;
namespace PlumbingRepairDataBaseImplement.Models
{
[DataContract]
public class Work : IWorkModel
{
[DataMember]
public int Id { get; set; }
[Required]
[DataMember]
public string WorkName { get; set; } = string.Empty;
[Required]
[DataMember]
public double Price { get; set; }
private Dictionary<int, (IComponentModel, int)>? _workComponents =
null;
[NotMapped]
[DataMember]
public Dictionary<int, (IComponentModel, int)> WorkComponents
{
get

View File

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

View File

@ -0,0 +1,27 @@
using PlumbingRepairContracts.DI;
using PlumbingRepairContracts.StoragesContracts;
using PlumbingRepairFileImplement.Implements;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace PlumbingRepairFileImplement
{
public class FileImplementationExtension : IImplementationExtension
{
public int Priority => 1;
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<IWorkStorage, WorkStorage>();
DependencyManager.Instance.RegisterType<IBackUpInfo, BackUpInfo>();
}
}
}

View File

@ -0,0 +1,37 @@
using PlumbingRepairContracts.StoragesContracts;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace PlumbingRepairFileImplement.Implements
{
public class BackUpInfo : IBackUpInfo
{
public List<T>? GetList<T>() where T : class, new()
{
var source = DataFileSingleton.GetInstance();
return (List<T>?)source.GetType().GetProperties()
.FirstOrDefault(x => x.PropertyType.IsGenericType && x.PropertyType.GetGenericArguments()[0] == typeof(T))
?.GetValue(source);
}
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

@ -4,17 +4,23 @@ using PlumbingRepairDataModels.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;
namespace PlumbingRepairFileImplement.Models
{
[DataContract]
public class Client : IClientModel
{
[DataMember]
public int Id { get; private set; }
[DataMember]
public string ClientFIO { get; private set; } = string.Empty;
[DataMember]
public string Email { get; private set; } = string.Empty;
[DataMember]
public string Password { get; private set; } = string.Empty;
public static Client? Create(ClientBindingModel model)
{

View File

@ -1,14 +1,19 @@
using PlumbingRepairContracts.BindingModels;
using PlumbingRepairContracts.ViewModels;
using PlumbingRepairDataModels.Models;
using System.Runtime.Serialization;
using System.Xml.Linq;
namespace PlumbingRepairFileImplement.Models
{
[DataContract]
public class Component : IComponentModel
{
[DataMember]
public int Id { get; private set; }
[DataMember]
public string ComponentName { get; private set; } = string.Empty;
[DataMember]
public double Cost { get; set; }
public static Component? Create(ComponentBindingModel model)
{

View File

@ -4,22 +4,25 @@ using PlumbingRepairDataModels.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;
namespace PlumbingRepairFileImplement.Models
{
[DataContract]
public class Implementer : IImplementerModel
{
[DataMember]
public string ImplementerFIO { get; set; } = string.Empty;
[DataMember]
public string Password { get; set; } = string.Empty;
[DataMember]
public int WorkExperience { get; set; }
[DataMember]
public int Qualification { get; set; }
[DataMember]
public int Id { get; set; }
public static Implementer? Create(ImplementerBindingModel? model)

View File

@ -4,24 +4,27 @@ using PlumbingRepairDataModels.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;
namespace PlumbingRepairFileImplement.Models
{
[DataContract]
public class Message : IMessageInfoModel
{
[DataMember]
public string MessageId { get; private set; } = string.Empty;
[DataMember]
public int? ClientId { get; private set; }
[DataMember]
public string SenderName { get; private set; } = string.Empty;
[DataMember]
public DateTime DateDelivery { get; private set; } = DateTime.Now;
[DataMember]
public string Subject { get; private set; } = string.Empty;
[DataMember]
public string Body { get; private set; } = string.Empty;
public static Message? Create(MessageInfoBindingModel model)
@ -76,5 +79,6 @@ namespace PlumbingRepairFileImplement.Models
new XAttribute("SenderName", SenderName),
new XAttribute("DateDelivery", DateDelivery.ToString())
);
public int Id => throw new NotImplementedException();
}
}

View File

@ -5,23 +5,35 @@ using PlumbingRepairDataModels.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;
namespace PlumbingRepairFileImplement.Models
{
[DataContract]
public class Order : IOrderModel
{
[DataMember]
public int Id { get; private set; }
[DataMember]
public int WorkId { get; private set; }
[DataMember]
public int ClientId { get; private set; }
[DataMember]
public int? ImplementerId { get; private set; }
[DataMember]
public String WorkName { get; private set; } = string.Empty;
[DataMember]
public int Count { get; private set; }
[DataMember]
public double Sum { get; private set; }
[DataMember]
public OrderStatus Status { get; private set; } = OrderStatus.Неизвестен;
[DataMember]
public DateTime DateCreate { get; private set; }
[DataMember]
public DateTime? DateImplement { get; private set; }
public static Order? Create(OrderBindingModel? model)
@ -50,6 +62,7 @@ namespace PlumbingRepairFileImplement.Models
{
return null;
}
DateTime.TryParse(element.Element("DateImplement")!.Value, out DateTime dateImpl);
return new Order()
{
Id = Convert.ToInt32(element.Attribute("Id")!.Value),
@ -59,10 +72,9 @@ namespace PlumbingRepairFileImplement.Models
ImplementerId = Convert.ToInt32(element.Element("ImplementerId")!.Value),
Count = Convert.ToInt32(element.Element("Count")!.Value),
Sum = Convert.ToDouble(element.Element("Sum")!.Value),
Status = (OrderStatus)Enum.Parse(typeof(OrderStatus), element.Element("Status")!.Value),
DateCreate = Convert.ToDateTime(element.Element("DateCreate")!.Value),
DateImplement = string.IsNullOrEmpty(element.Element("DateImplement")!.Value) ? null
: Convert.ToDateTime(element.Element("DateImplement")!.Value)
Status = (OrderStatus)Convert.ToInt32(element.Element("Status")!.Value),
DateCreate = DateTime.ParseExact(element.Element("DateCreate")!.Value, "G", null),
DateImplement = dateImpl
};
}
public void Update(OrderBindingModel? model)

View File

@ -4,19 +4,25 @@ using PlumbingRepairDataModels.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;
namespace PlumbingRepairFileImplement.Models
{
[DataContract]
public class Work : IWorkModel
{
[DataMember]
public int Id { get; private set; }
[DataMember]
public string WorkName { get; private set; } = string.Empty;
[DataMember]
public double Price { get; private set; }
public Dictionary<int, int> Components { get; private set; } = new();
private Dictionary<int, (IComponentModel, int)>? _workComponents = null;
[DataMember]
public Dictionary<int, (IComponentModel, int)> WorkComponents
{
get

View File

@ -0,0 +1,22 @@
using PlumbingRepairContracts.StoragesContracts;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace PlumbingRepairListImplement.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,27 @@
using PlumbingRepairContracts.DI;
using PlumbingRepairContracts.StoragesContracts;
using PlumbingRepairListImplement.Implements;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace PlumbingRepairListImplement
{
public class ListImplementationExtension : 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<IWorkStorage, WorkStorage>();
DependencyManager.Instance.RegisterType<IBackUpInfo, BackUpInfo>();
}
}
}

View File

@ -49,5 +49,6 @@ namespace PlumbingRepairListImplement.Models
ClientId = ClientId,
MessageId = MessageId
};
public int Id => throw new NotImplementedException();
}
}