Agliullov D. A. Lab Work 8 Hard #22

Closed
d.agliullov wants to merge 13 commits from Lab8_Hard into Lab7_Hard
62 changed files with 1179 additions and 380 deletions

3
.gitignore vendored
View File

@ -14,6 +14,9 @@
# User-specific files (MonoDevelop/Xamarin Studio) # User-specific files (MonoDevelop/Xamarin Studio)
*.userprefs *.userprefs
# dll файлы
*.dll
# Mono auto generated files # Mono auto generated files
mono_crash.* mono_crash.*

View File

@ -0,0 +1,103 @@
using ConfectioneryContracts.BindingModels;
using ConfectioneryContracts.BusinessLogicsContracts;
using ConfectioneryContracts.StoragesContract;
using ConfectioneryDataModels;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.IO.Compression;
using System.Linq;
using System.Reflection;
using System.Runtime.Serialization.Json;
using System.Text;
using System.Threading.Tasks;
namespace ConfectioneryBusinessLogic
{
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

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

View File

@ -0,0 +1,39 @@
using ConfectioneryBusinessLogic.BusinessLogics;
using ConfectioneryBusinessLogic.MailWorker;
using ConfectioneryBusinessLogic.OfficePackage.Implements;
using ConfectioneryBusinessLogic.OfficePackage;
using ConfectioneryContracts.BusinessLogicsContracts;
using ConfectioneryContracts.DI;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConfectioneryBusinessLogic
{
public class ImplementationBusinessLogicExtension : IImplementationBusinessLogicExtension
{
public int Priority => 0;
public void RegisterServices()
{
DependencyManager.Instance.RegisterType<IComponentLogic, ComponentLogic>();
DependencyManager.Instance.RegisterType<IOrderLogic, OrderLogic>();
DependencyManager.Instance.RegisterType<IPastryLogic, PastryLogic>();
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>();
DependencyManager.Instance.RegisterType<IShopLogic, ShopLogic>();
DependencyManager.Instance.RegisterType<AbstractMailWorker, MailKitWorker>(true);
DependencyManager.Instance.RegisterType<AbstractSaveToExcel, SaveToExcel>();
DependencyManager.Instance.RegisterType<AbstractSaveToWord, SaveToWord>();
DependencyManager.Instance.RegisterType<AbstractSaveToPdf, SaveToPdf>();
}
}
}

View File

@ -1,9 +1,4 @@
using ConfectioneryContracts.ViewModels; using ConfectioneryContracts.ViewModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConfectioneryBusinessLogic.OfficePackage.HelperModels namespace ConfectioneryBusinessLogic.OfficePackage.HelperModels
{ {

View File

@ -0,0 +1,34 @@
using ConfectioneryContracts.StoragesContract;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConfectioneryFileImplement
{
public class BackUpInfo : IBackUpInfo
{
public List<T>? GetList<T>() where T : class, new()
{
// Получаем значения из singleton-объекта универсального свойства содержащее тип T
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,20 +4,23 @@ using ConfectioneryDataModels;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Runtime.Serialization;
using System.Text; using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
using System.Xml.Linq; using System.Xml.Linq;
namespace ConfectioneryFileImplement namespace ConfectioneryFileImplement
{ {
[DataContract]
public class Client : IClientModel public class Client : IClientModel
{ {
[DataMember]
public string ClientFIO { get; private set; } = string.Empty; public string ClientFIO { get; private set; } = string.Empty;
[DataMember]
public string Email { get; private set; } = string.Empty; public string Email { get; private set; } = string.Empty;
[DataMember]
public string Password { get; private set; } = string.Empty; public string Password { get; private set; } = string.Empty;
[DataMember]
public int Id { get; private set; } public int Id { get; private set; }
public static Client? Create(ClientBindingModel model) public static Client? Create(ClientBindingModel model)

View File

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

View File

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

View File

@ -0,0 +1,24 @@
using ConfectioneryContracts.DI;
using ConfectioneryContracts.StoragesContract;
using ConfectioneryFileImplement.Implements;
namespace ConfectioneryFileImplement
{
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<IPastryStorage, PastryStorage>();
DependencyManager.Instance.RegisterType<IShopStorage, ShopStorage>();
DependencyManager.Instance.RegisterType<IBackUpInfo, BackUpInfo>();
}
}
}

View File

@ -5,22 +5,29 @@ using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Data; using System.Data;
using System.Linq; using System.Linq;
using System.Runtime.Serialization;
using System.Text; using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
using System.Xml.Linq; using System.Xml.Linq;
namespace ConfectioneryFileImplement namespace ConfectioneryFileImplement
{ {
[DataContract]
public class Implementer : IImplementerModel public class Implementer : IImplementerModel
{ {
[DataMember]
public int Id { get; private set; } public int Id { get; private set; }
[DataMember]
public string ImplementerFIO { get; private set; } = string.Empty; public string ImplementerFIO { get; private set; } = string.Empty;
[DataMember]
public string Password { get; private set; } = string.Empty; public string Password { get; private set; } = string.Empty;
[DataMember]
public int WorkExperience { get; private set; } public int WorkExperience { get; private set; }
[DataMember]
public int Qualification { get; private set; } public int Qualification { get; private set; }
public static Implementer? Create(XElement element) public static Implementer? Create(XElement element)

View File

@ -4,6 +4,7 @@ using ConfectioneryDataModels;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Runtime.Serialization;
using System.Text; using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
using System.Xml.Linq; using System.Xml.Linq;
@ -11,20 +12,29 @@ using System.Xml.Linq;
namespace ConfectioneryFileImplement.Models namespace ConfectioneryFileImplement.Models
{ {
// Update в этой сущности не нужен, поскольку в логике мы не изменяем никакие поля после создания письма // Update в этой сущности не нужен, поскольку в логике мы не изменяем никакие поля после создания письма
[DataContract]
public class MessageInfo : IMessageInfoModel public class MessageInfo : IMessageInfoModel
{ {
[DataMember]
public string MessageId { get; private set; } = string.Empty; public string MessageId { get; private set; } = string.Empty;
[DataMember]
public int? ClientId { get; private set; } public int? ClientId { get; private set; }
[DataMember]
public string SenderName { get; private set; } = string.Empty; public string SenderName { get; private set; } = string.Empty;
[DataMember]
public DateTime DateDelivery { get; private set; } = DateTime.Now; public DateTime DateDelivery { get; private set; } = DateTime.Now;
[DataMember]
public string Subject { get; private set; } = string.Empty; public string Subject { get; private set; } = string.Empty;
[DataMember]
public string Body { get; private set; } = string.Empty; public string Body { get; private set; } = string.Empty;
[DataMember]
public bool HasRead { get; private set; } public bool HasRead { get; private set; }
[DataMember]
public string? Reply { get; private set; } public string? Reply { get; private set; }
public static MessageInfo? Create(MessageInfoBindingModel model) public static MessageInfo? Create(MessageInfoBindingModel model)
@ -97,6 +107,8 @@ namespace ConfectioneryFileImplement.Models
new XAttribute("SenderName", SenderName), new XAttribute("SenderName", SenderName),
new XAttribute("DateDelivery", DateDelivery) new XAttribute("DateDelivery", DateDelivery)
); );
public int Id => throw new NotImplementedException();
} }
} }

View File

@ -2,28 +2,39 @@
using ConfectioneryContracts.ViewModels; using ConfectioneryContracts.ViewModels;
using ConfectioneryDataModels.Enums; using ConfectioneryDataModels.Enums;
using ConfectioneryDataModels.Models; using ConfectioneryDataModels.Models;
using System.Runtime.Serialization;
using System.Xml.Linq; using System.Xml.Linq;
namespace ConfectioneryFileImplement.Models namespace ConfectioneryFileImplement.Models
{ {
[DataContract]
public class Order : IOrderModel public class Order : IOrderModel
{ {
[DataMember]
public int Id { get; private set; } public int Id { get; private set; }
[DataMember]
public int PastryId { get; private set; } public int PastryId { get; private set; }
[DataMember]
public int ClientId { get; set; } public int ClientId { get; set; }
[DataMember]
public int? ImplementerId { get; set; } public int? ImplementerId { get; set; }
[DataMember]
public int Count { get; private set; } public int Count { get; private set; }
[DataMember]
public double Sum { get; private set; } public double Sum { get; private set; }
[DataMember]
public OrderStatus Status { get; private set; } public OrderStatus Status { get; private set; }
[DataMember]
public DateTime DateCreate { get; private set; } public DateTime DateCreate { get; private set; }
[DataMember]
public DateTime? DateImplement { get; private set; } public DateTime? DateImplement { get; private set; }
public static Order? Create(OrderBindingModel? model) public static Order? Create(OrderBindingModel? model)

View File

@ -1,17 +1,24 @@
using ConfectioneryContracts.BindingModels; using ConfectioneryContracts.BindingModels;
using ConfectioneryContracts.ViewModels; using ConfectioneryContracts.ViewModels;
using ConfectioneryDataModels.Models; using ConfectioneryDataModels.Models;
using System.Runtime.Serialization;
using System.Xml.Linq; using System.Xml.Linq;
namespace ConfectioneryFileImplement.Models namespace ConfectioneryFileImplement.Models
{ {
[DataContract]
public class Pastry : IPastryModel public class Pastry : IPastryModel
{ {
[DataMember]
public int Id { get; private set; } public int Id { get; private set; }
[DataMember]
public string PastryName { get; private set; } = string.Empty; public string PastryName { get; private set; } = string.Empty;
[DataMember]
public double Price { get; private set; } public double Price { get; private set; }
public Dictionary<int, int> Components { get; private set; } = new(); public Dictionary<int, int> Components { get; private set; } = new();
private Dictionary<int, (IComponentModel, int)>? _PastryComponents = null; private Dictionary<int, (IComponentModel, int)>? _PastryComponents = null;
[DataMember]
public Dictionary<int, (IComponentModel, int)> PastryComponents public Dictionary<int, (IComponentModel, int)> PastryComponents
{ {
get get

View File

@ -2,23 +2,30 @@
using ConfectioneryContracts.ViewModels; using ConfectioneryContracts.ViewModels;
using ConfectioneryDataModels; using ConfectioneryDataModels;
using ConfectioneryDataModels.Models; using ConfectioneryDataModels.Models;
using System.Runtime.Serialization;
using System.Xml.Linq; using System.Xml.Linq;
namespace ConfectioneryFileImplement namespace ConfectioneryFileImplement
{ {
[DataContract]
public class Shop : IShopModel public class Shop : IShopModel
{ {
[DataMember]
public string Name { get; private set; } = string.Empty; public string Name { get; private set; } = string.Empty;
[DataMember]
public string Address { get; private set; } = string.Empty; public string Address { get; private set; } = string.Empty;
[DataMember]
public int MaxCountPastries { get; private set; } public int MaxCountPastries { get; private set; }
[DataMember]
public DateTime DateOpening { get; private set; } public DateTime DateOpening { get; private set; }
public Dictionary<int, int> CountPastries { get; private set; } = new(); public Dictionary<int, int> CountPastries { get; private set; } = new();
private Dictionary<int, (IPastryModel, int)>? _cachedPastries = null; private Dictionary<int, (IPastryModel, int)>? _cachedPastries = null;
[DataMember]
public Dictionary<int, (IPastryModel, int)> Pastries public Dictionary<int, (IPastryModel, int)> Pastries
{ {
get get
@ -34,6 +41,7 @@ namespace ConfectioneryFileImplement
} }
} }
[DataMember]
public int Id { get; private set; } public int Id { get; private set; }
public static Shop? Create(ShopBindingModel? model) public static Shop? Create(ShopBindingModel? model)

View File

@ -0,0 +1,22 @@
using ConfectioneryContracts.StoragesContract;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConfectioneryListImplement
{
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

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

View File

@ -0,0 +1,29 @@
using ConfectioneryContracts.DI;
using ConfectioneryContracts.StoragesContract;
using ConfectioneryListImplement.Implements;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConfectioneryListImplement
{
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<IPastryStorage, PastryStorage>();
DependencyManager.Instance.RegisterType<IShopStorage, ShopStorage>();
DependencyManager.Instance.RegisterType<IBackUpInfo, BackUpInfo>();
}
}
}

View File

@ -67,6 +67,7 @@ namespace ConfectioneryListImplement.Models
DateDelivery = DateDelivery, DateDelivery = DateDelivery,
}; };
public int Id => throw new NotImplementedException();
} }
} }

View File

@ -0,0 +1,47 @@
using ConfectioneryContracts.Attributes;
namespace ConfectioneryView
{
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;
column.DefaultCellStyle.Format = columnAttr.Format;
if (columnAttr.IsUseAutoSize)
{
column.AutoSizeMode = (DataGridViewAutoSizeColumnMode)Enum.Parse(typeof(DataGridViewAutoSizeColumnMode), columnAttr.GridViewAutoSize.ToString());
}
else
{
column.Width = columnAttr.Width;
}
}
}
}
}
}

View File

@ -1,5 +1,6 @@
using ConfectioneryContracts.BindingModels; using ConfectioneryContracts.BindingModels;
using ConfectioneryContracts.BusinessLogicsContracts; using ConfectioneryContracts.BusinessLogicsContracts;
using ConfectioneryContracts.DI;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
namespace ConfectioneryView namespace ConfectioneryView
@ -22,14 +23,7 @@ namespace ConfectioneryView
{ {
try try
{ {
var list = _logic.ReadList(null); dataGridView.FillAndConfigGrid(_logic.ReadList(null));
if (list != null)
{
dataGridView.DataSource = list;
dataGridView.Columns["Id"].Visible = false;
dataGridView.Columns["ComponentName"].AutoSizeMode =
DataGridViewAutoSizeColumnMode.Fill;
}
_logger.LogInformation("Загрузка компонентов"); _logger.LogInformation("Загрузка компонентов");
} }
catch (Exception ex) catch (Exception ex)
@ -41,23 +35,17 @@ namespace ConfectioneryView
} }
private void ButtonAdd_Click(object sender, EventArgs e) private void ButtonAdd_Click(object sender, EventArgs e)
{ {
var service = var form = DependencyManager.Instance.Resolve<FormComponent>();
Program.ServiceProvider?.GetService(typeof(FormComponent));
if (service is FormComponent form)
{
if (form.ShowDialog() == DialogResult.OK) if (form.ShowDialog() == DialogResult.OK)
{ {
LoadData(); LoadData();
} }
} }
}
private void ButtonUpd_Click(object sender, EventArgs e) private void ButtonUpd_Click(object sender, EventArgs e)
{ {
if (dataGridView.SelectedRows.Count == 1) if (dataGridView.SelectedRows.Count == 1)
{ {
var service = Program.ServiceProvider?.GetService(typeof(FormComponent)); var form = DependencyManager.Instance.Resolve<FormComponent>();
if (service is FormComponent form)
{
form.Id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value); form.Id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value);
if (form.ShowDialog() == DialogResult.OK) if (form.ShowDialog() == DialogResult.OK)
{ {
@ -65,7 +53,6 @@ namespace ConfectioneryView
} }
} }
} }
}
private void ButtonDel_Click(object sender, EventArgs e) private void ButtonDel_Click(object sender, EventArgs e)
{ {
if (dataGridView.SelectedRows.Count == 1) if (dataGridView.SelectedRows.Count == 1)

View File

@ -42,21 +42,22 @@
pastriesToolStripMenuItem = new ToolStripMenuItem(); pastriesToolStripMenuItem = new ToolStripMenuItem();
pastryComponentsToolStripMenuItem = new ToolStripMenuItem(); pastryComponentsToolStripMenuItem = new ToolStripMenuItem();
ordersToolStripMenuItem = new ToolStripMenuItem(); ordersToolStripMenuItem = new ToolStripMenuItem();
DoWorkToolStripMenuItem = new ToolStripMenuItem();
mailToolStripMenuItem = new ToolStripMenuItem(); mailToolStripMenuItem = new ToolStripMenuItem();
dataGridView = new DataGridView(); dataGridView = new DataGridView();
buttonCreateOrder = new Button(); buttonCreateOrder = new Button();
button3 = new Button(); button3 = new Button();
button4 = new Button(); button4 = new Button();
buttonAddPastryInShop = new Button(); buttonAddPastryInShop = new Button();
DoWorkToolStripMenuItem = new ToolStripMenuItem();
buttonSellPastry = new Button(); buttonSellPastry = new Button();
createBackupToolStripMenuItem = new ToolStripMenuItem();
menuStrip1.SuspendLayout(); menuStrip1.SuspendLayout();
((System.ComponentModel.ISupportInitialize)dataGridView).BeginInit(); ((System.ComponentModel.ISupportInitialize)dataGridView).BeginInit();
SuspendLayout(); SuspendLayout();
// //
// menuStrip1 // menuStrip1
// //
menuStrip1.Items.AddRange(new ToolStripItem[] { справочникиToolStripMenuItem, reportsToolStripMenuItem, DoWorkToolStripMenuItem, mailToolStripMenuItem }); menuStrip1.Items.AddRange(new ToolStripItem[] { справочникиToolStripMenuItem, reportsToolStripMenuItem, DoWorkToolStripMenuItem, mailToolStripMenuItem, createBackupToolStripMenuItem });
menuStrip1.Location = new Point(0, 0); menuStrip1.Location = new Point(0, 0);
menuStrip1.Name = "menuStrip1"; menuStrip1.Name = "menuStrip1";
menuStrip1.Size = new Size(783, 24); menuStrip1.Size = new Size(783, 24);
@ -161,6 +162,13 @@
DoWorkToolStripMenuItem.Text = "Запуск работ"; DoWorkToolStripMenuItem.Text = "Запуск работ";
DoWorkToolStripMenuItem.Click += DoWorkToolStripMenuItem_Click; DoWorkToolStripMenuItem.Click += DoWorkToolStripMenuItem_Click;
// //
// mailToolStripMenuItem
//
mailToolStripMenuItem.Name = "mailToolStripMenuItem";
mailToolStripMenuItem.Size = new Size(62, 20);
mailToolStripMenuItem.Text = "Письма";
mailToolStripMenuItem.Click += MailToolStripMenuItem_Click;
//
// dataGridView // dataGridView
// //
dataGridView.Anchor = AnchorStyles.Top | AnchorStyles.Bottom | AnchorStyles.Left | AnchorStyles.Right; dataGridView.Anchor = AnchorStyles.Top | AnchorStyles.Bottom | AnchorStyles.Left | AnchorStyles.Right;
@ -182,13 +190,6 @@
buttonCreateOrder.UseVisualStyleBackColor = true; buttonCreateOrder.UseVisualStyleBackColor = true;
buttonCreateOrder.Click += ButtonCreateOrder_Click; buttonCreateOrder.Click += ButtonCreateOrder_Click;
// //
// mailToolStripMenuItem
//
mailToolStripMenuItem.Name = "mailToolStripMenuItem";
mailToolStripMenuItem.Size = new Size(62, 20);
mailToolStripMenuItem.Text = "Письма";
mailToolStripMenuItem.Click += MailToolStripMenuItem_Click;
//
// button3 // button3
// //
button3.Anchor = AnchorStyles.Top | AnchorStyles.Right; button3.Anchor = AnchorStyles.Top | AnchorStyles.Right;
@ -233,6 +234,13 @@
buttonSellPastry.UseVisualStyleBackColor = true; buttonSellPastry.UseVisualStyleBackColor = true;
buttonSellPastry.Click += ButtonSellPastry_Click; buttonSellPastry.Click += ButtonSellPastry_Click;
// //
// createBackupToolStripMenuItem
//
createBackupToolStripMenuItem.Name = "createBackupToolStripMenuItem";
createBackupToolStripMenuItem.Size = new Size(97, 20);
createBackupToolStripMenuItem.Text = "Создать бекап";
createBackupToolStripMenuItem.Click += CreateBackupToolStripMenuItem_Click;
//
// FormMain // FormMain
// //
AutoScaleDimensions = new SizeF(7F, 15F); AutoScaleDimensions = new SizeF(7F, 15F);
@ -280,5 +288,6 @@
private ToolStripMenuItem ImplementersToolStripMenuItem; private ToolStripMenuItem ImplementersToolStripMenuItem;
private ToolStripMenuItem DoWorkToolStripMenuItem; private ToolStripMenuItem DoWorkToolStripMenuItem;
private ToolStripMenuItem mailToolStripMenuItem; private ToolStripMenuItem mailToolStripMenuItem;
private ToolStripMenuItem createBackupToolStripMenuItem;
} }
} }

View File

@ -1,6 +1,8 @@
using ConfectioneryBusinessLogic;
using ConfectioneryBusinessLogic.BusinessLogics; using ConfectioneryBusinessLogic.BusinessLogics;
using ConfectioneryContracts.BindingModels; using ConfectioneryContracts.BindingModels;
using ConfectioneryContracts.BusinessLogicsContracts; using ConfectioneryContracts.BusinessLogicsContracts;
using ConfectioneryContracts.DI;
using ConfectioneryDataModels.Enums; using ConfectioneryDataModels.Enums;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
using System.Windows.Forms; using System.Windows.Forms;
@ -13,14 +15,16 @@ namespace ConfectioneryView
private readonly IOrderLogic _orderLogic; private readonly IOrderLogic _orderLogic;
private readonly IReportLogic _reportLogic; private readonly IReportLogic _reportLogic;
private readonly IWorkProcess _workProcess; private readonly IWorkProcess _workProcess;
private readonly IBackUpLogic _backUpLogic;
public FormMain(ILogger<FormMain> logger, IOrderLogic orderLogic, IReportLogic reportLogic, IWorkProcess workProcess) public FormMain(ILogger<FormMain> logger, IOrderLogic orderLogic, IReportLogic reportLogic, IWorkProcess workProcess, IBackUpLogic backUpLogic)
{ {
InitializeComponent(); InitializeComponent();
_logger = logger; _logger = logger;
_orderLogic = orderLogic; _orderLogic = orderLogic;
_reportLogic = reportLogic; _reportLogic = reportLogic;
_workProcess = workProcess; _workProcess = workProcess;
_backUpLogic = backUpLogic;
} }
private void FormMain_Load(object sender, EventArgs e) private void FormMain_Load(object sender, EventArgs e)
{ {
@ -30,18 +34,7 @@ namespace ConfectioneryView
{ {
try try
{ {
var list = _orderLogic.ReadList(null); dataGridView.FillAndConfigGrid(_orderLogic.ReadList(null));
if (list != null)
{
dataGridView.DataSource = list;
dataGridView.Columns["Id"].HeaderText = "Íîìåð çàêàçà";
dataGridView.Columns["PastryId"].Visible = false;
dataGridView.Columns["ClientId"].Visible = false;
dataGridView.Columns["ImplementerId"].Visible = false;
dataGridView.Columns["PastryName"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
dataGridView.Columns["ClientFIO"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
dataGridView.Columns["ImplementerFIO"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
}
_logger.LogInformation("Çàãðóçêà çàêàçîâ"); _logger.LogInformation("Çàãðóçêà çàêàçîâ");
} }
catch (Exception ex) catch (Exception ex)
@ -54,29 +47,21 @@ namespace ConfectioneryView
private void ComponentsToolStripMenuItem_Click(object sender, EventArgs private void ComponentsToolStripMenuItem_Click(object sender, EventArgs
e) e)
{ {
var service = Program.ServiceProvider?.GetService(typeof(FormComponents)); var form = DependencyManager.Instance.Resolve<FormComponents>();
if (service is FormComponents form)
{
form.ShowDialog(); form.ShowDialog();
} }
}
private void PastryToolStripMenuItem_Click(object sender, EventArgs e) private void PastryToolStripMenuItem_Click(object sender, EventArgs e)
{ {
var service = Program.ServiceProvider?.GetService(typeof(FormViewPastry)); var form = DependencyManager.Instance.Resolve<FormViewPastry>();
if (service is FormViewPastry form)
{
form.ShowDialog(); form.ShowDialog();
} }
}
private void ButtonCreateOrder_Click(object sender, EventArgs e) private void ButtonCreateOrder_Click(object sender, EventArgs e)
{ {
var service = Program.ServiceProvider?.GetService(typeof(FormCreateOrder)); var form = DependencyManager.Instance.Resolve<FormCreateOrder>();
if (service is FormCreateOrder form)
{
form.ShowDialog(); form.ShowDialog();
LoadData(); LoadData();
}
} }
private void ButtonIssuedOrder_Click(object sender, EventArgs e) private void ButtonIssuedOrder_Click(object sender, EventArgs e)
@ -133,89 +118,64 @@ namespace ConfectioneryView
private void ShopPastriesToolStripMenuItem_Click(object sender, EventArgs e) private void ShopPastriesToolStripMenuItem_Click(object sender, EventArgs e)
{ {
var service = Program.ServiceProvider?.GetService(typeof(FormReportShopPastries)); var form = DependencyManager.Instance.Resolve<FormReportShopPastries>();
if (service is FormReportShopPastries form)
{
form.ShowDialog(); form.ShowDialog();
} }
}
private void PastryComponentsToolStripMenuItem_Click(object sender, EventArgs e) private void PastryComponentsToolStripMenuItem_Click(object sender, EventArgs e)
{ {
var service = Program.ServiceProvider?.GetService(typeof(FormReportPastryComponents)); var form = DependencyManager.Instance.Resolve<FormReportPastryComponents>();
if (service is FormReportPastryComponents form)
{
form.ShowDialog(); form.ShowDialog();
} }
}
private void GroupOrdersToolStripMenuItem_Click(object sender, EventArgs e) private void GroupOrdersToolStripMenuItem_Click(object sender, EventArgs e)
{ {
var service = Program.ServiceProvider?.GetService(typeof(FormReportGroupOrders)); var form = DependencyManager.Instance.Resolve<FormReportGroupOrders>();
if (service is FormReportGroupOrders form)
{
form.ShowDialog(); form.ShowDialog();
} }
}
private void OrdersToolStripMenuItem_Click(object sender, EventArgs e) private void OrdersToolStripMenuItem_Click(object sender, EventArgs e)
{ {
var service = Program.ServiceProvider?.GetService(typeof(FormReportOrders)); var form = DependencyManager.Instance.Resolve<FormReportOrders>();
if (service is FormReportOrders form)
{
form.ShowDialog(); form.ShowDialog();
}
} }
private void ShopsToolStripMenuItem_Click(object sender, EventArgs e) private void ShopsToolStripMenuItem_Click(object sender, EventArgs e)
{ {
var service = Program.ServiceProvider?.GetService(typeof(FormViewShops)); var form = DependencyManager.Instance.Resolve<FormViewShops>();
if (service is FormViewShops form)
{
form.ShowDialog(); form.ShowDialog();
} }
}
private void ButtonAddPastryInShop_Click(object sender, EventArgs e) private void ButtonAddPastryInShop_Click(object sender, EventArgs e)
{ {
var service = Program.ServiceProvider?.GetService(typeof(FormAddPastryInShop)); var form = DependencyManager.Instance.Resolve<FormAddPastryInShop>();
if (service is FormAddPastryInShop form)
{
form.ShowDialog(); form.ShowDialog();
} }
}
private void ButtonSellPastry_Click(object sender, EventArgs e) private void ButtonSellPastry_Click(object sender, EventArgs e)
{ {
var service = Program.ServiceProvider?.GetService(typeof(FormSellPastry)); var form = DependencyManager.Instance.Resolve<FormSellPastry>();
if (service is FormSellPastry form)
{
form.ShowDialog(); form.ShowDialog();
} }
}
private void ClientsToolStripMenuItem_Click(object sender, EventArgs e) private void ClientsToolStripMenuItem_Click(object sender, EventArgs e)
{ {
var service = Program.ServiceProvider?.GetService(typeof(FormViewClients)); var form = DependencyManager.Instance.Resolve<FormViewClients>();
if (service is FormViewClients form)
{
form.ShowDialog(); form.ShowDialog();
} }
}
private void ImplementersToolStripMenuItem_Click(object sender, EventArgs e) private void ImplementersToolStripMenuItem_Click(object sender, EventArgs e)
{ {
var service = Program.ServiceProvider?.GetService(typeof(FormViewImplementers)); var form = DependencyManager.Instance.Resolve<FormViewImplementers>();
if (service is FormViewImplementers form)
{
form.ShowDialog(); form.ShowDialog();
}
} }
private void DoWorkToolStripMenuItem_Click(object sender, EventArgs e) private void DoWorkToolStripMenuItem_Click(object sender, EventArgs e)
{ {
_workProcess.DoWork(( _workProcess.DoWork(
Program.ServiceProvider?.GetService(typeof(IImplementerLogic)) as IImplementerLogic)!, DependencyManager.Instance.Resolve<IImplementerLogic>(),
_orderLogic); _orderLogic);
MessageBox.Show("Ïðîöåññ îáðàáîòêè çàïóùåí", "Ñîîáùåíèå", MessageBox.Show("Ïðîöåññ îáðàáîòêè çàïóùåí", "Ñîîáùåíèå",
MessageBoxButtons.OK, MessageBoxIcon.Information); MessageBoxButtons.OK, MessageBoxIcon.Information);
@ -223,11 +183,33 @@ namespace ConfectioneryView
private void MailToolStripMenuItem_Click(object sender, EventArgs e) private void MailToolStripMenuItem_Click(object sender, EventArgs e)
{ {
var service = Program.ServiceProvider?.GetService(typeof(FormViewMail)); var form = DependencyManager.Instance.Resolve<FormViewMail>();
if (service is FormViewMail form)
{
form.ShowDialog(); form.ShowDialog();
} }
private void CreateBackupToolStripMenuItem_Click(object sender, EventArgs e)
{
try
{
if (_backUpLogic != null)
{
var fbd = new FolderBrowserDialog();
if (fbd.ShowDialog() == DialogResult.OK)
{
_backUpLogic.CreateBackUp(new BackUpSaveBinidngModel
{
FolderName = fbd.SelectedPath
});
MessageBox.Show("Áåêàï ñîçäàí", "Ñîîáùåíèå",
MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Îøèáêà", MessageBoxButtons.OK,
MessageBoxIcon.Error);
}
} }
} }
} }

View File

@ -1,5 +1,6 @@
using ConfectioneryContracts.BindingModels; using ConfectioneryContracts.BindingModels;
using ConfectioneryContracts.BusinessLogicsContracts; using ConfectioneryContracts.BusinessLogicsContracts;
using ConfectioneryContracts.DI;
using ConfectioneryContracts.SearchModels; using ConfectioneryContracts.SearchModels;
using ConfectioneryDataModels.Models; using ConfectioneryDataModels.Models;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
@ -72,10 +73,7 @@ namespace ConfectioneryView
} }
private void ButtonAdd_Click(object sender, EventArgs e) private void ButtonAdd_Click(object sender, EventArgs e)
{ {
var service = var form = DependencyManager.Instance.Resolve<FormPastryComponent>();
Program.ServiceProvider?.GetService(typeof(FormPastryComponent));
if (service is FormPastryComponent form)
{
if (form.ShowDialog() == DialogResult.OK) if (form.ShowDialog() == DialogResult.OK)
{ {
if (form.ComponentModel == null) if (form.ComponentModel == null)
@ -97,14 +95,11 @@ namespace ConfectioneryView
LoadData(); LoadData();
} }
} }
}
private void ButtonUpd_Click(object sender, EventArgs e) private void ButtonUpd_Click(object sender, EventArgs e)
{ {
if (dataGridView.SelectedRows.Count == 1) if (dataGridView.SelectedRows.Count == 1)
{ {
var service = Program.ServiceProvider?.GetService(typeof(FormPastryComponent)); var form = DependencyManager.Instance.Resolve<FormPastryComponent>();
if (service is FormPastryComponent form)
{
int id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells[0].Value); int id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells[0].Value);
form.Id = id; form.Id = id;
form.Count = _pastryComponents[id].Item2; form.Count = _pastryComponents[id].Item2;
@ -121,7 +116,6 @@ namespace ConfectioneryView
} }
} }
} }
}
private void ButtonDel_Click(object sender, EventArgs e) private void ButtonDel_Click(object sender, EventArgs e)
{ {
if (dataGridView.SelectedRows.Count == 1) if (dataGridView.SelectedRows.Count == 1)

View File

@ -31,13 +31,7 @@ namespace ConfectioneryView
{ {
try try
{ {
var list = _logic.ReadList(null); dataGridView.FillAndConfigGrid(_logic.ReadList(null));
if (list != null)
{
dataGridView.DataSource = list;
dataGridView.Columns["Id"].Visible = false;
dataGridView.Columns["ClientFIO"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
}
_logger.LogInformation("Загрузка клиентов"); _logger.LogInformation("Загрузка клиентов");
} }
catch (Exception ex) catch (Exception ex)

View File

@ -1,5 +1,6 @@
using ConfectioneryContracts.BindingModels; using ConfectioneryContracts.BindingModels;
using ConfectioneryContracts.BusinessLogicsContracts; using ConfectioneryContracts.BusinessLogicsContracts;
using ConfectioneryContracts.DI;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
@ -31,13 +32,7 @@ namespace ConfectioneryView
{ {
try try
{ {
var list = _logic.ReadList(null); dataGridView.FillAndConfigGrid(_logic.ReadList(null));
if (list != null)
{
dataGridView.DataSource = list;
dataGridView.Columns["Id"].Visible = false;
dataGridView.Columns["ImplementerFIO"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
}
_logger.LogInformation("Загрузка исполнителей"); _logger.LogInformation("Загрузка исполнителей");
} }
catch (Exception ex) catch (Exception ex)
@ -49,22 +44,17 @@ namespace ConfectioneryView
} }
private void ButtonAdd_Click(object sender, EventArgs e) private void ButtonAdd_Click(object sender, EventArgs e)
{ {
var service = Program.ServiceProvider?.GetService(typeof(FormImplementer)); var form = DependencyManager.Instance.Resolve<FormImplementer>();
if (service is FormImplementer form)
{
if (form.ShowDialog() == DialogResult.OK) if (form.ShowDialog() == DialogResult.OK)
{ {
LoadData(); LoadData();
} }
} }
}
private void ButtonUpd_Click(object sender, EventArgs e) private void ButtonUpd_Click(object sender, EventArgs e)
{ {
if (dataGridView.SelectedRows.Count == 1) if (dataGridView.SelectedRows.Count == 1)
{ {
var service = Program.ServiceProvider?.GetService(typeof(FormImplementer)); var form = DependencyManager.Instance.Resolve<FormImplementer>();
if (service is FormImplementer form)
{
form.Id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value); form.Id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value);
if (form.ShowDialog() == DialogResult.OK) if (form.ShowDialog() == DialogResult.OK)
{ {
@ -72,7 +62,6 @@ namespace ConfectioneryView
} }
} }
} }
}
private void ButtonDel_Click(object sender, EventArgs e) private void ButtonDel_Click(object sender, EventArgs e)
{ {
if (dataGridView.SelectedRows.Count == 1) if (dataGridView.SelectedRows.Count == 1)

View File

@ -11,6 +11,7 @@ using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
using System.Windows.Forms; using System.Windows.Forms;
using ConfectioneryContracts.ViewModels; using ConfectioneryContracts.ViewModels;
using ConfectioneryContracts.DI;
namespace ConfectioneryView namespace ConfectioneryView
{ {
@ -38,18 +39,11 @@ namespace ConfectioneryView
{ {
try try
{ {
var list = _logic.ReadList(new() dataGridView.FillAndConfigGrid(_logic.ReadList(new()
{ {
Page = currentPage, Page = currentPage,
PageSize = pageSize, PageSize = pageSize,
}); }));
if (list != null)
{
dataGridView.DataSource = list;
dataGridView.Columns["ClientId"].Visible = false;
dataGridView.Columns["MessageId"].Visible = false;
dataGridView.Columns["Body"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
}
_logger.LogInformation("Загрузка списка писем"); _logger.LogInformation("Загрузка списка писем");
labelInfoPages.Text = $"{currentPage} страница"; labelInfoPages.Text = $"{currentPage} страница";
return true; return true;
@ -99,13 +93,10 @@ namespace ConfectioneryView
private void dataGridView_RowHeaderMouseClick(object sender, DataGridViewCellMouseEventArgs e) private void dataGridView_RowHeaderMouseClick(object sender, DataGridViewCellMouseEventArgs e)
{ {
var service = Program.ServiceProvider?.GetService(typeof(FormReplyMail)); var form = DependencyManager.Instance.Resolve<FormReplyMail>();
if (service is FormReplyMail form)
{
form.MessageId = (string)dataGridView.Rows[e.RowIndex].Cells["MessageId"].Value; form.MessageId = (string)dataGridView.Rows[e.RowIndex].Cells["MessageId"].Value;
form.ShowDialog(); form.ShowDialog();
MailLoad(); MailLoad();
} }
} }
}
} }

View File

@ -1,5 +1,6 @@
using ConfectioneryContracts.BindingModels; using ConfectioneryContracts.BindingModels;
using ConfectioneryContracts.BusinessLogicsContracts; using ConfectioneryContracts.BusinessLogicsContracts;
using ConfectioneryContracts.DI;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
@ -31,15 +32,7 @@ namespace ConfectioneryView
{ {
try try
{ {
var list = _logic.ReadList(null); dataGridView.FillAndConfigGrid(_logic.ReadList(null));
if (list != null)
{
dataGridView.DataSource = list;
dataGridView.Columns["Id"].Visible = false;
dataGridView.Columns["PastryComponents"].Visible = false;
dataGridView.Columns["PastryName"].AutoSizeMode =
DataGridViewAutoSizeColumnMode.Fill;
}
_logger.LogInformation("Загрузка изделий"); _logger.LogInformation("Загрузка изделий");
} }
catch (Exception ex) catch (Exception ex)
@ -51,28 +44,23 @@ namespace ConfectioneryView
} }
private void ButtonAdd_Click(object sender, EventArgs e) private void ButtonAdd_Click(object sender, EventArgs e)
{ {
var service = Program.ServiceProvider?.GetService(typeof(FormPastry)); var form = DependencyManager.Instance.Resolve<FormPastry>();
if (service is FormPastry form)
{
if (form.ShowDialog() == DialogResult.OK) if (form.ShowDialog() == DialogResult.OK)
{ {
LoadData(); LoadData();
} }
} }
}
private void ButtonUpd_Click(object sender, EventArgs e) private void ButtonUpd_Click(object sender, EventArgs e)
{ {
if (dataGridView.SelectedRows.Count == 1) if (dataGridView.SelectedRows.Count == 1)
{ {
var service = Program.ServiceProvider?.GetService(typeof(FormPastry)); var form = DependencyManager.Instance.Resolve<FormPastry>();
if (service is FormPastry form)
{
form.Id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value); form.Id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value);
if (form.ShowDialog() == DialogResult.OK) if (form.ShowDialog() == DialogResult.OK)
{ {
LoadData(); LoadData();
} }
}
} }
} }
private void ButtonDel_Click(object sender, EventArgs e) private void ButtonDel_Click(object sender, EventArgs e)

View File

@ -1,5 +1,6 @@
using ConfectioneryContracts.BindingModels; using ConfectioneryContracts.BindingModels;
using ConfectioneryContracts.BusinessLogicsContracts; using ConfectioneryContracts.BusinessLogicsContracts;
using ConfectioneryContracts.DI;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
namespace ConfectioneryView namespace ConfectioneryView
@ -22,16 +23,7 @@ namespace ConfectioneryView
{ {
try try
{ {
var list = _logic.ReadList(null); dataGridView.FillAndConfigGrid(_logic.ReadList(null));
if (list != null)
{
dataGridView.DataSource = list;
dataGridView.Columns["Id"].Visible = false;
dataGridView.Columns["Pastries"].Visible = false;
dataGridView.Columns["Name"].AutoSizeMode =
DataGridViewAutoSizeColumnMode.Fill;
}
_logger.LogInformation("Загрузка магазинов"); _logger.LogInformation("Загрузка магазинов");
} }
catch (Exception ex) catch (Exception ex)
@ -43,20 +35,17 @@ namespace ConfectioneryView
} }
private void ButtonAdd_Click(object sender, EventArgs e) private void ButtonAdd_Click(object sender, EventArgs e)
{ {
var service = Program.ServiceProvider?.GetService(typeof(FormShop)); var form = DependencyManager.Instance.Resolve<FormShop>();
if (service is FormShop form)
{
if (form.ShowDialog() == DialogResult.OK) if (form.ShowDialog() == DialogResult.OK)
{ {
LoadData(); LoadData();
} }
} }
}
private void ButtonUpd_Click(object sender, EventArgs e) private void ButtonUpd_Click(object sender, EventArgs e)
{ {
if (dataGridView.SelectedRows.Count == 1) if (dataGridView.SelectedRows.Count == 1)
{ {
var service = Program.ServiceProvider?.GetService(typeof(FormShop)); var service = DependencyManager.Instance.Resolve<FormShop>();
if (service is FormShop form) if (service is FormShop form)
{ {
form.Id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value); form.Id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value);

View File

@ -2,22 +2,19 @@ using ConfectioneryDatabaseImplement.Implements;
using ConfectioneryDatabaseImplement; using ConfectioneryDatabaseImplement;
using ConfectioneryBusinessLogic.BusinessLogics; using ConfectioneryBusinessLogic.BusinessLogics;
using ConfectioneryContracts.BusinessLogicsContracts; using ConfectioneryContracts.BusinessLogicsContracts;
using ConfectioneryContracts.StoragesContract; using ConfectioneryContracts.DI;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using NLog.Extensions.Logging; using NLog.Extensions.Logging;
using ConfectioneryBusinessLogic; using ConfectioneryBusinessLogic;
using ConfectioneryBusinessLogic.OfficePackage.Implements; using ConfectioneryBusinessLogic.OfficePackage.Implements;
using ConfectioneryBusinessLogic.OfficePackage; using ConfectioneryBusinessLogic.OfficePackage;
using ConfectioneryBusinessLogic.MailWorker; using ConfectioneryBusinessLogic.MailWorker;
using ConfectioneryContracts.BindingModels; using ConfectioneryContracts.BindingModels;
using Microsoft.Extensions.Logging;
namespace ConfectioneryView namespace ConfectioneryView
{ {
internal static class Program internal static class Program
{ {
private static ServiceProvider? _serviceProvider;
public static ServiceProvider? ServiceProvider => _serviceProvider;
/// <summary> /// <summary>
/// The main entry point for the application. /// The main entry point for the application.
/// </summary> /// </summary>
@ -27,13 +24,11 @@ namespace ConfectioneryView
// To customize application configuration such as set high DPIsettings or default font, // To customize application configuration such as set high DPIsettings or default font,
// see https://aka.ms/applicationconfiguration. // see https://aka.ms/applicationconfiguration.
ApplicationConfiguration.Initialize(); ApplicationConfiguration.Initialize();
var services = new ServiceCollection(); InitDependency();
ConfigureServices(services);
_serviceProvider = services.BuildServiceProvider();
try try
{ {
var mailSender = _serviceProvider.GetService<AbstractMailWorker>(); var mailSender = DependencyManager.Instance.Resolve<AbstractMailWorker>();
mailSender?.MailConfig(new MailConfigBindingModel mailSender?.MailConfig(new MailConfigBindingModel
{ {
MailLogin = System.Configuration.ConfigurationManager.AppSettings["MailLogin"] ?? string.Empty, MailLogin = System.Configuration.ConfigurationManager.AppSettings["MailLogin"] ?? string.Empty,
@ -49,65 +44,45 @@ namespace ConfectioneryView
} }
catch (Exception ex) catch (Exception ex)
{ {
var logger = _serviceProvider.GetService<ILogger>(); var logger = DependencyManager.Instance.Resolve<ILogger>();
logger?.LogError(ex, "Îøèáêà ðàáîòû ñ ïî÷òîé"); 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.SetMinimumLevel(LogLevel.Information);
option.AddNLog("nlog.config"); option.AddNLog("nlog.config");
}); });
services.AddTransient<IComponentStorage, ComponentStorage>();
services.AddTransient<IOrderStorage, OrderStorage>();
services.AddTransient<IPastryStorage, PastryStorage>();
services.AddTransient<IClientStorage, ClientStorage>();
services.AddTransient<IImplementerStorage, ImplementerStorage>();
services.AddTransient<IShopStorage, ShopStorage>();
services.AddTransient<IMessageInfoStorage, MessageInfoStorage>();
services.AddTransient<IComponentLogic, ComponentLogic>(); DependencyManager.Instance.RegisterType<FormMain>();
services.AddTransient<IOrderLogic, OrderLogic>(); DependencyManager.Instance.RegisterType<FormComponent>();
services.AddTransient<IPastryLogic, PastryLogic>(); DependencyManager.Instance.RegisterType<FormComponents>();
services.AddTransient<IReportLogic, ReportLogic>(); DependencyManager.Instance.RegisterType<FormCreateOrder>();
services.AddTransient<IClientLogic, ClientLogic>(); DependencyManager.Instance.RegisterType<FormPastry>();
services.AddTransient<IShopLogic, ShopLogic>(); DependencyManager.Instance.RegisterType<FormPastryComponent>();
services.AddTransient<IImplementerLogic, ImplementerLogic>(); DependencyManager.Instance.RegisterType<FormViewPastry>();
services.AddTransient<IMessageInfoLogic, MessageInfoLogic>(); DependencyManager.Instance.RegisterType<FormReportPastryComponents>();
services.AddTransient<IWorkProcess, WorkModeling>(); DependencyManager.Instance.RegisterType<FormReportOrders>();
DependencyManager.Instance.RegisterType<FormViewClients>();
DependencyManager.Instance.RegisterType<FormViewImplementers>();
DependencyManager.Instance.RegisterType<FormImplementer>();
DependencyManager.Instance.RegisterType<FormViewMail>();
services.AddSingleton<AbstractMailWorker, MailKitWorker>(); DependencyManager.Instance.RegisterType<FormReportShopPastries>();
DependencyManager.Instance.RegisterType<FormReportGroupOrders>();
services.AddTransient<AbstractSaveToExcel, SaveToExcel>(); DependencyManager.Instance.RegisterType<FormShop>();
services.AddTransient<AbstractSaveToWord, SaveToWord>(); DependencyManager.Instance.RegisterType<FormViewShops>();
services.AddTransient<AbstractSaveToPdf, SaveToPdf>(); DependencyManager.Instance.RegisterType<FormSellPastry>();
DependencyManager.Instance.RegisterType<FormReplyMail>();
services.AddTransient<FormMain>(); DependencyManager.Instance.RegisterType<FormAddPastryInShop>();
services.AddTransient<FormComponent>();
services.AddTransient<FormComponents>();
services.AddTransient<FormCreateOrder>();
services.AddTransient<FormPastry>();
services.AddTransient<FormPastryComponent>();
services.AddTransient<FormViewPastry>();
services.AddTransient<FormAddPastryInShop>();
services.AddTransient<FormViewShops>();
services.AddTransient<FormShop>();
services.AddTransient<FormSellPastry>();
services.AddTransient<FormReportShopPastries>();
services.AddTransient<FormReportPastryComponents>();
services.AddTransient<FormReportGroupOrders>();
services.AddTransient<FormReportOrders>();
services.AddTransient<FormViewClients>();
services.AddTransient<FormViewImplementers>();
services.AddTransient<FormImplementer>();
services.AddTransient<FormViewMail>();
services.AddTransient<FormReplyMail>();
} }
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,34 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConfectioneryContracts.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 string Format { get; private set; }
public ColumnAttribute(string title = "", bool visible = true, int width = 0, GridViewAutoSize gridViewAutoSize = GridViewAutoSize.None, bool isUseAutoSize = false, string format = "")
{
Title = title;
Visible = visible;
Width = width;
GridViewAutoSize = gridViewAutoSize;
IsUseAutoSize = isUseAutoSize;
Format = format;
}
}
}

View File

@ -0,0 +1,27 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConfectioneryContracts.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 ConfectioneryContracts.BindingModels
{
public class BackUpSaveBinidngModel
{
public string FolderName { get; set; } = string.Empty;
}
}

View File

@ -23,5 +23,6 @@ namespace ConfectioneryContracts.BindingModels
public bool HasRead { get; set; } public bool HasRead { get; set; }
public string? Reply { get; set; } public string? Reply { get; set; }
public int Id => throw new NotImplementedException();
} }
} }

View File

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

View File

@ -6,6 +6,14 @@
<Nullable>enable</Nullable> <Nullable>enable</Nullable>
</PropertyGroup> </PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="7.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging" Version="7.0.0" />
<PackageReference Include="NLog" Version="5.1.1" />
<PackageReference Include="Unity" Version="5.11.10" />
<PackageReference Include="Unity.Microsoft.Logging" Version="5.11.1" />
</ItemGroup>
<ItemGroup> <ItemGroup>
<ProjectReference Include="..\ConfectioneryDataModels\ConfectioneryDataModels.csproj" /> <ProjectReference Include="..\ConfectioneryDataModels\ConfectioneryDataModels.csproj" />
</ItemGroup> </ItemGroup>

View File

@ -0,0 +1,69 @@
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConfectioneryContracts.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 extList = ServiceProviderLoader.GetImplementationExtensions();
foreach(var ext in extList)
{
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,35 @@
using Microsoft.Extensions.Logging;
namespace ConfectioneryContracts.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,14 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConfectioneryContracts.DI
{
/// <summary>
/// Интерфейс для индентификации и отделения загрузки бизнес-логики от загрузки хранилищ
/// </summary>
/// <seealso cref="ConfectioneryContracts.DI.IImplementationExtension" />
public interface IImplementationBusinessLogicExtension : IImplementationExtension { }
}

View File

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

View File

@ -0,0 +1,57 @@
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
namespace ConfectioneryContracts.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,65 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
namespace ConfectioneryContracts.DI
{
public class ServiceProviderLoader
{
/// <summary>
/// Загрузка всех классов-реализаций IImplementationExtension
/// </summary>
/// <returns></returns>
public static List<IImplementationExtension?> GetImplementationExtensions()
{
// Список типов, по каждому из которых, должна быть выбрана наиболее приоритетная реализация
// IImplementationExtension должен быть последним, поскольку все классы реализации, наследуются от него и являются им в частности
Type[] handledTypes =
{
typeof(IImplementationBusinessLogicExtension),
typeof(IImplementationExtension)
};
var result = handledTypes.Select(x => (IImplementationExtension?)null).ToList();
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())
{
for (var i = 0; i < handledTypes.Length; i++)
{
if (t.IsClass && handledTypes[i].IsAssignableFrom(t))
{
if (result[i] == null)
{
result[i] = (IImplementationExtension)Activator.CreateInstance(t)!;
}
else
{
var newSource = (IImplementationExtension)Activator.CreateInstance(t)!;
if (newSource.Priority > result[i].Priority)
{
result[i] = newSource;
}
}
}
}
}
}
return result;
}
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,40 @@
using Microsoft.Extensions.Logging;
using System.ComponentModel;
using Unity;
using Unity.Lifetime;
using Unity.Microsoft.Logging;
namespace ConfectioneryContracts.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

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

View File

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

View File

@ -1,4 +1,5 @@
using ConfectioneryDataModels.Models; using ConfectioneryContracts.Attributes;
using ConfectioneryDataModels.Models;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.ComponentModel; using System.ComponentModel;
@ -10,12 +11,13 @@ namespace ConfectioneryContracts.ViewModels
{ {
public class ComponentViewModel : IComponentModel public class ComponentViewModel : IComponentModel
{ {
[Column(visible: false)]
public int Id { get; set; } public int Id { get; set; }
[DisplayName("Название компонента")] [Column("Название компонента", gridViewAutoSize: GridViewAutoSize.Fill, isUseAutoSize: true)]
public string ComponentName { get; set; } = string.Empty; public string ComponentName { get; set; } = string.Empty;
[DisplayName("Цена")] [Column("Цена", width: 80, format: "0.00")]
public double Cost { get; set; } public double Cost { get; set; }
} }
} }

View File

@ -1,4 +1,5 @@
using ConfectioneryDataModels; using ConfectioneryContracts.Attributes;
using ConfectioneryDataModels;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.ComponentModel; using System.ComponentModel;
@ -13,18 +14,19 @@ namespace ConfectioneryContracts.ViewModels
/// </summary> /// </summary>
public class ImplementerViewModel : IImplementerModel public class ImplementerViewModel : IImplementerModel
{ {
[Column(visible: false)]
public int Id { get; set; } public int Id { get; set; }
[DisplayName("ФИО исполнителя")] [Column("ФИО исполнителя", gridViewAutoSize: GridViewAutoSize.Fill, isUseAutoSize: true)]
public string ImplementerFIO { get; set; } = string.Empty; public string ImplementerFIO { get; set; } = string.Empty;
[DisplayName("Пароль")] [Column("Пароль", width: 150)]
public string Password { get; set; } = string.Empty; public string Password { get; set; } = string.Empty;
[DisplayName("Стаж работы")] [Column("Стаж работы", gridViewAutoSize: GridViewAutoSize.AllCells, isUseAutoSize: true)]
public int WorkExperience { get; set; } public int WorkExperience { get; set; }
[DisplayName("Квалификация")] [Column("Квалификация", gridViewAutoSize: GridViewAutoSize.AllCells, isUseAutoSize: true)]
public int Qualification { get; set; } public int Qualification { get; set; }
} }
} }

View File

@ -1,4 +1,5 @@
using ConfectioneryDataModels; using ConfectioneryContracts.Attributes;
using ConfectioneryDataModels;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.ComponentModel; using System.ComponentModel;
@ -10,26 +11,32 @@ namespace ConfectioneryContracts.ViewModels
{ {
public class MessageInfoViewModel : IMessageInfoModel public class MessageInfoViewModel : IMessageInfoModel
{ {
[Column(visible: false)]
public string MessageId { get; set; } = string.Empty; public string MessageId { get; set; } = string.Empty;
[Column(visible: false)]
public int? ClientId { get; set; } public int? ClientId { get; set; }
[DisplayName("Отправитель")] [Column("Отправитель", gridViewAutoSize: GridViewAutoSize.DisplayedCells, isUseAutoSize: true)]
public string SenderName { get; set; } = string.Empty; public string SenderName { get; set; } = string.Empty;
[DisplayName("Дата письма")] [Column("Дата письма", width: 100, format: "D")]
public DateTime DateDelivery { get; set; } public DateTime DateDelivery { get; set; }
[DisplayName("Заголовок")] [Column("Заголовок", width: 150)]
public string Subject { get; set; } = string.Empty; public string Subject { get; set; } = string.Empty;
[DisplayName("Текст")] [Column("Текст", gridViewAutoSize: GridViewAutoSize.Fill, isUseAutoSize: true)]
public string Body { get; set; } = string.Empty; public string Body { get; set; } = string.Empty;
[DisplayName("Прочитано")] [Column(visible: false)]
public int Id => throw new NotImplementedException();
[Column("Прочитано", gridViewAutoSize: GridViewAutoSize.AllCellsExceptHeader, isUseAutoSize: true)]
public bool HasRead { get; set; } public bool HasRead { get; set; }
[DisplayName("Ответ")] [Column("Ответ", gridViewAutoSize: GridViewAutoSize.Fill, isUseAutoSize: true)]
public string? Reply { get; set; } public string? Reply { get; set; }
} }
} }

View File

@ -1,4 +1,5 @@
using ConfectioneryDataModels.Enums; using ConfectioneryContracts.Attributes;
using ConfectioneryDataModels.Enums;
using ConfectioneryDataModels.Models; using ConfectioneryDataModels.Models;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
@ -11,36 +12,40 @@ namespace ConfectioneryContracts.ViewModels
{ {
public class OrderViewModel : IOrderModel public class OrderViewModel : IOrderModel
{ {
[DisplayName("Номер")] [Column("Номер", gridViewAutoSize: GridViewAutoSize.AllCells, isUseAutoSize: true)]
public int Id { get; set; } public int Id { get; set; }
[Column(visible: false)]
public int PastryId { get; set; } public int PastryId { get; set; }
[Column(visible: false)]
public int ClientId { get; set; } public int ClientId { get; set; }
[Column(visible: false)]
public int? ImplementerId { get; set; } public int? ImplementerId { get; set; }
[DisplayName("Фамилия клиента")] [Column("Фамилия клиента", gridViewAutoSize: GridViewAutoSize.Fill, isUseAutoSize: true)]
public string ClientFIO { get; set; } = string.Empty; public string ClientFIO { get; set; } = string.Empty;
[DisplayName("Фамилия исполнителя")] [Column("Фамилия исполнителя", gridViewAutoSize: GridViewAutoSize.Fill, isUseAutoSize: true)]
public string ImplementerFIO { get; set; } = string.Empty; public string ImplementerFIO { get; set; } = string.Empty;
[DisplayName("Изделие")] [Column("Изделие", gridViewAutoSize: GridViewAutoSize.AllCells, isUseAutoSize: true)]
public string PastryName { get; set; } = string.Empty; public string PastryName { get; set; } = string.Empty;
[DisplayName("Количество")] [Column("Количество", gridViewAutoSize: GridViewAutoSize.AllCells, isUseAutoSize: true)]
public int Count { get; set; } public int Count { get; set; }
[DisplayName("Сумма")] [Column("Сумма", gridViewAutoSize: GridViewAutoSize.AllCells, isUseAutoSize: true, format: "0.00")]
public double Sum { get; set; } public double Sum { get; set; }
[DisplayName("Статус")] [Column("Статус", gridViewAutoSize: GridViewAutoSize.AllCells, isUseAutoSize: true)]
public OrderStatus Status { get; set; } = OrderStatus.Неизвестен; public OrderStatus Status { get; set; } = OrderStatus.Неизвестен;
[DisplayName("Дата создания")] [Column("Дата создания", width: 100, format: "D")]
public DateTime DateCreate { get; set; } = DateTime.Now; public DateTime DateCreate { get; set; } = DateTime.Now;
[DisplayName("Дата выполнения")] [Column("Дата выполнения", width: 100, format: "D")]
public DateTime? DateImplement { get; set; } public DateTime? DateImplement { get; set; }
} }
} }

View File

@ -1,4 +1,5 @@
using ConfectioneryDataModels.Models; using ConfectioneryContracts.Attributes;
using ConfectioneryDataModels.Models;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.ComponentModel; using System.ComponentModel;
@ -10,11 +11,14 @@ namespace ConfectioneryContracts.ViewModels
{ {
public class PastryViewModel : IPastryModel public class PastryViewModel : IPastryModel
{ {
[Column(visible: false)]
public int Id { get; set; } public int Id { get; set; }
[DisplayName("Название изделия")] [Column("Название изделия", gridViewAutoSize: GridViewAutoSize.Fill, isUseAutoSize: true)]
public string PastryName { get; set; } = string.Empty; public string PastryName { get; set; } = string.Empty;
[DisplayName("Цена")]
[Column("Цена", width: 100, format: "0.00")]
public double Price { get; set; } public double Price { get; set; }
[Column(visible: false)]
public Dictionary<int, (IComponentModel, int)> PastryComponents public Dictionary<int, (IComponentModel, int)> PastryComponents
{ {
get; get;

View File

@ -1,4 +1,5 @@
using ConfectioneryDataModels; using ConfectioneryContracts.Attributes;
using ConfectioneryDataModels;
using ConfectioneryDataModels.Models; using ConfectioneryDataModels.Models;
using System.ComponentModel; using System.ComponentModel;
@ -6,24 +7,26 @@ namespace ConfectioneryContracts.ViewModels
{ {
public class ShopViewModel : IShopModel public class ShopViewModel : IShopModel
{ {
[DisplayName("Название магазина")] [Column("Название магазина", gridViewAutoSize: GridViewAutoSize.AllCells, isUseAutoSize: true)]
public string Name { get; set; } = string.Empty; public string Name { get; set; } = string.Empty;
[DisplayName("Адрес магазина")] [Column("Адрес магазина", gridViewAutoSize: GridViewAutoSize.Fill, isUseAutoSize: true)]
public string Address { get; set; } = string.Empty; public string Address { get; set; } = string.Empty;
[DisplayName("Максимальное количество изделий в магазине")] [Column("Максимальное количество изделий в магазине", gridViewAutoSize: GridViewAutoSize.DisplayedCells, isUseAutoSize: true)]
public int MaxCountPastries { get; set; } public int MaxCountPastries { get; set; }
[DisplayName("Время открытия")] [Column("Время открытия", gridViewAutoSize: GridViewAutoSize.AllCells, isUseAutoSize: true, format: "f")]
public DateTime DateOpening { get; set; } = DateTime.Now; public DateTime DateOpening { get; set; } = DateTime.Now;
[Column(visible: false)]
public Dictionary<int, (IPastryModel, int)> Pastries public Dictionary<int, (IPastryModel, int)> Pastries
{ {
get; get;
set; set;
} = new(); } = new();
[Column(visible: false)]
public int Id { get; set; } public int Id { get; set; }
} }

View File

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

View File

@ -0,0 +1,31 @@
using ConfectioneryContracts.StoragesContract;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConfectioneryDatabaseImplement
{
public class BackUpInfo : IBackUpInfo
{
public List<T>? GetList<T>() where T : class, new()
{
using var context = new ConfectioneryDatabase();
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

@ -6,22 +6,28 @@ using System.Collections.Generic;
using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema; using System.ComponentModel.DataAnnotations.Schema;
using System.Linq; using System.Linq;
using System.Runtime.Serialization;
using System.Text; using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
namespace ConfectioneryDatabaseImplement.Models namespace ConfectioneryDatabaseImplement.Models
{ {
[DataContract]
public class Client : IClientModel public class Client : IClientModel
{ {
[Required] [Required]
[DataMember]
public string ClientFIO { get; private set; } = string.Empty; public string ClientFIO { get; private set; } = string.Empty;
[Required] [Required]
[DataMember]
public string Email { get; private set; } = string.Empty; public string Email { get; private set; } = string.Empty;
[Required] [Required]
[DataMember]
public string Password { get; private set; } = string.Empty; public string Password { get; private set; } = string.Empty;
[DataMember]
public int Id { get; private set; } public int Id { get; private set; }
[ForeignKey("ClientId")] [ForeignKey("ClientId")]

View File

@ -3,15 +3,20 @@ using ConfectioneryDataModels.Models;
using System.ComponentModel.DataAnnotations.Schema; using System.ComponentModel.DataAnnotations.Schema;
using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations;
using ConfectioneryContracts.ViewModels; using ConfectioneryContracts.ViewModels;
using System.Runtime.Serialization;
namespace ConfectioneryDatabaseImplement.Models namespace ConfectioneryDatabaseImplement.Models
{ {
[DataContract]
public class Component : IComponentModel public class Component : IComponentModel
{ {
[DataMember]
public int Id { get; private set; } public int Id { get; private set; }
[Required] [Required]
[DataMember]
public string ComponentName { get; private set; } = string.Empty; public string ComponentName { get; private set; } = string.Empty;
[Required] [Required]
[DataMember]
public double Cost { get; set; } public double Cost { get; set; }
[ForeignKey("ComponentId")] [ForeignKey("ComponentId")]

View File

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

View File

@ -0,0 +1,24 @@
using ConfectioneryContracts.DI;
using ConfectioneryContracts.StoragesContract;
using ConfectioneryDatabaseImplement.Implements;
namespace ConfectioneryDatabaseImplement
{
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<IPastryStorage, PastryStorage>();
DependencyManager.Instance.RegisterType<IShopStorage, ShopStorage>();
DependencyManager.Instance.RegisterType<IBackUpInfo, BackUpInfo>();
}
}
}

View File

@ -2,19 +2,26 @@
using ConfectioneryContracts.ViewModels; using ConfectioneryContracts.ViewModels;
using ConfectioneryDataModels; using ConfectioneryDataModels;
using System.ComponentModel.DataAnnotations.Schema; using System.ComponentModel.DataAnnotations.Schema;
using System.Runtime.Serialization;
namespace ConfectioneryDatabaseImplement.Models namespace ConfectioneryDatabaseImplement.Models
{ {
[DataContract]
public class Implementer : IImplementerModel public class Implementer : IImplementerModel
{ {
[DataMember]
public int Id { get; private set; } public int Id { get; private set; }
[DataMember]
public string ImplementerFIO { get; private set; } = string.Empty; public string ImplementerFIO { get; private set; } = string.Empty;
[DataMember]
public string Password { get; private set; } = string.Empty; public string Password { get; private set; } = string.Empty;
[DataMember]
public int WorkExperience { get; private set; } public int WorkExperience { get; private set; }
[DataMember]
public int Qualification { get; private set; } public int Qualification { get; private set; }
[ForeignKey("ImplementerId")] [ForeignKey("ImplementerId")]

View File

@ -2,13 +2,16 @@
using ConfectioneryContracts.ViewModels; using ConfectioneryContracts.ViewModels;
using ConfectioneryDataModels; using ConfectioneryDataModels;
using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations;
using System.Runtime.Serialization;
namespace ConfectioneryDatabaseImplement.Models namespace ConfectioneryDatabaseImplement.Models
{ {
// Update в этой сущности не нужен, поскольку в логике мы не изменяем никакие поля после создания письма // Update в этой сущности не нужен, поскольку в логике мы не изменяем никакие поля после создания письма
[DataContract]
public class MessageInfo : IMessageInfoModel public class MessageInfo : IMessageInfoModel
{ {
[Key] [Key]
[DataMember]
public string MessageId { get; private set; } = string.Empty; public string MessageId { get; private set; } = string.Empty;
public int? ClientId { get; private set; } public int? ClientId { get; private set; }
@ -67,6 +70,7 @@ namespace ConfectioneryDatabaseImplement.Models
DateDelivery = DateDelivery, DateDelivery = DateDelivery,
}; };
public int Id => throw new NotImplementedException();
} }
} }

View File

@ -8,36 +8,46 @@ using System.Collections.Generic;
using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema; using System.ComponentModel.DataAnnotations.Schema;
using System.Linq; using System.Linq;
using System.Runtime.Serialization;
using System.Text; using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
using System.Xml.Linq; using System.Xml.Linq;
namespace ConfectioneryDatabaseImplement.Models namespace ConfectioneryDatabaseImplement.Models
{ {
[DataContract]
public class Order : IOrderModel public class Order : IOrderModel
{ {
public int Id { get; private set; } public int Id { get; private set; }
[Required] [Required]
[DataMember]
public int PastryId { get; private set; } public int PastryId { get; private set; }
[Required] [Required]
[DataMember]
public int ClientId { get; private set; } public int ClientId { get; private set; }
[DataMember]
public int? ImplementerId { get; private set; } public int? ImplementerId { get; private set; }
[Required] [Required]
[DataMember]
public int Count { get; private set; } public int Count { get; private set; }
[Required] [Required]
[DataMember]
public double Sum { get; private set; } public double Sum { get; private set; }
[Required] [Required]
[DataMember]
public OrderStatus Status { get; private set; } public OrderStatus Status { get; private set; }
[Required] [Required]
[DataMember]
public DateTime DateCreate { get; private set; } public DateTime DateCreate { get; private set; }
[DataMember]
public DateTime? DateImplement { get; private set; } public DateTime? DateImplement { get; private set; }
public Pastry Pastry { get; private set; } public Pastry Pastry { get; private set; }

View File

@ -3,19 +3,25 @@ using System.ComponentModel.DataAnnotations.Schema;
using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations;
using ConfectioneryContracts.BindingModels; using ConfectioneryContracts.BindingModels;
using ConfectioneryContracts.ViewModels; using ConfectioneryContracts.ViewModels;
using System.Runtime.Serialization;
namespace ConfectioneryDatabaseImplement.Models namespace ConfectioneryDatabaseImplement.Models
{ {
[DataContract]
public class Pastry : IPastryModel public class Pastry : IPastryModel
{ {
[DataMember]
public int Id { get; set; } public int Id { get; set; }
[Required] [Required]
[DataMember]
public string PastryName { get; set; } = string.Empty; public string PastryName { get; set; } = string.Empty;
[Required] [Required]
[DataMember]
public double Price { get; set; } public double Price { get; set; }
private Dictionary<int, (IComponentModel, int)>? _pastryComponents = null; private Dictionary<int, (IComponentModel, int)>? _pastryComponents = null;
[NotMapped] [NotMapped]
[DataMember]
public Dictionary<int, (IComponentModel, int)> PastryComponents public Dictionary<int, (IComponentModel, int)> PastryComponents
{ {
get get

View File

@ -7,25 +7,32 @@ using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging.Abstractions; using Microsoft.Extensions.Logging.Abstractions;
using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema; using System.ComponentModel.DataAnnotations.Schema;
using System.Runtime.Serialization;
using System.Xml.Linq; using System.Xml.Linq;
namespace ConfectioneryDatabaseImplement.Models namespace ConfectioneryDatabaseImplement.Models
{ {
[DataContract]
public class Shop : IShopModel public class Shop : IShopModel
{ {
[Required] [Required]
[DataMember]
public string Name { get; private set; } = string.Empty; public string Name { get; private set; } = string.Empty;
[Required] [Required]
[DataMember]
public string Address { get; private set; } = string.Empty; public string Address { get; private set; } = string.Empty;
[Required] [Required]
[DataMember]
public int MaxCountPastries { get; private set; } public int MaxCountPastries { get; private set; }
[DataMember]
public DateTime DateOpening { get; private set; } public DateTime DateOpening { get; private set; }
private Dictionary<int, (IPastryModel, int)>? _cachedPastries = null; private Dictionary<int, (IPastryModel, int)>? _cachedPastries = null;
[NotMapped] [NotMapped]
[DataMember]
public Dictionary<int, (IPastryModel, int)> Pastries public Dictionary<int, (IPastryModel, int)> Pastries
{ {
get get
@ -41,6 +48,7 @@ namespace ConfectioneryDatabaseImplement.Models
} }
} }
[DataMember]
public int Id { get; private set; } public int Id { get; private set; }
[ForeignKey("ShopId")] [ForeignKey("ShopId")]